From 6ae2361403612aefd9be5acaee0e0c3dc426d720 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Tue, 5 Sep 2023 16:04:22 +0200 Subject: [PATCH 01/12] Fix UB in a few return arguments - argument.rs: These previously returned the owned types, which would cause a double-release - library.rs: These returned `&*mut NSArray` instead of `&NSArray` - device.rs: `retain` returns a pointer to the object, not `void`/`()` --- src/argument.rs | 8 ++++---- src/device.rs | 8 ++++---- src/library.rs | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/argument.rs b/src/argument.rs index a85a737..2a10be2 100644 --- a/src/argument.rs +++ b/src/argument.rs @@ -158,11 +158,11 @@ impl StructMemberRef { unsafe { msg_send![self, dataType] } } - pub fn struct_type(&self) -> MTLStructType { + pub fn struct_type(&self) -> &StructTypeRef { unsafe { msg_send![self, structType] } } - pub fn array_type(&self) -> MTLArrayType { + pub fn array_type(&self) -> &ArrayTypeRef { unsafe { msg_send![self, arrayType] } } } @@ -225,11 +225,11 @@ impl ArrayTypeRef { unsafe { msg_send![self, elementType] } } - pub fn element_struct_type(&self) -> MTLStructType { + pub fn element_struct_type(&self) -> &StructTypeRef { unsafe { msg_send![self, elementStructType] } } - pub fn element_array_type(&self) -> MTLArrayType { + pub fn element_array_type(&self) -> &ArrayTypeRef { unsafe { msg_send![self, elementArrayType] } } } diff --git a/src/device.rs b/src/device.rs index 11b5575..fa175d0 100644 --- a/src/device.rs +++ b/src/device.rs @@ -1796,7 +1796,7 @@ impl DeviceRef { let state = RenderPipelineState::from_ptr(pipeline_state); - let () = msg_send![reflection, retain]; + let reflection: *mut AnyObject = msg_send![reflection, retain]; let reflection = RenderPipelineReflection::from_ptr(reflection as _); Ok((state, reflection)) @@ -1834,7 +1834,7 @@ impl DeviceRef { let state = RenderPipelineState::from_ptr(pipeline_state); - let () = msg_send![reflection, retain]; + let reflection: *mut AnyObject = msg_send![reflection, retain]; let reflection = RenderPipelineReflection::from_ptr(reflection as _); Ok((state, reflection)) @@ -1902,7 +1902,7 @@ impl DeviceRef { let state = ComputePipelineState::from_ptr(pipeline_state); - let () = msg_send![reflection, retain]; + let reflection: *mut AnyObject = msg_send![reflection, retain]; let reflection = ComputePipelineReflection::from_ptr(reflection as _); Ok((state, reflection)) @@ -2109,7 +2109,7 @@ impl DeviceRef { let ret = (0..count) .map(|i| { let csp: *mut MTLCounterSet = msg_send![counter_sets, objectAtIndex: i]; - let () = msg_send![csp, retain]; + let csp: *mut MTLCounterSet = msg_send![csp, retain]; CounterSet::from_ptr(csp) }) .collect(); diff --git a/src/library.rs b/src/library.rs index 2c7d0c9..3d52e22 100644 --- a/src/library.rs +++ b/src/library.rs @@ -321,12 +321,12 @@ impl FunctionRef { } /// Only available on (macos(10.12), ios(10.0)) - pub fn vertex_attributes(&self) -> &Array { + pub fn vertex_attributes(&self) -> &ArrayRef { unsafe { msg_send![self, vertexAttributes] } } /// Only available on (macos(10.12), ios(10.0)) - pub fn stage_input_attributes(&self) -> &Array { + pub fn stage_input_attributes(&self) -> &ArrayRef { unsafe { msg_send![self, stageInputAttributes] } } From f5d709e22bc592b327fdc13405b3d66562aaaf79 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Tue, 5 Sep 2023 16:20:34 +0200 Subject: [PATCH 02/12] Use objc2 - Implement Encode and RefEncode for most types --- Cargo.toml | 10 +- examples/argument-buffer/main.rs | 4 +- examples/bind/main.rs | 4 +- examples/bindless/main.rs | 4 +- examples/circle/main.rs | 7 +- examples/compute/compute-argument-buffer.rs | 4 +- examples/compute/embedded-lib.rs | 4 +- examples/compute/main.rs | 4 +- examples/events/main.rs | 2 +- examples/mesh-shader/main.rs | 8 +- examples/raytracing/main.rs | 8 +- examples/raytracing/renderer.rs | 2 +- examples/reflection/main.rs | 4 +- examples/shader-dylib/main.rs | 7 +- examples/texture/Cargo.toml | 9 +- examples/texture/src/main.rs | 4 +- examples/window/main.rs | 9 +- guide/internals/README.md | 8 +- src/accelerator_structure.rs | 57 +++++++++ src/argument.rs | 15 ++- src/capturedescriptor.rs | 4 + src/commandbuffer.rs | 18 ++- src/constants.rs | 6 + src/depthstencil.rs | 11 +- src/device.rs | 47 ++++++- src/encoder.rs | 69 ++++++++++ src/heap.rs | 4 + src/indirect_encoder.rs | 4 + src/lib.rs | 134 ++++++++++++-------- src/library.rs | 50 +++++--- src/mps.rs | 69 ++++++++-- src/pipeline/compute.rs | 10 +- src/pipeline/mod.rs | 4 + src/pipeline/render.rs | 18 ++- src/renderpass.rs | 19 +++ src/resource.rs | 32 ++++- src/sampler.rs | 18 ++- src/sync.rs | 11 +- src/texture.rs | 14 +- src/types.rs | 38 +++++- src/vertexdescriptor.rs | 10 +- 41 files changed, 606 insertions(+), 158 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index fe80094..da72be3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,17 +22,15 @@ mps = [] link = [] [dependencies] -core-graphics-types = "0.1" +# Branch: objc2. TODO: Remove this +core-graphics-types = { git = "https://github.com/madsmtm/core-foundation-rs.git", rev = "7d593d016175755e492a92ef89edca68ac3bd5cd" } bitflags = "2" log = "0.4" -block = "0.1.6" +block2 = "=0.2.0-alpha.6" foreign-types = "0.5" dispatch = { version = "0.2", optional = true } paste = "1" - -[dependencies.objc] -version = "0.2.4" -features = ["objc_exception"] +objc2 = "=0.3.0-beta.2" [dev-dependencies] cocoa = "0.24.0" diff --git a/examples/argument-buffer/main.rs b/examples/argument-buffer/main.rs index 23e8899..8e0f432 100644 --- a/examples/argument-buffer/main.rs +++ b/examples/argument-buffer/main.rs @@ -6,10 +6,10 @@ // copied, modified, or distributed except according to those terms. use metal::*; -use objc::rc::autoreleasepool; +use objc2::rc::autoreleasepool; fn main() { - autoreleasepool(|| { + autoreleasepool(|_| { let device = Device::system_default().expect("no device found"); /* diff --git a/examples/bind/main.rs b/examples/bind/main.rs index 811b1c5..13e57bd 100644 --- a/examples/bind/main.rs +++ b/examples/bind/main.rs @@ -6,10 +6,10 @@ // copied, modified, or distributed except according to those terms. use metal::*; -use objc::rc::autoreleasepool; +use objc2::rc::autoreleasepool; fn main() { - autoreleasepool(|| { + autoreleasepool(|_| { let device = Device::system_default().expect("no device found"); let buffer = device.new_buffer(4, MTLResourceOptions::empty()); diff --git a/examples/bindless/main.rs b/examples/bindless/main.rs index 09c3a59..e7e90ed 100644 --- a/examples/bindless/main.rs +++ b/examples/bindless/main.rs @@ -6,7 +6,7 @@ // copied, modified, or distributed except according to those terms. use metal::*; -use objc::rc::autoreleasepool; +use objc2::rc::autoreleasepool; const BINDLESS_TEXTURE_COUNT: NSUInteger = 100_000; // ~25Mb @@ -16,7 +16,7 @@ const BINDLESS_TEXTURE_COUNT: NSUInteger = 100_000; // ~25Mb /// - How to create bindless resources via Metal's argument buffers. /// - How to bind argument buffer to render encoder fn main() { - autoreleasepool(|| { + autoreleasepool(|_| { let device = Device::system_default().expect("no device found"); /* diff --git a/examples/circle/main.rs b/examples/circle/main.rs index ed17a73..7731f93 100644 --- a/examples/circle/main.rs +++ b/examples/circle/main.rs @@ -9,7 +9,8 @@ use winit::{ use cocoa::{appkit::NSView, base::id as cocoa_id}; use core_graphics_types::geometry::CGSize; -use objc::{rc::autoreleasepool, runtime::YES}; +use objc2::rc::autoreleasepool; +use objc2::runtime::Bool; use std::mem; @@ -101,7 +102,7 @@ fn main() { unsafe { let view = window.ns_view() as cocoa_id; - view.setWantsLayer(YES); + view.setWantsLayer(Bool::YES.as_raw()); view.setLayer(mem::transmute(layer.as_ref())); } @@ -120,7 +121,7 @@ fn main() { }; event_loop.run(move |event, _, control_flow| { - autoreleasepool(|| { + autoreleasepool(|_| { // ControlFlow::Wait pauses the event loop if no events are available to process. // This is ideal for non-game applications that only update in response to user // input, and uses significantly less power/CPU time than ControlFlow::Poll. diff --git a/examples/compute/compute-argument-buffer.rs b/examples/compute/compute-argument-buffer.rs index 9752709..cc4535f 100644 --- a/examples/compute/compute-argument-buffer.rs +++ b/examples/compute/compute-argument-buffer.rs @@ -6,13 +6,13 @@ // copied, modified, or distributed except according to those terms. use metal::*; -use objc::rc::autoreleasepool; +use objc2::rc::autoreleasepool; use std::mem; static LIBRARY_SRC: &str = include_str!("compute-argument-buffer.metal"); fn main() { - autoreleasepool(|| { + autoreleasepool(|_| { let device = Device::system_default().expect("no device found"); let command_queue = device.new_command_queue(); diff --git a/examples/compute/embedded-lib.rs b/examples/compute/embedded-lib.rs index 0fd193a..9f3692f 100644 --- a/examples/compute/embedded-lib.rs +++ b/examples/compute/embedded-lib.rs @@ -6,12 +6,12 @@ // copied, modified, or distributed except according to those terms. use metal::*; -use objc::rc::autoreleasepool; +use objc2::rc::autoreleasepool; fn main() { let library_data = include_bytes!("shaders.metallib"); - autoreleasepool(|| { + autoreleasepool(|_| { let device = Device::system_default().expect("no device found"); let library = device.new_library_with_data(&library_data[..]).unwrap(); diff --git a/examples/compute/main.rs b/examples/compute/main.rs index b654a66..be266e3 100644 --- a/examples/compute/main.rs +++ b/examples/compute/main.rs @@ -1,5 +1,5 @@ use metal::*; -use objc::rc::autoreleasepool; +use objc2::rc::autoreleasepool; use std::path::PathBuf; const NUM_SAMPLES: u64 = 2; @@ -10,7 +10,7 @@ fn main() { .map(|s| s.parse::().unwrap()) .unwrap_or(64 * 64); - autoreleasepool(|| { + autoreleasepool(|_| { let device = Device::system_default().expect("No device found"); let mut cpu_start = 0; let mut gpu_start = 0; diff --git a/examples/events/main.rs b/examples/events/main.rs index 9e4fe0e..5f482db 100644 --- a/examples/events/main.rs +++ b/examples/events/main.rs @@ -30,7 +30,7 @@ fn main() { let shared_event_listener = SharedEventListener::from_queue(&my_queue); // Register CPU work - let notify_block = block::ConcreteBlock::new(move |evt: &SharedEventRef, val: u64| { + let notify_block = block2::ConcreteBlock::new(move |evt: &SharedEventRef, val: u64| { println!("Got notification from GPU: {}", val); evt.set_signaled_value(3); }); diff --git a/examples/mesh-shader/main.rs b/examples/mesh-shader/main.rs index 8edb30c..ce06e10 100644 --- a/examples/mesh-shader/main.rs +++ b/examples/mesh-shader/main.rs @@ -1,10 +1,8 @@ -extern crate objc; - use cocoa::{appkit::NSView, base::id as cocoa_id}; use core_graphics_types::geometry::CGSize; use metal::*; -use objc::{rc::autoreleasepool, runtime::YES}; +use objc2::{rc::autoreleasepool, runtime::Bool}; use std::mem; use winit::platform::macos::WindowExtMacOS; @@ -41,7 +39,7 @@ fn main() { unsafe { let view = window.ns_view() as cocoa_id; - view.setWantsLayer(YES); + view.setWantsLayer(Bool::YES.as_raw()); view.setLayer(mem::transmute(layer.as_ref())); } @@ -71,7 +69,7 @@ fn main() { let command_queue = device.new_command_queue(); events_loop.run(move |event, _, control_flow| { - autoreleasepool(|| { + autoreleasepool(|_| { *control_flow = ControlFlow::Poll; match event { diff --git a/examples/raytracing/main.rs b/examples/raytracing/main.rs index 68eaf3d..457deb3 100644 --- a/examples/raytracing/main.rs +++ b/examples/raytracing/main.rs @@ -1,9 +1,7 @@ -extern crate objc; - use cocoa::{appkit::NSView, base::id as cocoa_id}; use core_graphics_types::geometry::CGSize; use metal::*; -use objc::{rc::autoreleasepool, runtime::YES}; +use objc2::{rc::autoreleasepool, runtime::Bool}; use std::mem; use winit::{ event::{Event, WindowEvent}, @@ -49,7 +47,7 @@ fn main() { unsafe { let view = window.ns_view() as cocoa_id; - view.setWantsLayer(YES); + view.setWantsLayer(Bool::YES.as_raw()); view.setLayer(mem::transmute(layer.as_ref())); } @@ -61,7 +59,7 @@ fn main() { renderer.window_resized(cg_size); events_loop.run(move |event, _, control_flow| { - autoreleasepool(|| { + autoreleasepool(|_| { *control_flow = ControlFlow::Poll; match event { diff --git a/examples/raytracing/renderer.rs b/examples/raytracing/renderer.rs index f483d3e..856a2c8 100644 --- a/examples/raytracing/renderer.rs +++ b/examples/raytracing/renderer.rs @@ -363,7 +363,7 @@ impl Renderer { self.update_uniforms(); let command_buffer = self.queue.new_command_buffer(); let sem = self.semaphore.clone(); - let block = block::ConcreteBlock::new(move |_| { + let block = block2::ConcreteBlock::new(move |_| { sem.release(); }) .copy(); diff --git a/examples/reflection/main.rs b/examples/reflection/main.rs index 058199c..c06ffc4 100644 --- a/examples/reflection/main.rs +++ b/examples/reflection/main.rs @@ -6,7 +6,7 @@ // copied, modified, or distributed except according to those terms. use metal::*; -use objc::rc::autoreleasepool; +use objc2::rc::autoreleasepool; const PROGRAM: &'static str = r" #include @@ -41,7 +41,7 @@ const PROGRAM: &'static str = r" "; fn main() { - autoreleasepool(|| { + autoreleasepool(|_| { let device = Device::system_default().expect("no device found"); let options = CompileOptions::new(); diff --git a/examples/shader-dylib/main.rs b/examples/shader-dylib/main.rs index 60b6aa0..b9f5237 100644 --- a/examples/shader-dylib/main.rs +++ b/examples/shader-dylib/main.rs @@ -2,7 +2,8 @@ use cocoa::{appkit::NSView, base::id as cocoa_id}; use core_graphics_types::geometry::CGSize; use metal::*; -use objc::{rc::autoreleasepool, runtime::YES}; +use objc2::rc::autoreleasepool; +use objc2::runtime::Bool; use winit::{ event::{Event, WindowEvent}, @@ -44,7 +45,7 @@ impl App { layer.set_framebuffer_only(false); unsafe { let view = window.ns_view() as cocoa_id; - view.setWantsLayer(YES); + view.setWantsLayer(Bool::YES.as_raw()); view.setLayer(mem::transmute(layer.as_ref())); } let draw_size = window.inner_size(); @@ -153,7 +154,7 @@ fn main() { let mut app = App::new(&window); events_loop.run(move |event, _, control_flow| { - autoreleasepool(|| { + autoreleasepool(|_| { *control_flow = ControlFlow::Poll; match event { diff --git a/examples/texture/Cargo.toml b/examples/texture/Cargo.toml index 8af54a9..460420c 100644 --- a/examples/texture/Cargo.toml +++ b/examples/texture/Cargo.toml @@ -9,13 +9,10 @@ edition = "2018" bindgen = { version = "0.60", default-features = false, features = ["logging", "runtime", "which-rustfmt"] } [dependencies] -core-graphics-types = "0.1" +# Branch: objc2. TODO: Remove this +core-graphics-types = { git = "https://github.com/madsmtm/core-foundation-rs.git", rev = "7d593d016175755e492a92ef89edca68ac3bd5cd" } cocoa = "0.24" -core-graphics = "0.22" png = "0.17" metal = { path = "../../" } winit = "0.27" - -[dependencies.objc] -version = "0.2.4" -features = ["objc_exception"] +objc2 = "=0.3.0-beta.2" diff --git a/examples/texture/src/main.rs b/examples/texture/src/main.rs index de7a476..406b465 100644 --- a/examples/texture/src/main.rs +++ b/examples/texture/src/main.rs @@ -5,7 +5,7 @@ use std::path::PathBuf; use cocoa::{appkit::NSView, base::id as cocoa_id}; use core_graphics_types::geometry::CGSize; -use objc::rc::autoreleasepool; +use objc2::rc::autoreleasepool; use winit::dpi::LogicalSize; use winit::event_loop::{ControlFlow, EventLoop}; use winit::platform::macos::WindowExtMacOS; @@ -58,7 +58,7 @@ fn main() { let command_queue = device.new_command_queue(); event_loop.run(move |event, _, control_flow| { - autoreleasepool(|| { + autoreleasepool(|_| { *control_flow = ControlFlow::Poll; match event { diff --git a/examples/window/main.rs b/examples/window/main.rs index 08936e8..ba439a3 100644 --- a/examples/window/main.rs +++ b/examples/window/main.rs @@ -5,13 +5,12 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -extern crate objc; - use cocoa::{appkit::NSView, base::id as cocoa_id}; use core_graphics_types::geometry::CGSize; use metal::*; -use objc::{rc::autoreleasepool, runtime::YES}; +use objc2::rc::autoreleasepool; +use objc2::runtime::Bool; use std::mem; use winit::platform::macos::WindowExtMacOS; @@ -103,7 +102,7 @@ fn main() { unsafe { let view = window.ns_view() as cocoa_id; - view.setWantsLayer(YES); + view.setWantsLayer(Bool::YES.as_raw()); view.setLayer(mem::transmute(layer.as_ref())); } @@ -162,7 +161,7 @@ fn main() { ); events_loop.run(move |event, _, control_flow| { - autoreleasepool(|| { + autoreleasepool(|_| { *control_flow = ControlFlow::Poll; match event { diff --git a/guide/internals/README.md b/guide/internals/README.md index 612ebab..483c5b6 100644 --- a/guide/internals/README.md +++ b/guide/internals/README.md @@ -1,6 +1,6 @@ Under the hood, `metal-rs` is powered by three main dependencies. -[rust-objc] and [rust-block] and [foreign-types]. +[`objc2`] and [`block2`] and [`foreign-types`]. These dependencies are used to communicate with the [Objective-C runtime] in order to allocate, de-allocate and call methods on the classes and objects that power Metal applications. @@ -50,8 +50,8 @@ foreign_obj_type! { ensures that when the owned `StencilDescriptor` is dropped it will call `release` on the backing Objective-C object, leading to the memory being deallocated. -[rust-objc]: https://github.com/SSheldon/rust-objc -[rust-block]: https://github.com/SSheldon/rust-block -[foreign-types]: https://github.com/sfackler/foreign-types +[`objc2`]: https://crates.io/crates/objc2 +[`block2`]: https://crates.io/crates/block2 +[`foreign-types`]: https://crates.io/crates/foreign-types [Objective-C runtime]: https://developer.apple.com/documentation/objectivec/objective-c_runtime [memory management policy]: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html#//apple_ref/doc/uid/20000994-BAJHFBGH diff --git a/src/accelerator_structure.rs b/src/accelerator_structure.rs index 5c8ac4d..1723fca 100644 --- a/src/accelerator_structure.rs +++ b/src/accelerator_structure.rs @@ -5,6 +5,8 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. +use std::os::raw::c_float; + use super::*; bitflags! { @@ -18,6 +20,10 @@ bitflags! { } } +unsafe impl Encode for MTLAccelerationStructureInstanceOptions { + const ENCODING: Encoding = u32::ENCODING; +} + /// See #[repr(u64)] #[allow(non_camel_case_types)] @@ -28,6 +34,10 @@ pub enum MTLAccelerationStructureInstanceDescriptorType { Motion = 2, } +unsafe impl Encode for MTLAccelerationStructureInstanceDescriptorType { + const ENCODING: Encoding = u64::ENCODING; +} + #[derive(Clone, Copy, PartialEq, Debug, Default)] #[repr(C)] pub struct MTLAccelerationStructureInstanceDescriptor { @@ -38,6 +48,39 @@ pub struct MTLAccelerationStructureInstanceDescriptor { pub acceleration_structure_index: u32, } +const PACKED_FLOAT_4_3_ENCODING: Encoding = Encoding::Struct( + "_MTLPackedFloat4x3", + &[Encoding::Array( + 4, + &Encoding::Struct( + "_MTLPackedFloat3", + &[Encoding::Union( + "?", + &[ + Encoding::Struct( + "?", + &[c_float::ENCODING, c_float::ENCODING, c_float::ENCODING], + ), + Encoding::Array(3, &c_float::ENCODING), + ], + )], + ), + )], +); + +unsafe impl Encode for MTLAccelerationStructureInstanceDescriptor { + const ENCODING: Encoding = Encoding::Struct( + "?", + &[ + PACKED_FLOAT_4_3_ENCODING, + MTLAccelerationStructureInstanceOptions::ENCODING, + u32::ENCODING, + u32::ENCODING, + u32::ENCODING, + ], + ); +} + #[derive(Clone, Copy, PartialEq, Debug, Default)] #[repr(C)] pub struct MTLAccelerationStructureUserIDInstanceDescriptor { @@ -49,6 +92,20 @@ pub struct MTLAccelerationStructureUserIDInstanceDescriptor { pub user_id: u32, } +unsafe impl Encode for MTLAccelerationStructureUserIDInstanceDescriptor { + const ENCODING: Encoding = Encoding::Struct( + "?", + &[ + PACKED_FLOAT_4_3_ENCODING, + MTLAccelerationStructureInstanceOptions::ENCODING, + u32::ENCODING, + u32::ENCODING, + u32::ENCODING, + u32::ENCODING, + ], + ); +} + pub enum MTLAccelerationStructureDescriptor {} foreign_obj_type! { diff --git a/src/argument.rs b/src/argument.rs index 2a10be2..6ee067e 100644 --- a/src/argument.rs +++ b/src/argument.rs @@ -5,8 +5,7 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use super::{MTLTextureType, NSUInteger}; -use objc::runtime::{NO, YES}; +use super::*; /// See #[repr(u64)] @@ -108,6 +107,10 @@ pub enum MTLDataType { RGB9E5Float = 77, } +unsafe impl Encode for MTLDataType { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[deprecated( @@ -124,6 +127,10 @@ pub enum MTLArgumentType { Imageblock = 17, } +unsafe impl Encode for MTLArgumentType { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[allow(non_camel_case_types)] @@ -134,6 +141,10 @@ pub enum MTLArgumentAccess { WriteOnly = 2, } +unsafe impl Encode for MTLArgumentAccess { + const ENCODING: Encoding = u64::ENCODING; +} + /// See pub enum MTLStructMember {} diff --git a/src/capturedescriptor.rs b/src/capturedescriptor.rs index 1e620cc..e8dab16 100644 --- a/src/capturedescriptor.rs +++ b/src/capturedescriptor.rs @@ -18,6 +18,10 @@ pub enum MTLCaptureDestination { GpuTraceDocument = 2, } +unsafe impl Encode for MTLCaptureDestination { + const ENCODING: Encoding = u64::ENCODING; +} + /// See pub enum MTLCaptureDescriptor {} diff --git a/src/commandbuffer.rs b/src/commandbuffer.rs index 26fea2e..30a2f8c 100644 --- a/src/commandbuffer.rs +++ b/src/commandbuffer.rs @@ -7,7 +7,7 @@ use super::*; -use block::Block; +use block2::Block; /// See #[repr(u32)] @@ -22,6 +22,10 @@ pub enum MTLCommandBufferStatus { Error = 5, } +unsafe impl Encode for MTLCommandBufferStatus { + const ENCODING: Encoding = u32::ENCODING; +} + /// See #[repr(u32)] #[allow(non_camel_case_types)] @@ -39,6 +43,10 @@ pub enum MTLCommandBufferError { DeviceRemoved = 11, } +unsafe impl Encode for MTLCommandBufferError { + const ENCODING: Encoding = u32::ENCODING; +} + /// See #[repr(u32)] #[allow(non_camel_case_types)] @@ -48,6 +56,10 @@ pub enum MTLDispatchType { Concurrent = 1, } +unsafe impl Encode for MTLDispatchType { + const ENCODING: Encoding = u32::ENCODING; +} + type CommandBufferHandler<'a> = Block<(&'a CommandBufferRef,), ()>; /// See . @@ -58,6 +70,10 @@ foreign_obj_type! { pub struct CommandBuffer; } +unsafe impl Encode for CommandBufferRef { + const ENCODING: Encoding = Encoding::Unknown; // TODO +} + impl CommandBufferRef { pub fn label(&self) -> &str { unsafe { diff --git a/src/constants.rs b/src/constants.rs index 4e0e7a9..e70f82f 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -5,6 +5,8 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. +use super::*; + /// See #[repr(u64)] #[allow(non_camel_case_types)] @@ -150,3 +152,7 @@ pub enum MTLPixelFormat { BGR10_XR = 554, BGR10_XR_SRGB = 555, } + +unsafe impl Encode for MTLPixelFormat { + const ENCODING: Encoding = u64::ENCODING; +} diff --git a/src/depthstencil.rs b/src/depthstencil.rs index fe0611b..ce54142 100644 --- a/src/depthstencil.rs +++ b/src/depthstencil.rs @@ -5,8 +5,7 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use crate::DeviceRef; -use objc::runtime::{NO, YES}; +use super::*; /// See #[repr(u64)] @@ -22,6 +21,10 @@ pub enum MTLCompareFunction { Always = 7, } +unsafe impl Encode for MTLCompareFunction { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] @@ -36,6 +39,10 @@ pub enum MTLStencilOperation { DecrementWrap = 7, } +unsafe impl Encode for MTLStencilOperation { + const ENCODING: Encoding = u64::ENCODING; +} + /// See pub enum MTLStencilDescriptor {} diff --git a/src/device.rs b/src/device.rs index fa175d0..e7fce36 100644 --- a/src/device.rs +++ b/src/device.rs @@ -7,9 +7,9 @@ use super::*; -use block::{Block, ConcreteBlock}; +use block2::{Block, ConcreteBlock}; use foreign_types::ForeignType; -use objc::runtime::{Object, NO, YES}; +use objc2::runtime::Object; use std::{ffi::CStr, os::raw::c_char, path::Path, ptr}; @@ -57,6 +57,10 @@ pub enum MTLFeatureSet { macOS_GPUFamily2_v1 = 10005, } +unsafe impl Encode for MTLFeatureSet { + const ENCODING: Encoding = u64::ENCODING; +} + /// Available on macOS 10.15+, iOS 13.0+ /// /// See @@ -83,6 +87,10 @@ pub enum MTLGPUFamily { Metal3 = 5001, } +unsafe impl Encode for MTLGPUFamily { + const ENCODING: Encoding = i64::ENCODING; +} + /// See #[repr(u64)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] @@ -93,6 +101,10 @@ pub enum MTLDeviceLocation { Unspecified = u64::MAX, } +unsafe impl Encode for MTLDeviceLocation { + const ENCODING: Encoding = u64::ENCODING; +} + bitflags! { #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct PixelFormatCapabilities: u32 { @@ -1398,6 +1410,10 @@ pub enum MTLArgumentBuffersTier { Tier2 = 1, } +unsafe impl Encode for MTLArgumentBuffersTier { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] @@ -1407,6 +1423,10 @@ pub enum MTLReadWriteTextureTier { Tier2 = 2, } +unsafe impl Encode for MTLReadWriteTextureTier { + const ENCODING: Encoding = u64::ENCODING; +} + /// Only available on (macos(11.0), ios(14.0)) /// /// See @@ -1420,6 +1440,10 @@ pub enum MTLCounterSamplingPoint { AtBlitBoundary = 4, } +unsafe impl Encode for MTLCounterSamplingPoint { + const ENCODING: Encoding = u64::ENCODING; +} + /// Only available on (macos(11.0), macCatalyst(14.0), ios(13.0)) /// Kinda a long name! /// @@ -1431,6 +1455,10 @@ pub enum MTLSparseTextureRegionAlignmentMode { Inward = 1, } +unsafe impl Encode for MTLSparseTextureRegionAlignmentMode { + const ENCODING: Encoding = u64::ENCODING; +} + bitflags! { /// Options that determine how Metal prepares the pipeline. #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] @@ -1449,6 +1477,10 @@ bitflags! { } } +unsafe impl Encode for MTLPipelineOption { + const ENCODING: Encoding = NSUInteger::ENCODING; +} + /// See #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] #[repr(C)] @@ -1458,6 +1490,17 @@ pub struct MTLAccelerationStructureSizes { pub refit_scratch_buffer_size: NSUInteger, } +unsafe impl Encode for MTLAccelerationStructureSizes { + const ENCODING: Encoding = Encoding::Struct( + "?", + &[ + NSUInteger::ENCODING, + NSUInteger::ENCODING, + NSUInteger::ENCODING, + ], + ); +} + #[cfg_attr(feature = "link", link(name = "Metal", kind = "framework"))] extern "C" { fn MTLCreateSystemDefaultDevice() -> *mut MTLDevice; diff --git a/src/encoder.rs b/src/encoder.rs index 7ecc56d..bf22abe 100644 --- a/src/encoder.rs +++ b/src/encoder.rs @@ -23,6 +23,10 @@ pub enum MTLPrimitiveType { TriangleStrip = 4, } +unsafe impl Encode for MTLPrimitiveType { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[allow(non_camel_case_types)] @@ -32,6 +36,10 @@ pub enum MTLIndexType { UInt32 = 1, } +unsafe impl Encode for MTLIndexType { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] @@ -41,6 +49,10 @@ pub enum MTLVisibilityResultMode { Counting = 2, } +unsafe impl Encode for MTLVisibilityResultMode { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] @@ -50,6 +62,10 @@ pub enum MTLCullMode { Back = 2, } +unsafe impl Encode for MTLCullMode { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] @@ -58,6 +74,10 @@ pub enum MTLWinding { CounterClockwise = 1, } +unsafe impl Encode for MTLWinding { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] @@ -66,6 +86,10 @@ pub enum MTLDepthClipMode { Clamp = 1, } +unsafe impl Encode for MTLDepthClipMode { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] @@ -74,6 +98,10 @@ pub enum MTLTriangleFillMode { Lines = 1, } +unsafe impl Encode for MTLTriangleFillMode { + const ENCODING: Encoding = u64::ENCODING; +} + bitflags! { /// https://developer.apple.com/documentation/metal/mtlblitoption #[allow(non_upper_case_globals)] @@ -90,6 +118,10 @@ bitflags! { } } +unsafe impl Encode for MTLBlitOption { + const ENCODING: Encoding = NSUInteger::ENCODING; +} + /// See #[repr(C)] #[derive(Copy, Clone, Debug)] @@ -100,6 +132,18 @@ pub struct MTLScissorRect { pub height: NSUInteger, } +unsafe impl Encode for MTLScissorRect { + const ENCODING: Encoding = Encoding::Struct( + "MTLScissorRect", + &[ + NSUInteger::ENCODING, + NSUInteger::ENCODING, + NSUInteger::ENCODING, + NSUInteger::ENCODING, + ], + ); +} + /// See #[repr(C)] #[derive(Copy, Clone, Debug)] @@ -112,6 +156,20 @@ pub struct MTLViewport { pub zfar: f64, } +unsafe impl Encode for MTLViewport { + const ENCODING: Encoding = Encoding::Struct( + "MTLViewport", + &[ + f64::ENCODING, + f64::ENCODING, + f64::ENCODING, + f64::ENCODING, + f64::ENCODING, + f64::ENCODING, + ], + ); +} + /// See #[repr(C)] #[derive(Copy, Clone, Debug)] @@ -141,6 +199,17 @@ pub struct VertexAmplificationViewMapping { pub viewportArrayIndexOffset: u32, } +unsafe impl Encode for VertexAmplificationViewMapping { + const ENCODING: Encoding = Encoding::Struct( + "VertexAmplificationViewMapping", + &[u32::ENCODING, u32::ENCODING], + ); +} + +unsafe impl RefEncode for VertexAmplificationViewMapping { + const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING); +} + #[allow(dead_code)] type MTLVertexAmplicationViewMapping = VertexAmplificationViewMapping; diff --git a/src/heap.rs b/src/heap.rs index d2c11bb..eac0eac 100644 --- a/src/heap.rs +++ b/src/heap.rs @@ -19,6 +19,10 @@ pub enum MTLHeapType { Sparse = 2, } +unsafe impl Encode for MTLHeapType { + const ENCODING: Encoding = u64::ENCODING; +} + /// See pub enum MTLHeap {} diff --git a/src/indirect_encoder.rs b/src/indirect_encoder.rs index e434d34..9243a8c 100644 --- a/src/indirect_encoder.rs +++ b/src/indirect_encoder.rs @@ -14,6 +14,10 @@ bitflags! { } } +unsafe impl Encode for MTLIndirectCommandType { + const ENCODING: Encoding = NSUInteger::ENCODING; +} + /// See pub enum MTLIndirectCommandBufferDescriptor {} diff --git a/src/lib.rs b/src/lib.rs index b79acf6..6ba9435 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,7 +14,7 @@ pub extern crate bitflags; #[macro_use] pub extern crate log; #[macro_use] -pub extern crate objc; +pub extern crate objc2; #[macro_use] pub extern crate foreign_types; #[macro_use] @@ -30,7 +30,8 @@ use std::{ use core_graphics_types::{base::CGFloat, geometry::CGSize}; use foreign_types::ForeignType; -use objc::runtime::{Object, NO, YES}; +pub(crate) use objc2::encode::{Encode, Encoding, RefEncode}; +use objc2::runtime::{Bool, Object, Protocol}; /// See #[cfg(target_pointer_width = "64")] @@ -56,6 +57,11 @@ pub struct NSRange { pub length: NSUInteger, } +unsafe impl objc2::Encode for NSRange { + const ENCODING: objc2::Encoding = + objc2::Encoding::Struct("_NSRange", &[NSUInteger::ENCODING, NSUInteger::ENCODING]); +} + impl NSRange { #[inline] pub fn new(location: NSUInteger, length: NSUInteger) -> NSRange { @@ -63,7 +69,7 @@ impl NSRange { } } -fn nsstring_as_str(nsstr: &objc::runtime::Object) -> &str { +fn nsstring_as_str(nsstr: &Object) -> &str { let bytes = unsafe { let bytes: *const std::os::raw::c_char = msg_send![nsstr, UTF8String]; bytes as *const u8 @@ -75,20 +81,20 @@ fn nsstring_as_str(nsstr: &objc::runtime::Object) -> &str { } } -fn nsstring_from_str(string: &str) -> *mut objc::runtime::Object { +fn nsstring_from_str(string: &str) -> *mut Object { const UTF8_ENCODING: usize = 4; let cls = class!(NSString); let bytes = string.as_ptr() as *const c_void; unsafe { - let obj: *mut objc::runtime::Object = msg_send![cls, alloc]; - let obj: *mut objc::runtime::Object = msg_send![ + let obj: *mut Object = msg_send![cls, alloc]; + let obj: *mut Object = msg_send![ obj, initWithBytes:bytes length:string.len() encoding:UTF8_ENCODING ]; - let _: *mut c_void = msg_send![obj, autorelease]; + let _: *mut Object = msg_send![obj, autorelease]; obj } } @@ -174,15 +180,24 @@ macro_rules! foreign_obj_type { } } - unsafe impl ::objc::Message for $raw_ident { + unsafe impl ::objc2::encode::Encode for $owned_ident { + const ENCODING: ::objc2::Encoding = ::objc2::Encoding::Object; + } + unsafe impl ::objc2::encode::RefEncode for $raw_ident { + const ENCODING_REF: ::objc2::Encoding = ::objc2::Encoding::Object; + } + unsafe impl ::objc2::encode::RefEncode for paste!{[<$owned_ident Ref>]} { + const ENCODING_REF: ::objc2::Encoding = ::objc2::Encoding::Object; } - unsafe impl ::objc::Message for paste!{[<$owned_ident Ref>]} { + unsafe impl ::objc2::Message for $raw_ident { + } + unsafe impl ::objc2::Message for paste!{[<$owned_ident Ref>]} { } impl ::std::fmt::Debug for paste!{[<$owned_ident Ref>]} { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { unsafe { - let string: *mut ::objc::runtime::Object = msg_send![self, debugDescription]; + let string: *mut ::objc2::runtime::Object = msg_send![self, debugDescription]; write!(f, "{}", crate::nsstring_as_str(&*string)) } } @@ -201,7 +216,7 @@ macro_rules! try_objc { $err_name: ident => $body:expr } => { { - let mut $err_name: *mut Object = ::std::ptr::null_mut(); + let mut $err_name: *mut ::objc2::runtime::Object = ::std::ptr::null_mut(); let value = $body; if !$err_name.is_null() { let desc: *mut Object = msg_send![$err_name, localizedDescription]; @@ -214,29 +229,10 @@ macro_rules! try_objc { }; } -macro_rules! msg_send_bool { - ($obj:expr, $name:ident) => {{ - match msg_send![$obj, $name] { - YES => true, - NO => false, - #[cfg(not(target_arch = "aarch64"))] - _ => unreachable!(), - } - }}; - ($obj:expr, $name:ident : $arg:expr) => {{ - match msg_send![$obj, $name: $arg] { - YES => true, - NO => false, - #[cfg(not(target_arch = "aarch64"))] - _ => unreachable!(), - } - }}; -} - macro_rules! msg_send_bool_error_check { ($obj:expr, $name:ident: $arg:expr) => {{ let mut err: *mut Object = ptr::null_mut(); - let result: BOOL = msg_send![$obj, $name:$arg + let result: Bool = msg_send![$obj, $name:$arg error:&mut err]; if !err.is_null() { let desc: *mut Object = msg_send![err, localizedDescription]; @@ -244,12 +240,7 @@ macro_rules! msg_send_bool_error_check { let message = CStr::from_ptr(c_msg).to_string_lossy().into_owned(); Err(message) } else { - match result { - YES => Ok(true), - NO => Ok(false), - #[cfg(not(target_arch = "aarch64"))] - _ => unreachable!(), - } + Ok(result.as_bool()) } }}; } @@ -262,17 +253,17 @@ pub struct NSArray { pub struct Array(*mut NSArray) where T: ForeignType + 'static, - T::Ref: objc::Message + 'static; + T::Ref: objc2::Message + 'static; pub struct ArrayRef(foreign_types::Opaque, PhantomData) where T: ForeignType + 'static, - T::Ref: objc::Message + 'static; + T::Ref: objc2::Message + 'static; impl Drop for Array where T: ForeignType + 'static, - T::Ref: objc::Message + 'static, + T::Ref: objc2::Message + 'static, { fn drop(&mut self) { unsafe { @@ -284,31 +275,55 @@ where impl Clone for Array where T: ForeignType + 'static, - T::Ref: objc::Message + 'static, + T::Ref: objc2::Message + 'static, { fn clone(&self) -> Self { unsafe { Array(msg_send![self.0, retain]) } } } -unsafe impl objc::Message for NSArray +unsafe impl RefEncode for NSArray +where + T: ForeignType + 'static, + T::Ref: objc2::Message + 'static, +{ + const ENCODING_REF: Encoding = Encoding::Object; +} + +unsafe impl objc2::Message for NSArray +where + T: ForeignType + 'static, + T::Ref: objc2::Message + 'static, +{ +} + +unsafe impl RefEncode for ArrayRef +where + T: ForeignType + 'static, + T::Ref: objc2::Message + 'static, +{ + const ENCODING_REF: Encoding = Encoding::Object; +} + +unsafe impl objc2::Message for ArrayRef where T: ForeignType + 'static, - T::Ref: objc::Message + 'static, + T::Ref: objc2::Message + 'static, { } -unsafe impl objc::Message for ArrayRef +unsafe impl Encode for Array where T: ForeignType + 'static, - T::Ref: objc::Message + 'static, + T::Ref: objc2::Message + 'static, { + const ENCODING: ::objc2::Encoding = Encoding::Object; } impl Array where T: ForeignType + 'static, - T::Ref: objc::Message + 'static, + T::Ref: objc2::Message + 'static, { pub fn from_slice<'a>(s: &[&T::Ref]) -> &'a ArrayRef { unsafe { @@ -316,11 +331,19 @@ where msg_send![class, arrayWithObjects: s.as_ptr() count: s.len()] } } +} +impl Array +where + T: ForeignType + objc2::Encode + 'static, + T::Ref: objc2::Message + 'static, +{ pub fn from_owned_slice<'a>(s: &[T]) -> &'a ArrayRef { unsafe { let class = class!(NSArray); - msg_send![class, arrayWithObjects: s.as_ptr() count: s.len()] + let ptr: *const T = s.as_ptr(); + let ptr: *const *const T::Ref = ptr.cast(); + msg_send![class, arrayWithObjects: ptr count: s.len()] } } } @@ -328,7 +351,7 @@ where unsafe impl foreign_types::ForeignType for Array where T: ForeignType + 'static, - T::Ref: objc::Message + 'static, + T::Ref: objc2::Message + 'static, { type CType = NSArray; type Ref = ArrayRef; @@ -345,7 +368,7 @@ where unsafe impl foreign_types::ForeignTypeRef for ArrayRef where T: ForeignType + 'static, - T::Ref: objc::Message + 'static, + T::Ref: objc2::Message + 'static, { type CType = NSArray; } @@ -353,7 +376,7 @@ where impl Deref for Array where T: ForeignType + 'static, - T::Ref: objc::Message + 'static, + T::Ref: objc2::Message + 'static, { type Target = ArrayRef; @@ -366,7 +389,7 @@ where impl Borrow> for Array where T: ForeignType + 'static, - T::Ref: objc::Message + 'static, + T::Ref: objc2::Message + 'static, { fn borrow(&self) -> &ArrayRef { unsafe { mem::transmute(self.as_ptr()) } @@ -376,7 +399,7 @@ where impl ToOwned for ArrayRef where T: ForeignType + 'static, - T::Ref: objc::Message + 'static, + T::Ref: objc2::Message + 'static, { type Owned = Array; @@ -411,7 +434,7 @@ impl NsObjectRef { pub fn conforms_to_protocol(&self) -> Result { let name = ::std::any::type_name::(); if let Some(name) = name.split("::").last() { - if let Some(protocol) = objc::runtime::Protocol::get(name) { + if let Some(protocol) = Protocol::get(name) { Ok(unsafe { msg_send![self, conformsToProtocol: protocol] }) } else { Err(format!("Can not find the protocol for type: {}.", name)) @@ -607,12 +630,13 @@ pub use { #[inline] unsafe fn obj_drop(p: *mut T) { - msg_send![(p as *mut Object), release] + msg_send![p as *mut Object, release] } #[inline] unsafe fn obj_clone(p: *mut T) -> *mut T { - msg_send![(p as *mut Object), retain] + let p: *mut Object = msg_send![p as *mut Object, retain]; + p as *mut T } #[allow(non_camel_case_types)] diff --git a/src/library.rs b/src/library.rs index 3d52e22..d0be3e0 100644 --- a/src/library.rs +++ b/src/library.rs @@ -8,7 +8,7 @@ use super::*; use foreign_types::ForeignType; -use objc::runtime::{Object, BOOL, NO, YES}; +use objc2::runtime::Object; use std::ffi::CStr; use std::os::raw::{c_char, c_void}; @@ -25,6 +25,10 @@ pub enum MTLPatchType { Quad = 2, } +unsafe impl Encode for MTLPatchType { + const ENCODING: Encoding = u64::ENCODING; +} + /// See pub enum MTLVertexAttribute {} @@ -118,6 +122,10 @@ pub enum MTLFunctionType { Intersection = 6, } +unsafe impl Encode for MTLFunctionType { + const ENCODING: Encoding = u64::ENCODING; +} + /// Only available on (macos(10.12), ios(10.0)) /// /// See @@ -160,6 +168,10 @@ bitflags! { } } +unsafe impl Encode for MTLFunctionOptions { + const ENCODING: Encoding = NSUInteger::ENCODING; +} + /// Only available on (macos(11.0), ios(14.0)) /// /// See @@ -363,6 +375,10 @@ pub enum MTLLanguageVersion { V2_4 = 0x20004, } +unsafe impl Encode for MTLLanguageVersion { + const ENCODING: Encoding = u64::ENCODING; +} + /// See pub enum MTLFunctionConstantValues {} @@ -417,6 +433,10 @@ pub enum MTLLibraryType { Dynamic = 1, } +unsafe impl Encode for MTLLibraryType { + const ENCODING: Encoding = u64::ENCODING; +} + /// See pub enum MTLCompileOptions {} @@ -551,6 +571,10 @@ pub enum MTLLibraryError { FileNotFound = 6, } +unsafe impl Encode for MTLLibraryError { + const ENCODING: Encoding = u64::ENCODING; +} + /// See pub enum MTLLibrary {} @@ -692,6 +716,10 @@ pub enum MTLDynamicLibraryError { Unsupported = 5, } +unsafe impl Encode for MTLDynamicLibraryError { + const ENCODING: Encoding = u64::ENCODING; +} + /// See pub enum MTLDynamicLibrary {} @@ -811,25 +839,7 @@ impl BinaryArchiveRef { // error:(NSError * _Nullable *)error; pub fn serialize_to_url(&self, url: &URLRef) -> Result { - unsafe { - let mut err: *mut Object = ptr::null_mut(); - let result: BOOL = msg_send![self, serializeToURL:url - error:&mut err]; - if !err.is_null() { - // FIXME: copy pasta - let desc: *mut Object = msg_send![err, localizedDescription]; - let c_msg: *const c_char = msg_send![desc, UTF8String]; - let message = CStr::from_ptr(c_msg).to_string_lossy().into_owned(); - Err(message) - } else { - match result { - YES => Ok(true), - NO => Ok(false), - #[cfg(not(target_arch = "aarch64"))] - _ => unreachable!(), - } - } - } + unsafe { msg_send_bool_error_check![self, serializeToURL: url] } } } diff --git a/src/mps.rs b/src/mps.rs index edd4936..f61e764 100644 --- a/src/mps.rs +++ b/src/mps.rs @@ -7,19 +7,21 @@ use super::*; -use objc::runtime::{BOOL, YES}; +use objc2::runtime::Bool; -#[cfg_attr(feature = "link", link(name = "MetalPerformanceShaders", kind = "framework"))] +#[cfg_attr( + feature = "link", + link(name = "MetalPerformanceShaders", kind = "framework") +)] extern "C" { - fn MPSSupportsMTLDevice(device: *const std::ffi::c_void) -> BOOL; + fn MPSSupportsMTLDevice(device: *const std::ffi::c_void) -> Bool; } pub fn mps_supports_device(device: &DeviceRef) -> bool { - let b: BOOL = unsafe { + unsafe { let ptr: *const DeviceRef = device; - MPSSupportsMTLDevice(ptr as _) - }; - b == YES + MPSSupportsMTLDevice(ptr as _).as_bool() + } } /// See @@ -31,12 +33,17 @@ foreign_obj_type! { } /// See +#[repr(usize)] // NSUInteger pub enum MPSRayDataType { OriginDirection = 0, OriginMinDistanceDirectionMaxDistance = 1, OriginMaskDirectionMaxDistance = 2, } +unsafe impl Encode for MPSRayDataType { + const ENCODING: Encoding = NSUInteger::ENCODING; +} + bitflags! { /// See #[allow(non_upper_case_globals)] @@ -49,9 +56,14 @@ bitflags! { } } +unsafe impl Encode for MPSRayMaskOptions { + const ENCODING: Encoding = NSUInteger::ENCODING; +} + /// Options that determine the data contained in an intersection result. /// /// See +#[repr(usize)] // NSUInteger pub enum MPSIntersectionDataType { Distance = 0, DistancePrimitiveIndex = 1, @@ -60,7 +72,12 @@ pub enum MPSIntersectionDataType { DistancePrimitiveIndexInstanceIndexCoordinates = 4, } +unsafe impl Encode for MPSIntersectionDataType { + const ENCODING: Encoding = NSUInteger::ENCODING; +} + /// See +#[repr(usize)] // NSUInteger pub enum MPSIntersectionType { /// Find the closest intersection to the ray's origin along the ray direction. /// This is potentially slower than `Any` but is well suited to primary visibility rays. @@ -70,7 +87,12 @@ pub enum MPSIntersectionType { Any = 1, } +unsafe impl Encode for MPSIntersectionType { + const ENCODING: Encoding = NSUInteger::ENCODING; +} + /// See +#[repr(usize)] // NSUInteger pub enum MPSRayMaskOperator { /// Accept the intersection if `(primitive mask & ray mask) != 0`. And = 0, @@ -96,7 +118,12 @@ pub enum MPSRayMaskOperator { GreaterThanOrEqualTo = 9, } +unsafe impl Encode for MPSRayMaskOperator { + const ENCODING: Encoding = NSUInteger::ENCODING; +} + /// See +#[repr(usize)] // NSUInteger pub enum MPSTriangleIntersectionTestType { /// Use the default ray/triangle intersection test Default = 0, @@ -106,13 +133,22 @@ pub enum MPSTriangleIntersectionTestType { Watertight = 1, } +unsafe impl Encode for MPSTriangleIntersectionTestType { + const ENCODING: Encoding = NSUInteger::ENCODING; +} + /// See #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] +#[repr(usize)] // NSUInteger pub enum MPSAccelerationStructureStatus { Unbuilt = 0, Built = 1, } +unsafe impl Encode for MPSAccelerationStructureStatus { + const ENCODING: Encoding = NSUInteger::ENCODING; +} + bitflags! { /// See #[allow(non_upper_case_globals)] @@ -129,12 +165,17 @@ bitflags! { } } +unsafe impl Encode for MPSAccelerationStructureUsage { + const ENCODING: Encoding = NSUInteger::ENCODING; +} + /// A common bit for all floating point data types. -const MPSDataTypeFloatBit: isize = 0x10000000; -const MPSDataTypeSignedBit: isize = 0x20000000; -const MPSDataTypeNormalizedBit: isize = 0x40000000; +const MPSDataTypeFloatBit: u32 = 0x10000000; +const MPSDataTypeSignedBit: u32 = 0x20000000; +const MPSDataTypeNormalizedBit: u32 = 0x40000000; /// See +#[repr(u32)] // uint32_t pub enum MPSDataType { Invalid = 0, @@ -156,6 +197,10 @@ pub enum MPSDataType { Unorm8 = MPSDataTypeNormalizedBit | 8, } +unsafe impl Encode for MPSDataType { + const ENCODING: Encoding = u32::ENCODING; +} + /// A kernel that performs intersection tests between rays and geometry. /// /// See @@ -414,6 +459,10 @@ pub enum MPSTransformType { Identity = 1, } +unsafe impl Encode for MPSTransformType { + const ENCODING: Encoding = u64::ENCODING; +} + /// An acceleration structure built over instances of other acceleration structures /// /// See diff --git a/src/pipeline/compute.rs b/src/pipeline/compute.rs index bcadc3d..dc1ac23 100644 --- a/src/pipeline/compute.rs +++ b/src/pipeline/compute.rs @@ -7,8 +7,6 @@ use super::*; -use objc::runtime::{NO, YES}; - /// See #[repr(u64)] #[allow(non_camel_case_types)] @@ -68,6 +66,10 @@ pub enum MTLAttributeFormat { Half = 53, } +unsafe impl Encode for MTLAttributeFormat { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[allow(non_camel_case_types)] @@ -84,6 +86,10 @@ pub enum MTLStepFunction { ThreadPositionInGridYIndexed = 8, } +unsafe impl Encode for MTLStepFunction { + const ENCODING: Encoding = u64::ENCODING; +} + /// See pub enum MTLComputePipelineDescriptor {} diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs index fe46bca..c10032b 100644 --- a/src/pipeline/mod.rs +++ b/src/pipeline/mod.rs @@ -23,6 +23,10 @@ pub enum MTLMutability { Immutable = 2, } +unsafe impl Encode for MTLMutability { + const ENCODING: Encoding = u64::ENCODING; +} + impl Default for MTLMutability { #[inline] fn default() -> Self { diff --git a/src/pipeline/render.rs b/src/pipeline/render.rs index 5c06546..f3716ac 100644 --- a/src/pipeline/render.rs +++ b/src/pipeline/render.rs @@ -7,8 +7,6 @@ use super::*; -use objc::runtime::{NO, YES}; - /// See #[repr(u64)] #[allow(non_camel_case_types)] @@ -35,6 +33,10 @@ pub enum MTLBlendFactor { OneMinusSource1Alpha = 18, } +unsafe impl Encode for MTLBlendFactor { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[allow(non_camel_case_types)] @@ -47,6 +49,10 @@ pub enum MTLBlendOperation { Max = 4, } +unsafe impl Encode for MTLBlendOperation { + const ENCODING: Encoding = u64::ENCODING; +} + bitflags! { /// See #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] @@ -60,6 +66,10 @@ bitflags! { } } +unsafe impl Encode for MTLColorWriteMask { + const ENCODING: Encoding = NSUInteger::ENCODING; +} + /// See #[repr(u64)] #[allow(non_camel_case_types)] @@ -71,6 +81,10 @@ pub enum MTLPrimitiveTopologyClass { Triangle = 3, } +unsafe impl Encode for MTLPrimitiveTopologyClass { + const ENCODING: Encoding = u64::ENCODING; +} + // TODO: MTLTessellationPartitionMode // TODO: MTLTessellationFactorStepFunction // TODO: MTLTessellationFactorFormat diff --git a/src/renderpass.rs b/src/renderpass.rs index f9aa50b..78267b1 100644 --- a/src/renderpass.rs +++ b/src/renderpass.rs @@ -16,6 +16,10 @@ pub enum MTLLoadAction { Clear = 2, } +unsafe impl Encode for MTLLoadAction { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[derive(Copy, Clone, Debug)] @@ -28,6 +32,10 @@ pub enum MTLStoreAction { CustomSampleDepthStore = 5, } +unsafe impl Encode for MTLStoreAction { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(C)] #[derive(Copy, Clone, Debug)] @@ -38,6 +46,13 @@ pub struct MTLClearColor { pub alpha: f64, } +unsafe impl Encode for MTLClearColor { + const ENCODING: Encoding = Encoding::Struct( + "MTLClearColor", + &[f64::ENCODING, f64::ENCODING, f64::ENCODING, f64::ENCODING], + ); +} + impl MTLClearColor { #[inline] pub fn new(red: f64, green: f64, blue: f64, alpha: f64) -> Self { @@ -58,6 +73,10 @@ pub enum MTLMultisampleStencilResolveFilter { DepthResolvedSample = 1, } +unsafe impl Encode for MTLMultisampleStencilResolveFilter { + const ENCODING: Encoding = u32::ENCODING; +} + /// See pub enum MTLRenderPassAttachmentDescriptor {} diff --git a/src/resource.rs b/src/resource.rs index 19cee90..72119fd 100644 --- a/src/resource.rs +++ b/src/resource.rs @@ -6,7 +6,6 @@ // copied, modified, or distributed except according to those terms. use super::*; -use objc::runtime::{NO, YES}; /// See #[repr(u64)] @@ -18,6 +17,10 @@ pub enum MTLPurgeableState { Empty = 4, } +unsafe impl Encode for MTLPurgeableState { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] @@ -26,6 +29,10 @@ pub enum MTLCPUCacheMode { WriteCombined = 1, } +unsafe impl Encode for MTLCPUCacheMode { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] @@ -37,6 +44,10 @@ pub enum MTLStorageMode { Memoryless = 3, } +unsafe impl Encode for MTLStorageMode { + const ENCODING: Encoding = u64::ENCODING; +} + /// Only available on macos(10.15), ios(13.0) /// /// See @@ -48,6 +59,10 @@ pub enum MTLHazardTrackingMode { Tracked = 2, } +unsafe impl Encode for MTLHazardTrackingMode { + const ENCODING: Encoding = u64::ENCODING; +} + pub const MTLResourceCPUCacheModeShift: NSUInteger = 0; pub const MTLResourceCPUCacheModeMask: NSUInteger = 0xf << MTLResourceCPUCacheModeShift; pub const MTLResourceStorageModeShift: NSUInteger = 4; @@ -77,6 +92,10 @@ bitflags! { } } +unsafe impl Encode for MTLResourceOptions { + const ENCODING: Encoding = NSUInteger::ENCODING; +} + bitflags! { /// Options that describe how a graphics or compute function uses an argument buffer’s resource. /// @@ -97,6 +116,10 @@ bitflags! { } } +unsafe impl Encode for MTLResourceUsage { + const ENCODING: Encoding = NSUInteger::ENCODING; +} + /// See #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] #[repr(C)] @@ -105,6 +128,13 @@ pub struct MTLSizeAndAlign { pub align: NSUInteger, } +unsafe impl Encode for MTLSizeAndAlign { + const ENCODING: Encoding = Encoding::Struct( + "MTLSizeAndAlign", + &[NSUInteger::ENCODING, NSUInteger::ENCODING], + ); +} + /// See pub enum MTLResource {} diff --git a/src/sampler.rs b/src/sampler.rs index e9f6416..35255da 100644 --- a/src/sampler.rs +++ b/src/sampler.rs @@ -5,7 +5,7 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use super::{depthstencil::MTLCompareFunction, DeviceRef, NSUInteger}; +use super::{depthstencil::MTLCompareFunction, *}; /// See #[repr(u64)] @@ -15,6 +15,10 @@ pub enum MTLSamplerMinMagFilter { Linear = 1, } +unsafe impl Encode for MTLSamplerMinMagFilter { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] @@ -24,6 +28,10 @@ pub enum MTLSamplerMipFilter { Linear = 2, } +unsafe impl Encode for MTLSamplerMipFilter { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] @@ -36,6 +44,10 @@ pub enum MTLSamplerAddressMode { ClampToBorderColor = 5, } +unsafe impl Encode for MTLSamplerAddressMode { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] @@ -45,6 +57,10 @@ pub enum MTLSamplerBorderColor { OpaqueWhite = 2, } +unsafe impl Encode for MTLSamplerBorderColor { + const ENCODING: Encoding = u64::ENCODING; +} + /// See pub enum MTLSamplerDescriptor {} diff --git a/src/sync.rs b/src/sync.rs index 550e06b..a9958de 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -6,7 +6,8 @@ // copied, modified, or distributed except according to those terms. use super::*; -use block::{Block, RcBlock}; +use block2::{Block, RcBlock}; +use objc2::encode::EncodeArguments; use std::mem; #[cfg(feature = "dispatch_queue")] @@ -154,6 +155,10 @@ bitflags! { } } +unsafe impl Encode for MTLRenderStages { + const ENCODING: Encoding = u64::ENCODING; +} + const BLOCK_HAS_COPY_DISPOSE: i32 = 0x02000000; const BLOCK_HAS_SIGNATURE: i32 = 0x40000000; @@ -168,6 +173,10 @@ struct BlockBase { type BlockExtraDtor = extern "C" fn(*mut BlockBase); +unsafe impl RefEncode for BlockBase { + const ENCODING_REF: Encoding = Encoding::Block; +} + #[repr(C)] struct BlockExtra { unknown0: *mut i32, // 0x00 diff --git a/src/texture.rs b/src/texture.rs index 01655d6..9f26d89 100644 --- a/src/texture.rs +++ b/src/texture.rs @@ -7,8 +7,6 @@ use super::*; -use objc::runtime::{NO, YES}; - /// See #[repr(u64)] #[allow(non_camel_case_types)] @@ -25,6 +23,10 @@ pub enum MTLTextureType { D2MultisampleArray = 8, } +unsafe impl Encode for MTLTextureType { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] @@ -33,6 +35,10 @@ pub enum MTLTextureCompressionType { Lossy = 1, } +unsafe impl Encode for MTLTextureCompressionType { + const ENCODING: Encoding = u64::ENCODING; +} + bitflags! { /// See #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] @@ -45,6 +51,10 @@ bitflags! { } } +unsafe impl Encode for MTLTextureUsage { + const ENCODING: Encoding = NSUInteger::ENCODING; +} + /// See pub enum MTLTextureDescriptor {} diff --git a/src/types.rs b/src/types.rs index 92f9daf..3cc29f9 100644 --- a/src/types.rs +++ b/src/types.rs @@ -5,7 +5,7 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use super::NSUInteger; +use super::*; use std::default::Default; /// See @@ -17,6 +17,17 @@ pub struct MTLOrigin { pub z: NSUInteger, } +unsafe impl Encode for MTLOrigin { + const ENCODING: Encoding = Encoding::Struct( + "?", + &[ + NSUInteger::ENCODING, + NSUInteger::ENCODING, + NSUInteger::ENCODING, + ], + ); +} + /// See #[repr(C)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Default)] @@ -26,6 +37,17 @@ pub struct MTLSize { pub depth: NSUInteger, } +unsafe impl Encode for MTLSize { + const ENCODING: Encoding = Encoding::Struct( + "?", + &[ + NSUInteger::ENCODING, + NSUInteger::ENCODING, + NSUInteger::ENCODING, + ], + ); +} + impl MTLSize { pub fn new(width: NSUInteger, height: NSUInteger, depth: NSUInteger) -> Self { Self { @@ -44,6 +66,11 @@ pub struct MTLRegion { pub size: MTLSize, } +unsafe impl Encode for MTLRegion { + const ENCODING: Encoding = + Encoding::Struct("MTLRegion", &[MTLOrigin::ENCODING, MTLSize::ENCODING]); +} + impl MTLRegion { #[inline] pub fn new_1d(x: NSUInteger, width: NSUInteger) -> Self { @@ -83,8 +110,17 @@ pub struct MTLSamplePosition { pub y: f32, } +unsafe impl Encode for MTLSamplePosition { + const ENCODING: Encoding = + Encoding::Struct("MTLSamplePosition", &[f32::ENCODING, f32::ENCODING]); +} + #[repr(C)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Default)] pub struct MTLResourceID { pub _impl: u64, } + +unsafe impl Encode for MTLResourceID { + const ENCODING: Encoding = Encoding::Struct("MTLResourceID", &[u64::ENCODING]); +} diff --git a/src/vertexdescriptor.rs b/src/vertexdescriptor.rs index 5e01be4..c3ab8e1 100644 --- a/src/vertexdescriptor.rs +++ b/src/vertexdescriptor.rs @@ -5,7 +5,7 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use super::NSUInteger; +use super::*; /// See #[repr(u64)] @@ -66,6 +66,10 @@ pub enum MTLVertexFormat { Half = 53, } +unsafe impl Encode for MTLVertexFormat { + const ENCODING: Encoding = u64::ENCODING; +} + /// See #[repr(u64)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] @@ -77,6 +81,10 @@ pub enum MTLVertexStepFunction { PerPatchControlPoint = 4, } +unsafe impl Encode for MTLVertexStepFunction { + const ENCODING: Encoding = u64::ENCODING; +} + /// See pub enum MTLVertexBufferLayoutDescriptor {} From 5ab94d3d10c16baa38d9316dbc35c901d0f24e44 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Tue, 5 Sep 2023 15:52:07 +0200 Subject: [PATCH 03/12] Use common types from objc2::foundation NSUInteger is now usize, so a bunch of `as u64` casts were removed --- Cargo.toml | 2 -- examples/circle/main.rs | 9 +++-- examples/compute/compute-argument-buffer.rs | 6 ++-- examples/compute/main.rs | 19 +++++----- examples/headless-render/main.rs | 8 ++--- examples/mesh-shader/main.rs | 1 - examples/mps/main.rs | 16 ++++----- examples/raytracing/main.rs | 1 - examples/raytracing/renderer.rs | 24 +++++++------ examples/shader-dylib/main.rs | 1 - examples/texture/Cargo.toml | 2 -- examples/texture/src/main.rs | 19 +++++----- examples/window/main.rs | 13 ++++--- src/buffer.rs | 10 +++--- src/device.rs | 5 ++- src/drawable.rs | 2 +- src/encoder.rs | 2 +- src/indirect_encoder.rs | 2 +- src/lib.rs | 40 ++------------------- src/texture.rs | 6 ++-- 20 files changed, 75 insertions(+), 113 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index da72be3..5eb7681 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,8 +22,6 @@ mps = [] link = [] [dependencies] -# Branch: objc2. TODO: Remove this -core-graphics-types = { git = "https://github.com/madsmtm/core-foundation-rs.git", rev = "7d593d016175755e492a92ef89edca68ac3bd5cd" } bitflags = "2" log = "0.4" block2 = "=0.2.0-alpha.6" diff --git a/examples/circle/main.rs b/examples/circle/main.rs index 7731f93..f479af9 100644 --- a/examples/circle/main.rs +++ b/examples/circle/main.rs @@ -7,7 +7,6 @@ use winit::{ }; use cocoa::{appkit::NSView, base::id as cocoa_id}; -use core_graphics_types::geometry::CGSize; use objc2::rc::autoreleasepool; use objc2::runtime::Bool; @@ -53,7 +52,7 @@ fn main() { device.sample_timestamps(&mut cpu_start, &mut gpu_start); let counter_sample_buffer = create_counter_sample_buffer(&device); let destination_buffer = device.new_buffer( - (std::mem::size_of::() * 4 as usize) as u64, + std::mem::size_of::() * 4, MTLResourceOptions::StorageModeShared, ); let counter_sampling_point = MTLCounterSamplingPoint::AtStageBoundary; @@ -115,7 +114,7 @@ fn main() { device.new_buffer_with_data( vertex_data.as_ptr() as *const _, - (vertex_data.len() * mem::size_of::()) as u64, + vertex_data.len() * mem::size_of::(), MTLResourceOptions::CPUCacheModeDefaultCache | MTLResourceOptions::StorageModeManaged, ) }; @@ -302,9 +301,9 @@ fn resolve_samples_into_buffer( let blit_encoder = command_buffer.new_blit_command_encoder(); blit_encoder.resolve_counters( &counter_sample_buffer, - crate::NSRange::new(0_u64, 4), + NSRange::new(0, 4), &destination_buffer, - 0_u64, + 0, ); blit_encoder.end_encoding(); } diff --git a/examples/compute/compute-argument-buffer.rs b/examples/compute/compute-argument-buffer.rs index cc4535f..1fdae43 100644 --- a/examples/compute/compute-argument-buffer.rs +++ b/examples/compute/compute-argument-buffer.rs @@ -23,7 +23,7 @@ fn main() { let buffer = device.new_buffer_with_data( unsafe { mem::transmute(data.as_ptr()) }, - (data.len() * mem::size_of::()) as u64, + data.len() * mem::size_of::(), MTLResourceOptions::CPUCacheModeDefaultCache, ); @@ -31,7 +31,7 @@ fn main() { let data = [0u32]; device.new_buffer_with_data( unsafe { mem::transmute(data.as_ptr()) }, - (data.len() * mem::size_of::()) as u64, + data.len() * mem::size_of::(), MTLResourceOptions::CPUCacheModeDefaultCache, ) }; @@ -77,7 +77,7 @@ fn main() { }; let thread_group_size = MTLSize { - width: (data.len() as u64 + width) / width, + width: (data.len() + width) / width, height: 1, depth: 1, }; diff --git a/examples/compute/main.rs b/examples/compute/main.rs index be266e3..a1456f8 100644 --- a/examples/compute/main.rs +++ b/examples/compute/main.rs @@ -2,7 +2,7 @@ use metal::*; use objc2::rc::autoreleasepool; use std::path::PathBuf; -const NUM_SAMPLES: u64 = 2; +const NUM_SAMPLES: usize = 2; fn main() { let num_elements = std::env::args() @@ -18,7 +18,7 @@ fn main() { let counter_sample_buffer = create_counter_sample_buffer(&device); let destination_buffer = device.new_buffer( - (std::mem::size_of::() * NUM_SAMPLES as usize) as u64, + std::mem::size_of::() * NUM_SAMPLES, MTLResourceOptions::StorageModeShared, ); @@ -117,9 +117,9 @@ fn resolve_samples_into_buffer( let blit_encoder = command_buffer.new_blit_command_encoder(); blit_encoder.resolve_counters( counter_sample_buffer, - crate::NSRange::new(0_u64, NUM_SAMPLES), + crate::NSRange::new(0, NUM_SAMPLES), destination_buffer, - 0_u64, + 0, ); blit_encoder.end_encoding(); } @@ -132,10 +132,7 @@ fn handle_timestamps( gpu_end: u64, ) { let samples = unsafe { - std::slice::from_raw_parts( - resolved_sample_buffer.contents() as *const u64, - NUM_SAMPLES as usize, - ) + std::slice::from_raw_parts(resolved_sample_buffer.contents() as *const u64, NUM_SAMPLES) }; let pass_start = samples[0]; let pass_end = samples[1]; @@ -150,7 +147,7 @@ fn handle_timestamps( fn create_counter_sample_buffer(device: &Device) -> CounterSampleBuffer { let counter_sample_buffer_desc = metal::CounterSampleBufferDescriptor::new(); counter_sample_buffer_desc.set_storage_mode(metal::MTLStorageMode::Shared); - counter_sample_buffer_desc.set_sample_count(NUM_SAMPLES); + counter_sample_buffer_desc.set_sample_count(NUM_SAMPLES as u64); let counter_sets = device.counter_sets(); let timestamp_counter = counter_sets.iter().find(|cs| cs.name() == "timestamp"); @@ -171,7 +168,7 @@ fn create_input_and_output_buffers( let buffer = device.new_buffer_with_data( unsafe { std::mem::transmute(data.as_ptr()) }, - (data.len() * std::mem::size_of::()) as u64, + data.len() * std::mem::size_of::(), MTLResourceOptions::CPUCacheModeDefaultCache, ); @@ -179,7 +176,7 @@ fn create_input_and_output_buffers( let data = [0u32]; device.new_buffer_with_data( unsafe { std::mem::transmute(data.as_ptr()) }, - (data.len() * std::mem::size_of::()) as u64, + data.len() * std::mem::size_of::(), MTLResourceOptions::CPUCacheModeDefaultCache, ) }; diff --git a/examples/headless-render/main.rs b/examples/headless-render/main.rs index 4491702..f9603e3 100644 --- a/examples/headless-render/main.rs +++ b/examples/headless-render/main.rs @@ -12,9 +12,9 @@ use metal::{ }; use png::ColorType; -const VIEW_WIDTH: u64 = 512; -const VIEW_HEIGHT: u64 = 512; -const TOTAL_BYTES: usize = (VIEW_WIDTH * VIEW_HEIGHT * 4) as usize; +const VIEW_WIDTH: usize = 512; +const VIEW_HEIGHT: usize = 512; +const TOTAL_BYTES: usize = VIEW_WIDTH * VIEW_HEIGHT * 4; const VERTEX_SHADER: &'static str = "triangle_vertex"; const FRAGMENT_SHADER: &'static str = "triangle_fragment"; @@ -144,7 +144,7 @@ fn prepare_pipeline_state(device: &DeviceRef, library: &LibraryRef) -> RenderPip fn create_vertex_buffer(device: &DeviceRef) -> Buffer { device.new_buffer_with_data( VERTEX_ATTRIBS.as_ptr() as *const _, - (VERTEX_ATTRIBS.len() * mem::size_of::()) as u64, + VERTEX_ATTRIBS.len() * mem::size_of::(), MTLResourceOptions::CPUCacheModeDefaultCache | MTLResourceOptions::StorageModeManaged, ) } diff --git a/examples/mesh-shader/main.rs b/examples/mesh-shader/main.rs index ce06e10..717aab6 100644 --- a/examples/mesh-shader/main.rs +++ b/examples/mesh-shader/main.rs @@ -1,5 +1,4 @@ use cocoa::{appkit::NSView, base::id as cocoa_id}; -use core_graphics_types::geometry::CGSize; use metal::*; use objc2::{rc::autoreleasepool, runtime::Bool}; diff --git a/examples/mps/main.rs b/examples/mps/main.rs index cc01b7a..f275979 100644 --- a/examples/mps/main.rs +++ b/examples/mps/main.rs @@ -50,13 +50,13 @@ fn main() { let vertex_buffer = device.new_buffer_with_data( vertices.as_ptr() as *const c_void, - (vertex_stride * vertices.len()) as u64, + vertex_stride * vertices.len(), buffer_opts, ); let index_buffer = device.new_buffer_with_data( indices.as_ptr() as *const c_void, - (mem::size_of::() * indices.len()) as u64, + mem::size_of::() * indices.len(), buffer_opts, ); @@ -65,7 +65,7 @@ fn main() { .expect("Failed to create acceleration structure"); acceleration_structure.set_vertex_buffer(Some(&vertex_buffer)); - acceleration_structure.set_vertex_stride(vertex_stride as u64); + acceleration_structure.set_vertex_stride(vertex_stride); acceleration_structure.set_index_buffer(Some(&index_buffer)); acceleration_structure.set_index_type(mps::MPSDataType::UInt32); acceleration_structure.set_triangle_count(1); @@ -75,9 +75,9 @@ fn main() { let ray_intersector = mps::RayIntersector::from_device(&device).expect("Failed to create ray intersector"); - ray_intersector.set_ray_stride(mem::size_of::() as u64); + ray_intersector.set_ray_stride(mem::size_of::()); ray_intersector.set_ray_data_type(mps::MPSRayDataType::OriginMinDistanceDirectionMaxDistance); - ray_intersector.set_intersection_stride(mem::size_of::() as u64); + ray_intersector.set_intersection_stride(mem::size_of::()); ray_intersector.set_intersection_data_type( mps::MPSIntersectionDataType::DistancePrimitiveIndexCoordinates, ); @@ -85,12 +85,12 @@ fn main() { // Create a buffer to hold generated rays and intersection results let ray_count = 1024; let ray_buffer = device.new_buffer( - (mem::size_of::() * ray_count) as u64, + mem::size_of::() * ray_count, MTLResourceOptions::StorageModePrivate, ); let intersection_buffer = device.new_buffer( - (mem::size_of::() * ray_count) as u64, + mem::size_of::() * ray_count, MTLResourceOptions::StorageModePrivate, ); @@ -120,7 +120,7 @@ fn main() { 0, &intersection_buffer, 0, - ray_count as u64, + ray_count, &acceleration_structure, ); diff --git a/examples/raytracing/main.rs b/examples/raytracing/main.rs index 457deb3..70fb9cc 100644 --- a/examples/raytracing/main.rs +++ b/examples/raytracing/main.rs @@ -1,5 +1,4 @@ use cocoa::{appkit::NSView, base::id as cocoa_id}; -use core_graphics_types::geometry::CGSize; use metal::*; use objc2::{rc::autoreleasepool, runtime::Bool}; use std::mem; diff --git a/examples/raytracing/renderer.rs b/examples/raytracing/renderer.rs index 856a2c8..f39ef2d 100644 --- a/examples/raytracing/renderer.rs +++ b/examples/raytracing/renderer.rs @@ -1,4 +1,3 @@ -use core_graphics_types::{base::CGFloat, geometry::CGSize}; use std::{ collections::BTreeMap, ffi::c_void, @@ -292,7 +291,7 @@ impl Renderer { pub fn window_resized(&mut self, size: CGSize) { self.size = size; let texture_descriptor = - Self::create_target_descriptor(size.width as NSUInteger, size.height as NSUInteger); + Self::create_target_descriptor(size.width() as NSUInteger, size.height() as NSUInteger); self.accumulation_targets[0] = self.device.new_texture(&texture_descriptor); self.accumulation_targets[1] = self.device.new_texture(&texture_descriptor); texture_descriptor.set_pixel_format(MTLPixelFormat::R32Uint); @@ -300,15 +299,20 @@ impl Renderer { texture_descriptor.set_storage_mode(MTLStorageMode::Managed); self.random_texture = self.device.new_texture(&texture_descriptor); let mut rng = thread_rng(); - let mut random_values = vec![0u32; (size.width * size.height) as usize]; + let mut random_values = vec![0u32; (size.width() * size.height()) as usize]; for v in &mut random_values { *v = rng.next_u32(); } self.random_texture.replace_region( - MTLRegion::new_2d(0, 0, size.width as NSUInteger, size.height as NSUInteger), + MTLRegion::new_2d( + 0, + 0, + size.width() as NSUInteger, + size.height() as NSUInteger, + ), 0, random_values.as_ptr() as *const c_void, - size_of::() as NSUInteger * size.width as NSUInteger, + size_of::() as NSUInteger * size.width() as NSUInteger, ); self.frame_index = 0; } @@ -335,15 +339,15 @@ impl Renderer { uniforms.camera.up = Vec4::from((up, 0.0)); let field_of_view = 45.0 * (std::f32::consts::PI / 180.0); - let aspect_ratio = self.size.width as f32 / self.size.height as f32; + let aspect_ratio = self.size.width() as f32 / self.size.height() as f32; let image_plane_height = f32::tan(field_of_view / 2.0); let image_plane_width = aspect_ratio * image_plane_height; uniforms.camera.right *= image_plane_width; uniforms.camera.up *= image_plane_height; - uniforms.width = self.size.width as u32; - uniforms.height = self.size.height as u32; + uniforms.width = self.size.width() as u32; + uniforms.height = self.size.height() as u32; uniforms.frame_index = self.frame_index as u32; self.frame_index += 1; @@ -368,8 +372,8 @@ impl Renderer { }) .copy(); command_buffer.add_completed_handler(&block); - let width = self.size.width as NSUInteger; - let height = self.size.height as NSUInteger; + let width = self.size.width() as NSUInteger; + let height = self.size.height() as NSUInteger; let threads_per_thread_group = MTLSize::new(8, 8, 1); let thread_groups = MTLSize::new( (width + threads_per_thread_group.width - 1) / threads_per_thread_group.width, diff --git a/examples/shader-dylib/main.rs b/examples/shader-dylib/main.rs index b9f5237..03c259e 100644 --- a/examples/shader-dylib/main.rs +++ b/examples/shader-dylib/main.rs @@ -1,5 +1,4 @@ use cocoa::{appkit::NSView, base::id as cocoa_id}; -use core_graphics_types::geometry::CGSize; use metal::*; use objc2::rc::autoreleasepool; diff --git a/examples/texture/Cargo.toml b/examples/texture/Cargo.toml index 460420c..8acbe56 100644 --- a/examples/texture/Cargo.toml +++ b/examples/texture/Cargo.toml @@ -9,8 +9,6 @@ edition = "2018" bindgen = { version = "0.60", default-features = false, features = ["logging", "runtime", "which-rustfmt"] } [dependencies] -# Branch: objc2. TODO: Remove this -core-graphics-types = { git = "https://github.com/madsmtm/core-foundation-rs.git", rev = "7d593d016175755e492a92ef89edca68ac3bd5cd" } cocoa = "0.24" png = "0.17" metal = { path = "../../" } diff --git a/examples/texture/src/main.rs b/examples/texture/src/main.rs index 406b465..55db8f0 100644 --- a/examples/texture/src/main.rs +++ b/examples/texture/src/main.rs @@ -4,7 +4,6 @@ use std::path::PathBuf; use cocoa::{appkit::NSView, base::id as cocoa_id}; -use core_graphics_types::geometry::CGSize; use objc2::rc::autoreleasepool; use winit::dpi::LogicalSize; use winit::event_loop::{ControlFlow, EventLoop}; @@ -40,7 +39,7 @@ fn main() { let vertex_data = vertices(); let vertex_buffer = device.new_buffer_with_data( vertex_data.as_ptr() as *const _, - (vertex_data.len() * std::mem::size_of::()) as u64, + vertex_data.len() * std::mem::size_of::(), MTLResourceOptions::CPUCacheModeDefaultCache | MTLResourceOptions::StorageModeManaged, ); @@ -113,7 +112,7 @@ fn create_texture_to_display(device: &Device) -> Texture { let mut reader = decoder.read_info().unwrap(); let info = reader.info(); - let (width, height) = (info.width as u64, info.height as u64); + let (width, height) = (info.width as usize, info.height as usize); let mut buf = vec![0; reader.output_buffer_size()]; reader.next_frame(&mut buf).unwrap(); @@ -226,12 +225,12 @@ fn handle_window_event( fn update_viewport_size_buffer(viewport_size_buffer: &Buffer, size: (u32, u32)) { let contents = viewport_size_buffer.contents(); let viewport_size: [u32; 2] = [size.0, size.1]; - let byte_count = (viewport_size.len() * std::mem::size_of::()) as usize; + let byte_count = viewport_size.len() * std::mem::size_of::(); unsafe { std::ptr::copy(viewport_size.as_ptr(), contents as *mut u32, byte_count); } - viewport_size_buffer.did_modify_range(metal::NSRange::new(0, byte_count as u64)); + viewport_size_buffer.did_modify_range(NSRange::new(0, byte_count)); } fn redraw( @@ -255,9 +254,13 @@ fn redraw( let encoder = command_buffer.new_render_command_encoder(&render_pass_descriptor); encoder.set_render_pipeline_state(&pipeline_state); - encoder.set_vertex_buffer(VerticesBufferIdx as u64, Some(vertex_buffer), 0); - encoder.set_vertex_buffer(ViewportSizeBufferIdx as u64, Some(viewport_size_buffer), 0); - encoder.set_fragment_texture(TextureBaseColorIdx as u64, Some(texture_to_render)); + encoder.set_vertex_buffer(VerticesBufferIdx as usize, Some(vertex_buffer), 0); + encoder.set_vertex_buffer( + ViewportSizeBufferIdx as usize, + Some(viewport_size_buffer), + 0, + ); + encoder.set_fragment_texture(TextureBaseColorIdx as usize, Some(texture_to_render)); encoder.draw_primitives(MTLPrimitiveType::Triangle, 0, 6); encoder.end_encoding(); diff --git a/examples/window/main.rs b/examples/window/main.rs index ba439a3..89c023b 100644 --- a/examples/window/main.rs +++ b/examples/window/main.rs @@ -6,7 +6,6 @@ // copied, modified, or distributed except according to those terms. use cocoa::{appkit::NSView, base::id as cocoa_id}; -use core_graphics_types::geometry::CGSize; use metal::*; use objc2::rc::autoreleasepool; @@ -132,7 +131,7 @@ fn main() { device.new_buffer_with_data( vertex_data.as_ptr() as *const _, - (vertex_data.len() * mem::size_of::()) as u64, + vertex_data.len() * mem::size_of::(), MTLResourceOptions::CPUCacheModeDefaultCache | MTLResourceOptions::StorageModeManaged, ) }; @@ -156,7 +155,7 @@ fn main() { let clear_rect_buffer = device.new_buffer_with_data( clear_rect.as_ptr() as *const _, - mem::size_of::() as u64, + mem::size_of::(), MTLResourceOptions::CPUCacheModeDefaultCache | MTLResourceOptions::StorageModeManaged, ); @@ -199,13 +198,13 @@ fn main() { std::ptr::copy( vertex_data.as_ptr(), p as *mut f32, - (vertex_data.len() * mem::size_of::()) as usize, + vertex_data.len() * mem::size_of::(), ); } - vbuf.did_modify_range(crate::NSRange::new( - 0 as u64, - (vertex_data.len() * mem::size_of::()) as u64, + vbuf.did_modify_range(NSRange::new( + 0, + vertex_data.len() * mem::size_of::(), )); let drawable = match layer.next_drawable() { diff --git a/src/buffer.rs b/src/buffer.rs index 8f3108a..c250c73 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -17,7 +17,7 @@ foreign_obj_type! { } impl BufferRef { - pub fn length(&self) -> u64 { + pub fn length(&self) -> usize { unsafe { msg_send![self, length] } } @@ -25,15 +25,15 @@ impl BufferRef { unsafe { msg_send![self, contents] } } - pub fn did_modify_range(&self, range: crate::NSRange) { + pub fn did_modify_range(&self, range: NSRange) { unsafe { msg_send![self, didModifyRange: range] } } pub fn new_texture_with_descriptor( &self, descriptor: &TextureDescriptorRef, - offset: u64, - bytes_per_row: u64, + offset: usize, + bytes_per_row: usize, ) -> Texture { unsafe { msg_send![self, @@ -54,7 +54,7 @@ impl BufferRef { unsafe { msg_send![self, newRemoteBufferViewForDevice: device] } } - pub fn add_debug_marker(&self, name: &str, range: crate::NSRange) { + pub fn add_debug_marker(&self, name: &str, range: NSRange) { unsafe { let name = crate::nsstring_from_str(name); msg_send![self, addDebugMarker:name range:range] diff --git a/src/device.rs b/src/device.rs index e7fce36..e63468e 100644 --- a/src/device.rs +++ b/src/device.rs @@ -1501,6 +1501,9 @@ unsafe impl Encode for MTLAccelerationStructureSizes { ); } +// Note: For some reason it is required by `MTLCreateSystemDefaultDevice` +// that we link to `CoreGraphics`? +#[cfg_attr(feature = "link", link(name = "CoreGraphics", kind = "framework"))] #[cfg_attr(feature = "link", link(name = "Metal", kind = "framework"))] extern "C" { fn MTLCreateSystemDefaultDevice() -> *mut MTLDevice; @@ -1952,7 +1955,7 @@ impl DeviceRef { } } - pub fn new_buffer(&self, length: u64, options: MTLResourceOptions) -> Buffer { + pub fn new_buffer(&self, length: NSUInteger, options: MTLResourceOptions) -> Buffer { unsafe { msg_send![self, newBufferWithLength:length options:options] diff --git a/src/drawable.rs b/src/drawable.rs index 5c03584..c05e75b 100644 --- a/src/drawable.rs +++ b/src/drawable.rs @@ -5,7 +5,7 @@ // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. -use super::NSUInteger; +use super::*; /// See pub enum MTLDrawable {} diff --git a/src/encoder.rs b/src/encoder.rs index bf22abe..c47b05d 100644 --- a/src/encoder.rs +++ b/src/encoder.rs @@ -1319,7 +1319,7 @@ impl BlitCommandEncoderRef { unsafe { msg_send![self, synchronizeResource: resource] } } - pub fn fill_buffer(&self, destination_buffer: &BufferRef, range: crate::NSRange, value: u8) { + pub fn fill_buffer(&self, destination_buffer: &BufferRef, range: NSRange, value: u8) { unsafe { msg_send![self, fillBuffer: destination_buffer diff --git a/src/indirect_encoder.rs b/src/indirect_encoder.rs index 9243a8c..07d6cf2 100644 --- a/src/indirect_encoder.rs +++ b/src/indirect_encoder.rs @@ -108,7 +108,7 @@ impl IndirectCommandBufferRef { unsafe { msg_send![self, indirectComputeCommandAtIndex: index] } } - pub fn reset_with_range(&self, range: crate::NSRange) { + pub fn reset_with_range(&self, range: NSRange) { unsafe { msg_send![self, resetWithRange: range] } } } diff --git a/src/lib.rs b/src/lib.rs index 6ba9435..670055f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -28,47 +28,11 @@ use std::{ os::raw::c_void, }; -use core_graphics_types::{base::CGFloat, geometry::CGSize}; use foreign_types::ForeignType; pub(crate) use objc2::encode::{Encode, Encoding, RefEncode}; +pub use objc2::foundation::{CGFloat, NSInteger, NSRange, NSSize as CGSize, NSUInteger}; use objc2::runtime::{Bool, Object, Protocol}; -/// See -#[cfg(target_pointer_width = "64")] -pub type NSInteger = i64; - -/// See -#[cfg(not(target_pointer_width = "64"))] -pub type NSInteger = i32; - -/// See -#[cfg(target_pointer_width = "64")] -pub type NSUInteger = u64; - -/// See -#[cfg(target_pointer_width = "32")] -pub type NSUInteger = u32; - -/// See -#[repr(C)] -#[derive(Copy, Clone)] -pub struct NSRange { - pub location: NSUInteger, - pub length: NSUInteger, -} - -unsafe impl objc2::Encode for NSRange { - const ENCODING: objc2::Encoding = - objc2::Encoding::Struct("_NSRange", &[NSUInteger::ENCODING, NSUInteger::ENCODING]); -} - -impl NSRange { - #[inline] - pub fn new(location: NSUInteger, length: NSUInteger) -> NSRange { - NSRange { location, length } - } -} - fn nsstring_as_str(nsstr: &Object) -> &str { let bytes = unsafe { let bytes: *const std::os::raw::c_char = msg_send![nsstr, UTF8String]; @@ -76,7 +40,7 @@ fn nsstring_as_str(nsstr: &Object) -> &str { }; let len: NSUInteger = unsafe { msg_send![nsstr, length] }; unsafe { - let bytes = std::slice::from_raw_parts(bytes, len as usize); + let bytes = std::slice::from_raw_parts(bytes, len); std::str::from_utf8(bytes).unwrap() } } diff --git a/src/texture.rs b/src/texture.rs index 9f26d89..7da2abb 100644 --- a/src/texture.rs +++ b/src/texture.rs @@ -127,7 +127,7 @@ impl TextureDescriptorRef { height, depth, } = size; - let count = (width.max(height).max(depth) as f64).log2().ceil() as u64; + let count = (width.max(height).max(depth) as f64).log2().ceil() as NSUInteger; self.set_mipmap_level_count(count); } @@ -344,8 +344,8 @@ impl TextureRef { &self, pixel_format: MTLPixelFormat, texture_type: MTLTextureType, - mipmap_levels: crate::NSRange, - slices: crate::NSRange, + mipmap_levels: NSRange, + slices: NSRange, ) -> Texture { unsafe { msg_send![self, newTextureViewWithPixelFormat:pixel_format From 456eff672c624c99f50c1d0523d231dfb71e1477 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Tue, 1 Aug 2023 15:57:49 +0200 Subject: [PATCH 04/12] Update objc2 to v0.3.0-beta.4 --- Cargo.toml | 8 ++++++-- examples/raytracing/renderer.rs | 23 +++++++++-------------- examples/texture/Cargo.toml | 6 +++++- src/lib.rs | 2 +- 4 files changed, 21 insertions(+), 18 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5eb7681..af240ab 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,11 +24,15 @@ link = [] [dependencies] bitflags = "2" log = "0.4" -block2 = "=0.2.0-alpha.6" +block2 = "=0.2.0-alpha.7" foreign-types = "0.5" dispatch = { version = "0.2", optional = true } paste = "1" -objc2 = "=0.3.0-beta.2" +objc2 = "=0.3.0-beta.4" + +[dependencies.icrate] +version = "0.0.1" +features = ["Foundation"] [dev-dependencies] cocoa = "0.24.0" diff --git a/examples/raytracing/renderer.rs b/examples/raytracing/renderer.rs index f39ef2d..126e4ad 100644 --- a/examples/raytracing/renderer.rs +++ b/examples/raytracing/renderer.rs @@ -291,7 +291,7 @@ impl Renderer { pub fn window_resized(&mut self, size: CGSize) { self.size = size; let texture_descriptor = - Self::create_target_descriptor(size.width() as NSUInteger, size.height() as NSUInteger); + Self::create_target_descriptor(size.width as NSUInteger, size.height as NSUInteger); self.accumulation_targets[0] = self.device.new_texture(&texture_descriptor); self.accumulation_targets[1] = self.device.new_texture(&texture_descriptor); texture_descriptor.set_pixel_format(MTLPixelFormat::R32Uint); @@ -299,20 +299,15 @@ impl Renderer { texture_descriptor.set_storage_mode(MTLStorageMode::Managed); self.random_texture = self.device.new_texture(&texture_descriptor); let mut rng = thread_rng(); - let mut random_values = vec![0u32; (size.width() * size.height()) as usize]; + let mut random_values = vec![0u32; (size.width * size.height) as usize]; for v in &mut random_values { *v = rng.next_u32(); } self.random_texture.replace_region( - MTLRegion::new_2d( - 0, - 0, - size.width() as NSUInteger, - size.height() as NSUInteger, - ), + MTLRegion::new_2d(0, 0, size.width as NSUInteger, size.height as NSUInteger), 0, random_values.as_ptr() as *const c_void, - size_of::() as NSUInteger * size.width() as NSUInteger, + size_of::() as NSUInteger * size.width as NSUInteger, ); self.frame_index = 0; } @@ -339,15 +334,15 @@ impl Renderer { uniforms.camera.up = Vec4::from((up, 0.0)); let field_of_view = 45.0 * (std::f32::consts::PI / 180.0); - let aspect_ratio = self.size.width() as f32 / self.size.height() as f32; + let aspect_ratio = self.size.width as f32 / self.size.height as f32; let image_plane_height = f32::tan(field_of_view / 2.0); let image_plane_width = aspect_ratio * image_plane_height; uniforms.camera.right *= image_plane_width; uniforms.camera.up *= image_plane_height; - uniforms.width = self.size.width() as u32; - uniforms.height = self.size.height() as u32; + uniforms.width = self.size.width as u32; + uniforms.height = self.size.height as u32; uniforms.frame_index = self.frame_index as u32; self.frame_index += 1; @@ -372,8 +367,8 @@ impl Renderer { }) .copy(); command_buffer.add_completed_handler(&block); - let width = self.size.width() as NSUInteger; - let height = self.size.height() as NSUInteger; + let width = self.size.width as NSUInteger; + let height = self.size.height as NSUInteger; let threads_per_thread_group = MTLSize::new(8, 8, 1); let thread_groups = MTLSize::new( (width + threads_per_thread_group.width - 1) / threads_per_thread_group.width, diff --git a/examples/texture/Cargo.toml b/examples/texture/Cargo.toml index 8acbe56..5cdfcd7 100644 --- a/examples/texture/Cargo.toml +++ b/examples/texture/Cargo.toml @@ -13,4 +13,8 @@ cocoa = "0.24" png = "0.17" metal = { path = "../../" } winit = "0.27" -objc2 = "=0.3.0-beta.2" +objc2 = "=0.3.0-beta.4" + +[dependencies.icrate] +version = "0.0.1" +features = ["Foundation"] diff --git a/src/lib.rs b/src/lib.rs index 670055f..38f6670 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -29,8 +29,8 @@ use std::{ }; use foreign_types::ForeignType; +pub use icrate::Foundation::{CGFloat, NSInteger, NSRange, NSSize as CGSize, NSUInteger}; pub(crate) use objc2::encode::{Encode, Encoding, RefEncode}; -pub use objc2::foundation::{CGFloat, NSInteger, NSRange, NSSize as CGSize, NSUInteger}; use objc2::runtime::{Bool, Object, Protocol}; fn nsstring_as_str(nsstr: &Object) -> &str { From bfe8061df47780856d946813eae350c748416766 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Tue, 1 Aug 2023 15:57:35 +0200 Subject: [PATCH 05/12] Update objc2 to v0.3.0-beta.5 --- Cargo.toml | 6 +++--- examples/texture/Cargo.toml | 4 ++-- src/sync.rs | 3 +-- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index af240ab..0ed55c3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,14 +24,14 @@ link = [] [dependencies] bitflags = "2" log = "0.4" -block2 = "=0.2.0-alpha.7" +block2 = "=0.2.0-alpha.8" foreign-types = "0.5" dispatch = { version = "0.2", optional = true } paste = "1" -objc2 = "=0.3.0-beta.4" +objc2 = "=0.3.0-beta.5" [dependencies.icrate] -version = "0.0.1" +version = "0.0.2" features = ["Foundation"] [dev-dependencies] diff --git a/examples/texture/Cargo.toml b/examples/texture/Cargo.toml index 5cdfcd7..8361dc2 100644 --- a/examples/texture/Cargo.toml +++ b/examples/texture/Cargo.toml @@ -13,8 +13,8 @@ cocoa = "0.24" png = "0.17" metal = { path = "../../" } winit = "0.27" -objc2 = "=0.3.0-beta.4" +objc2 = "=0.3.0-beta.5" [dependencies.icrate] -version = "0.0.1" +version = "0.0.2" features = ["Foundation"] diff --git a/src/sync.rs b/src/sync.rs index a9958de..ea64f43 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -7,7 +7,6 @@ use super::*; use block2::{Block, RcBlock}; -use objc2::encode::EncodeArguments; use std::mem; #[cfg(feature = "dispatch_queue")] @@ -173,7 +172,7 @@ struct BlockBase { type BlockExtraDtor = extern "C" fn(*mut BlockBase); -unsafe impl RefEncode for BlockBase { +unsafe impl RefEncode for BlockBase<(&SharedEventRef, u64), ()> { const ENCODING_REF: Encoding = Encoding::Block; } From e958dcccb570b02e9466af1facfac5ec13b76de1 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Tue, 1 Aug 2023 15:57:13 +0200 Subject: [PATCH 06/12] Update objc2 to v0.4.1 --- Cargo.toml | 6 +++--- examples/texture/Cargo.toml | 4 ++-- src/device.rs | 33 ++++++++++++++++----------------- src/lib.rs | 26 +++++++++++++------------- src/library.rs | 17 ++++++++--------- src/mps.rs | 10 +++++----- src/pipeline/compute.rs | 4 ++-- src/pipeline/render.rs | 6 +++--- src/sync.rs | 2 +- 9 files changed, 53 insertions(+), 55 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 0ed55c3..a6299b9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,14 +24,14 @@ link = [] [dependencies] bitflags = "2" log = "0.4" -block2 = "=0.2.0-alpha.8" +block2 = "0.3.0" foreign-types = "0.5" dispatch = { version = "0.2", optional = true } paste = "1" -objc2 = "=0.3.0-beta.5" +objc2 = "0.4.1" [dependencies.icrate] -version = "0.0.2" +version = "0.0.4" features = ["Foundation"] [dev-dependencies] diff --git a/examples/texture/Cargo.toml b/examples/texture/Cargo.toml index 8361dc2..44131fc 100644 --- a/examples/texture/Cargo.toml +++ b/examples/texture/Cargo.toml @@ -13,8 +13,8 @@ cocoa = "0.24" png = "0.17" metal = { path = "../../" } winit = "0.27" -objc2 = "=0.3.0-beta.5" +objc2 = "0.4.1" [dependencies.icrate] -version = "0.0.2" +version = "0.0.4" features = ["Foundation"] diff --git a/src/device.rs b/src/device.rs index e63468e..82e82a8 100644 --- a/src/device.rs +++ b/src/device.rs @@ -9,7 +9,6 @@ use super::*; use block2::{Block, ConcreteBlock}; use foreign_types::ForeignType; -use objc2::runtime::Object; use std::{ffi::CStr, os::raw::c_char, path::Path, ptr}; @@ -1508,13 +1507,13 @@ unsafe impl Encode for MTLAccelerationStructureSizes { extern "C" { fn MTLCreateSystemDefaultDevice() -> *mut MTLDevice; #[cfg(not(target_os = "ios"))] - fn MTLCopyAllDevices() -> *mut Object; //TODO: Array + fn MTLCopyAllDevices() -> *mut AnyObject; //TODO: Array } #[allow(non_camel_case_types)] -type dispatch_data_t = *mut Object; +type dispatch_data_t = *mut AnyObject; #[allow(non_camel_case_types)] -pub type dispatch_queue_t = *mut Object; +pub type dispatch_queue_t = *mut AnyObject; #[allow(non_camel_case_types)] type dispatch_block_t = *const Block<(), ()>; @@ -1577,7 +1576,7 @@ impl Device { // The elements of this array are references---we convert them to owned references // (which just means that we increment the reference count here, and it is // decremented in the `Drop` impl for `Device`) - .map(|device: *mut Object| msg_send![device, retain]) + .map(|device: *mut AnyObject| msg_send![device, retain]) .collect(); let () = msg_send![array, release]; ret @@ -1718,12 +1717,12 @@ impl DeviceRef { ) -> Result { let source = nsstring_from_str(src); unsafe { - let mut err: *mut Object = ptr::null_mut(); + let mut err: *mut AnyObject = ptr::null_mut(); let library: *mut MTLLibrary = msg_send![self, newLibraryWithSource:source options:options error:&mut err]; if !err.is_null() { - let desc: *mut Object = msg_send![err, localizedDescription]; + let desc: *mut AnyObject = msg_send![err, localizedDescription]; let compile_error: *const c_char = msg_send![desc, UTF8String]; let message = CStr::from_ptr(compile_error).to_string_lossy().into_owned(); if library.is_null() { @@ -1771,12 +1770,12 @@ impl DeviceRef { /// Only available on (macos(11.0), ios(14.0)) pub fn new_dynamic_library(&self, library: &LibraryRef) -> Result { unsafe { - let mut err: *mut Object = ptr::null_mut(); + let mut err: *mut AnyObject = ptr::null_mut(); let dynamic_library: *mut MTLDynamicLibrary = msg_send![self, newDynamicLibrary:library error:&mut err]; if !err.is_null() { // FIXME: copy pasta - let desc: *mut Object = msg_send![err, localizedDescription]; + let desc: *mut AnyObject = msg_send![err, localizedDescription]; let compile_error: *const c_char = msg_send![desc, UTF8String]; let message = CStr::from_ptr(compile_error).to_string_lossy().into_owned(); Err(message) @@ -1789,12 +1788,12 @@ impl DeviceRef { /// Only available on (macos(11.0), ios(14.0)) pub fn new_dynamic_library_with_url(&self, url: &URLRef) -> Result { unsafe { - let mut err: *mut Object = ptr::null_mut(); + let mut err: *mut AnyObject = ptr::null_mut(); let dynamic_library: *mut MTLDynamicLibrary = msg_send![self, newDynamicLibraryWithURL:url error:&mut err]; if !err.is_null() { // FIXME: copy pasta - let desc: *mut Object = msg_send![err, localizedDescription]; + let desc: *mut AnyObject = msg_send![err, localizedDescription]; let compile_error: *const c_char = msg_send![desc, UTF8String]; let message = CStr::from_ptr(compile_error).to_string_lossy().into_owned(); Err(message) @@ -1810,12 +1809,12 @@ impl DeviceRef { descriptor: &BinaryArchiveDescriptorRef, ) -> Result { unsafe { - let mut err: *mut Object = ptr::null_mut(); + let mut err: *mut AnyObject = ptr::null_mut(); let binary_archive: *mut MTLBinaryArchive = msg_send![self, newBinaryArchiveWithDescriptor:descriptor error:&mut err]; if !err.is_null() { // TODO: copy pasta - let desc: *mut Object = msg_send![err, localizedDescription]; + let desc: *mut AnyObject = msg_send![err, localizedDescription]; let c_msg: *const c_char = msg_send![desc, UTF8String]; let message = CStr::from_ptr(c_msg).to_string_lossy().into_owned(); Err(message) @@ -1832,7 +1831,7 @@ impl DeviceRef { reflection_options: MTLPipelineOption, ) -> Result<(RenderPipelineState, RenderPipelineReflection), String> { unsafe { - let mut reflection: *mut Object = ptr::null_mut(); + let mut reflection: *mut AnyObject = ptr::null_mut(); let pipeline_state: *mut MTLRenderPipelineState = try_objc! { err => msg_send![self, newRenderPipelineStateWithDescriptor:descriptor options:reflection_options @@ -1870,7 +1869,7 @@ impl DeviceRef { reflection_options: MTLPipelineOption, ) -> Result<(RenderPipelineState, RenderPipelineReflection), String> { unsafe { - let mut reflection: *mut Object = ptr::null_mut(); + let mut reflection: *mut AnyObject = ptr::null_mut(); let pipeline_state: *mut MTLRenderPipelineState = try_objc! { err => msg_send![self, newRenderPipelineStateWithMeshDescriptor:descriptor options:reflection_options @@ -1938,7 +1937,7 @@ impl DeviceRef { reflection_options: MTLPipelineOption, ) -> Result<(ComputePipelineState, ComputePipelineReflection), String> { unsafe { - let mut reflection: *mut Object = ptr::null_mut(); + let mut reflection: *mut AnyObject = ptr::null_mut(); let pipeline_state: *mut MTLComputePipelineState = try_objc! { err => msg_send![self, newComputePipelineStateWithDescriptor:descriptor options:reflection_options @@ -2150,7 +2149,7 @@ impl DeviceRef { pub fn counter_sets(&self) -> Vec { unsafe { - let counter_sets: *mut Object = msg_send![self, counterSets]; + let counter_sets: *mut AnyObject = msg_send![self, counterSets]; let count: NSUInteger = msg_send![counter_sets, count]; let ret = (0..count) .map(|i| { diff --git a/src/lib.rs b/src/lib.rs index 38f6670..8278b46 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -31,9 +31,9 @@ use std::{ use foreign_types::ForeignType; pub use icrate::Foundation::{CGFloat, NSInteger, NSRange, NSSize as CGSize, NSUInteger}; pub(crate) use objc2::encode::{Encode, Encoding, RefEncode}; -use objc2::runtime::{Bool, Object, Protocol}; +use objc2::runtime::{AnyObject, Bool, Protocol}; -fn nsstring_as_str(nsstr: &Object) -> &str { +fn nsstring_as_str(nsstr: &AnyObject) -> &str { let bytes = unsafe { let bytes: *const std::os::raw::c_char = msg_send![nsstr, UTF8String]; bytes as *const u8 @@ -45,20 +45,20 @@ fn nsstring_as_str(nsstr: &Object) -> &str { } } -fn nsstring_from_str(string: &str) -> *mut Object { +fn nsstring_from_str(string: &str) -> *mut AnyObject { const UTF8_ENCODING: usize = 4; let cls = class!(NSString); let bytes = string.as_ptr() as *const c_void; unsafe { - let obj: *mut Object = msg_send![cls, alloc]; - let obj: *mut Object = msg_send![ + let obj: *mut AnyObject = msg_send![cls, alloc]; + let obj: *mut AnyObject = msg_send![ obj, initWithBytes:bytes length:string.len() encoding:UTF8_ENCODING ]; - let _: *mut Object = msg_send![obj, autorelease]; + let _: *mut AnyObject = msg_send![obj, autorelease]; obj } } @@ -161,7 +161,7 @@ macro_rules! foreign_obj_type { impl ::std::fmt::Debug for paste!{[<$owned_ident Ref>]} { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { unsafe { - let string: *mut ::objc2::runtime::Object = msg_send![self, debugDescription]; + let string: *mut ::objc2::runtime::AnyObject = msg_send![self, debugDescription]; write!(f, "{}", crate::nsstring_as_str(&*string)) } } @@ -180,10 +180,10 @@ macro_rules! try_objc { $err_name: ident => $body:expr } => { { - let mut $err_name: *mut ::objc2::runtime::Object = ::std::ptr::null_mut(); + let mut $err_name: *mut ::objc2::runtime::AnyObject = ::std::ptr::null_mut(); let value = $body; if !$err_name.is_null() { - let desc: *mut Object = msg_send![$err_name, localizedDescription]; + let desc: *mut AnyObject = msg_send![$err_name, localizedDescription]; let compile_error: *const std::os::raw::c_char = msg_send![desc, UTF8String]; let message = CStr::from_ptr(compile_error).to_string_lossy().into_owned(); return Err(message); @@ -195,11 +195,11 @@ macro_rules! try_objc { macro_rules! msg_send_bool_error_check { ($obj:expr, $name:ident: $arg:expr) => {{ - let mut err: *mut Object = ptr::null_mut(); + let mut err: *mut AnyObject = ptr::null_mut(); let result: Bool = msg_send![$obj, $name:$arg error:&mut err]; if !err.is_null() { - let desc: *mut Object = msg_send![err, localizedDescription]; + let desc: *mut AnyObject = msg_send![err, localizedDescription]; let c_msg: *const c_char = msg_send![desc, UTF8String]; let message = CStr::from_ptr(c_msg).to_string_lossy().into_owned(); Err(message) @@ -594,12 +594,12 @@ pub use { #[inline] unsafe fn obj_drop(p: *mut T) { - msg_send![p as *mut Object, release] + msg_send![p as *mut AnyObject, release] } #[inline] unsafe fn obj_clone(p: *mut T) -> *mut T { - let p: *mut Object = msg_send![p as *mut Object, retain]; + let p: *mut AnyObject = msg_send![p as *mut AnyObject, retain]; p as *mut T } diff --git a/src/library.rs b/src/library.rs index d0be3e0..a3c7bcd 100644 --- a/src/library.rs +++ b/src/library.rs @@ -8,7 +8,6 @@ use super::*; use foreign_types::ForeignType; -use objc2::runtime::Object; use std::ffi::CStr; use std::os::raw::{c_char, c_void}; @@ -349,7 +348,7 @@ impl FunctionRef { } } - pub fn function_constants_dictionary(&self) -> *mut Object { + pub fn function_constants_dictionary(&self) -> *mut AnyObject { unsafe { msg_send![self, functionConstantsDictionary] } } @@ -455,11 +454,11 @@ impl CompileOptions { } impl CompileOptionsRef { - pub unsafe fn preprocessor_macros(&self) -> *mut Object { + pub unsafe fn preprocessor_macros(&self) -> *mut AnyObject { msg_send![self, preprocessorMacros] } - pub unsafe fn set_preprocessor_macros(&self, defines: *mut Object) { + pub unsafe fn set_preprocessor_macros(&self, defines: *mut AnyObject) { msg_send![self, setPreprocessorMacros: defines] } @@ -512,7 +511,7 @@ impl CompileOptionsRef { /// Marshal to Rust Vec pub fn libraries(&self) -> Vec { unsafe { - let libraries: *mut Object = msg_send![self, libraries]; + let libraries: *mut AnyObject = msg_send![self, libraries]; let count: NSUInteger = msg_send![libraries, count]; let ret = (0..count) .map(|i| { @@ -632,7 +631,7 @@ impl LibraryRef { pub fn function_names(&self) -> Vec { unsafe { - let names: *mut Object = msg_send![self, functionNames]; + let names: *mut AnyObject = msg_send![self, functionNames]; let count: NSUInteger = msg_send![names, count]; let ret = (0..count) .map(|i| { @@ -652,7 +651,7 @@ impl LibraryRef { /// Only available on (macos(11.0), ios(14.0)) pub fn install_name(&self) -> Option<&str> { unsafe { - let maybe_name: *mut Object = msg_send![self, installName]; + let maybe_name: *mut AnyObject = msg_send![self, installName]; maybe_name.as_ref().map(crate::nsstring_as_str) } } @@ -866,7 +865,7 @@ impl LinkedFunctionsRef { /// Marshal to Rust Vec pub fn functions(&self) -> Vec { unsafe { - let functions: *mut Object = msg_send![self, functions]; + let functions: *mut AnyObject = msg_send![self, functions]; let count: NSUInteger = msg_send![functions, count]; let ret = (0..count) .map(|i| { @@ -887,7 +886,7 @@ impl LinkedFunctionsRef { /// Marshal to Rust Vec pub fn binary_functions(&self) -> Vec { unsafe { - let functions: *mut Object = msg_send![self, binaryFunctions]; + let functions: *mut AnyObject = msg_send![self, binaryFunctions]; let count: NSUInteger = msg_send![functions, count]; let ret = (0..count) .map(|i| { diff --git a/src/mps.rs b/src/mps.rs index f61e764..b03d1c6 100644 --- a/src/mps.rs +++ b/src/mps.rs @@ -216,7 +216,7 @@ impl RayIntersector { pub fn from_device(device: &DeviceRef) -> Option { unsafe { let intersector: RayIntersector = msg_send![class!(MPSRayIntersector), alloc]; - let ptr: *mut Object = msg_send![intersector.as_ref(), initWithDevice: device]; + let ptr: *mut AnyObject = msg_send![intersector.as_ref(), initWithDevice: device]; if ptr.is_null() { None } else { @@ -320,7 +320,7 @@ impl AccelerationStructureGroup { unsafe { let group: AccelerationStructureGroup = msg_send![class!(MPSAccelerationStructureGroup), alloc]; - let ptr: *mut Object = msg_send![group.as_ref(), initWithDevice: device]; + let ptr: *mut AnyObject = msg_send![group.as_ref(), initWithDevice: device]; if ptr.is_null() { None } else { @@ -431,7 +431,7 @@ impl TriangleAccelerationStructure { unsafe { let structure: TriangleAccelerationStructure = msg_send![class!(MPSTriangleAccelerationStructure), alloc]; - let ptr: *mut Object = msg_send![structure.as_ref(), initWithDevice: device]; + let ptr: *mut AnyObject = msg_send![structure.as_ref(), initWithDevice: device]; if ptr.is_null() { None } else { @@ -479,7 +479,7 @@ impl InstanceAccelerationStructure { unsafe { let structure: InstanceAccelerationStructure = msg_send![class!(MPSInstanceAccelerationStructure), alloc]; - let ptr: *mut Object = msg_send![structure.as_ref(), initWithGroup: group]; + let ptr: *mut AnyObject = msg_send![structure.as_ref(), initWithGroup: group]; if ptr.is_null() { None } else { @@ -493,7 +493,7 @@ impl InstanceAccelerationStructureRef { /// Marshal to Rust Vec pub fn acceleration_structures(&self) -> Vec { unsafe { - let acs: *mut Object = msg_send![self, accelerationStructures]; + let acs: *mut AnyObject = msg_send![self, accelerationStructures]; let count: NSUInteger = msg_send![acs, count]; let ret = (0..count) .map(|i| { diff --git a/src/pipeline/compute.rs b/src/pipeline/compute.rs index dc1ac23..e82c32f 100644 --- a/src/pipeline/compute.rs +++ b/src/pipeline/compute.rs @@ -190,7 +190,7 @@ impl ComputePipelineDescriptorRef { /// Marshal to Rust Vec pub fn insert_libraries(&self) -> Vec { unsafe { - let libraries: *mut Object = msg_send![self, insertLibraries]; + let libraries: *mut AnyObject = msg_send![self, insertLibraries]; let count: NSUInteger = msg_send![libraries, count]; let ret = (0..count) .map(|i| { @@ -212,7 +212,7 @@ impl ComputePipelineDescriptorRef { /// Marshal to Rust Vec pub fn binary_archives(&self) -> Vec { unsafe { - let archives: *mut Object = msg_send![self, binaryArchives]; + let archives: *mut AnyObject = msg_send![self, binaryArchives]; let count: NSUInteger = msg_send![archives, count]; let ret = (0..count) .map(|i| { diff --git a/src/pipeline/render.rs b/src/pipeline/render.rs index f3716ac..7810df3 100644 --- a/src/pipeline/render.rs +++ b/src/pipeline/render.rs @@ -192,7 +192,7 @@ impl RenderPipelineReflection { ) -> Self { let class = class!(MTLRenderPipelineReflection); let this: RenderPipelineReflection = msg_send![class, alloc]; - let this_alias: *mut Object = msg_send![this.as_ref(), initWithVertexData:vertex_data + let this_alias: *mut AnyObject = msg_send![this.as_ref(), initWithVertexData:vertex_data fragmentData:fragment_data serializedVertexDescriptor:vertex_desc device:device @@ -627,7 +627,7 @@ impl RenderPipelineDescriptorRef { pub unsafe fn serialize_vertex_data(&self) -> *mut std::ffi::c_void { use std::ptr; let flags = 0; - let err: *mut Object = ptr::null_mut(); + let err: *mut AnyObject = ptr::null_mut(); msg_send![self, newSerializedVertexDataWithFlags:flags error:err] } @@ -659,7 +659,7 @@ impl RenderPipelineDescriptorRef { /// Marshal to Rust Vec pub fn binary_archives(&self) -> Vec { unsafe { - let archives: *mut Object = msg_send![self, binaryArchives]; + let archives: *mut AnyObject = msg_send![self, binaryArchives]; let count: NSUInteger = msg_send![archives, count]; let ret = (0..count) .map(|i| { diff --git a/src/sync.rs b/src/sync.rs index ea64f43..014976d 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -92,7 +92,7 @@ foreign_obj_type! { impl SharedEventListener { pub unsafe fn from_queue_handle(queue: dispatch_queue_t) -> Self { let listener: SharedEventListener = msg_send![class!(MTLSharedEventListener), alloc]; - let ptr: *mut Object = msg_send![listener.as_ref(), initWithDispatchQueue: queue]; + let ptr: *mut AnyObject = msg_send![listener.as_ref(), initWithDispatchQueue: queue]; if ptr.is_null() { panic!("[MTLSharedEventListener alloc] initWithDispatchQueue failed"); } From d3791b4339d7e71a7a529fd079720f250784d950 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Tue, 1 Aug 2023 15:56:50 +0200 Subject: [PATCH 07/12] Make NSInteger and NSUInteger invisible to outside crates --- examples/bindless/main.rs | 4 +-- examples/circle/main.rs | 8 +++--- examples/compute/main.rs | 12 ++++----- examples/raytracing/geometry.rs | 30 +++++++++++------------ examples/raytracing/renderer.rs | 43 ++++++++++++++++----------------- examples/raytracing/scene.rs | 4 +-- src/lib.rs | 7 +++++- 7 files changed, 55 insertions(+), 53 deletions(-) diff --git a/examples/bindless/main.rs b/examples/bindless/main.rs index e7e90ed..698fd40 100644 --- a/examples/bindless/main.rs +++ b/examples/bindless/main.rs @@ -8,7 +8,7 @@ use metal::*; use objc2::rc::autoreleasepool; -const BINDLESS_TEXTURE_COUNT: NSUInteger = 100_000; // ~25Mb +const BINDLESS_TEXTURE_COUNT: usize = 100_000; // ~25Mb /// This example demonstrates: /// - How to create a heap @@ -93,7 +93,7 @@ fn main() { // Encode textures to the argument buffer. textures.iter().enumerate().for_each(|(index, texture)| { // Offset encoder to a proper texture slot - let offset = index as NSUInteger * encoder.encoded_length(); + let offset = index * encoder.encoded_length(); encoder.set_argument_buffer(&argument_buffer, offset); encoder.set_texture(0, texture); }); diff --git a/examples/circle/main.rs b/examples/circle/main.rs index f479af9..19acc56 100644 --- a/examples/circle/main.rs +++ b/examples/circle/main.rs @@ -248,10 +248,10 @@ fn handle_render_pass_sample_buffer_attachment( let sample_buffer_attachment_descriptor = descriptor.sample_buffer_attachments().object_at(0).unwrap(); sample_buffer_attachment_descriptor.set_sample_buffer(&counter_sample_buffer); - sample_buffer_attachment_descriptor.set_start_of_vertex_sample_index(0 as NSUInteger); - sample_buffer_attachment_descriptor.set_end_of_vertex_sample_index(1 as NSUInteger); - sample_buffer_attachment_descriptor.set_start_of_fragment_sample_index(2 as NSUInteger); - sample_buffer_attachment_descriptor.set_end_of_fragment_sample_index(3 as NSUInteger); + sample_buffer_attachment_descriptor.set_start_of_vertex_sample_index(0); + sample_buffer_attachment_descriptor.set_end_of_vertex_sample_index(1); + sample_buffer_attachment_descriptor.set_start_of_fragment_sample_index(2); + sample_buffer_attachment_descriptor.set_end_of_fragment_sample_index(3); } fn handle_render_pass_color_attachment(descriptor: &RenderPassDescriptorRef, texture: &TextureRef) { diff --git a/examples/compute/main.rs b/examples/compute/main.rs index a1456f8..fbb66ca 100644 --- a/examples/compute/main.rs +++ b/examples/compute/main.rs @@ -7,7 +7,7 @@ const NUM_SAMPLES: usize = 2; fn main() { let num_elements = std::env::args() .nth(1) - .map(|s| s.parse::().unwrap()) + .map(|s| s.parse::().unwrap()) .unwrap_or(64 * 64); autoreleasepool(|_| { @@ -46,7 +46,7 @@ fn main() { let num_threads = pipeline_state.thread_execution_width(); let thread_group_count = MTLSize { - width: ((num_elements as NSUInteger + num_threads) / num_threads), + width: (num_elements + num_threads) / num_threads, height: 1, depth: 1, }; @@ -71,9 +71,7 @@ fn main() { let ptr = sum.contents() as *mut u32; println!("Compute shader sum: {}", unsafe { *ptr }); - unsafe { - assert_eq!(num_elements, *ptr); - } + assert_eq!(num_elements, unsafe { *ptr } as usize); handle_timestamps(&destination_buffer, cpu_start, cpu_end, gpu_start, gpu_end); }); @@ -162,9 +160,9 @@ fn create_counter_sample_buffer(device: &Device) -> CounterSampleBuffer { fn create_input_and_output_buffers( device: &Device, - num_elements: u32, + num_elements: usize, ) -> (metal::Buffer, metal::Buffer) { - let data = vec![1u32; num_elements as usize]; + let data = vec![1u32; num_elements]; let buffer = device.new_buffer_with_data( unsafe { std::mem::transmute(data.as_ptr()) }, diff --git a/examples/raytracing/geometry.rs b/examples/raytracing/geometry.rs index 93fdc19..3cca339 100644 --- a/examples/raytracing/geometry.rs +++ b/examples/raytracing/geometry.rs @@ -200,35 +200,35 @@ impl Geometry for TriangleGeometry { self.index_buffer = Some(unsafe { self.device.new_buffer_with_data( transmute(self.indices.as_ptr()), - (self.indices.len() * size_of::()) as NSUInteger, + self.indices.len() * size_of::(), get_managed_buffer_storage_mode(), ) }); self.vertex_position_buffer = Some(unsafe { self.device.new_buffer_with_data( transmute(self.vertices.as_ptr()), - (self.vertices.len() * size_of::()) as NSUInteger, + self.vertices.len() * size_of::(), get_managed_buffer_storage_mode(), ) }); self.vertex_normal_buffer = Some(unsafe { self.device.new_buffer_with_data( transmute(self.normals.as_ptr()), - (self.normals.len() * size_of::()) as NSUInteger, + self.normals.len() * size_of::(), get_managed_buffer_storage_mode(), ) }); self.vertex_colour_buffer = Some(unsafe { self.device.new_buffer_with_data( transmute(self.colours.as_ptr()), - (self.colours.len() * size_of::()) as NSUInteger, + self.colours.len() * size_of::(), get_managed_buffer_storage_mode(), ) }); self.per_primitive_data_buffer = Some(unsafe { self.device.new_buffer_with_data( transmute(self.triangles.as_ptr()), - (self.triangles.len() * size_of::()) as NSUInteger, + self.triangles.len() * size_of::(), get_managed_buffer_storage_mode(), ) }); @@ -304,12 +304,12 @@ impl Geometry for TriangleGeometry { descriptor.set_index_buffer(Some(self.index_buffer.as_ref().unwrap())); descriptor.set_index_type(MTLIndexType::UInt16); descriptor.set_vertex_buffer(Some(self.vertex_position_buffer.as_ref().unwrap())); - descriptor.set_vertex_stride(size_of::() as NSUInteger); - descriptor.set_triangle_count((self.indices.len() / 3) as NSUInteger); + descriptor.set_vertex_stride(size_of::()); + descriptor.set_triangle_count(self.indices.len() / 3); descriptor .set_primitive_data_buffer(Some(self.per_primitive_data_buffer.as_ref().unwrap())); - descriptor.set_primitive_data_stride(size_of::() as NSUInteger); - descriptor.set_primitive_data_element_size(size_of::() as NSUInteger); + descriptor.set_primitive_data_stride(size_of::()); + descriptor.set_primitive_data_element_size(size_of::()); From::from(descriptor) } @@ -366,7 +366,7 @@ impl Geometry for SphereGeometry { self.sphere_buffer = Some(unsafe { self.device.new_buffer_with_data( transmute(self.spheres.as_ptr()), - (self.spheres.len() * size_of::()) as NSUInteger, + self.spheres.len() * size_of::(), get_managed_buffer_storage_mode(), ) }); @@ -384,7 +384,7 @@ impl Geometry for SphereGeometry { self.bounding_box_buffer = Some(unsafe { self.device.new_buffer_with_data( transmute(bounding_boxes.as_ptr()), - (bounding_boxes.len() * size_of::()) as NSUInteger, + bounding_boxes.len() * size_of::(), get_managed_buffer_storage_mode(), ) }); @@ -415,10 +415,10 @@ impl Geometry for SphereGeometry { fn get_geometry_descriptor(&self) -> AccelerationStructureGeometryDescriptor { let descriptor = AccelerationStructureBoundingBoxGeometryDescriptor::descriptor(); descriptor.set_bounding_box_buffer(Some(self.bounding_box_buffer.as_ref().unwrap())); - descriptor.set_bounding_box_count(self.spheres.len() as NSUInteger); + descriptor.set_bounding_box_count(self.spheres.len()); descriptor.set_primitive_data_buffer(Some(&self.sphere_buffer.as_ref().unwrap())); - descriptor.set_primitive_data_stride(size_of::() as NSUInteger); - descriptor.set_primitive_data_element_size(size_of::() as NSUInteger); + descriptor.set_primitive_data_stride(size_of::()); + descriptor.set_primitive_data_element_size(size_of::()); From::from(descriptor) } @@ -435,7 +435,7 @@ pub struct GeometryInstance { pub geometry: Arc, pub transform: Mat4, pub mask: u32, - pub index_in_scene: NSUInteger, + pub index_in_scene: usize, } #[repr(C)] diff --git a/examples/raytracing/renderer.rs b/examples/raytracing/renderer.rs index 126e4ad..da82088 100644 --- a/examples/raytracing/renderer.rs +++ b/examples/raytracing/renderer.rs @@ -22,9 +22,9 @@ struct Uniforms { pub camera: Camera, } -pub const MAX_FRAMES_IN_FLIGHT: NSUInteger = 3; -pub const ALIGNED_UNIFORMS_SIZE: NSUInteger = (size_of::() as NSUInteger + 255) & !255; -pub const UNIFORM_BUFFER_SIZE: NSUInteger = MAX_FRAMES_IN_FLIGHT * ALIGNED_UNIFORMS_SIZE; +pub const MAX_FRAMES_IN_FLIGHT: usize = 3; +pub const ALIGNED_UNIFORMS_SIZE: usize = (size_of::() + 255) & !255; +pub const UNIFORM_BUFFER_SIZE: usize = MAX_FRAMES_IN_FLIGHT * ALIGNED_UNIFORMS_SIZE; #[derive(Clone)] struct Semaphore { @@ -61,9 +61,9 @@ pub struct Renderer { pub instance_acceleration_structure: AccelerationStructure, pub accumulation_targets: [Texture; 2], pub random_texture: Texture, - pub frame_index: NSUInteger, - pub uniform_buffer_index: NSUInteger, - pub uniform_buffer_offset: NSUInteger, + pub frame_index: usize, + pub uniform_buffer_index: usize, + pub uniform_buffer_offset: usize, pub size: CGSize, semaphore: Semaphore, pub queue: CommandQueue, @@ -123,7 +123,7 @@ impl Renderer { } let resource_buffer = device.new_buffer_with_data( resource_buffer_data.as_ptr() as *const c_void, - (resource_buffer_data.len() * size_of::()) as NSUInteger, + resource_buffer_data.len() * size_of::(), get_managed_buffer_storage_mode(), ); resource_buffer.set_label("resource buffer"); @@ -133,7 +133,7 @@ impl Renderer { for i in 0..scene.geometries.len() { let mesh = scene.geometries[i].as_ref(); let geometry_descriptor = mesh.get_geometry_descriptor(); - geometry_descriptor.set_intersection_function_table_offset(i as NSUInteger); + geometry_descriptor.set_intersection_function_table_offset(i); let geometry_descriptors = Array::from_owned_slice(&[geometry_descriptor]); let accel_descriptor = PrimitiveAccelerationStructureDescriptor::descriptor(); accel_descriptor.set_geometry_descriptors(&geometry_descriptors); @@ -173,8 +173,8 @@ impl Renderer { } let instance_buffer = device.new_buffer_with_data( instance_descriptors.as_ptr() as *const c_void, - (size_of::() - * scene.geometry_instances.len()) as NSUInteger, + size_of::() + * scene.geometry_instances.len(), get_managed_buffer_storage_mode(), ); instance_buffer.set_label("instance buffer"); @@ -184,7 +184,7 @@ impl Renderer { accel_descriptor.set_instanced_acceleration_structures(&Array::from_owned_slice( &primitive_acceleration_structures, )); - accel_descriptor.set_instance_count(scene.geometry_instances.len() as NSUInteger); + accel_descriptor.set_instance_count(scene.geometry_instances.len()); accel_descriptor.set_instance_descriptor_buffer(&instance_buffer); let accel_descriptor: AccelerationStructureDescriptor = From::from(accel_descriptor); let instance_acceleration_structure = @@ -218,8 +218,7 @@ impl Renderer { &intersection_function_array, ); let intersection_function_table_descriptor = IntersectionFunctionTableDescriptor::new(); - intersection_function_table_descriptor - .set_function_count(scene.geometries.len() as NSUInteger); + intersection_function_table_descriptor.set_function_count(scene.geometries.len()); let intersection_function_table = raytracing_pipeline .new_intersection_function_table_with_descriptor( &intersection_function_table_descriptor, @@ -231,7 +230,7 @@ impl Renderer { let handle = raytracing_pipeline .function_handle_with_function(intersection_function) .unwrap(); - intersection_function_table.set_function(handle, geometry_index as NSUInteger); + intersection_function_table.set_function(handle, geometry_index); } } let render_descriptor = RenderPipelineDescriptor::new(); @@ -277,7 +276,7 @@ impl Renderer { } } - fn create_target_descriptor(width: NSUInteger, height: NSUInteger) -> TextureDescriptor { + fn create_target_descriptor(width: usize, height: usize) -> TextureDescriptor { let texture_descriptor = TextureDescriptor::new(); texture_descriptor.set_pixel_format(MTLPixelFormat::RGBA32Float); texture_descriptor.set_texture_type(MTLTextureType::D2); @@ -291,7 +290,7 @@ impl Renderer { pub fn window_resized(&mut self, size: CGSize) { self.size = size; let texture_descriptor = - Self::create_target_descriptor(size.width as NSUInteger, size.height as NSUInteger); + Self::create_target_descriptor(size.width as usize, size.height as usize); self.accumulation_targets[0] = self.device.new_texture(&texture_descriptor); self.accumulation_targets[1] = self.device.new_texture(&texture_descriptor); texture_descriptor.set_pixel_format(MTLPixelFormat::R32Uint); @@ -304,10 +303,10 @@ impl Renderer { *v = rng.next_u32(); } self.random_texture.replace_region( - MTLRegion::new_2d(0, 0, size.width as NSUInteger, size.height as NSUInteger), + MTLRegion::new_2d(0, 0, size.width as usize, size.height as usize), 0, random_values.as_ptr() as *const c_void, - size_of::() as NSUInteger * size.width as NSUInteger, + size_of::() * size.width as usize, ); self.frame_index = 0; } @@ -367,8 +366,8 @@ impl Renderer { }) .copy(); command_buffer.add_completed_handler(&block); - let width = self.size.width as NSUInteger; - let height = self.size.height as NSUInteger; + let width = self.size.width as usize; + let height = self.size.height as usize; let threads_per_thread_group = MTLSize::new(8, 8, 1); let thread_groups = MTLSize::new( (width + threads_per_thread_group.width - 1) / threads_per_thread_group.width, @@ -434,7 +433,7 @@ impl Renderer { let command_buffer = queue.new_command_buffer(); let command_encoder = command_buffer.new_acceleration_structure_command_encoder(); let compacted_size_buffer = device.new_buffer( - size_of::() as NSUInteger, + size_of::() as usize, MTLResourceOptions::StorageModeShared, ); command_encoder.build_acceleration_structure( @@ -452,7 +451,7 @@ impl Renderer { command_buffer.commit(); command_buffer.wait_until_completed(); let compacted_size: *const u32 = unsafe { transmute(compacted_size_buffer.contents()) }; - let compacted_size = unsafe { *compacted_size } as NSUInteger; + let compacted_size = unsafe { *compacted_size } as usize; let compacted_acceleration_structure = device.new_acceleration_structure_with_size(compacted_size); let command_buffer = queue.new_command_buffer(); diff --git a/examples/raytracing/scene.rs b/examples/raytracing/scene.rs index 8ecf856..095f3f8 100644 --- a/examples/raytracing/scene.rs +++ b/examples/raytracing/scene.rs @@ -3,7 +3,7 @@ use std::{ffi::c_void, mem::size_of, sync::Arc}; use glam::{Mat4, Vec3, Vec4}; use rand::{thread_rng, Rng}; -use metal::{Buffer, Device, NSRange, NSUInteger}; +use metal::{Buffer, Device, NSRange}; use super::{camera::Camera, geometry::*}; @@ -117,7 +117,7 @@ impl Scene { } let lights_buffer = device.new_buffer_with_data( lights.as_ptr() as *const c_void, - (lights.len() * size_of::()) as NSUInteger, + lights.len() * size_of::(), get_managed_buffer_storage_mode(), ); lights_buffer.did_modify_range(NSRange::new(0, lights_buffer.length())); diff --git a/src/lib.rs b/src/lib.rs index 8278b46..63a4550 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -29,10 +29,15 @@ use std::{ }; use foreign_types::ForeignType; -pub use icrate::Foundation::{CGFloat, NSInteger, NSRange, NSSize as CGSize, NSUInteger}; +pub use icrate::Foundation::{CGFloat, NSRange, NSSize as CGSize}; pub(crate) use objc2::encode::{Encode, Encoding, RefEncode}; use objc2::runtime::{AnyObject, Bool, Protocol}; +// Explicitly doesn't use `icrate::Foundation::NS[U]Integer`, so that the +// documentation will just show the simple Rust type. +pub(crate) type NSInteger = isize; +pub(crate) type NSUInteger = usize; + fn nsstring_as_str(nsstr: &AnyObject) -> &str { let bytes = unsafe { let bytes: *const std::os::raw::c_char = msg_send![nsstr, UTF8String]; From e427fc1f77982edcb9bea412623833d166a872b7 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Tue, 1 Aug 2023 16:04:11 +0200 Subject: [PATCH 08/12] Make NSRange invisible to outside crates --- examples/circle/main.rs | 7 +------ examples/compute/main.rs | 7 +------ examples/raytracing/geometry.rs | 35 +++++++-------------------------- examples/raytracing/renderer.rs | 11 +++++------ examples/raytracing/scene.rs | 4 ++-- examples/texture/src/main.rs | 2 +- examples/window/main.rs | 5 +---- src/buffer.rs | 6 ++++-- src/encoder.rs | 20 ++++++++++++------- src/indirect_encoder.rs | 3 ++- src/lib.rs | 5 +++-- src/library.rs | 3 ++- src/texture.rs | 6 ++++-- 13 files changed, 46 insertions(+), 68 deletions(-) diff --git a/examples/circle/main.rs b/examples/circle/main.rs index 19acc56..21d3cbf 100644 --- a/examples/circle/main.rs +++ b/examples/circle/main.rs @@ -299,12 +299,7 @@ fn resolve_samples_into_buffer( destination_buffer: &BufferRef, ) { let blit_encoder = command_buffer.new_blit_command_encoder(); - blit_encoder.resolve_counters( - &counter_sample_buffer, - NSRange::new(0, 4), - &destination_buffer, - 0, - ); + blit_encoder.resolve_counters(&counter_sample_buffer, 0..4, &destination_buffer, 0); blit_encoder.end_encoding(); } diff --git a/examples/compute/main.rs b/examples/compute/main.rs index fbb66ca..c83a6fa 100644 --- a/examples/compute/main.rs +++ b/examples/compute/main.rs @@ -113,12 +113,7 @@ fn resolve_samples_into_buffer( destination_buffer: &BufferRef, ) { let blit_encoder = command_buffer.new_blit_command_encoder(); - blit_encoder.resolve_counters( - counter_sample_buffer, - crate::NSRange::new(0, NUM_SAMPLES), - destination_buffer, - 0, - ); + blit_encoder.resolve_counters(counter_sample_buffer, 0..NUM_SAMPLES, destination_buffer, 0); blit_encoder.end_encoding(); } diff --git a/examples/raytracing/geometry.rs b/examples/raytracing/geometry.rs index 3cca339..0de779c 100644 --- a/examples/raytracing/geometry.rs +++ b/examples/raytracing/geometry.rs @@ -235,38 +235,23 @@ impl Geometry for TriangleGeometry { self.index_buffer .as_ref() .unwrap() - .did_modify_range(NSRange::new( - 0, - self.index_buffer.as_ref().unwrap().length(), - )); + .did_modify_range(0..self.index_buffer.as_ref().unwrap().length()); self.vertex_position_buffer .as_ref() .unwrap() - .did_modify_range(NSRange::new( - 0, - self.vertex_position_buffer.as_ref().unwrap().length(), - )); + .did_modify_range(0..self.vertex_position_buffer.as_ref().unwrap().length()); self.vertex_normal_buffer .as_ref() .unwrap() - .did_modify_range(NSRange::new( - 0, - self.vertex_normal_buffer.as_ref().unwrap().length(), - )); + .did_modify_range(0..self.vertex_normal_buffer.as_ref().unwrap().length()); self.vertex_colour_buffer .as_ref() .unwrap() - .did_modify_range(NSRange::new( - 0, - self.vertex_colour_buffer.as_ref().unwrap().length(), - )); + .did_modify_range(0..self.vertex_colour_buffer.as_ref().unwrap().length()); self.per_primitive_data_buffer .as_ref() .unwrap() - .did_modify_range(NSRange::new( - 0, - self.per_primitive_data_buffer.as_ref().unwrap().length(), - )); + .did_modify_range(0..self.per_primitive_data_buffer.as_ref().unwrap().length()); self.index_buffer .as_ref() @@ -395,17 +380,11 @@ impl Geometry for SphereGeometry { self.sphere_buffer .as_ref() .unwrap() - .did_modify_range(NSRange::new( - 0, - self.sphere_buffer.as_ref().unwrap().length(), - )); + .did_modify_range(0..self.sphere_buffer.as_ref().unwrap().length()); self.bounding_box_buffer .as_ref() .unwrap() - .did_modify_range(NSRange::new( - 0, - self.bounding_box_buffer.as_ref().unwrap().length(), - )); + .did_modify_range(0..self.bounding_box_buffer.as_ref().unwrap().length()); } fn clear(&mut self) { diff --git a/examples/raytracing/renderer.rs b/examples/raytracing/renderer.rs index da82088..2522a3c 100644 --- a/examples/raytracing/renderer.rs +++ b/examples/raytracing/renderer.rs @@ -127,7 +127,7 @@ impl Renderer { get_managed_buffer_storage_mode(), ); resource_buffer.set_label("resource buffer"); - resource_buffer.did_modify_range(NSRange::new(0, resource_buffer.length())); + resource_buffer.did_modify_range(0..resource_buffer.length()); let mut primitive_acceleration_structures = Vec::new(); for i in 0..scene.geometries.len() { @@ -178,7 +178,7 @@ impl Renderer { get_managed_buffer_storage_mode(), ); instance_buffer.set_label("instance buffer"); - instance_buffer.did_modify_range(NSRange::new(0, instance_buffer.length())); + instance_buffer.did_modify_range(0..instance_buffer.length()); let accel_descriptor = InstanceAccelerationStructureDescriptor::descriptor(); accel_descriptor.set_instanced_acceleration_structures(&Array::from_owned_slice( @@ -348,10 +348,9 @@ impl Renderer { uniforms.light_count = self.scene.lights.len() as u32; - self.uniform_buffer.did_modify_range(NSRange { - location: self.uniform_buffer_offset, - length: ALIGNED_UNIFORMS_SIZE, - }); + self.uniform_buffer.did_modify_range( + self.uniform_buffer_offset..(self.uniform_buffer_offset + ALIGNED_UNIFORMS_SIZE), + ); self.uniform_buffer_index = (self.uniform_buffer_index + 1) % MAX_FRAMES_IN_FLIGHT; } diff --git a/examples/raytracing/scene.rs b/examples/raytracing/scene.rs index 095f3f8..7d068ce 100644 --- a/examples/raytracing/scene.rs +++ b/examples/raytracing/scene.rs @@ -3,7 +3,7 @@ use std::{ffi::c_void, mem::size_of, sync::Arc}; use glam::{Mat4, Vec3, Vec4}; use rand::{thread_rng, Rng}; -use metal::{Buffer, Device, NSRange}; +use metal::{Buffer, Device}; use super::{camera::Camera, geometry::*}; @@ -120,7 +120,7 @@ impl Scene { lights.len() * size_of::(), get_managed_buffer_storage_mode(), ); - lights_buffer.did_modify_range(NSRange::new(0, lights_buffer.length())); + lights_buffer.did_modify_range(0..lights_buffer.length()); lights_buffer.set_label("lights buffer"); Self { diff --git a/examples/texture/src/main.rs b/examples/texture/src/main.rs index 55db8f0..b3a0292 100644 --- a/examples/texture/src/main.rs +++ b/examples/texture/src/main.rs @@ -230,7 +230,7 @@ fn update_viewport_size_buffer(viewport_size_buffer: &Buffer, size: (u32, u32)) unsafe { std::ptr::copy(viewport_size.as_ptr(), contents as *mut u32, byte_count); } - viewport_size_buffer.did_modify_range(NSRange::new(0, byte_count)); + viewport_size_buffer.did_modify_range(0..byte_count); } fn redraw( diff --git a/examples/window/main.rs b/examples/window/main.rs index 89c023b..8fed626 100644 --- a/examples/window/main.rs +++ b/examples/window/main.rs @@ -202,10 +202,7 @@ fn main() { ); } - vbuf.did_modify_range(NSRange::new( - 0, - vertex_data.len() * mem::size_of::(), - )); + vbuf.did_modify_range(0..vertex_data.len() * mem::size_of::()); let drawable = match layer.next_drawable() { Some(drawable) => drawable, diff --git a/src/buffer.rs b/src/buffer.rs index c250c73..1a3d90c 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -25,7 +25,8 @@ impl BufferRef { unsafe { msg_send![self, contents] } } - pub fn did_modify_range(&self, range: NSRange) { + pub fn did_modify_range(&self, range: Range) { + let range: NSRange = range.into(); unsafe { msg_send![self, didModifyRange: range] } } @@ -54,7 +55,8 @@ impl BufferRef { unsafe { msg_send![self, newRemoteBufferViewForDevice: device] } } - pub fn add_debug_marker(&self, name: &str, range: NSRange) { + pub fn add_debug_marker(&self, name: &str, range: Range) { + let range: NSRange = range.into(); unsafe { let name = crate::nsstring_from_str(name); msg_send![self, addDebugMarker:name range:range] diff --git a/src/encoder.rs b/src/encoder.rs index c47b05d..4f446ac 100644 --- a/src/encoder.rs +++ b/src/encoder.rs @@ -1265,9 +1265,10 @@ impl RenderCommandEncoderRef { pub fn execute_commands_in_buffer( &self, buffer: &IndirectCommandBufferRef, - with_range: NSRange, + range: Range, ) { - unsafe { msg_send![self, executeCommandsInBuffer:buffer withRange:with_range] } + let range: NSRange = range.into(); + unsafe { msg_send![self, executeCommandsInBuffer:buffer withRange: range] } } pub fn update_fence(&self, fence: &FenceRef, after_stages: MTLRenderStages) { @@ -1319,7 +1320,8 @@ impl BlitCommandEncoderRef { unsafe { msg_send![self, synchronizeResource: resource] } } - pub fn fill_buffer(&self, destination_buffer: &BufferRef, range: NSRange, value: u8) { + pub fn fill_buffer(&self, destination_buffer: &BufferRef, range: Range, value: u8) { + let range: NSRange = range.into(); unsafe { msg_send![self, fillBuffer: destination_buffer @@ -1487,10 +1489,11 @@ impl BlitCommandEncoderRef { pub fn copy_indirect_command_buffer( &self, source: &IndirectCommandBufferRef, - source_range: NSRange, + source_range: Range, destination: &IndirectCommandBufferRef, destination_index: NSUInteger, ) { + let source_range: NSRange = source_range.into(); unsafe { msg_send![self, copyIndirectCommandBuffer: source @@ -1501,7 +1504,8 @@ impl BlitCommandEncoderRef { } } - pub fn reset_commands_in_buffer(&self, buffer: &IndirectCommandBufferRef, range: NSRange) { + pub fn reset_commands_in_buffer(&self, buffer: &IndirectCommandBufferRef, range: Range) { + let range: NSRange = range.into(); unsafe { msg_send![self, resetCommandsInBuffer: buffer @@ -1513,8 +1517,9 @@ impl BlitCommandEncoderRef { pub fn optimize_indirect_command_buffer( &self, buffer: &IndirectCommandBufferRef, - range: NSRange, + range: Range, ) { + let range: NSRange = range.into(); unsafe { msg_send![self, optimizeIndirectCommandBuffer: buffer @@ -1543,10 +1548,11 @@ impl BlitCommandEncoderRef { pub fn resolve_counters( &self, sample_buffer: &CounterSampleBufferRef, - range: crate::NSRange, + range: Range, destination_buffer: &BufferRef, destination_offset: NSUInteger, ) { + let range: NSRange = range.into(); unsafe { msg_send![self, resolveCounters: sample_buffer diff --git a/src/indirect_encoder.rs b/src/indirect_encoder.rs index 07d6cf2..407e7d7 100644 --- a/src/indirect_encoder.rs +++ b/src/indirect_encoder.rs @@ -108,7 +108,8 @@ impl IndirectCommandBufferRef { unsafe { msg_send![self, indirectComputeCommandAtIndex: index] } } - pub fn reset_with_range(&self, range: NSRange) { + pub fn reset_with_range(&self, range: Range) { + let range: NSRange = range.into(); unsafe { msg_send![self, resetWithRange: range] } } } diff --git a/src/lib.rs b/src/lib.rs index 63a4550..ac4ef9f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -24,12 +24,13 @@ use std::{ borrow::{Borrow, ToOwned}, marker::PhantomData, mem, - ops::Deref, + ops::{Deref, Range}, os::raw::c_void, }; use foreign_types::ForeignType; -pub use icrate::Foundation::{CGFloat, NSRange, NSSize as CGSize}; +pub(crate) use icrate::Foundation::NSRange; +pub use icrate::Foundation::{CGFloat, NSSize as CGSize}; pub(crate) use objc2::encode::{Encode, Encoding, RefEncode}; use objc2::runtime::{AnyObject, Bool, Protocol}; diff --git a/src/library.rs b/src/library.rs index a3c7bcd..4ec67e8 100644 --- a/src/library.rs +++ b/src/library.rs @@ -409,8 +409,9 @@ impl FunctionConstantValuesRef { &self, values: *const c_void, ty: MTLDataType, - range: NSRange, + range: Range, ) { + let range: NSRange = range.into(); unsafe { msg_send![self, setConstantValues:values type:ty withRange:range] } } diff --git a/src/texture.rs b/src/texture.rs index 7da2abb..ecdc436 100644 --- a/src/texture.rs +++ b/src/texture.rs @@ -344,9 +344,11 @@ impl TextureRef { &self, pixel_format: MTLPixelFormat, texture_type: MTLTextureType, - mipmap_levels: NSRange, - slices: NSRange, + mipmap_levels: Range, + slices: Range, ) -> Texture { + let mipmap_levels: NSRange = mipmap_levels.into(); + let slices: NSRange = slices.into(); unsafe { msg_send![self, newTextureViewWithPixelFormat:pixel_format textureType:texture_type From b7319e687172a1079331b8f71ed251220b6738b1 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Tue, 1 Aug 2023 16:16:35 +0200 Subject: [PATCH 09/12] Make CGFloat invisible to outside crates --- examples/raytracing/renderer.rs | 2 +- src/lib.rs | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/examples/raytracing/renderer.rs b/examples/raytracing/renderer.rs index 2522a3c..84aa8f8 100644 --- a/examples/raytracing/renderer.rs +++ b/examples/raytracing/renderer.rs @@ -265,7 +265,7 @@ impl Renderer { frame_index: 0, uniform_buffer_index: 0, uniform_buffer_offset: 0, - size: CGSize::new(1024 as CGFloat, 1024 as CGFloat), + size: CGSize::new(1024.0, 1024.0), semaphore: Semaphore::new((MAX_FRAMES_IN_FLIGHT - 2) as usize), instance_buffer, queue, diff --git a/src/lib.rs b/src/lib.rs index ac4ef9f..f1782ed 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -29,8 +29,8 @@ use std::{ }; use foreign_types::ForeignType; -pub(crate) use icrate::Foundation::NSRange; -pub use icrate::Foundation::{CGFloat, NSSize as CGSize}; +pub use icrate::Foundation::NSSize as CGSize; +pub(crate) use icrate::Foundation::{CGFloat, NSRange}; pub(crate) use objc2::encode::{Encode, Encoding, RefEncode}; use objc2::runtime::{AnyObject, Bool, Protocol}; @@ -497,11 +497,13 @@ impl MetalLayerRef { unsafe { msg_send![self, nextDrawable] } } - pub fn contents_scale(&self) -> CGFloat { - unsafe { msg_send![self, contentsScale] } + pub fn contents_scale(&self) -> f64 { + let res: CGFloat = unsafe { msg_send![self, contentsScale] }; + res as f64 } - pub fn set_contents_scale(&self, scale: CGFloat) { + pub fn set_contents_scale(&self, scale: f64) { + let scale = scale as CGFloat; unsafe { msg_send![self, setContentsScale: scale] } } From 2e95531a6f2d0878c800e3f5772ad7a7b6bdc5e1 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Tue, 1 Aug 2023 16:16:05 +0200 Subject: [PATCH 10/12] Make CGSize invisible to outside crates --- examples/circle/main.rs | 2 +- examples/mesh-shader/main.rs | 4 ++-- examples/raytracing/main.rs | 10 ++++------ examples/raytracing/renderer.rs | 32 ++++++++++++++++---------------- examples/shader-dylib/main.rs | 5 ++--- examples/texture/src/main.rs | 6 +++--- examples/window/main.rs | 4 ++-- src/lib.rs | 13 +++++++------ 8 files changed, 37 insertions(+), 39 deletions(-) diff --git a/examples/circle/main.rs b/examples/circle/main.rs index 21d3cbf..b0baebf 100644 --- a/examples/circle/main.rs +++ b/examples/circle/main.rs @@ -106,7 +106,7 @@ fn main() { } let draw_size = window.inner_size(); - layer.set_drawable_size(CGSize::new(draw_size.width as f64, draw_size.height as f64)); + layer.set_drawable_size(draw_size.width as f64, draw_size.height as f64); let vbuf = { let vertex_data = create_vertex_points_for_circle(); diff --git a/examples/mesh-shader/main.rs b/examples/mesh-shader/main.rs index 717aab6..3a2f372 100644 --- a/examples/mesh-shader/main.rs +++ b/examples/mesh-shader/main.rs @@ -43,7 +43,7 @@ fn main() { } let draw_size = window.inner_size(); - layer.set_drawable_size(CGSize::new(draw_size.width as f64, draw_size.height as f64)); + layer.set_drawable_size(draw_size.width as f64, draw_size.height as f64); let library_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("examples/mesh-shader/shaders.metallib"); @@ -75,7 +75,7 @@ fn main() { Event::WindowEvent { event, .. } => match event { WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, WindowEvent::Resized(size) => { - layer.set_drawable_size(CGSize::new(size.width as f64, size.height as f64)); + layer.set_drawable_size(size.width as f64, size.height as f64); } _ => (), }, diff --git a/examples/raytracing/main.rs b/examples/raytracing/main.rs index 70fb9cc..927406b 100644 --- a/examples/raytracing/main.rs +++ b/examples/raytracing/main.rs @@ -51,11 +51,10 @@ fn main() { } let draw_size = window.inner_size(); - let cg_size = CGSize::new(draw_size.width as f64, draw_size.height as f64); - layer.set_drawable_size(cg_size); + layer.set_drawable_size(draw_size.width as f64, draw_size.height as f64); let mut renderer = renderer::Renderer::new(device); - renderer.window_resized(cg_size); + renderer.window_resized(draw_size.width as usize, draw_size.height as usize); events_loop.run(move |event, _, control_flow| { autoreleasepool(|_| { @@ -65,9 +64,8 @@ fn main() { Event::WindowEvent { event, .. } => match event { WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, WindowEvent::Resized(size) => { - let size = CGSize::new(size.width as f64, size.height as f64); - layer.set_drawable_size(size); - renderer.window_resized(size); + layer.set_drawable_size(size.width as f64, size.height as f64); + renderer.window_resized(size.width as usize, size.height as usize); } _ => (), }, diff --git a/examples/raytracing/renderer.rs b/examples/raytracing/renderer.rs index 84aa8f8..61613c4 100644 --- a/examples/raytracing/renderer.rs +++ b/examples/raytracing/renderer.rs @@ -64,7 +64,8 @@ pub struct Renderer { pub frame_index: usize, pub uniform_buffer_index: usize, pub uniform_buffer_offset: usize, - pub size: CGSize, + pub width: usize, + pub height: usize, semaphore: Semaphore, pub queue: CommandQueue, instance_buffer: Buffer, @@ -265,7 +266,8 @@ impl Renderer { frame_index: 0, uniform_buffer_index: 0, uniform_buffer_offset: 0, - size: CGSize::new(1024.0, 1024.0), + width: 1024, + height: 1024, semaphore: Semaphore::new((MAX_FRAMES_IN_FLIGHT - 2) as usize), instance_buffer, queue, @@ -287,10 +289,10 @@ impl Renderer { texture_descriptor } - pub fn window_resized(&mut self, size: CGSize) { - self.size = size; - let texture_descriptor = - Self::create_target_descriptor(size.width as usize, size.height as usize); + pub fn window_resized(&mut self, width: usize, height: usize) { + self.width = width; + self.height = height; + let texture_descriptor = Self::create_target_descriptor(width, height); self.accumulation_targets[0] = self.device.new_texture(&texture_descriptor); self.accumulation_targets[1] = self.device.new_texture(&texture_descriptor); texture_descriptor.set_pixel_format(MTLPixelFormat::R32Uint); @@ -298,15 +300,15 @@ impl Renderer { texture_descriptor.set_storage_mode(MTLStorageMode::Managed); self.random_texture = self.device.new_texture(&texture_descriptor); let mut rng = thread_rng(); - let mut random_values = vec![0u32; (size.width * size.height) as usize]; + let mut random_values = vec![0u32; width * height]; for v in &mut random_values { *v = rng.next_u32(); } self.random_texture.replace_region( - MTLRegion::new_2d(0, 0, size.width as usize, size.height as usize), + MTLRegion::new_2d(0, 0, width, height), 0, random_values.as_ptr() as *const c_void, - size_of::() * size.width as usize, + size_of::() * width, ); self.frame_index = 0; } @@ -333,15 +335,15 @@ impl Renderer { uniforms.camera.up = Vec4::from((up, 0.0)); let field_of_view = 45.0 * (std::f32::consts::PI / 180.0); - let aspect_ratio = self.size.width as f32 / self.size.height as f32; + let aspect_ratio = self.width as f32 / self.height as f32; let image_plane_height = f32::tan(field_of_view / 2.0); let image_plane_width = aspect_ratio * image_plane_height; uniforms.camera.right *= image_plane_width; uniforms.camera.up *= image_plane_height; - uniforms.width = self.size.width as u32; - uniforms.height = self.size.height as u32; + uniforms.width = self.width as u32; + uniforms.height = self.height as u32; uniforms.frame_index = self.frame_index as u32; self.frame_index += 1; @@ -365,12 +367,10 @@ impl Renderer { }) .copy(); command_buffer.add_completed_handler(&block); - let width = self.size.width as usize; - let height = self.size.height as usize; let threads_per_thread_group = MTLSize::new(8, 8, 1); let thread_groups = MTLSize::new( - (width + threads_per_thread_group.width - 1) / threads_per_thread_group.width, - (height + threads_per_thread_group.height - 1) / threads_per_thread_group.height, + (self.width + threads_per_thread_group.width - 1) / threads_per_thread_group.width, + (self.height + threads_per_thread_group.height - 1) / threads_per_thread_group.height, 1, ); let compute_encoder = command_buffer.new_compute_command_encoder(); diff --git a/examples/shader-dylib/main.rs b/examples/shader-dylib/main.rs index 03c259e..0c20601 100644 --- a/examples/shader-dylib/main.rs +++ b/examples/shader-dylib/main.rs @@ -48,7 +48,7 @@ impl App { view.setLayer(mem::transmute(layer.as_ref())); } let draw_size = window.inner_size(); - layer.set_drawable_size(CGSize::new(draw_size.width as f64, draw_size.height as f64)); + layer.set_drawable_size(draw_size.width as f64, draw_size.height as f64); // compile dynamic lib shader let dylib_src_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) @@ -108,8 +108,7 @@ impl App { } fn resize(&mut self, width: u32, height: u32) { - self.layer - .set_drawable_size(CGSize::new(width as f64, height as f64)); + self.layer.set_drawable_size(width as f64, height as f64); self.width = width; self.height = height; } diff --git a/examples/texture/src/main.rs b/examples/texture/src/main.rs index b3a0292..50cd00c 100644 --- a/examples/texture/src/main.rs +++ b/examples/texture/src/main.rs @@ -167,10 +167,10 @@ fn get_window_layer(window: &Window, device: &Device) -> MetalLayer { // https://developer.apple.com/documentation/quartzcore/cametallayer/1478157-presentswithtransaction layer.set_presents_with_transaction(false); - layer.set_drawable_size(CGSize::new( + layer.set_drawable_size( window.inner_size().width as f64, window.inner_size().height as f64, - )); + ); unsafe { let view = window.ns_view() as cocoa_id; @@ -214,7 +214,7 @@ fn handle_window_event( match event { WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, WindowEvent::Resized(size) => { - layer.set_drawable_size(CGSize::new(size.width as f64, size.height as f64)); + layer.set_drawable_size(size.width as f64, size.height as f64); update_viewport_size_buffer(viewport_size_buffer, (size.width, size.height)); } diff --git a/examples/window/main.rs b/examples/window/main.rs index 8fed626..c202ede 100644 --- a/examples/window/main.rs +++ b/examples/window/main.rs @@ -106,7 +106,7 @@ fn main() { } let draw_size = window.inner_size(); - layer.set_drawable_size(CGSize::new(draw_size.width as f64, draw_size.height as f64)); + layer.set_drawable_size(draw_size.width as f64, draw_size.height as f64); let library_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("examples/window/shaders.metallib"); @@ -167,7 +167,7 @@ fn main() { Event::WindowEvent { event, .. } => match event { WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, WindowEvent::Resized(size) => { - layer.set_drawable_size(CGSize::new(size.width as f64, size.height as f64)); + layer.set_drawable_size(size.width as f64, size.height as f64); } _ => (), }, diff --git a/src/lib.rs b/src/lib.rs index f1782ed..74b5fea 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -29,9 +29,8 @@ use std::{ }; use foreign_types::ForeignType; -pub use icrate::Foundation::NSSize as CGSize; -pub(crate) use icrate::Foundation::{CGFloat, NSRange}; -pub(crate) use objc2::encode::{Encode, Encoding, RefEncode}; +use icrate::Foundation::{CGFloat, CGSize, NSRange}; +use objc2::encode::{Encode, Encoding, RefEncode}; use objc2::runtime::{AnyObject, Bool, Protocol}; // Explicitly doesn't use `icrate::Foundation::NS[U]Integer`, so that the @@ -449,11 +448,13 @@ impl MetalLayerRef { unsafe { msg_send![self, setPixelFormat: pixel_format] } } - pub fn drawable_size(&self) -> CGSize { - unsafe { msg_send![self, drawableSize] } + pub fn drawable_size(&self) -> (f64, f64) { + let res: CGSize = unsafe { msg_send![self, drawableSize] }; + (res.width as _, res.height as _) } - pub fn set_drawable_size(&self, size: CGSize) { + pub fn set_drawable_size(&self, width: f64, height: f64) { + let size = CGSize::new(width as _, height as _); unsafe { msg_send![self, setDrawableSize: size] } } From ae0bd16968df63b6f5bdd69c5a6d45e0403502ec Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Tue, 1 Aug 2023 22:41:40 +0200 Subject: [PATCH 11/12] Fix encoding names on structs whose name is unknown --- src/encoder.rs | 6 +++--- src/renderpass.rs | 2 +- src/resource.rs | 2 +- src/types.rs | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/encoder.rs b/src/encoder.rs index 4f446ac..fc371e5 100644 --- a/src/encoder.rs +++ b/src/encoder.rs @@ -134,7 +134,7 @@ pub struct MTLScissorRect { unsafe impl Encode for MTLScissorRect { const ENCODING: Encoding = Encoding::Struct( - "MTLScissorRect", + "?", &[ NSUInteger::ENCODING, NSUInteger::ENCODING, @@ -158,7 +158,7 @@ pub struct MTLViewport { unsafe impl Encode for MTLViewport { const ENCODING: Encoding = Encoding::Struct( - "MTLViewport", + "?", &[ f64::ENCODING, f64::ENCODING, @@ -201,7 +201,7 @@ pub struct VertexAmplificationViewMapping { unsafe impl Encode for VertexAmplificationViewMapping { const ENCODING: Encoding = Encoding::Struct( - "VertexAmplificationViewMapping", + "?", &[u32::ENCODING, u32::ENCODING], ); } diff --git a/src/renderpass.rs b/src/renderpass.rs index 78267b1..5ac0995 100644 --- a/src/renderpass.rs +++ b/src/renderpass.rs @@ -48,7 +48,7 @@ pub struct MTLClearColor { unsafe impl Encode for MTLClearColor { const ENCODING: Encoding = Encoding::Struct( - "MTLClearColor", + "?", &[f64::ENCODING, f64::ENCODING, f64::ENCODING, f64::ENCODING], ); } diff --git a/src/resource.rs b/src/resource.rs index 72119fd..d3c6c2b 100644 --- a/src/resource.rs +++ b/src/resource.rs @@ -130,7 +130,7 @@ pub struct MTLSizeAndAlign { unsafe impl Encode for MTLSizeAndAlign { const ENCODING: Encoding = Encoding::Struct( - "MTLSizeAndAlign", + "?", &[NSUInteger::ENCODING, NSUInteger::ENCODING], ); } diff --git a/src/types.rs b/src/types.rs index 3cc29f9..0e961a5 100644 --- a/src/types.rs +++ b/src/types.rs @@ -68,7 +68,7 @@ pub struct MTLRegion { unsafe impl Encode for MTLRegion { const ENCODING: Encoding = - Encoding::Struct("MTLRegion", &[MTLOrigin::ENCODING, MTLSize::ENCODING]); + Encoding::Struct("?", &[MTLOrigin::ENCODING, MTLSize::ENCODING]); } impl MTLRegion { @@ -112,7 +112,7 @@ pub struct MTLSamplePosition { unsafe impl Encode for MTLSamplePosition { const ENCODING: Encoding = - Encoding::Struct("MTLSamplePosition", &[f32::ENCODING, f32::ENCODING]); + Encoding::Struct("?", &[f32::ENCODING, f32::ENCODING]); } #[repr(C)] From cc9c0b6aef0e6b011d4ede658f867af694643ba7 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Tue, 5 Sep 2023 16:22:00 +0200 Subject: [PATCH 12/12] Fix repr of MTLLibraryType --- src/library.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/library.rs b/src/library.rs index 4ec67e8..09f6eb1 100644 --- a/src/library.rs +++ b/src/library.rs @@ -426,7 +426,7 @@ impl FunctionConstantValuesRef { /// Only available on (macos(11.0), ios(14.0)) /// /// See -#[repr(u64)] +#[repr(isize)] #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub enum MTLLibraryType { Executable = 0, @@ -434,7 +434,7 @@ pub enum MTLLibraryType { } unsafe impl Encode for MTLLibraryType { - const ENCODING: Encoding = u64::ENCODING; + const ENCODING: Encoding = isize::ENCODING; } /// See