oarust 0.9.0

GPU-first semantic computing engine written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! UI compute pipelines — one per compositor command family.
//!
//! Strict uses the shared Engine heap. Compatibility uses immutable per-command
//! sets with one storage image and the exact zero, one or two source buffers.
//!
//! Donor reference: `oa::Ui::initBlit` in `ui.cpp`

use std::sync::Arc;

use super::command::UiCmd;
use crate::{Error, Result};

// Embedded compiled SPIR-V — one per UI shader.
static CLEAR_COMPOSE_SPV: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/ui_clear_compose.spv"));
static BLIT_RGBA_SPV: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/ui_blit_rgba.spv"));
static DRAW_RECT_SPV: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_rect.spv"));
static DRAW_RECT_OUTLINE_SPV: &[u8] =
	include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_rect_outline.spv"));
static DRAW_LINE_SPV: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_line.spv"));
static DRAW_PLOT_LINE_SPV: &[u8] =
	include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_plot_line.spv"));
static DRAW_GLYPHS_SPV: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_glyphs.spv"));

static CLEAR_COMPOSE_BOUNDED_SPV: &[u8] =
	include_bytes!(concat!(env!("OUT_DIR"), "/ui_clear_compose_bounded.spv"));

static BLIT_RGBA_BOUNDED_SPV: &[u8] =
	include_bytes!(concat!(env!("OUT_DIR"), "/ui_blit_rgba_bounded.spv"));

static DRAW_RECT_BOUNDED_SPV: &[u8] =
	include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_rect_bounded.spv"));

static DRAW_RECT_OUTLINE_BOUNDED_SPV: &[u8] = include_bytes!(concat!(
	env!("OUT_DIR"),
	"/ui_draw_rect_outline_bounded.spv"
));

static DRAW_LINE_BOUNDED_SPV: &[u8] =
	include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_line_bounded.spv"));

static DRAW_PLOT_LINE_BOUNDED_SPV: &[u8] =
	include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_plot_line_bounded.spv"));

static DRAW_GLYPHS_BOUNDED_SPV: &[u8] =
	include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_glyphs_bounded.spv"));

static DRAW_CANVAS_GRID_SPV: &[u8] =
	include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_canvas_grid.spv"));
static DRAW_CANVAS_GRID_BOUNDED_SPV: &[u8] =
	include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_canvas_grid_bounded.spv"));

static DRAW_TRIANGLE_SPV: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_triangle.spv"));
static DRAW_TRIANGLE_BOUNDED_SPV: &[u8] =
	include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_triangle_bounded.spv"));

static MASK_ROUNDED_VIEWPORT_SPV: &[u8] =
	include_bytes!(concat!(env!("OUT_DIR"), "/ui_mask_rounded_viewport.spv"));
static MASK_ROUNDED_VIEWPORT_BOUNDED_SPV: &[u8] = include_bytes!(concat!(
	env!("OUT_DIR"),
	"/ui_mask_rounded_viewport_bounded.spv"
));

static DRAW_WAVEFORM_SPV: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_waveform.spv"));
static DRAW_WAVEFORM_BOUNDED_SPV: &[u8] =
	include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_waveform_bounded.spv"));
static DRAW_HEATMAP_SPV: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_heatmap.spv"));
static DRAW_HEATMAP_BOUNDED_SPV: &[u8] =
	include_bytes!(concat!(env!("OUT_DIR"), "/ui_draw_heatmap_bounded.spv"));

/// All twelve UI compute pipelines owned by one `Ui` instance.
pub(super) struct UiPipelines {
	pub(super) clear_compose: UiPipeline,
	pub(super) blit_rgba: UiPipeline,
	pub(super) draw_rect: UiPipeline,
	pub(super) draw_rect_outline: UiPipeline,
	pub(super) draw_line: UiPipeline,
	pub(super) draw_plot_line: UiPipeline,
	pub(super) draw_glyphs: UiPipeline,
	pub(super) draw_canvas_grid: UiPipeline,
	pub(super) draw_triangle: UiPipeline,
	pub(super) mask_rounded_viewport: UiPipeline,
	pub(super) draw_waveform: UiPipeline,
	pub(super) draw_heatmap: UiPipeline,
	pub(super) bounded: Option<UiLayouts>,
}

impl UiPipelines {
	pub(super) fn new(
		device: &Arc<vk::Device>,
		layout: vk::PipelineLayout,
		bounded: bool,
		cache: vk::PipelineCache,
	) -> Result<Self> {
		let layouts = if bounded {
			Some(UiLayouts::new(device)?)
		} else {
			None
		};
		let select = |count: usize| {
			layouts
				.as_ref()
				.map_or(layout, |layouts| layouts.pipelines[count])
		};
		Ok(Self {
			clear_compose: UiPipeline::new(
				device,
				select(0),
				if bounded {
					CLEAR_COMPOSE_BOUNDED_SPV
				} else {
					CLEAR_COMPOSE_SPV
				},
				cache,
			)?,
			blit_rgba: UiPipeline::new(
				device,
				select(1),
				if bounded {
					BLIT_RGBA_BOUNDED_SPV
				} else {
					BLIT_RGBA_SPV
				},
				cache,
			)?,
			draw_rect: UiPipeline::new(
				device,
				select(0),
				if bounded {
					DRAW_RECT_BOUNDED_SPV
				} else {
					DRAW_RECT_SPV
				},
				cache,
			)?,
			draw_rect_outline: UiPipeline::new(
				device,
				select(0),
				if bounded {
					DRAW_RECT_OUTLINE_BOUNDED_SPV
				} else {
					DRAW_RECT_OUTLINE_SPV
				},
				cache,
			)?,
			draw_line: UiPipeline::new(
				device,
				select(0),
				if bounded {
					DRAW_LINE_BOUNDED_SPV
				} else {
					DRAW_LINE_SPV
				},
				cache,
			)?,
			draw_plot_line: UiPipeline::new(
				device,
				select(1),
				if bounded {
					DRAW_PLOT_LINE_BOUNDED_SPV
				} else {
					DRAW_PLOT_LINE_SPV
				},
				cache,
			)?,
			draw_glyphs: UiPipeline::new(
				device,
				select(2),
				if bounded {
					DRAW_GLYPHS_BOUNDED_SPV
				} else {
					DRAW_GLYPHS_SPV
				},
				cache,
			)?,
			draw_canvas_grid: UiPipeline::new(
				device,
				select(0),
				if bounded {
					DRAW_CANVAS_GRID_BOUNDED_SPV
				} else {
					DRAW_CANVAS_GRID_SPV
				},
				cache,
			)?,
			draw_triangle: UiPipeline::new(
				device,
				select(0),
				if bounded {
					DRAW_TRIANGLE_BOUNDED_SPV
				} else {
					DRAW_TRIANGLE_SPV
				},
				cache,
			)?,
			mask_rounded_viewport: UiPipeline::new(
				device,
				select(0),
				if bounded {
					MASK_ROUNDED_VIEWPORT_BOUNDED_SPV
				} else {
					MASK_ROUNDED_VIEWPORT_SPV
				},
				cache,
			)?,
			draw_waveform: UiPipeline::new(
				device,
				select(1),
				if bounded {
					DRAW_WAVEFORM_BOUNDED_SPV
				} else {
					DRAW_WAVEFORM_SPV
				},
				cache,
			)?,
			draw_heatmap: UiPipeline::new(
				device,
				select(1),
				if bounded {
					DRAW_HEATMAP_BOUNDED_SPV
				} else {
					DRAW_HEATMAP_SPV
				},
				cache,
			)?,
			bounded: layouts,
		})
	}
}

/// One compute pipeline with a shared layout.
pub(super) struct UiPipeline {
	handle: vk::Pipeline,
	layout: vk::PipelineLayout,
	device: Arc<vk::Device>,
}

impl UiPipeline {
	fn new(
		device: &Arc<vk::Device>,
		layout: vk::PipelineLayout,
		spv: &[u8],
		cache: vk::PipelineCache,
	) -> Result<Self> {
		let words = decode_spirv(spv)?;
		let module = create_shader_module(device, &words)?;
		let entry = c"main";
		let stage = vk::PipelineShaderStageCreateInfo::default()
			.stage(vk::ShaderStageFlagBits::COMPUTE_BIT)
			.module(module)
			.name(entry);
		let create_info = vk::ComputePipelineCreateInfo::default()
			.stage(stage)
			.layout(layout);
		let mut pipelines = [vk::Pipeline::default(); 1];
		// SAFETY: the create-info and output slot remain live and writable for the
		// call; partial output is destroyed on failure below.
		let result = unsafe {
			device.create_compute_pipelines(
				cache,
				std::slice::from_ref(&create_info),
				None,
				&mut pipelines,
			)
		};
		let _ = unsafe { device.destroy_shader_module(module, None) };
		let handle = match result {
			Ok(vk::Result::SUCCESS) => pipelines[0],
			result => {
				// SAFETY: partial results were never recorded or submitted.
				for pipeline in pipelines
					.into_iter()
					.filter(|handle| *handle != vk::Pipeline::default())
				{
					let _ = unsafe { device.destroy_pipeline(pipeline, None) };
				}
				return Err(Error::backend_dispatch_failure(
					"Vulkan",
					"UI compute pipeline creation",
					result,
				));
			}
		};
		Ok(Self {
			handle,
			layout,
			device: device.clone(),
		})
	}

	pub(super) const fn layout(&self) -> vk::PipelineLayout {
		self.layout
	}

	pub(super) const fn raw(&self) -> vk::Pipeline {
		self.handle
	}
}

impl Drop for UiPipeline {
	fn drop(&mut self) {
		// SAFETY: pipeline belongs to the device; layout is external and must be kept alive.
		let _ = unsafe { self.device.destroy_pipeline(self.handle, None) };
	}
}

// ── helpers ───────────────────────────────────────────────────────────────────

fn decode_spirv(bytes: &[u8]) -> Result<Vec<u32>> {
	if !bytes.len().is_multiple_of(4) {
		return Err(Error::backend_failure(
			"SPIR-V",
			"UI shader byte alignment",
			std::io::Error::other("SPIR-V byte count is not a multiple of 4"),
		));
	}
	Ok(
		bytes
			.as_chunks::<4>()
			.0
			.iter()
			.map(|chunk| u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
			.collect(),
	)
}

fn create_shader_module(device: &vk::Device, words: &[u32]) -> Result<vk::ShaderModule> {
	let info = vk::ShaderModuleCreateInfo::default().code(words);
	unsafe { device.create_shader_module(&info, None) }
		.map_err(|source| Error::backend_failure("Vulkan", "UI shader module creation", source))
}

/// Exact fixed descriptor layouts: one image and zero, one or two buffers.
/// Field order in UiPipelines retires pipelines before their layouts.
pub(super) struct UiLayouts {
	device: Arc<vk::Device>,
	descriptors: Vec<vk::DescriptorSetLayout>,
	pipelines: Vec<vk::PipelineLayout>,
}

impl UiLayouts {
	fn new(device: &Arc<vk::Device>) -> Result<Self> {
		let mut result = Self {
			device: device.clone(),
			descriptors: Vec::new(),
			pipelines: Vec::new(),
		};
		for count in 0..=2 {
			let mut bindings = vec![
				vk::DescriptorSetLayoutBinding::default()
					.binding(1)
					.descriptor_type(vk::DescriptorType::STORAGE_IMAGE)
					.descriptor_count(1)
					.stage_flags(vk::ShaderStageFlagBits::COMPUTE_BIT),
			];
			if count != 0 {
				bindings.push(
					vk::DescriptorSetLayoutBinding::default()
						.binding(0)
						.descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
						.descriptor_count(count)
						.stage_flags(vk::ShaderStageFlagBits::COMPUTE_BIT),
				);
			}
			// SAFETY: fixed counts match the bounded artifacts; no indexing flags.
			let descriptor = unsafe {
				device.create_descriptor_set_layout(
					&(vk::DescriptorSetLayoutCreateInfo::default()
						.bindings(&bindings)
						.map_err(Error::from)?),
					None,
				)
			}
			.map_err(|e| Error::backend_failure("Vulkan", "bounded UI descriptor layout", e))?;
			result.descriptors.push(descriptor);
			let descriptors = [descriptor];
			let push = [vk::PushConstantRange::default()
				.size(128)
				.stage_flags(vk::ShaderStageFlagBits::COMPUTE_BIT)];
			// SAFETY: the descriptor layout is retained by result and push range is legal.
			let pipeline = unsafe {
				device.create_pipeline_layout(
					&vk::PipelineLayoutCreateInfo::default()
						.set_layouts(&descriptors)
						.map_err(Error::from)?
						.push_constant_ranges(&push)
						.map_err(Error::from)?,
					None,
				)
			}
			.map_err(|e| Error::backend_failure("Vulkan", "bounded UI pipeline layout", e))?;
			result.pipelines.push(pipeline);
		}
		Ok(result)
	}
}

impl Drop for UiLayouts {
	fn drop(&mut self) {
		// SAFETY: pipelines and submitted descriptor owners have retired first.
		unsafe {
			for layout in &self.pipelines {
				let _ = self.device.destroy_pipeline_layout(*layout, None);
			}
			for layout in &self.descriptors {
				let _ = self.device.destroy_descriptor_set_layout(*layout, None);
			}
		}
	}
}

/// Immutable descriptor pool and locally remapped commands for one composition.
/// The presentation slot or exact readback completion retains this allocation.
pub(super) struct UiFrameBindings {
	device: Arc<vk::Device>,
	_engine: crate::runtime::EngineHandle,
	pool: vk::DescriptorPool,
	pub(super) sets: Vec<vk::DescriptorSet>,
	pub(super) commands: Vec<UiCmd>,
	pub(super) layouts: Vec<vk::PipelineLayout>,
}

impl UiFrameBindings {
	pub(super) fn new(
		engine: &crate::runtime::EngineHandle,
		layouts: &UiLayouts,
		image: vk::ImageView,
		commands: &[UiCmd],
		resolve: impl Fn(u32) -> Result<vk::DescriptorBufferInfo>,
	) -> Result<Self> {
		let device = engine.raw_device();
		let mut buffers = Vec::with_capacity(commands.len());
		let mut remapped = commands.to_vec();
		for command in &mut remapped {
			let indices = match command {
				UiCmd::BlitRgba { src_idx, .. } => {
					let index = *src_idx;
					*src_idx = 0;
					vec![index]
				}
				UiCmd::PlotLine { values_idx, .. }
				| UiCmd::Waveform { values_idx, .. }
				| UiCmd::Heatmap { values_idx, .. } => {
					let index = *values_idx;
					*values_idx = 0;
					vec![index]
				}
				UiCmd::Glyphs {
					glyph_idx,
					atlas_idx,
					..
				} => {
					let indices = vec![*glyph_idx, *atlas_idx];
					*glyph_idx = 0;
					*atlas_idx = 1;
					indices
				}
				_ => Vec::new(),
			};
			buffers.push(
				indices
					.into_iter()
					.map(&resolve)
					.collect::<Result<Vec<_>>>()?,
			);
		}
		let count = u32::try_from(commands.len())
			.map_err(|_| Error::resource_exhausted("too many UI commands"))?;
		let buffer_count = buffers.iter().try_fold(0_u32, |total, buffer| {
			total
				.checked_add(buffer.len() as u32)
				.ok_or_else(|| Error::resource_exhausted("UI descriptor count overflow"))
		})?;
		let mut sizes = vec![
			vk::DescriptorPoolSize::default()
				.r#type(vk::DescriptorType::STORAGE_IMAGE)
				.descriptor_count(count.max(1)),
		];
		if buffer_count != 0 {
			sizes.push(
				vk::DescriptorPoolSize::default()
					.r#type(vk::DescriptorType::STORAGE_BUFFER)
					.descriptor_count(buffer_count),
			);
		}
		// SAFETY: sizes cover all exact per-command layouts; sets are immutable.
		let pool = unsafe {
			device.create_descriptor_pool(
				&(vk::DescriptorPoolCreateInfo::default())
					.max_sets(count.max(1))
					.pool_sizes(&sizes)
					.map_err(Error::from)?,
				None,
			)
		}
		.map_err(|e| Error::backend_failure("Vulkan", "bounded UI descriptor pool", e))?;
		let mut result = Self {
			device: device.clone(),
			_engine: engine.clone(),
			pool,
			sets: Vec::new(),
			commands: remapped,
			layouts: buffers.iter().map(|b| layouts.pipelines[b.len()]).collect(),
		};
		if count == 0 {
			return Ok(result);
		}
		let descriptors: Vec<_> = buffers
			.iter()
			.map(|b| layouts.descriptors[b.len()])
			.collect();
		let mut sets = vec![vk::DescriptorSet::default(); descriptors.len()];
		// SAFETY: layouts belong to device and the new pool has exact capacity.
		unsafe {
			device.allocate_descriptor_sets(
				&vk::DescriptorSetAllocateInfo::default()
					.descriptor_pool(pool)
					.set_layouts(&descriptors)
					.map_err(Error::from)?,
				&mut sets,
			)
		}
		.map_err(|e| Error::backend_failure("Vulkan", "bounded UI descriptor allocation", e))?;
		result.sets = sets;
		let images = [vk::DescriptorImageInfo::default()
			.image_view(image)
			.image_layout(vk::ImageLayout::GENERAL)];
		for (&set, buffers) in result.sets.iter().zip(&buffers) {
			let mut writes = vec![
				vk::WriteDescriptorSet::default()
					.dst_set(set)
					.dst_binding(1)
					.descriptor_type(vk::DescriptorType::STORAGE_IMAGE)
					.image_info(&images)
					.map_err(Error::from)?,
			];
			if !buffers.is_empty() {
				writes.push(
					vk::WriteDescriptorSet::default()
						.dst_set(set)
						.dst_binding(0)
						.descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
						.buffer_info(buffers)
						.map_err(Error::from)?,
				);
			}
			// SAFETY: fresh unsubmitted sets, live retained sources, exact ranges.
			unsafe {
				device.update_descriptor_sets(&writes, &[])?;
			}
		}
		Ok(result)
	}
}

impl Drop for UiFrameBindings {
	fn drop(&mut self) {
		// SAFETY: exact presentation/readback completion precedes final owner release.
		let _ = unsafe { self.device.destroy_descriptor_pool(self.pool, None) };
	}
}