Debian Codegraph @

third_party/rust/metal/examples/circle/main.rs

raw
1 use metal::*;
2
3 use winit::{
4 event::{Event, WindowEvent},
5 event_loop::{ControlFlow, EventLoop},
6 raw_window_handle::{HasWindowHandle, RawWindowHandle},
7 };
8
9 use cocoa::{appkit::NSView, base::id as cocoa_id};
10 use core_graphics_types::geometry::CGSize;
11
12 use objc::{rc::autoreleasepool, runtime::YES};
13
14 // Declare the data structures needed to carry vertex layout to
15 // metal shading language(MSL) program. Use #[repr(C)], to make
16 // the data structure compatible with C++ type data structure
17 // for vertex defined in MSL program as MSL program is broadly
18 // based on C++
19 #[repr(C)]
20 #[derive(Debug)]
21 pub struct Position(std::ffi::c_float, std::ffi::c_float);
22 #[repr(C)]
23 #[derive(Debug)]
24 pub struct Color(std::ffi::c_float, std::ffi::c_float, std::ffi::c_float);
25 #[repr(C)]
26 #[derive(Debug)]
27 pub struct AAPLVertex {
28 p: Position,
29 c: Color,
30 }
31
32 fn main() {
33 // Create a window for viewing the content
34 let event_loop = EventLoop::new().unwrap();
35 let size = winit::dpi::LogicalSize::new(800, 600);
36
37 let window = winit::window::WindowBuilder::new()
38 .with_inner_size(size)
39 .with_title("Metal".to_string())
40 .build(&event_loop)
41 .unwrap();
42
43 // Set up the GPU device found in the system
44 let device = Device::system_default().expect("no device found");
45 println!("Your device is: {}", device.name(),);
46
47 // Scaffold required to sample the GPU and CPU timestamps
48 let mut cpu_start = 0;
49 let mut gpu_start = 0;
50 device.sample_timestamps(&mut cpu_start, &mut gpu_start);
51 let counter_sample_buffer = create_counter_sample_buffer(&device);
52 let destination_buffer = device.new_buffer(
53 (size_of::<u64>() * 4usize) as u64,
54 MTLResourceOptions::StorageModeShared,
55 );
56 let counter_sampling_point = MTLCounterSamplingPoint::AtStageBoundary;
57 assert!(device.supports_counter_sampling(counter_sampling_point));
58
59 let binary_archive_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
60 .join("examples/circle/binary_archive.metallib");
61
62 let binary_archive_url =
63 URL::new_with_string(&format!("file://{}", binary_archive_path.display()));
64
65 let binary_archive_descriptor = BinaryArchiveDescriptor::new();
66 if binary_archive_path.exists() {
67 binary_archive_descriptor.set_url(&binary_archive_url);
68 }
69
70 // Set up a binary archive to cache compiled shaders.
71 let binary_archive = device
72 .new_binary_archive_with_descriptor(&binary_archive_descriptor)
73 .unwrap();
74
75 let library_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
76 .join("examples/circle/shaders.metallib");
77
78 // Use the metallib file generated out of .metal shader file
79 let library = device.new_library_with_file(library_path).unwrap();
80
81 // The render pipeline generated from the vertex and fragment shaders in the .metal shader file.
82 let pipeline_state = prepare_pipeline_state(&device, &library, &binary_archive);
83
84 // Serialize the binary archive to disk.
85 binary_archive
86 .serialize_to_url(&binary_archive_url)
87 .unwrap();
88
89 // Set the command queue used to pass commands to the device.
90 let command_queue = device.new_command_queue();
91
92 // Currently, MetalLayer is the only interface that provide
93 // layers to carry drawable texture from GPU rendaring through metal
94 // library to viewable windows.
95 let mut layer = MetalLayer::new();
96 layer.set_device(&device);
97 layer.set_pixel_format(MTLPixelFormat::BGRA8Unorm);
98 layer.set_presents_with_transaction(false);
99
100 unsafe {
101 if let Ok(RawWindowHandle::AppKit(rw)) = window.window_handle().map(|wh| wh.as_raw()) {
102 let view = rw.ns_view.as_ptr() as cocoa_id;
103 view.setWantsLayer(YES);
104 view.setLayer(<*mut _>::cast(layer.as_mut()));
105 }
106 }
107
108 let draw_size = window.inner_size();
109 layer.set_drawable_size(CGSize::new(draw_size.width as f64, draw_size.height as f64));
110
111 let vbuf = {
112 let vertex_data = create_vertex_points_for_circle();
113
114 device.new_buffer_with_data(
115 vertex_data.as_ptr().cast(),
116 size_of_val(vertex_data.as_slice()) as u64,
117 MTLResourceOptions::CPUCacheModeDefaultCache | MTLResourceOptions::StorageModeManaged,
118 )
119 };
120
121 event_loop
122 .run(move |event, event_loop| {
123 autoreleasepool(|| {
124 // ControlFlow::Wait pauses the event loop if no events are available to process.
125 // This is ideal for non-game applications that only update in response to user
126 // input, and uses significantly less power/CPU time than ControlFlow::Poll.
127 event_loop.set_control_flow(ControlFlow::Wait);
128
129 match event {
130 Event::AboutToWait => window.request_redraw(),
131 Event::WindowEvent { event, .. } => {
132 match event {
133 WindowEvent::CloseRequested => {
134 println!("The close button was pressed; stopping");
135 event_loop.exit();
136 }
137 WindowEvent::RedrawRequested => {
138 // It's preferrable to render in this event rather than in MainEventsCleared, since
139 // rendering in here allows the program to gracefully handle redraws requested
140 // by the OS.
141 let drawable = match layer.next_drawable() {
142 Some(drawable) => drawable,
143 None => return,
144 };
145
146 // Create a new command buffer for each render pass to the current drawable
147 let command_buffer = command_queue.new_command_buffer();
148
149 // Obtain a renderPassDescriptor generated from the view's drawable textures.
150 let render_pass_descriptor = RenderPassDescriptor::new();
151 handle_render_pass_color_attachment(
152 render_pass_descriptor,
153 drawable.texture(),
154 );
155 handle_render_pass_sample_buffer_attachment(
156 render_pass_descriptor,
157 &counter_sample_buffer,
158 );
159
160 // Create a render command encoder.
161 let encoder = command_buffer
162 .new_render_command_encoder(render_pass_descriptor);
163 encoder.set_render_pipeline_state(&pipeline_state);
164 // Pass in the parameter data.
165 encoder.set_vertex_buffer(0, Some(&vbuf), 0);
166 // Draw the triangles which will eventually form the circle.
167 encoder.draw_primitives(MTLPrimitiveType::TriangleStrip, 0, 1080);
168 encoder.end_encoding();
169
170 resolve_samples_into_buffer(
171 command_buffer,
172 &counter_sample_buffer,
173 &destination_buffer,
174 );
175
176 // Schedule a present once the framebuffer is complete using the current drawable.
177 command_buffer.present_drawable(drawable);
178
179 // Finalize rendering here & push the command buffer to the GPU.
180 command_buffer.commit();
181 command_buffer.wait_until_completed();
182
183 let mut cpu_end = 0;
184 let mut gpu_end = 0;
185 device.sample_timestamps(&mut cpu_end, &mut gpu_end);
186 handle_timestamps(
187 &destination_buffer,
188 cpu_start,
189 cpu_end,
190 gpu_start,
191 gpu_end,
192 );
193 }
194 _ => (),
195 }
196 }
197 _ => (),
198 }
199 });
200 })
201 .unwrap();
202 }
203
204 // If we want to draw a circle, we need to draw it out of the three primitive
205 // types available with metal framework. Triangle is used in this case to form
206 // the circle. If we consider a circle to be total of 360 degree at center, we
207 // can form small triangle with one point at origin and two points at the
208 // perimeter of the circle for each degree. Eventually, if we can take enough
209 // triangle virtices for total of 360 degree, the triangles together will
210 // form a circle. This function captures the triangle vertices for each degree
211 // and push the co-ordinates of the vertices to a rust vector
212 fn create_vertex_points_for_circle() -> Vec<AAPLVertex> {
213 let mut v: Vec<AAPLVertex> = Vec::new();
214 let origin_x: f32 = 0.0;
215 let origin_y: f32 = 0.0;
216
217 // Size of the circle
218 let circle_size = 0.8f32;
219
220 for i in 0..720 {
221 let y = i as f32;
222 // Get the X co-ordinate of each point on the perimeter of circle
223 let position_x: f32 = y.to_radians().cos() * 100.0;
224 let position_x: f32 = position_x.trunc() / 100.0;
225 // Set the size of the circle
226 let position_x: f32 = position_x * circle_size;
227 // Get the Y co-ordinate of each point on the perimeter of circle
228 let position_y: f32 = y.to_radians().sin() * 100.0;
229 let position_y: f32 = position_y.trunc() / 100.0;
230 // Set the size of the circle
231 let position_y: f32 = position_y * circle_size;
232
233 v.push(AAPLVertex {
234 p: Position(position_x, position_y),
235 c: Color(0.7, 0.3, 0.5),
236 });
237
238 if (i + 1) % 2 == 0 {
239 // For each two points on perimeter, push one point of origin
240 v.push(AAPLVertex {
241 p: Position(origin_x, origin_y),
242 c: Color(0.2, 0.7, 0.4),
243 });
244 }
245 }
246
247 v
248 }
249
250 fn handle_render_pass_sample_buffer_attachment(
251 descriptor: &RenderPassDescriptorRef,
252 counter_sample_buffer: &CounterSampleBufferRef,
253 ) {
254 let sample_buffer_attachment_descriptor =
255 descriptor.sample_buffer_attachments().object_at(0).unwrap();
256 sample_buffer_attachment_descriptor.set_sample_buffer(counter_sample_buffer);
257 sample_buffer_attachment_descriptor.set_start_of_vertex_sample_index(0 as NSUInteger);
258 sample_buffer_attachment_descriptor.set_end_of_vertex_sample_index(1 as NSUInteger);
259 sample_buffer_attachment_descriptor.set_start_of_fragment_sample_index(2 as NSUInteger);
260 sample_buffer_attachment_descriptor.set_end_of_fragment_sample_index(3 as NSUInteger);
261 }
262
263 fn handle_render_pass_color_attachment(descriptor: &RenderPassDescriptorRef, texture: &TextureRef) {
264 let color_attachment = descriptor.color_attachments().object_at(0).unwrap();
265
266 color_attachment.set_texture(Some(texture));
267 color_attachment.set_load_action(MTLLoadAction::Clear);
268 // Setting a background color
269 color_attachment.set_clear_color(MTLClearColor::new(0.5, 0.5, 0.8, 1.0));
270 color_attachment.set_store_action(MTLStoreAction::Store);
271 }
272
273 fn prepare_pipeline_state(
274 device: &Device,
275 library: &Library,
276 binary_archive: &BinaryArchive,
277 ) -> RenderPipelineState {
278 let vert = library.get_function("vs", None).unwrap();
279 let frag = library.get_function("ps", None).unwrap();
280
281 let pipeline_state_descriptor = RenderPipelineDescriptor::new();
282 pipeline_state_descriptor.set_vertex_function(Some(&vert));
283 pipeline_state_descriptor.set_fragment_function(Some(&frag));
284 pipeline_state_descriptor
285 .color_attachments()
286 .object_at(0)
287 .unwrap()
288 .set_pixel_format(MTLPixelFormat::BGRA8Unorm);
289 // Set the binary archives to search for a cached pipeline in.
290 pipeline_state_descriptor.set_binary_archives(&[binary_archive]);
291
292 // Add the pipeline descriptor to the binary archive cache.
293 binary_archive
294 .add_render_pipeline_functions_with_descriptor(&pipeline_state_descriptor)
295 .unwrap();
296
297 device
298 .new_render_pipeline_state(&pipeline_state_descriptor)
299 .unwrap()
300 }
301
302 fn resolve_samples_into_buffer(
303 command_buffer: &CommandBufferRef,
304 counter_sample_buffer: &CounterSampleBufferRef,
305 destination_buffer: &BufferRef,
306 ) {
307 let blit_encoder = command_buffer.new_blit_command_encoder();
308 blit_encoder.resolve_counters(
309 counter_sample_buffer,
310 crate::NSRange::new(0u64, 4),
311 destination_buffer,
312 0u64,
313 );
314 blit_encoder.end_encoding();
315 }
316
317 fn handle_timestamps(
318 resolved_sample_buffer: &BufferRef,
319 cpu_start: u64,
320 cpu_end: u64,
321 gpu_start: u64,
322 gpu_end: u64,
323 ) {
324 let samples = unsafe {
325 std::slice::from_raw_parts(resolved_sample_buffer.contents().cast::<u64>(), 4usize)
326 };
327 let vertex_pass_start = samples[0];
328 let vertex_pass_end = samples[1];
329 let fragment_pass_start = samples[2];
330 let fragment_pass_end = samples[3];
331
332 let cpu_time_span = cpu_end - cpu_start;
333 let gpu_time_span = gpu_end - gpu_start;
334
335 let vertex_micros = microseconds_between_begin(
336 vertex_pass_start,
337 vertex_pass_end,
338 gpu_time_span,
339 cpu_time_span,
340 );
341 let fragment_micros = microseconds_between_begin(
342 fragment_pass_start,
343 fragment_pass_end,
344 gpu_time_span,
345 cpu_time_span,
346 );
347
348 println!("Vertex pass duration: {:.2} µs", vertex_micros);
349 println!("Fragment pass duration: {:.2} µs\n", fragment_micros);
350 }
351
352 fn create_counter_sample_buffer(device: &Device) -> CounterSampleBuffer {
353 let counter_sample_buffer_desc = metal::CounterSampleBufferDescriptor::new();
354 counter_sample_buffer_desc.set_storage_mode(metal::MTLStorageMode::Shared);
355 counter_sample_buffer_desc.set_sample_count(4u64);
356 counter_sample_buffer_desc.set_counter_set(&fetch_timestamp_counter_set(device));
357
358 device
359 .new_counter_sample_buffer_with_descriptor(&counter_sample_buffer_desc)
360 .unwrap()
361 }
362
363 fn fetch_timestamp_counter_set(device: &Device) -> metal::CounterSet {
364 let counter_sets = device.counter_sets();
365 let mut timestamp_counter = None;
366 for cs in counter_sets.iter() {
367 if cs.name() == "timestamp" {
368 timestamp_counter = Some(cs);
369 break;
370 }
371 }
372 timestamp_counter
373 .expect("No timestamp counter found")
374 .clone()
375 }
376
377 /// <https://developer.apple.com/documentation/metal/gpu_counters_and_counter_sample_buffers/converting_gpu_timestamps_into_cpu_time>
378 fn microseconds_between_begin(begin: u64, end: u64, gpu_time_span: u64, cpu_time_span: u64) -> f64 {
379 let time_span = (end as f64) - (begin as f64);
380 let nanoseconds = time_span / (gpu_time_span as f64) * (cpu_time_span as f64);
381 nanoseconds / 1000.0
382 }