diff --git a/base/src/graphics.rs b/base/src/graphics.rs index 2d8c9799..b33e50b8 100644 --- a/base/src/graphics.rs +++ b/base/src/graphics.rs @@ -1,7 +1,6 @@ use crate::mthelper::SharedRef; use bedrock::{self as br, CommandBufferMut, CommandPoolMut, QueueMut}; use br::{Device, Instance, InstanceChild, PhysicalDevice, SubmissionBatch}; -use cfg_if::cfg_if; use log::{info, warn}; use std::{ collections::HashSet, @@ -269,10 +268,12 @@ impl Graphics { batches: &[br::vk::VkSubmitInfo], fence: &mut impl br::FenceMut, ) -> br::Result<()> { - self.graphics_queue - .q - .get_mut() - .submit_raw(batches, Some(fence.as_transparent_mut_ref())) + unsafe { + self.graphics_queue + .q + .get_mut() + .submit_raw(batches, Some(fence.as_transparent_mut_ref())) + } } /// Submits any commands as transient commands. diff --git a/base/src/lib.rs b/base/src/lib.rs index 11cf97b9..23d39cc7 100644 --- a/base/src/lib.rs +++ b/base/src/lib.rs @@ -321,12 +321,12 @@ impl Engine { pub fn back_buffer( &self, index: usize, - ) -> Option::BackBuffer>> { + ) -> Option<&SharedRef<::BackBuffer>> { self.presenter.back_buffer(index) } pub fn iter_back_buffers<'s>( &'s self, - ) -> impl Iterator::BackBuffer>> + 's + ) -> impl Iterator::BackBuffer>> + 's { (0..self.back_buffer_count()) .map(move |x| self.back_buffer(x).expect("unreachable while iteration")) @@ -537,6 +537,43 @@ impl LateInit { } } +pub struct Discardable1(Option); +impl Discardable1 { + pub const fn new() -> Self { + Self(None) + } + + pub fn set(&mut self, v: T) { + self.0 = Some(v); + } + + pub fn get<'v>(&'v self) -> &'v T { + self.0.as_ref().expect("value unset") + } + + pub fn get_mut<'v>(&'v mut self) -> &'v mut T { + self.0.as_mut().expect("value unset") + } + + pub fn discard(&mut self) { + self.0 = None; + } + + pub fn take(&mut self) -> Option { + self.0.take() + } + + pub const fn is_available(&self) -> bool { + self.0.is_some() + } +} +impl From for Discardable1 { + #[inline(always)] + fn from(value: T) -> Self { + Self(Some(value)) + } +} + pub struct Discardable(DynamicMut>); impl Discardable { pub fn new() -> Self { diff --git a/base/src/model.rs b/base/src/model.rs index dbbd5136..d8518ed8 100644 --- a/base/src/model.rs +++ b/base/src/model.rs @@ -11,7 +11,7 @@ pub trait ModelData { fn prealloc(&self, alloc: &mut BufferPrealloc) -> Self::PreallocOffsetType; fn stage_data_into( &self, - mem: &br::MappedMemoryRange, + mem: &br::MappedMemoryRange, offsets: Self::PreallocOffsetType, ) -> Self::RendererParams; } @@ -44,7 +44,7 @@ impl ModelData for Primitive { } fn stage_data_into( &self, - mem: &br::MappedMemoryRange, + mem: &br::MappedMemoryRange, vo: u64, ) { unsafe { @@ -70,7 +70,7 @@ impl ModelData for IndexedPrimitive { } fn stage_data_into( &self, - mem: &br::MappedMemoryRange, + mem: &br::MappedMemoryRange, (vo, io): (u64, u64), ) { unsafe { diff --git a/base/src/presenter.rs b/base/src/presenter.rs index eb1bd3c8..94b6f570 100644 --- a/base/src/presenter.rs +++ b/base/src/presenter.rs @@ -15,7 +15,7 @@ pub trait PlatformPresenter { fn format(&self) -> br::vk::VkFormat; fn back_buffer_count(&self) -> usize; - fn back_buffer(&self, index: usize) -> Option>; + fn back_buffer(&self, index: usize) -> Option<&SharedRef>; fn emit_initialize_back_buffer_commands<'r, CB: br::CommandBufferMut + ?Sized>( &self, @@ -137,7 +137,7 @@ impl IntegratedSwapchainObject { /// WSI Swapchain implementation for PlatformPresenter pub struct IntegratedSwapchain { surface_info: crate::SurfaceInfo, - swapchain: crate::Discardable>, + swapchain: crate::Discardable1>, rendering_order: br::SemaphoreObject, buffer_ready_order: br::SemaphoreObject, present_order: br::SemaphoreObject, @@ -163,30 +163,20 @@ impl IntegratedSwapchain { #[cfg(feature = "debug")] { rendering_order - .set_name(Some(unsafe { - std::ffi::CStr::from_bytes_with_nul_unchecked( - b"Peridot-Default Presenter-Rendering Order Semaphore\0", - ) - })) + .set_name(Some(c"Peridot-Default Presenter-Rendering Order Semaphore")) .expect("Failed to set Rendering Order Semaphore name"); buffer_ready_order - .set_name(Some(unsafe { - std::ffi::CStr::from_bytes_with_nul_unchecked( - b"Peridot-Default Presenter-BufferReady Order Semaphore\0", - ) - })) + .set_name(Some( + c"Peridot-Default Presenter-BufferReady Order Semaphore", + )) .expect("Failed to set BufferReady Order Semaphore name"); present_order - .set_name(Some(unsafe { - std::ffi::CStr::from_bytes_with_nul_unchecked( - b"Peridot-Default Presenter-Present Order Semaphore\0", - ) - })) + .set_name(Some(c"Peridot-Default Presenter-Present Order Semaphore")) .expect("Failed to set Present Order Semaphore name"); } Self { - swapchain: crate::Discardable::from(IntegratedSwapchainObject::new( + swapchain: crate::Discardable1::from(IntegratedSwapchainObject::new( g, surface, &surface_info, @@ -210,15 +200,15 @@ impl IntegratedSwapchain { } #[inline] - pub fn back_buffer( - &self, + pub fn back_buffer<'s>( + &'s self, index: usize, ) -> Option< - SharedRef< + &'s SharedRef< br::ImageViewObject>>, >, > { - self.swapchain.get().back_buffer_images.get(index).cloned() + self.swapchain.get().back_buffer_images.get(index) } pub fn emit_initialize_back_buffer_commands< @@ -252,7 +242,7 @@ impl IntegratedSwapchain { #[inline] pub fn acquire_next_back_buffer_index(&mut self) -> br::Result { - self.swapchain.get_mut_lw().swapchain.acquire_next( + self.swapchain.get_mut().swapchain.acquire_next( None, br::CompletionHandlerMut::Queue(self.rendering_order.as_transparent_mut_ref()), ) @@ -316,7 +306,7 @@ impl IntegratedSwapchain { g.submit_buffered_commands(&[render_submission], last_render_fence)?; } - self.swapchain.get_mut_lw().swapchain.queue_present( + self.swapchain.get_mut().swapchain.queue_present( g.graphics_queue.q.get_mut(), bb_index, &[self.present_order.as_transparent_ref()], @@ -324,7 +314,7 @@ impl IntegratedSwapchain { } pub fn resize(&mut self, g: &crate::Graphics, new_size: peridot_math::Vector2) { - if let Some(mut old) = self.swapchain.take_lw() { + if let Some(mut old) = self.swapchain.take() { old.back_buffer_images.clear(); let (_, s) = SharedRef::try_unwrap(old.swapchain) .unwrap_or_else(|refs| { @@ -335,7 +325,7 @@ impl IntegratedSwapchain { ) }) .deconstruct(); - self.swapchain.set_lw(IntegratedSwapchainObject::new( + self.swapchain.set(IntegratedSwapchainObject::new( g, s, &self.surface_info, diff --git a/base/src/resource.rs b/base/src/resource.rs index 5de403b5..c629e5ac 100644 --- a/base/src/resource.rs +++ b/base/src/resource.rs @@ -211,10 +211,7 @@ impl TexturePreallocatedGroup> { } impl TextureInstantiatedGroup { /// Copy texture pixels into a staging buffer. - pub fn stage_data( - &self, - mr: &br::MappedMemoryRange, - ) { + pub fn stage_data(&self, mr: &br::MappedMemoryRange) { trace!("Staging Texture Data..."); for &(ref pd, offs) in &self.0 { let s = unsafe { @@ -626,10 +623,7 @@ impl BufferWithLength { /// Describing the type that can be used as initializer of `FixedBuffer`s pub trait FixedBufferInitializer { /// Setup memory data in staging buffer - fn stage_data( - &mut self, - m: &br::MappedMemoryRange, - ); + fn stage_data(&mut self, m: &br::MappedMemoryRange); fn buffer_graphics_ready( &self, tfb: &mut TransferBatch, diff --git a/base/src/resource/buffer.rs b/base/src/resource/buffer.rs index 2a18c79e..ecae4288 100644 --- a/base/src/resource/buffer.rs +++ b/base/src/resource/buffer.rs @@ -37,7 +37,10 @@ impl< &mut self, range: std::ops::Range, f: impl FnOnce(&br::MappedMemoryRange) -> R, - ) -> br::Result { + ) -> br::Result + where + Memory: br::DeviceMemoryMut, + { let mut mem = self.1.borrow_mut(); let mapped_range = AutocloseMappedMemoryRange( mem.map((self.2 + range.start) as _..(self.2 + range.end) as _)? diff --git a/base/src/resource/memory.rs b/base/src/resource/memory.rs index 865a45f5..d09e5c6c 100644 --- a/base/src/resource/memory.rs +++ b/base/src/resource/memory.rs @@ -177,11 +177,10 @@ where } #[repr(transparent)] -pub struct AutocloseMappedMemoryRange< - 'm, - DeviceMemory: br::DeviceMemory + br::VkHandleMut + ?Sized + 'm, ->(pub(super) Option>); -impl<'m, DeviceMemory: br::DeviceMemory + br::VkHandleMut + ?Sized + 'm> std::ops::Deref +pub struct AutocloseMappedMemoryRange<'m, DeviceMemory: br::DeviceMemoryMut + ?Sized + 'm>( + pub(super) Option>, +); +impl<'m, DeviceMemory: br::DeviceMemoryMut + ?Sized + 'm> std::ops::Deref for AutocloseMappedMemoryRange<'m, DeviceMemory> { type Target = br::MappedMemoryRange<'m, DeviceMemory>; @@ -190,7 +189,7 @@ impl<'m, DeviceMemory: br::DeviceMemory + br::VkHandleMut + ?Sized + 'm> std::op self.0.as_ref().expect("object has been dropped") } } -impl<'m, DeviceMemory: br::DeviceMemory + br::VkHandleMut + ?Sized + 'm> Drop +impl<'m, DeviceMemory: br::DeviceMemoryMut + ?Sized + 'm> Drop for AutocloseMappedMemoryRange<'m, DeviceMemory> { fn drop(&mut self) { diff --git a/cradle/android/src/lib.rs b/cradle/android/src/lib.rs index a4a28ed8..044f7938 100644 --- a/cradle/android/src/lib.rs +++ b/cradle/android/src/lib.rs @@ -114,7 +114,7 @@ impl peridot::PlatformPresenter for Presenter { fn back_buffer_count(&self) -> usize { self.sc.back_buffer_count() } - fn back_buffer(&self, index: usize) -> Option> { + fn back_buffer(&self, index: usize) -> Option<&SharedRef> { self.sc.back_buffer(index) } diff --git a/cradle/linux/src/main.rs b/cradle/linux/src/main.rs index 000f7f32..0fa81a62 100644 --- a/cradle/linux/src/main.rs +++ b/cradle/linux/src/main.rs @@ -111,6 +111,7 @@ impl GameDriver { PP: PointerPositionProvider + Send + Sync + 'static, Arc>: PresenterProvider, > as PresenterProvider>::Presenter: Sync + Send, + <> as PresenterProvider>::Presenter as peridot::PlatformPresenter>::BackBuffer: Sync + Send { let (event_sender, event_receiver) = async_std::channel::unbounded(); let (frame_timing_sender, frame_timing_receiver) = async_std::channel::bounded(1); @@ -188,6 +189,8 @@ where W: WindowBackend + EventProcessor + PointerPositionProvider + Send + Sync + 'static, Arc>: PresenterProvider, > as PresenterProvider>::Presenter: Sync + Send, + <> as PresenterProvider>::Presenter as peridot::PlatformPresenter>::BackBuffer: + Sync + Send, { let gd = GameDriver::new(window_backend.clone()); diff --git a/cradle/linux/src/presenter/wayland.rs b/cradle/linux/src/presenter/wayland.rs index 21bd685e..1d9327d8 100644 --- a/cradle/linux/src/presenter/wayland.rs +++ b/cradle/linux/src/presenter/wayland.rs @@ -339,7 +339,7 @@ impl peridot::PlatformPresenter for Presenter { fn back_buffer_count(&self) -> usize { self.sc.back_buffer_count() } - fn back_buffer(&self, index: usize) -> Option> { + fn back_buffer(&self, index: usize) -> Option<&peridot::mthelper::SharedRef> { self.sc.back_buffer(index) } fn requesting_back_buffer_layout(&self) -> (br::ImageLayout, br::PipelineStageFlags) { diff --git a/cradle/linux/src/presenter/xcb.rs b/cradle/linux/src/presenter/xcb.rs index 260136e4..2d776933 100644 --- a/cradle/linux/src/presenter/xcb.rs +++ b/cradle/linux/src/presenter/xcb.rs @@ -288,7 +288,7 @@ impl peridot::PlatformPresenter for Presenter { fn back_buffer_count(&self) -> usize { self.sc.back_buffer_count() } - fn back_buffer(&self, index: usize) -> Option> { + fn back_buffer(&self, index: usize) -> Option<&peridot::mthelper::SharedRef> { self.sc.back_buffer(index) } fn requesting_back_buffer_layout(&self) -> (br::ImageLayout, br::PipelineStageFlags) { diff --git a/cradle/mac/src/lib.rs b/cradle/mac/src/lib.rs index 6e973250..41e6a02f 100644 --- a/cradle/mac/src/lib.rs +++ b/cradle/mac/src/lib.rs @@ -234,7 +234,7 @@ impl peridot::PlatformPresenter for Presenter { fn back_buffer_count(&self) -> usize { self.sc.back_buffer_count() } - fn back_buffer(&self, index: usize) -> Option> { + fn back_buffer(&self, index: usize) -> Option<&SharedRef> { self.sc.back_buffer(index) } fn requesting_back_buffer_layout(&self) -> (br::ImageLayout, br::PipelineStageFlags) { diff --git a/cradle/windows/src/presenter.rs b/cradle/windows/src/presenter.rs index 3ee4cd3d..a292bc8b 100644 --- a/cradle/windows/src/presenter.rs +++ b/cradle/windows/src/presenter.rs @@ -85,7 +85,7 @@ impl peridot::PlatformPresenter for Presenter { fn back_buffer_count(&self) -> usize { self.sc.back_buffer_count() } - fn back_buffer(&self, index: usize) -> Option> { + fn back_buffer(&self, index: usize) -> Option<&SharedRef> { self.sc.back_buffer(index) } @@ -509,8 +509,8 @@ impl peridot::PlatformPresenter for Presenter { fn back_buffer_count(&self) -> usize { 2 } - fn back_buffer(&self, index: usize) -> Option> { - self.back_buffers.get(index).map(|b| b.image_view.clone()) + fn back_buffer(&self, index: usize) -> Option<&SharedRef> { + self.back_buffers.get(index).map(|b| &b.image_view) } fn emit_initialize_back_buffer_commands< diff --git a/examples/image-plane/src/lib.rs b/examples/image-plane/src/lib.rs index 914d9b4a..a2729be4 100644 --- a/examples/image-plane/src/lib.rs +++ b/examples/image-plane/src/lib.rs @@ -243,9 +243,10 @@ pub async fn game_main(e: &mut peridot::Engine) { ) .create(e.graphics().device().clone()) .expect("Create RenderPass"); - let mut framebuffers = e - .iter_back_buffers() - .map(|b| br::FramebufferBuilder::new_with_attachment(&renderpass, b.clone()).create()) + let mut backbuffer_resources = e.iter_back_buffers().cloned().collect::>(); + let mut framebuffers = backbuffer_resources + .iter() + .map(|b| br::FramebufferBuilder::new_with_attachment(&renderpass, b).create()) .collect::, _>>() .expect("Bind Framebuffer"); @@ -366,8 +367,12 @@ pub async fn game_main(e: &mut peridot::Engine) { .apply(e.graphics().device()) .expect("Failed to set render cb name"); - let begin_main_rp = BeginRenderPass::for_entire_framebuffer(&renderpass, fb) - .with_clear_values(vec![br::ClearValue::color([0.0; 4])]); + let begin_main_rp = BeginRenderPass::new( + &renderpass, + fb, + screen_size.wh().into_rect(br::vk::VkOffset2D::ZERO), + ) + .with_clear_values(vec![br::ClearValue::color([0.0; 4])]); (&color_renders) .between(begin_main_rp, EndRenderPass) @@ -401,23 +406,28 @@ pub async fn game_main(e: &mut peridot::Engine) { e.wait_for_last_rendering_completion(); render_cb.reset().expect("Resetting RenderCB"); - framebuffers.clear(); + drop(framebuffers); + drop(backbuffer_resources); e.resize_presenter_backbuffers(new_size); - framebuffers = e - .iter_back_buffers() + backbuffer_resources = e.iter_back_buffers().cloned().collect(); + framebuffers = backbuffer_resources + .iter() .map(|b| { - br::FramebufferBuilder::new_with_attachment(&renderpass, b.clone()) - .create() + br::FramebufferBuilder::new_with_attachment(&renderpass, b).create() }) .collect::, _>>() .expect("Bind Framebuffers"); for (cb, fb) in render_cb.iter_mut().zip(&framebuffers) { - let begin_main_rp = - BeginRenderPass::for_entire_framebuffer(&renderpass, fb) - .with_clear_values(vec![br::ClearValue::color([0.0; 4])]); + let begin_main_rp = BeginRenderPass::new( + &renderpass, + fb, + br::vk::VkExtent2D::from(new_size) + .into_rect(br::vk::VkOffset2D::ZERO), + ) + .with_clear_values(vec![br::ClearValue::color([0.0; 4])]); (&color_renders) .between(begin_main_rp, EndRenderPass) @@ -458,21 +468,25 @@ pub async fn game_main(e: &mut peridot::Engine) { e.wait_for_last_rendering_completion(); render_cb.reset().expect("Resetting RenderCB"); - framebuffers.clear(); + drop(framebuffers); + drop(backbuffer_resources); e.resize_presenter_backbuffers(new_size); - framebuffers = e - .iter_back_buffers() - .map(|b| { - br::FramebufferBuilder::new_with_attachment(&renderpass, b.clone()).create() - }) + backbuffer_resources = e.iter_back_buffers().cloned().collect(); + framebuffers = backbuffer_resources + .iter() + .map(|b| br::FramebufferBuilder::new_with_attachment(&renderpass, b).create()) .collect::, _>>() .expect("Bind Framebuffers"); for (cb, fb) in render_cb.iter_mut().zip(&framebuffers) { - let begin_main_rp = BeginRenderPass::for_entire_framebuffer(&renderpass, fb) - .with_clear_values(vec![br::ClearValue::color([0.0; 4])]); + let begin_main_rp = BeginRenderPass::new( + &renderpass, + fb, + br::vk::VkExtent2D::from(new_size).into_rect(br::vk::VkOffset2D::ZERO), + ) + .with_clear_values(vec![br::ClearValue::color([0.0; 4])]); (&color_renders) .between(begin_main_rp, EndRenderPass) diff --git a/examples/tapfx/src/lib.rs b/examples/tapfx/src/lib.rs index 910c6d58..a2b76ed0 100644 --- a/examples/tapfx/src/lib.rs +++ b/examples/tapfx/src/lib.rs @@ -64,9 +64,10 @@ pub async fn game_main(e: &mut peridot::Engine) { ) .create(e.graphics().device().clone()) .expect("Failed to create RenderPass"); - let framebuffers: Vec<_> = e - .iter_back_buffers() - .map(|b| br::FramebufferBuilder::new_with_attachment(&renderpass, b.clone()).create()) + let backbuffer_resources = e.iter_back_buffers().cloned().collect::>(); + let framebuffers: Vec<_> = backbuffer_resources + .iter() + .map(|b| br::FramebufferBuilder::new_with_attachment(&renderpass, b).create()) .collect::>() .expect("Failed to create Framebuffer"); diff --git a/examples/vg-sdf-renderer/src/lib.rs b/examples/vg-sdf-renderer/src/lib.rs index 5325786f..49db2614 100644 --- a/examples/vg-sdf-renderer/src/lib.rs +++ b/examples/vg-sdf-renderer/src/lib.rs @@ -1,8 +1,7 @@ -use bedrock::{self as br, CommandBufferMut, RenderPass}; +use bedrock::{self as br, CommandBufferMut, Device, RenderPass}; use br::{GraphicsPipelineBuilder, Image, ImageChild, ImageSubresourceSlice, SubmissionBatch}; use peridot::mthelper::SharedRef; use peridot::SpecConstantStorage; -use peridot::{Engine, EngineEvents, FeatureRequests}; use peridot_command_object::{ BeginRenderPass, Blending, BufferUsage, ColorAttachmentBlending, EndRenderPass, GraphicsCommand, GraphicsCommandCombiner, GraphicsCommandSubmission, NextSubpass, @@ -553,565 +552,562 @@ impl TwoPassStencilSDFRenderer { } } -pub struct Game { - memory_manager: MemoryManager, - buffers: TwoPassStencilSDFRendererBuffers, - stencil_buffer_view: SharedRef>, - fb: Vec>, - sdf_renderer: TwoPassStencilSDFRenderer, - cmd: peridot::CommandBundle, - ph: std::marker::PhantomData<*const NL>, -} -impl Game { - const SDF_SIZE: f32 = 32.0; -} -impl FeatureRequests for Game {} -impl EngineEvents for Game { - fn init(e: &mut Engine) -> Self { - let back_buffer_size = e - .back_buffer(0) - .expect("no back-buffer?") - .image() - .size() - .wh(); +const SDF_SIZE: f32 = 32.0; - let font = peridot_vg::DefaultFontProvider::new() - .expect("Failed to create font provider") - .best_match("sans-serif", &peridot_vg::FontProperties::default(), 120.0) - .expect("no suitable font"); - let gid = font.glyph_id('A').expect("no glyph contained"); - let mut gen = peridot_vg::SDFGenerator::new(1.0, Self::SDF_SIZE); - let glyph_metrics = font.bounds(&gid).expect("Failed to get glyph bounds"); - font.outline( - &gid, - &peridot_vg::sdf_generator::Transform2D::create_translation( - -glyph_metrics.origin.x + Self::SDF_SIZE, - -glyph_metrics.origin.y - Self::SDF_SIZE, - ), - &mut gen, - ) - .expect("Failed to render glyph outline"); - let figure_vertices = gen.build(); - let ( - figure_fill_triangle_points_count, - figure_fill_triangle_indices_count, - figure_curve_triangles_count, - outline_rects_count, - ) = figure_vertices - .iter() - .fold((0, 0, 0, 0), |(t, t2, t3, t4), f| { - ( - t + f.fill_triangle_points.len(), - t2 + f.fill_triangle_indices.len(), - t3 + f.curve_triangles.len(), - t4 + f.parabola_rects.len(), - ) - }); +pub async fn game_main(e: &mut peridot::Engine) { + let back_buffer_size = e + .back_buffer(0) + .expect("no back-buffer?") + .image() + .size() + .wh(); - let mut memory_manager = MemoryManager::new(e.graphics()); + let font = peridot_vg::DefaultFontProvider::new() + .expect("Failed to create font provider") + .best_match("sans-serif", &peridot_vg::FontProperties::default(), 120.0) + .expect("no suitable font"); + let gid = font.glyph_id('A').expect("no glyph contained"); + let mut gen = peridot_vg::SDFGenerator::new(1.0, SDF_SIZE); + let glyph_metrics = font.bounds(&gid).expect("Failed to get glyph bounds"); + font.outline( + &gid, + &peridot_vg::sdf_generator::Transform2D::create_translation( + -glyph_metrics.origin.x + SDF_SIZE, + -glyph_metrics.origin.y - SDF_SIZE, + ), + &mut gen, + ) + .expect("Failed to render glyph outline"); + let figure_vertices = gen.build(); + let ( + figure_fill_triangle_points_count, + figure_fill_triangle_indices_count, + figure_curve_triangles_count, + outline_rects_count, + ) = figure_vertices + .iter() + .fold((0, 0, 0, 0), |(t, t2, t3, t4), f| { + ( + t + f.fill_triangle_points.len(), + t2 + f.fill_triangle_indices.len(), + t3 + f.curve_triangles.len(), + t4 + f.parabola_rects.len(), + ) + }); - let mut bp = peridot::BufferPrealloc::new(e.graphics()); - let flip_fill_rect = bp.add(peridot::BufferContent::vertex::< - [peridot::math::Vector2; 4], - >()); - let figures_fill_triangle_points_offset = - bp.add(peridot::BufferContent::vertices::< - peridot::math::Vector2, - >(figure_fill_triangle_points_count)); - let figures_fill_triangle_indices_offset = bp.add(peridot::BufferContent::indices::( - figure_fill_triangle_indices_count, - )); - let figure_curve_triangles_offset = bp.add(peridot::BufferContent::vertices::< - peridot::VertexUV2D, - >(figure_curve_triangles_count)); - let outline_rects_offset = bp.add(peridot::BufferContent::vertices::< - peridot_vg::sdf_generator::ParabolaRectVertex, - >(outline_rects_count * 6)); + let mut memory_manager = MemoryManager::new(e.graphics()); - let buffer = SharedRef::new( - memory_manager - .allocate_device_local_buffer( - e.graphics(), - bp.build_desc().and_usage(br::BufferUsage::TRANSFER_DEST), - ) - .expect("Failed to allocate buffer"), - ); - let mut buffer_init: RangedBuffer<_> = memory_manager - .allocate_upload_buffer( - e.graphics(), - bp.build_desc_custom_usage(br::BufferUsage::TRANSFER_SRC), - ) - .expect("Failed to allocate init buffer") - .into(); - let stencil_buffer = memory_manager - .allocate_device_local_image( + let mut bp = peridot::BufferPrealloc::new(e.graphics()); + let flip_fill_rect = bp.add(peridot::BufferContent::vertex::< + [peridot::math::Vector2; 4], + >()); + let figures_fill_triangle_points_offset = bp.add(peridot::BufferContent::vertices::< + peridot::math::Vector2, + >(figure_fill_triangle_points_count)); + let figures_fill_triangle_indices_offset = bp.add(peridot::BufferContent::indices::( + figure_fill_triangle_indices_count, + )); + let figure_curve_triangles_offset = bp.add(peridot::BufferContent::vertices::< + peridot::VertexUV2D, + >(figure_curve_triangles_count)); + let outline_rects_offset = bp.add(peridot::BufferContent::vertices::< + peridot_vg::sdf_generator::ParabolaRectVertex, + >(outline_rects_count * 6)); + + let buffer = SharedRef::new( + memory_manager + .allocate_device_local_buffer( e.graphics(), - br::ImageDesc::new(back_buffer_size.clone(), br::vk::VK_FORMAT_S8_UINT) - .as_depth_stencil_attachment(), + bp.build_desc().and_usage(br::BufferUsage::TRANSFER_DEST), ) - .expect("Failed to allocate stencil buffer"); - let stencil_buffer_view = SharedRef::new( - stencil_buffer - .subresource_range(br::AspectMask::STENCIL, 0..1, 0..1) - .view_builder() - .create() - .expect("Failed to create Stencil Buffer View"), - ); + .expect("Failed to allocate buffer"), + ); + let mut buffer_init: RangedBuffer<_> = memory_manager + .allocate_upload_buffer( + e.graphics(), + bp.build_desc_custom_usage(br::BufferUsage::TRANSFER_SRC), + ) + .expect("Failed to allocate init buffer") + .into(); + let mut stencil_buffer = memory_manager + .allocate_device_local_image( + e.graphics(), + br::ImageDesc::new(back_buffer_size.clone(), br::vk::VK_FORMAT_S8_UINT) + .as_depth_stencil_attachment(), + ) + .expect("Failed to allocate stencil buffer"); + let mut stencil_buffer_view = SharedRef::new( + stencil_buffer + .subresource_range(br::AspectMask::STENCIL, 0..1, 0..1) + .view_builder() + .create() + .expect("Failed to create Stencil Buffer View"), + ); - buffer_init - .0 - .guard_map(BufferMapMode::Write, |m| unsafe { - m.clone_slice_to( - flip_fill_rect as _, - &[ - peridot::math::Vector2(0.0f32, 0.0), - peridot::math::Vector2(1.0, 0.0), - peridot::math::Vector2(0.0, -1.0), - peridot::math::Vector2(1.0, -1.0), - ], - ); + buffer_init + .0 + .guard_map(BufferMapMode::Write, |m| unsafe { + m.clone_slice_to( + flip_fill_rect as _, + &[ + peridot::math::Vector2(0.0f32, 0.0), + peridot::math::Vector2(1.0, 0.0), + peridot::math::Vector2(0.0, -1.0), + peridot::math::Vector2(1.0, -1.0), + ], + ); - let s = m.slice_mut( - figures_fill_triangle_points_offset as _, - figure_fill_triangle_points_count, - ); - let si = m.slice_mut( - figures_fill_triangle_indices_offset as _, - figure_fill_triangle_indices_count, - ); - let c = m.slice_mut( - figure_curve_triangles_offset as _, - figure_curve_triangles_count, - ); - let o = m.slice_mut(outline_rects_offset as _, outline_rects_count * 6); - let (mut s_offset, mut si_offset, mut c_offset, mut o_offset) = (0, 0, 0, 0); - for f in figure_vertices.iter() { - s[s_offset..s_offset + f.fill_triangle_points.len()] - .clone_from_slice(&f.fill_triangle_points); - si[si_offset..si_offset + f.fill_triangle_indices.len()] - .copy_from_slice(&f.fill_triangle_indices); - c[c_offset..c_offset + f.curve_triangles.len()] - .clone_from_slice(&f.curve_triangles); - for pr in f.parabola_rects.iter() { - o[o_offset..o_offset + 6].clone_from_slice(&pr.make_vertices()); - o_offset += 6; - } - s_offset += f.fill_triangle_points.len(); - si_offset += f.fill_triangle_indices.len(); - c_offset += f.curve_triangles.len(); + let s = m.slice_mut( + figures_fill_triangle_points_offset as _, + figure_fill_triangle_points_count, + ); + let si = m.slice_mut( + figures_fill_triangle_indices_offset as _, + figure_fill_triangle_indices_count, + ); + let c = m.slice_mut( + figure_curve_triangles_offset as _, + figure_curve_triangles_count, + ); + let o = m.slice_mut(outline_rects_offset as _, outline_rects_count * 6); + let (mut s_offset, mut si_offset, mut c_offset, mut o_offset) = (0, 0, 0, 0); + for f in figure_vertices.iter() { + s[s_offset..s_offset + f.fill_triangle_points.len()] + .clone_from_slice(&f.fill_triangle_points); + si[si_offset..si_offset + f.fill_triangle_indices.len()] + .copy_from_slice(&f.fill_triangle_indices); + c[c_offset..c_offset + f.curve_triangles.len()] + .clone_from_slice(&f.curve_triangles); + for pr in f.parabola_rects.iter() { + o[o_offset..o_offset + 6].clone_from_slice(&pr.make_vertices()); + o_offset += 6; } - }) - .expect("Failed to set init data"); + s_offset += f.fill_triangle_points.len(); + si_offset += f.fill_triangle_indices.len(); + c_offset += f.curve_triangles.len(); + } + }) + .expect("Failed to set init data"); - { - let all_buffer = RangedBuffer::from(&*buffer); - let stencil_buffer = RangedImage::single_stencil_plane(stencil_buffer_view.image()); + { + let all_buffer = RangedBuffer::from(&*buffer); + let stencil_buffer = RangedImage::single_stencil_plane(stencil_buffer_view.image()); - let copy = all_buffer.byref_mirror_from(&buffer_init); + let copy = all_buffer.byref_mirror_from(&buffer_init); - let [all_buffer_in_barrier, all_buffer_out_barrier] = - all_buffer.clone().usage_barrier3( - BufferUsage::UNUSED, - BufferUsage::TRANSFER_DST, - BufferUsage::VERTEX_BUFFER | BufferUsage::INDEX_BUFFER, - ); - let in_barriers = [ - buffer_init - .make_ref() - .usage_barrier(BufferUsage::HOST_RW, BufferUsage::TRANSFER_SRC), - all_buffer_in_barrier, - ]; - let out_barriers = PipelineBarrier::new() - .with_barrier(all_buffer_out_barrier) - .with_barrier( - stencil_buffer - .barrier(br::ImageLayout::DepthStencilReadOnlyOpt.from_undefined()), - ) - .by_region(); + let [all_buffer_in_barrier, all_buffer_out_barrier] = all_buffer.clone().usage_barrier3( + BufferUsage::UNUSED, + BufferUsage::TRANSFER_DST, + BufferUsage::VERTEX_BUFFER | BufferUsage::INDEX_BUFFER, + ); + let in_barriers = [ + buffer_init + .make_ref() + .usage_barrier(BufferUsage::HOST_RW, BufferUsage::TRANSFER_SRC), + all_buffer_in_barrier, + ]; + let out_barriers = PipelineBarrier::new() + .with_barrier(all_buffer_out_barrier) + .with_barrier( + stencil_buffer.barrier(br::ImageLayout::DepthStencilReadOnlyOpt.from_undefined()), + ) + .by_region(); - copy.between(in_barriers, out_barriers) - .submit(e) - .expect("Failed to initialize resources"); - } + copy.between(in_barriers, out_barriers) + .submit(e) + .expect("Failed to initialize resources"); + } - let figures_fill_triangle_points_buffer = RangedBuffer::from_offset_length( - buffer.clone(), - figures_fill_triangle_points_offset, - core::mem::size_of::>() * figure_fill_triangle_points_count, - ); - let figures_fill_triangle_indices_buffer = RangedBuffer::from_offset_length( - buffer.clone(), - figures_fill_triangle_indices_offset, - core::mem::size_of::() * figure_fill_triangle_indices_count, - ); - let figures_curve_triangles_buffer = RangedBuffer::from_offset_length( - buffer.clone(), - figure_curve_triangles_offset, - core::mem::size_of::() * figure_curve_triangles_count, - ); - let outline_rects_buffer = RangedBuffer::from_offset_length( - buffer.clone(), - outline_rects_offset, - core::mem::size_of::() - * outline_rects_count, - ); - let flip_fill_rect_buffer = - RangedBuffer::for_type::<[peridot::math::Vector2; 4]>(buffer, flip_fill_rect as _); + let figures_fill_triangle_points_buffer = RangedBuffer::from_offset_length( + buffer.clone(), + figures_fill_triangle_points_offset, + core::mem::size_of::>() * figure_fill_triangle_points_count, + ); + let figures_fill_triangle_indices_buffer = RangedBuffer::from_offset_length( + buffer.clone(), + figures_fill_triangle_indices_offset, + core::mem::size_of::() * figure_fill_triangle_indices_count, + ); + let figures_curve_triangles_buffer = RangedBuffer::from_offset_length( + buffer.clone(), + figure_curve_triangles_offset, + core::mem::size_of::() * figure_curve_triangles_count, + ); + let outline_rects_buffer = RangedBuffer::from_offset_length( + buffer.clone(), + outline_rects_offset, + core::mem::size_of::() * outline_rects_count, + ); + let flip_fill_rect_buffer = + RangedBuffer::for_type::<[peridot::math::Vector2; 4]>(buffer, flip_fill_rect as _); - let sdf_renderer = TwoPassStencilSDFRenderer::new( - e, - e.back_buffer_format(), - e.requesting_back_buffer_layout().0, - e.requesting_back_buffer_layout().1, - back_buffer_size.clone().into(), - Self::SDF_SIZE, - ); + let mut sdf_renderer = TwoPassStencilSDFRenderer::new( + e, + e.back_buffer_format(), + e.requesting_back_buffer_layout().0, + e.requesting_back_buffer_layout().1, + back_buffer_size.clone().into(), + SDF_SIZE, + ); - let fb = e - .iter_back_buffers() - .map(|bb| { - br::FramebufferBuilder::new(&sdf_renderer.render_pass) - .with_attachment(bb.clone()) - .with_attachment(stencil_buffer_view.clone()) - .create() - }) - .collect::, _>>() - .expect("Failed to create Framebuffers"); + let mut backbuffer_resources = e.iter_back_buffers().cloned().collect::>(); + let mut fb = backbuffer_resources + .iter() + .map(|bb| { + br::FramebufferBuilder::new(&sdf_renderer.render_pass) + .with_attachment(bb) + .with_attachment(&stencil_buffer_view) + .create() + }) + .collect::, _>>() + .expect("Failed to create Framebuffers"); - let fill_triangle_groups: Vec<_> = figure_vertices - .iter() - .map(|f| { - ( - f.fill_triangle_points.len() as u32, - f.fill_triangle_indices.len() as u32, - ) + let fill_triangle_groups: Vec<_> = figure_vertices + .iter() + .map(|f| { + ( + f.fill_triangle_points.len() as u32, + f.fill_triangle_indices.len() as u32, + ) + }) + .collect(); + let mut buffers = TwoPassStencilSDFRendererBuffers { + fill_triangle_mesh: StandardIndexedMesh { + vertex_buffers: vec![figures_fill_triangle_points_buffer], + index_buffer: figures_fill_triangle_indices_buffer, + index_type: br::IndexType::U16, + vertex_count: 0, // ignored value + }, + fill_triangle_groups, + curve_triangles_mesh: StandardMesh { + vertex_buffers: vec![figures_curve_triangles_buffer], + vertex_count: figure_curve_triangles_count as _, + }, + outline_rects_mesh: StandardMesh { + vertex_buffers: vec![outline_rects_buffer], + vertex_count: (outline_rects_count * 6) as _, + }, + invert_fill_rect_mesh: StandardMesh { + vertex_buffers: vec![flip_fill_rect_buffer], + vertex_count: 4, + }, + }; + let mut cmd = peridot::CommandBundle::new( + e.graphics(), + peridot::CBSubmissionType::Graphics, + e.back_buffer_count(), + ) + .expect("Failed to create CommandBundle"); + for (cx, fb) in fb.iter().enumerate() { + sdf_renderer + .commands(fb, &buffers) + .execute_and_finish(unsafe { + cmd[cx] + .begin(e.graphics_device()) + .expect("Failed to begin recording commands") + .as_dyn_ref() }) - .collect(); - let buffers = TwoPassStencilSDFRendererBuffers { - fill_triangle_mesh: StandardIndexedMesh { - vertex_buffers: vec![figures_fill_triangle_points_buffer], - index_buffer: figures_fill_triangle_indices_buffer, - index_type: br::IndexType::U16, - vertex_count: 0, // ignored value - }, - fill_triangle_groups, - curve_triangles_mesh: StandardMesh { - vertex_buffers: vec![figures_curve_triangles_buffer], - vertex_count: figure_curve_triangles_count as _, - }, - outline_rects_mesh: StandardMesh { - vertex_buffers: vec![outline_rects_buffer], - vertex_count: (outline_rects_count * 6) as _, - }, - invert_fill_rect_mesh: StandardMesh { - vertex_buffers: vec![flip_fill_rect_buffer], - vertex_count: 4, - }, - }; - let mut cmd = peridot::CommandBundle::new( - e.graphics(), - peridot::CBSubmissionType::Graphics, - e.back_buffer_count(), - ) - .expect("Failed to create CommandBundle"); - for (cx, fb) in fb.iter().enumerate() { - sdf_renderer - .commands(fb, &buffers) - .execute_and_finish(unsafe { - cmd[cx] - .begin(e.graphics_device()) - .expect("Failed to begin recording commands") - .as_dyn_ref() - }) - .expect("Failed to record commands"); - } - - Self { - memory_manager, - buffers, - stencil_buffer_view, - sdf_renderer, - fb, - cmd, - ph: std::marker::PhantomData, - } + .expect("Failed to record commands"); } - fn update( - &mut self, - e: &mut Engine, - on_back_buffer_of: u32, - _delta_time: std::time::Duration, - ) { - e.do_render( - on_back_buffer_of, - None::, - br::EmptySubmissionBatch.with_command_buffers( - &self.cmd[on_back_buffer_of as usize..=on_back_buffer_of as usize], - ), - ) - .expect("Failed to present"); - } + /*Self { + memory_manager, + buffers, + stencil_buffer_view, + sdf_renderer, + fb, + cmd, + ph: std::marker::PhantomData, + }*/ - fn discard_back_buffer_resources(&mut self) { - self.fb.clear(); - } - fn on_resize(&mut self, e: &mut peridot::Engine, new_size: peridot::math::Vector2) { - // rebuild font meshes - let font = peridot_vg::DefaultFontProvider::new() - .expect("Failed to create font provider") - .best_match( - "MS UI Gothic", - &peridot_vg::FontProperties::default(), - 120.0, - ) - .expect("no suitable font"); - let gid = font.glyph_id('A').expect("no glyph contained"); - let mut gen = peridot_vg::SDFGenerator::new(1.0, Self::SDF_SIZE); - let glyph_metrics = font.bounds(&gid).expect("Failed to get glyph bounds"); - font.outline( - &gid, - &peridot_vg::sdf_generator::Transform2D::create_translation( - -glyph_metrics.origin.x + Self::SDF_SIZE, - -glyph_metrics.origin.y - Self::SDF_SIZE, - ), - &mut gen, - ) - .expect("Failed to render glyph outline"); - let figure_vertices = gen.build(); - let ( - figure_fill_triangle_points_count, - figure_fill_triangle_indices_count, - figure_curve_triangles_count, - outline_rects_count, - ) = figure_vertices - .iter() - .fold((0, 0, 0, 0), |(t, t2, t3, t4), f| { - ( - t + f.fill_triangle_points.len(), - t2 + f.fill_triangle_indices.len(), - t3 + f.curve_triangles.len(), - t4 + f.parabola_rects.len(), + while let Some(ev) = e.event_receivers().wait_for_event().await { + match ev { + peridot::Event::Shutdown => break, + peridot::Event::NextFrame => { + let fd = e.prepare_frame().expect("Failed to prepare frame"); + + e.do_render( + fd.backbuffer_index, + None::, + br::EmptySubmissionBatch.with_command_buffers( + &cmd[fd.backbuffer_index as usize..=fd.backbuffer_index as usize], + ), ) - }); + .expect("Failed to present"); + } + peridot::Event::Resize(new_size) => { + e.wait_for_last_rendering_completion(); - let mut bp = peridot::BufferPrealloc::new(e.graphics()); - let flip_fill_rect = bp.add(peridot::BufferContent::vertex::< - [peridot::math::Vector2; 4], - >()); - let figures_fill_triangle_points_offset = - bp.add(peridot::BufferContent::vertices::< - peridot::math::Vector2, - >(figure_fill_triangle_points_count)); - let figures_fill_triangle_indices_offset = bp.add(peridot::BufferContent::indices::( - figure_fill_triangle_indices_count, - )); - let figure_curve_triangles_offset = bp.add(peridot::BufferContent::vertices::< - peridot::VertexUV2D, - >(figure_curve_triangles_count)); - let outline_rects_offset = bp.add(peridot::BufferContent::vertices::< - peridot_vg::sdf_generator::ParabolaRectVertex, - >(outline_rects_count * 6)); + drop(fb); + drop(backbuffer_resources); - let buffer = SharedRef::new( - self.memory_manager - .allocate_device_local_buffer( - e.graphics(), - bp.build_desc().and_usage(br::BufferUsage::TRANSFER_DEST), - ) - .expect("Failed to allocate buffer"), - ); - let mut buffer_init: RangedBuffer<_> = self - .memory_manager - .allocate_upload_buffer( - e.graphics(), - bp.build_desc_custom_usage(br::BufferUsage::TRANSFER_SRC), - ) - .expect("Failed to allocate init buffer") - .into(); - let stencil_buffer = self - .memory_manager - .allocate_device_local_image( - e.graphics(), - br::ImageDesc::new( - peridot::math::Vector2(new_size.0 as u32, new_size.1 as u32), - br::vk::VK_FORMAT_S8_UINT, + e.resize_presenter_backbuffers(new_size); + + // rebuild font meshes + let font = peridot_vg::DefaultFontProvider::new() + .expect("Failed to create font provider") + .best_match( + "MS UI Gothic", + &peridot_vg::FontProperties::default(), + 120.0, + ) + .expect("no suitable font"); + let gid = font.glyph_id('A').expect("no glyph contained"); + let mut gen = peridot_vg::SDFGenerator::new(1.0, SDF_SIZE); + let glyph_metrics = font.bounds(&gid).expect("Failed to get glyph bounds"); + font.outline( + &gid, + &peridot_vg::sdf_generator::Transform2D::create_translation( + -glyph_metrics.origin.x + SDF_SIZE, + -glyph_metrics.origin.y - SDF_SIZE, + ), + &mut gen, ) - .as_depth_stencil_attachment(), - ) - .expect("Failed to allocate stencil buffer"); - self.stencil_buffer_view = SharedRef::new( - stencil_buffer - .subresource_range(br::AspectMask::STENCIL, 0..1, 0..1) - .view_builder() - .create() - .expect("Failed to create Stencil Buffer View"), - ); - self.fb = e - .iter_back_buffers() - .map(|bb| { - br::FramebufferBuilder::new(&self.sdf_renderer.render_pass) - .with_attachment(bb.clone()) - .with_attachment(self.stencil_buffer_view.clone()) - .create() - }) - .collect::, _>>() - .expect("Failed to create Framebuffers"); + .expect("Failed to render glyph outline"); + let figure_vertices = gen.build(); + let ( + figure_fill_triangle_points_count, + figure_fill_triangle_indices_count, + figure_curve_triangles_count, + outline_rects_count, + ) = figure_vertices + .iter() + .fold((0, 0, 0, 0), |(t, t2, t3, t4), f| { + ( + t + f.fill_triangle_points.len(), + t2 + f.fill_triangle_indices.len(), + t3 + f.curve_triangles.len(), + t4 + f.parabola_rects.len(), + ) + }); - buffer_init - .0 - .guard_map(BufferMapMode::Write, |m| unsafe { - m.clone_slice_to( - flip_fill_rect as _, - &[ - peridot::math::Vector2(0.0f32, 0.0), - peridot::math::Vector2(1.0, 0.0), - peridot::math::Vector2(0.0, -1.0), - peridot::math::Vector2(1.0, -1.0), - ], + sdf_renderer.resize( + e.graphics(), + peridot::math::Vector2(new_size.0 as _, new_size.1 as _), + SDF_SIZE, ); - let s = m.slice_mut( - figures_fill_triangle_points_offset as _, - figure_fill_triangle_points_count, + let mut bp = peridot::BufferPrealloc::new(e.graphics()); + let flip_fill_rect = bp.add(peridot::BufferContent::vertex::< + [peridot::math::Vector2; 4], + >()); + let figures_fill_triangle_points_offset = + bp.add(peridot::BufferContent::vertices::< + peridot::math::Vector2, + >(figure_fill_triangle_points_count)); + let figures_fill_triangle_indices_offset = bp.add( + peridot::BufferContent::indices::(figure_fill_triangle_indices_count), ); - let si = m.slice_mut( - figures_fill_triangle_indices_offset as _, - figure_fill_triangle_indices_count, + let figure_curve_triangles_offset = + bp.add(peridot::BufferContent::vertices::( + figure_curve_triangles_count, + )); + let outline_rects_offset = bp.add(peridot::BufferContent::vertices::< + peridot_vg::sdf_generator::ParabolaRectVertex, + >(outline_rects_count * 6)); + + let buffer = SharedRef::new( + memory_manager + .allocate_device_local_buffer( + e.graphics(), + bp.build_desc().and_usage(br::BufferUsage::TRANSFER_DEST), + ) + .expect("Failed to allocate buffer"), ); - let c = m.slice_mut( - figure_curve_triangles_offset as _, - figure_curve_triangles_count, + let mut buffer_init: RangedBuffer<_> = memory_manager + .allocate_upload_buffer( + e.graphics(), + bp.build_desc_custom_usage(br::BufferUsage::TRANSFER_SRC), + ) + .expect("Failed to allocate init buffer") + .into(); + stencil_buffer = memory_manager + .allocate_device_local_image( + e.graphics(), + br::ImageDesc::new( + peridot::math::Vector2(new_size.0 as u32, new_size.1 as u32), + br::vk::VK_FORMAT_S8_UINT, + ) + .as_depth_stencil_attachment(), + ) + .expect("Failed to allocate stencil buffer"); + stencil_buffer_view = SharedRef::new( + stencil_buffer + .subresource_range(br::AspectMask::STENCIL, 0..1, 0..1) + .view_builder() + .create() + .expect("Failed to create Stencil Buffer View"), ); - let o = m.slice_mut(outline_rects_offset as _, outline_rects_count * 6); - let (mut s_offset, mut si_offset, mut c_offset, mut o_offset) = (0, 0, 0, 0); - for f in figure_vertices.iter() { - s[s_offset..s_offset + f.fill_triangle_points.len()] - .clone_from_slice(&f.fill_triangle_points); - si[si_offset..si_offset + f.fill_triangle_indices.len()] - .copy_from_slice(&f.fill_triangle_indices); - c[c_offset..c_offset + f.curve_triangles.len()] - .clone_from_slice(&f.curve_triangles); - for pr in f.parabola_rects.iter() { - o[o_offset..o_offset + 6].clone_from_slice(&pr.make_vertices()); - o_offset += 6; - } - s_offset += f.fill_triangle_points.len(); - si_offset += f.fill_triangle_indices.len(); - c_offset += f.curve_triangles.len(); - } - }) - .expect("Failed to set init data"); + backbuffer_resources = e.iter_back_buffers().cloned().collect(); + fb = backbuffer_resources + .iter() + .map(|bb| { + br::FramebufferBuilder::new(&sdf_renderer.render_pass) + .with_attachment(bb) + .with_attachment(&stencil_buffer_view) + .create() + }) + .collect::, _>>() + .expect("Failed to create Framebuffers"); - { - let stg_copied_buffer = buffer_init.subslice_ref(0..bp.total_size() as _); - let all_buffer = RangedBuffer::from_offset_length(&*buffer, 0, bp.total_size() as _); - let stencil_buffer = - RangedImage::single_stencil_plane(self.stencil_buffer_view.image()); + buffer_init + .0 + .guard_map(BufferMapMode::Write, |m| unsafe { + m.clone_slice_to( + flip_fill_rect as _, + &[ + peridot::math::Vector2(0.0f32, 0.0), + peridot::math::Vector2(1.0, 0.0), + peridot::math::Vector2(0.0, -1.0), + peridot::math::Vector2(1.0, -1.0), + ], + ); - let copy = all_buffer.byref_mirror_from(&stg_copied_buffer); + let s = m.slice_mut( + figures_fill_triangle_points_offset as _, + figure_fill_triangle_points_count, + ); + let si = m.slice_mut( + figures_fill_triangle_indices_offset as _, + figure_fill_triangle_indices_count, + ); + let c = m.slice_mut( + figure_curve_triangles_offset as _, + figure_curve_triangles_count, + ); + let o = m.slice_mut(outline_rects_offset as _, outline_rects_count * 6); + let (mut s_offset, mut si_offset, mut c_offset, mut o_offset) = + (0, 0, 0, 0); + for f in figure_vertices.iter() { + s[s_offset..s_offset + f.fill_triangle_points.len()] + .clone_from_slice(&f.fill_triangle_points); + si[si_offset..si_offset + f.fill_triangle_indices.len()] + .copy_from_slice(&f.fill_triangle_indices); + c[c_offset..c_offset + f.curve_triangles.len()] + .clone_from_slice(&f.curve_triangles); + for pr in f.parabola_rects.iter() { + o[o_offset..o_offset + 6].clone_from_slice(&pr.make_vertices()); + o_offset += 6; + } + s_offset += f.fill_triangle_points.len(); + si_offset += f.fill_triangle_indices.len(); + c_offset += f.curve_triangles.len(); + } + }) + .expect("Failed to set init data"); - let [all_buffer_in_barrier, all_buffer_out_barrier] = - all_buffer.make_ref().usage_barrier3( - BufferUsage::UNUSED, - BufferUsage::TRANSFER_DST, - BufferUsage::VERTEX_BUFFER | BufferUsage::INDEX_BUFFER, - ); - let in_barriers = [ - stg_copied_buffer - .make_ref() - .usage_barrier(BufferUsage::HOST_RW, BufferUsage::TRANSFER_SRC), - all_buffer_in_barrier, - ]; - let out_barriers = PipelineBarrier::new() - .with_barrier(all_buffer_out_barrier) - .with_barrier( - stencil_buffer - .barrier(br::ImageLayout::DepthStencilReadOnlyOpt.from_undefined()), - ) - .by_region(); + { + let stg_copied_buffer = buffer_init.subslice_ref(0..bp.total_size() as _); + let all_buffer = + RangedBuffer::from_offset_length(&*buffer, 0, bp.total_size() as _); + let stencil_buffer = + RangedImage::single_stencil_plane(stencil_buffer_view.image()); - copy.between(in_barriers, out_barriers) - .submit(e) - .expect("Failed to initialize resources"); - } + let copy = all_buffer.byref_mirror_from(&stg_copied_buffer); - let figures_fill_triangle_points_buffer = RangedBuffer::from_offset_length( - buffer.clone(), - figures_fill_triangle_points_offset, - core::mem::size_of::>() * figure_fill_triangle_points_count, - ); - let figures_fill_triangle_indices_buffer = RangedBuffer::from_offset_length( - buffer.clone(), - figures_fill_triangle_indices_offset, - core::mem::size_of::() * figure_fill_triangle_indices_count, - ); - let figures_curve_triangles_buffer = RangedBuffer::from_offset_length( - buffer.clone(), - figure_curve_triangles_offset, - core::mem::size_of::() * figure_curve_triangles_count, - ); - let outline_rects_buffer = RangedBuffer::from_offset_length( - buffer.clone(), - outline_rects_offset, - core::mem::size_of::() - * outline_rects_count, - ); - let flip_fill_rect_buffer = - RangedBuffer::for_type::<[peridot::math::Vector2; 4]>(buffer, flip_fill_rect as _); + let [all_buffer_in_barrier, all_buffer_out_barrier] = + all_buffer.make_ref().usage_barrier3( + BufferUsage::UNUSED, + BufferUsage::TRANSFER_DST, + BufferUsage::VERTEX_BUFFER | BufferUsage::INDEX_BUFFER, + ); + let in_barriers = [ + stg_copied_buffer + .make_ref() + .usage_barrier(BufferUsage::HOST_RW, BufferUsage::TRANSFER_SRC), + all_buffer_in_barrier, + ]; + let out_barriers = PipelineBarrier::new() + .with_barrier(all_buffer_out_barrier) + .with_barrier( + stencil_buffer + .barrier(br::ImageLayout::DepthStencilReadOnlyOpt.from_undefined()), + ) + .by_region(); - self.sdf_renderer.resize( - e.graphics(), - peridot::math::Vector2(new_size.0 as _, new_size.1 as _), - Self::SDF_SIZE, - ); + copy.between(in_barriers, out_barriers) + .submit(e) + .expect("Failed to initialize resources"); + } - let fill_triangle_groups: Vec<_> = figure_vertices - .iter() - .map(|f| { - ( - f.fill_triangle_points.len() as u32, - f.fill_triangle_indices.len() as u32, + let figures_fill_triangle_points_buffer = RangedBuffer::from_offset_length( + buffer.clone(), + figures_fill_triangle_points_offset, + core::mem::size_of::>() + * figure_fill_triangle_points_count, + ); + let figures_fill_triangle_indices_buffer = RangedBuffer::from_offset_length( + buffer.clone(), + figures_fill_triangle_indices_offset, + core::mem::size_of::() * figure_fill_triangle_indices_count, + ); + let figures_curve_triangles_buffer = RangedBuffer::from_offset_length( + buffer.clone(), + figure_curve_triangles_offset, + core::mem::size_of::() * figure_curve_triangles_count, + ); + let outline_rects_buffer = RangedBuffer::from_offset_length( + buffer.clone(), + outline_rects_offset, + core::mem::size_of::() + * outline_rects_count, + ); + let flip_fill_rect_buffer = RangedBuffer::for_type::< + [peridot::math::Vector2; 4], + >(buffer, flip_fill_rect as _); + + let fill_triangle_groups: Vec<_> = figure_vertices + .iter() + .map(|f| { + ( + f.fill_triangle_points.len() as u32, + f.fill_triangle_indices.len() as u32, + ) + }) + .collect(); + buffers = TwoPassStencilSDFRendererBuffers { + fill_triangle_mesh: StandardIndexedMesh { + vertex_buffers: vec![figures_fill_triangle_points_buffer], + index_buffer: figures_fill_triangle_indices_buffer, + index_type: br::IndexType::U16, + vertex_count: 0, // ignored value + }, + fill_triangle_groups, + curve_triangles_mesh: StandardMesh { + vertex_buffers: vec![figures_curve_triangles_buffer], + vertex_count: figure_curve_triangles_count as _, + }, + outline_rects_mesh: StandardMesh { + vertex_buffers: vec![outline_rects_buffer], + vertex_count: (outline_rects_count * 6) as _, + }, + invert_fill_rect_mesh: StandardMesh { + vertex_buffers: vec![flip_fill_rect_buffer], + vertex_count: 4, + }, + }; + cmd = peridot::CommandBundle::new( + e.graphics(), + peridot::CBSubmissionType::Graphics, + e.back_buffer_count(), ) - }) - .collect(); - self.buffers = TwoPassStencilSDFRendererBuffers { - fill_triangle_mesh: StandardIndexedMesh { - vertex_buffers: vec![figures_fill_triangle_points_buffer], - index_buffer: figures_fill_triangle_indices_buffer, - index_type: br::IndexType::U16, - vertex_count: 0, // ignored value - }, - fill_triangle_groups, - curve_triangles_mesh: StandardMesh { - vertex_buffers: vec![figures_curve_triangles_buffer], - vertex_count: figure_curve_triangles_count as _, - }, - outline_rects_mesh: StandardMesh { - vertex_buffers: vec![outline_rects_buffer], - vertex_count: (outline_rects_count * 6) as _, - }, - invert_fill_rect_mesh: StandardMesh { - vertex_buffers: vec![flip_fill_rect_buffer], - vertex_count: 4, - }, - }; - self.cmd = peridot::CommandBundle::new( - e.graphics(), - peridot::CBSubmissionType::Graphics, - e.back_buffer_count(), - ) - .expect("Failed to create CommandBundle"); - for (cx, fb) in self.fb.iter().enumerate() { - self.sdf_renderer - .commands(fb, &self.buffers) - .execute_and_finish(unsafe { - self.cmd[cx] - .begin(e.graphics_device()) - .expect("Failed to begin recording commands") - .as_dyn_ref() - }) - .expect("Failed to record commands"); + .expect("Failed to create CommandBundle"); + for (cx, fb) in fb.iter().enumerate() { + sdf_renderer + .commands(fb, &buffers) + .execute_and_finish(unsafe { + cmd[cx] + .begin(e.graphics_device()) + .expect("Failed to begin recording commands") + .as_dyn_ref() + }) + .expect("Failed to record commands"); + } + } } } + + unsafe { + e.graphics().device().wait().expect("Failed to wait works"); + } } diff --git a/examples/vg/src/lib.rs b/examples/vg/src/lib.rs index b24ef327..44d7c8bf 100644 --- a/examples/vg/src/lib.rs +++ b/examples/vg/src/lib.rs @@ -20,7 +20,6 @@ use peridot_vg as pvg; use peridot_vg::{FlatPathBuilder, PathBuilder}; use pvg::{FontProvider, FontProviderConstruct, RenderVG}; use std::borrow::Cow; -use std::marker::PhantomData; #[derive(SpecConstantStorage)] #[repr(C)] @@ -38,554 +37,538 @@ const unsafe fn as_u8_slice(slice: &[T]) -> &[u8] { ) } -pub struct Game { - memory_manager: MemoryManager, - render_pass: br::RenderPassObject, - framebuffers: Vec>, - render_cb: CommandBundle, - _bufview: br::BufferViewObject>, - _bufview2: br::BufferViewObject>, - _descriptors: ( - br::DescriptorSetLayoutObject, - br::DescriptorPoolObject, - ), - render_vgs: - [pvg::RenderVG>; 2], - target_size: peridot::math::Vector2F32, - ph: PhantomData<*const PL>, -} -impl peridot::FeatureRequests for Game {} -impl peridot::EngineEvents for Game { - fn init(e: &mut peridot::Engine) -> Self { - let font_provider = - pvg::DefaultFontProvider::new().expect("FontProvider initialization error"); - let font = font_provider - .best_match("sans-serif", &pvg::FontProperties::default(), 18.0) - .expect("No Fonts"); - let mut ctx = pvg::Context::new(1.0); - ctx.text(&font, "Hello, World!|Opaque") - .expect("Text Rendering failed"); - { - let mut f0 = ctx.begin_figure(pvg::FillRule::Winding); - f0.move_to(Vector2(10.0, -10.0).into()); - f0.quadratic_bezier_to(Vector2(100.0, -35.0).into(), Vector2(100.0, -100.0).into()); - f0.end(); - } - /*{ - let mut f = ctx.begin_figure(pvg::FillRule::Winding); - f.move_to(Vector2(200.0, -200.0 - 10.0).into()); - f.line_to(Vector2(200.0, -200.0 - 90.0).into()); - f.quadratic_bezier_to(Vector2(200.0, -300.0).into(), Vector2(210.0, -300.0).into()); - f.line_to(Vector2(340.0, -300.0).into()); - f.quadratic_bezier_to(Vector2(350.0, -300.0).into(), Vector2(350.0, -290.0).into()); - f.line_to(Vector2(350.0, -210.0).into()); - f.quadratic_bezier_to(Vector2(350.0, -200.0).into(), Vector2(340.0, -200.0).into()); - f.line_to(Vector2(210.0, -200.0).into()); - f.quadratic_bezier_to(Vector2(200.0, -200.0).into(), Vector2(200.0, -210.0).into()); - f.close(); f.end(); - }*/ - let mut ctx2 = pvg::Context::new(1.0); - /*{ - let mut f0 = ctx2.begin_figure(pvg::FillRule::Winding); - f0.move_to(Vector2(10.0, -10.0).into()); - /*f0.cubic_bezier_to(Vector2(100.0, -35.0).into(), Vector2(35.0, -80.0).into(), - Vector2(100.0, -100.0).into());*/ - f0.quadratic_bezier_to(Vector2(100.0, -30.0).into(), Vector2(30.0, -100.0).into()); - // f0.quadratic_bezier_to(Vector2(200.0, -100.0).into(), Vector2(80.0, -60.0).into()); - // f0.stroke_outline(20.0); - // f0.close(); - f0.end(); - }*/ - /*{ - let mut sp = pvg::StrokePathBuilder::new(1.0); - sp.move_to(Vector2(200.0, -200.0 - 10.0).into()); - sp.line_to(Vector2(200.0, -200.0 - 90.0).into()); - sp.quadratic_bezier_to(Vector2(200.0, -300.0).into(), Vector2(210.0, -300.0).into()); - sp.line_to(Vector2(340.0, -300.0).into()); - sp.quadratic_bezier_to(Vector2(350.0, -300.0).into(), Vector2(350.0, -290.0).into()); - sp.line_to(Vector2(350.0, -210.0).into()); - sp.quadratic_bezier_to(Vector2(350.0, -200.0).into(), Vector2(340.0, -200.0).into()); - sp.line_to(Vector2(210.0, -200.0).into()); - sp.quadratic_bezier_to(Vector2(200.0, -200.0).into(), Vector2(200.0, -210.0).into()); - sp.close(); - let mut f = ctx2.begin_figure(vg::FillRule::EvenOdd); - sp.sink_widened(&mut f); - f.end(); - }*/ - { - let mut f = ctx2.begin_figure(pvg::FillRule::Winding); - f.move_to(Vector2(200.0, -200.0 - 10.0).into()); - f.line_to(Vector2(200.0, -200.0 - 90.0).into()); - f.quadratic_bezier_to(Vector2(200.0, -300.0).into(), Vector2(210.0, -300.0).into()); - f.line_to(Vector2(340.0, -300.0).into()); - f.quadratic_bezier_to(Vector2(350.0, -300.0).into(), Vector2(350.0, -290.0).into()); - f.line_to(Vector2(350.0, -210.0).into()); - f.quadratic_bezier_to(Vector2(350.0, -200.0).into(), Vector2(340.0, -200.0).into()); - f.line_to(Vector2(210.0, -200.0).into()); - f.quadratic_bezier_to(Vector2(200.0, -200.0).into(), Vector2(200.0, -210.0).into()); - f.close(); - f.end(); - } - - let mut bp = BufferPrealloc::new(&e.graphics()); - let vg_offs = ctx.prealloc(&mut bp); - let vg_offs2 = ctx.prealloc(&mut bp); +pub async fn game_main(e: &mut peridot::Engine) { + let font_provider = pvg::DefaultFontProvider::new().expect("FontProvider initialization error"); + let font = font_provider + .best_match("sans-serif", &pvg::FontProperties::default(), 18.0) + .expect("No Fonts"); + let mut ctx = pvg::Context::new(1.0); + ctx.text(&font, "Hello, World!|Opaque") + .expect("Text Rendering failed"); + { + let mut f0 = ctx.begin_figure(pvg::FillRule::Winding); + f0.move_to(Vector2(10.0, -10.0).into()); + f0.quadratic_bezier_to(Vector2(100.0, -35.0).into(), Vector2(100.0, -100.0).into()); + f0.end(); + } + /*{ + let mut f = ctx.begin_figure(pvg::FillRule::Winding); + f.move_to(Vector2(200.0, -200.0 - 10.0).into()); + f.line_to(Vector2(200.0, -200.0 - 90.0).into()); + f.quadratic_bezier_to(Vector2(200.0, -300.0).into(), Vector2(210.0, -300.0).into()); + f.line_to(Vector2(340.0, -300.0).into()); + f.quadratic_bezier_to(Vector2(350.0, -300.0).into(), Vector2(350.0, -290.0).into()); + f.line_to(Vector2(350.0, -210.0).into()); + f.quadratic_bezier_to(Vector2(350.0, -200.0).into(), Vector2(340.0, -200.0).into()); + f.line_to(Vector2(210.0, -200.0).into()); + f.quadratic_bezier_to(Vector2(200.0, -200.0).into(), Vector2(200.0, -210.0).into()); + f.close(); f.end(); + }*/ + let mut ctx2 = pvg::Context::new(1.0); + /*{ + let mut f0 = ctx2.begin_figure(pvg::FillRule::Winding); + f0.move_to(Vector2(10.0, -10.0).into()); + /*f0.cubic_bezier_to(Vector2(100.0, -35.0).into(), Vector2(35.0, -80.0).into(), + Vector2(100.0, -100.0).into());*/ + f0.quadratic_bezier_to(Vector2(100.0, -30.0).into(), Vector2(30.0, -100.0).into()); + // f0.quadratic_bezier_to(Vector2(200.0, -100.0).into(), Vector2(80.0, -60.0).into()); + // f0.stroke_outline(20.0); + // f0.close(); + f0.end(); + }*/ + /*{ + let mut sp = pvg::StrokePathBuilder::new(1.0); + sp.move_to(Vector2(200.0, -200.0 - 10.0).into()); + sp.line_to(Vector2(200.0, -200.0 - 90.0).into()); + sp.quadratic_bezier_to(Vector2(200.0, -300.0).into(), Vector2(210.0, -300.0).into()); + sp.line_to(Vector2(340.0, -300.0).into()); + sp.quadratic_bezier_to(Vector2(350.0, -300.0).into(), Vector2(350.0, -290.0).into()); + sp.line_to(Vector2(350.0, -210.0).into()); + sp.quadratic_bezier_to(Vector2(350.0, -200.0).into(), Vector2(340.0, -200.0).into()); + sp.line_to(Vector2(210.0, -200.0).into()); + sp.quadratic_bezier_to(Vector2(200.0, -200.0).into(), Vector2(200.0, -210.0).into()); + sp.close(); + let mut f = ctx2.begin_figure(vg::FillRule::EvenOdd); + sp.sink_widened(&mut f); + f.end(); + }*/ + { + let mut f = ctx2.begin_figure(pvg::FillRule::Winding); + f.move_to(Vector2(200.0, -200.0 - 10.0).into()); + f.line_to(Vector2(200.0, -200.0 - 90.0).into()); + f.quadratic_bezier_to(Vector2(200.0, -300.0).into(), Vector2(210.0, -300.0).into()); + f.line_to(Vector2(340.0, -300.0).into()); + f.quadratic_bezier_to(Vector2(350.0, -300.0).into(), Vector2(350.0, -290.0).into()); + f.line_to(Vector2(350.0, -210.0).into()); + f.quadratic_bezier_to(Vector2(350.0, -200.0).into(), Vector2(340.0, -200.0).into()); + f.line_to(Vector2(210.0, -200.0).into()); + f.quadratic_bezier_to(Vector2(200.0, -200.0).into(), Vector2(200.0, -210.0).into()); + f.close(); + f.end(); + } - let mut memory_manager = MemoryManager::new(e.graphics()); - let buffer = memory_manager - .allocate_device_local_buffer( - e.graphics(), - bp.build_desc().and_usage(br::BufferUsage::TRANSFER_DEST), - ) - .expect("Buffer Allocation"); - let buf_length = buffer.byte_length(); - let buffer = RangedBuffer::from_offset_length(SharedRef::new(buffer), 0, buf_length); - let mut stg_buffer: RangedBuffer<_> = memory_manager - .allocate_upload_buffer( - e.graphics(), - bp.build_desc_custom_usage(br::BufferUsage::TRANSFER_SRC), - ) - .expect("StgBuffer Allocation") - .into(); - - let rt_size = e - .back_buffer(0) - .expect("no back-buffers?") - .image() - .size() - .wh(); - let msaa_count = br::vk::VK_SAMPLE_COUNT_4_BIT; - let msaa_texture = memory_manager - .allocate_device_local_image( - e.graphics(), - br::ImageDesc::new(rt_size.clone(), e.back_buffer_format()) - .as_color_attachment() - .as_transient_attachment() - .sample_counts(msaa_count), - ) - .expect("Failed to create msaa render target"); - let msaa_texture = SharedRef::new( - msaa_texture - .subresource_range(br::AspectMask::COLOR, 0..1, 0..1) - .view_builder() - .create() - .expect("Failed to create msaa render target view"), - ); + let mut bp = BufferPrealloc::new(&e.graphics()); + let vg_offs = ctx.prealloc(&mut bp); + let vg_offs2 = ctx.prealloc(&mut bp); - let (vg_renderer_params, vg_renderer_params2) = stg_buffer - .0 - .guard_map(BufferMapMode::Write, |m| unsafe { - let p0 = ctx.write_data_into(m.ptr().as_ptr(), vg_offs); - let p1 = ctx2.write_data_into(m.ptr().as_ptr(), vg_offs2); - return (p0, p1); - }) - .expect("StgMem Initialization"); - - let bufview = buffer - .0 - .clone() - .create_view( - br::vk::VK_FORMAT_R32G32B32A32_SFLOAT, - vg_renderer_params.transforms_byterange(), - ) - .expect("Creating Transform BufferView"); - let bufview2 = buffer - .0 - .clone() - .create_view( - br::vk::VK_FORMAT_R32G32B32A32_SFLOAT, - vg_renderer_params2.transforms_byterange(), - ) - .expect("Creating Transform BufferView 2"); + let mut memory_manager = MemoryManager::new(e.graphics()); + let buffer = memory_manager + .allocate_device_local_buffer( + e.graphics(), + bp.build_desc().and_usage(br::BufferUsage::TRANSFER_DEST), + ) + .expect("Buffer Allocation"); + let buf_length = buffer.byte_length(); + let buffer = RangedBuffer::from_offset_length(SharedRef::new(buffer), 0, buf_length); + let mut stg_buffer: RangedBuffer<_> = memory_manager + .allocate_upload_buffer( + e.graphics(), + bp.build_desc_custom_usage(br::BufferUsage::TRANSFER_SRC), + ) + .expect("StgBuffer Allocation") + .into(); + + let rt_size = e + .back_buffer(0) + .expect("no back-buffers?") + .image() + .size() + .wh(); + let msaa_count = br::vk::VK_SAMPLE_COUNT_4_BIT; + let msaa_texture = memory_manager + .allocate_device_local_image( + e.graphics(), + br::ImageDesc::new(rt_size.clone(), e.back_buffer_format()) + .as_color_attachment() + .as_transient_attachment() + .sample_counts(msaa_count), + ) + .expect("Failed to create msaa render target"); + let mut msaa_texture = SharedRef::new( + msaa_texture + .subresource_range(br::AspectMask::COLOR, 0..1, 0..1) + .view_builder() + .create() + .expect("Failed to create msaa render target view"), + ); + + let (vg_renderer_params, vg_renderer_params2) = stg_buffer + .0 + .guard_map(BufferMapMode::Write, |m| unsafe { + let p0 = ctx.write_data_into(m.ptr().as_ptr(), vg_offs); + let p1 = ctx2.write_data_into(m.ptr().as_ptr(), vg_offs2); + return (p0, p1); + }) + .expect("StgMem Initialization"); + + let bufview = buffer + .0 + .clone() + .create_view( + br::vk::VK_FORMAT_R32G32B32A32_SFLOAT, + vg_renderer_params.transforms_byterange(), + ) + .expect("Creating Transform BufferView"); + let bufview2 = buffer + .0 + .clone() + .create_view( + br::vk::VK_FORMAT_R32G32B32A32_SFLOAT, + vg_renderer_params2.transforms_byterange(), + ) + .expect("Creating Transform BufferView 2"); - { - let copy = buffer.byref_mirror_from(&stg_buffer); + { + let copy = buffer.byref_mirror_from(&stg_buffer); - let [all_buffer_in_barrier, all_buffer_out_barrier] = buffer.make_ref().usage_barrier3( - BufferUsage::UNUSED, - BufferUsage::TRANSFER_DST, - BufferUsage::VERTEX_BUFFER - | BufferUsage::INDEX_BUFFER - | BufferUsage::VERTEX_STORAGE_RO, + let [all_buffer_in_barrier, all_buffer_out_barrier] = buffer.make_ref().usage_barrier3( + BufferUsage::UNUSED, + BufferUsage::TRANSFER_DST, + BufferUsage::VERTEX_BUFFER | BufferUsage::INDEX_BUFFER | BufferUsage::VERTEX_STORAGE_RO, + ); + let in_barrier = PipelineBarrier::new() + .with_barrier( + stg_buffer + .make_ref() + .usage_barrier(BufferUsage::HOST_RW, BufferUsage::TRANSFER_SRC), + ) + .with_barrier(all_buffer_in_barrier); + let out_barrier = PipelineBarrier::new() + .with_barrier(all_buffer_out_barrier) + .with_barrier( + RangedImage::single_color_plane(msaa_texture.image()) + .barrier(br::ImageLayout::ColorAttachmentOpt.from_undefined()), ); - let in_barrier = PipelineBarrier::new() - .with_barrier( - stg_buffer - .make_ref() - .usage_barrier(BufferUsage::HOST_RW, BufferUsage::TRANSFER_SRC), - ) - .with_barrier(all_buffer_in_barrier); - let out_barrier = PipelineBarrier::new() - .with_barrier(all_buffer_out_barrier) - .with_barrier( - RangedImage::single_color_plane(msaa_texture.image()) - .barrier(br::ImageLayout::ColorAttachmentOpt.from_undefined()), - ); - copy.between(in_barrier, out_barrier) - .submit(e) - .expect("ImmResource Initialization"); - } + copy.between(in_barrier, out_barrier) + .submit(e) + .expect("ImmResource Initialization"); + } - let attachments = [ - e.back_buffer_attachment_desc() - .color_memory_op(br::LoadOp::DontCare, br::StoreOp::Store), - br::AttachmentDescription::new( - e.back_buffer_format(), - br::ImageLayout::ColorAttachmentOpt, - br::ImageLayout::ColorAttachmentOpt, - ) - .color_memory_op(br::LoadOp::Clear, br::StoreOp::DontCare) - .samples(msaa_count), - ]; - let color_outputs = [br::AttachmentReference::new( - 1, + let attachments = [ + e.back_buffer_attachment_desc() + .color_memory_op(br::LoadOp::DontCare, br::StoreOp::Store), + br::AttachmentDescription::new( + e.back_buffer_format(), br::ImageLayout::ColorAttachmentOpt, - )]; - let color_resolves = [br::AttachmentReference::new( - 0, br::ImageLayout::ColorAttachmentOpt, - )]; - let color_subpass = - br::SubpassDescription::new().color_attachments(&color_outputs, &color_resolves); - let color_subpass_enter_dep = br::vk::VkSubpassDependency { - srcSubpass: br::vk::VK_SUBPASS_EXTERNAL, - dstSubpass: 0, - srcStageMask: br::PipelineStageFlags::BOTTOM_OF_PIPE.0, - dstStageMask: br::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT.0, - srcAccessMask: br::AccessFlags::MEMORY.read, - dstAccessMask: br::AccessFlags::COLOR_ATTACHMENT.write, - dependencyFlags: 0, - }; - let color_subpass_leave_dep = br::vk::VkSubpassDependency { - srcSubpass: 0, - dstSubpass: br::vk::VK_SUBPASS_EXTERNAL, - srcStageMask: br::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT.0, - dstStageMask: br::PipelineStageFlags::TOP_OF_PIPE.0, - srcAccessMask: br::AccessFlags::COLOR_ATTACHMENT.write, - dstAccessMask: br::AccessFlags::MEMORY.read, - dependencyFlags: 0, - }; - let render_pass = br::RenderPassBuilder::new( - &attachments, - &[color_subpass], - &[color_subpass_enter_dep, color_subpass_leave_dep], ) - .create(e.graphics_device().clone()) - .expect("Failed to create render pass"); - - let screen_size = e.back_buffer(0).expect("no backbuffer").image().size().wh(); - let framebuffers = e - .iter_back_buffers() - .map(|bb| { - br::FramebufferBuilder::new(&render_pass) - .with_attachment(bb.clone()) - .with_attachment(msaa_texture.clone()) - .create() - }) - .collect::, _>>() - .expect("Framebuffer Creation"); - - let dsl = br::DescriptorSetLayoutBuilder::new(&[br::DescriptorType::UniformTexelBuffer - .make_binding(0, 1) - .only_for_vertex()]) - .create(e.graphics().device().clone()) - .expect("DescriptorSetLayout Creation"); - let mut dp = br::DescriptorPoolBuilder::new( - 2, - &[br::DescriptorType::UniformTexelBuffer.make_size(2)], + .color_memory_op(br::LoadOp::Clear, br::StoreOp::DontCare) + .samples(msaa_count), + ]; + let color_outputs = [br::AttachmentReference::new( + 1, + br::ImageLayout::ColorAttachmentOpt, + )]; + let color_resolves = [br::AttachmentReference::new( + 0, + br::ImageLayout::ColorAttachmentOpt, + )]; + let color_subpass = + br::SubpassDescription::new().color_attachments(&color_outputs, &color_resolves); + let color_subpass_enter_dep = br::vk::VkSubpassDependency { + srcSubpass: br::vk::VK_SUBPASS_EXTERNAL, + dstSubpass: 0, + srcStageMask: br::PipelineStageFlags::BOTTOM_OF_PIPE.0, + dstStageMask: br::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT.0, + srcAccessMask: br::AccessFlags::MEMORY.read, + dstAccessMask: br::AccessFlags::COLOR_ATTACHMENT.write, + dependencyFlags: 0, + }; + let color_subpass_leave_dep = br::vk::VkSubpassDependency { + srcSubpass: 0, + dstSubpass: br::vk::VK_SUBPASS_EXTERNAL, + srcStageMask: br::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT.0, + dstStageMask: br::PipelineStageFlags::TOP_OF_PIPE.0, + srcAccessMask: br::AccessFlags::COLOR_ATTACHMENT.write, + dstAccessMask: br::AccessFlags::MEMORY.read, + dependencyFlags: 0, + }; + let render_pass = br::RenderPassBuilder::new( + &attachments, + &[color_subpass], + &[color_subpass_enter_dep, color_subpass_leave_dep], + ) + .create(e.graphics_device().clone()) + .expect("Failed to create render pass"); + + let screen_size = e.back_buffer(0).expect("no backbuffer").image().size().wh(); + let mut backbuffer_resources = e.iter_back_buffers().cloned().collect::>(); + let mut framebuffers = backbuffer_resources + .iter() + .map(|bb| { + br::FramebufferBuilder::new(&render_pass) + .with_attachment(bb) + .with_attachment(&msaa_texture) + .create() + }) + .collect::, _>>() + .expect("Framebuffer Creation"); + + let dsl = br::DescriptorSetLayoutBuilder::new(&[br::DescriptorType::UniformTexelBuffer + .make_binding(0, 1) + .only_for_vertex()]) + .create(e.graphics().device().clone()) + .expect("DescriptorSetLayout Creation"); + let mut dp = + br::DescriptorPoolBuilder::new(2, &[br::DescriptorType::UniformTexelBuffer.make_size(2)]) + .create(e.graphics().device().clone()) + .expect("DescriptorPool Creation"); + let [desc_interior, desc_curve] = dp + .alloc_array(&[ + br::DescriptorSetLayoutObjectRef::new(&dsl), + br::DescriptorSetLayoutObjectRef::new(&dsl), + ]) + .expect("DescriptorSet Allocation"); + + e.graphics().device().update_descriptor_sets( + &[ + desc_interior + .binding_at(0) + .write(br::DescriptorContents::UniformTexelBuffer(vec![ + br::VkHandleRef::new(&bufview), + ])), + desc_curve + .binding_at(1) + .write(br::DescriptorContents::UniformTexelBuffer(vec![ + br::VkHandleRef::new(&bufview2), + ])), + ], + &[], + ); + + let mut shader = PvpShaderModules::new( + e.graphics().device(), + e.load("shaders.interiorColorFixed") + .expect("Loading PvpContainer"), + ) + .expect("Creating Shader"); + let mut curve_shader = PvpShaderModules::new( + e.graphics().device(), + e.load("shaders.curveColorFixed") + .expect("Loading CurveShader"), + ) + .expect("Creating CurveShader"); + debug!("ScreenSize: {screen_size:?}"); + let sc = [screen_size.clone().into_rect(br::vk::VkOffset2D::ZERO)]; + let vp = [sc[0].make_viewport(0.0..1.0)]; + let pl = SharedRef::new( + br::PipelineLayoutBuilder::new( + &[br::DescriptorSetLayoutObjectRef::new(&dsl)], + &[br::PushConstantRange::new( + br::ShaderStage::VERTEX, + 0..4 * 4, + )], ) .create(e.graphics().device().clone()) - .expect("DescriptorPool Creation"); - let [desc_interior, desc_curve] = dp - .alloc_array(&[ - br::DescriptorSetLayoutObjectRef::new(&dsl), - br::DescriptorSetLayoutObjectRef::new(&dsl), - ]) - .expect("DescriptorSet Allocation"); - - e.graphics().device().update_descriptor_sets( - &[ - desc_interior - .binding_at(0) - .write(br::DescriptorContents::UniformTexelBuffer(vec![ - br::VkHandleRef::new(&bufview), - ])), - desc_curve - .binding_at(1) - .write(br::DescriptorContents::UniformTexelBuffer(vec![ - br::VkHandleRef::new(&bufview2), - ])), - ], - &[], - ); - - let mut shader = PvpShaderModules::new( - e.graphics().device(), - e.load("shaders.interiorColorFixed") - .expect("Loading PvpContainer"), + .expect("Create PipelineLayout"), + ); + let spc_map = &[ + br::vk::VkSpecializationMapEntry { + constantID: 0, + offset: 0, + size: 4, + }, + br::vk::VkSpecializationMapEntry { + constantID: 1, + offset: 4, + size: 4, + }, + ]; + shader.set_vertex_spec_constants( + Cow::Borrowed(spc_map), + Cow::Borrowed(unsafe { as_u8_slice(&pvg::renderer_pivot::LEFT_TOP[..]) }), + ); + curve_shader.set_vertex_spec_constants( + Cow::Borrowed(spc_map), + Cow::Borrowed(unsafe { as_u8_slice(&pvg::renderer_pivot::LEFT_TOP[..]) }), + ); + + let (color1_emap, color1_values) = VgRendererFragmentFixedColor { + r: 1.0, + g: 0.5, + b: 0.0, + a: 1.0, + } + .as_pair(); + // TODO: このcloneなんとかしたい + shader.set_fragment_spec_constants(color1_emap.clone(), color1_values.clone()); + curve_shader.set_fragment_spec_constants(color1_emap, color1_values); + let interior_vertex_processing = + shader.generate_vps(br::vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST); + let curve_vertex_processing = + curve_shader.generate_vps(br::vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST); + + let mut gpb = br::NonDerivedGraphicsPipelineBuilder::new( + &pl, + render_pass.subpass(0), + interior_vertex_processing, + ); + gpb.multisample_state(Some({ + let mut state = br::MultisampleState::new(); + state.rasterization_samples(msaa_count as _); + + state + })) + .viewport_scissors( + br::DynamicArrayState::Static(&vp), + br::DynamicArrayState::Static(&sc), + ) + .set_attachment_blends(vec![ColorAttachmentBlending::PREMULTIPLIED_ALPHA.into_vk()]); + let gp = LayoutedPipeline::combine( + gpb.create( + e.graphics().device().clone(), + None::<&br::PipelineCacheObject>, ) - .expect("Creating Shader"); - let mut curve_shader = PvpShaderModules::new( - e.graphics().device(), - e.load("shaders.curveColorFixed") - .expect("Loading CurveShader"), + .expect("Create GraphicsPipeline"), + pl.clone(), + ); + + let (color2_layout, color2_values) = VgRendererFragmentFixedColor { + r: 0.0, + g: 0.5, + b: 1.0, + a: 1.0, + } + .as_pair(); + gpb.vertex_processing_mut() + .shader_stages_mut() + .set_fragment_spec_constants(color2_layout.as_ref(), &color2_values); + let gp2 = LayoutedPipeline::combine( + gpb.create( + e.graphics().device().clone(), + None::<&br::PipelineCacheObject>, ) - .expect("Creating CurveShader"); - debug!("ScreenSize: {screen_size:?}"); - let sc = [screen_size.clone().into_rect(br::vk::VkOffset2D::ZERO)]; - let vp = [sc[0].make_viewport(0.0..1.0)]; - let pl = SharedRef::new( - br::PipelineLayoutBuilder::new( - &[br::DescriptorSetLayoutObjectRef::new(&dsl)], - &[br::PushConstantRange::new( - br::ShaderStage::VERTEX, - 0..4 * 4, - )], - ) - .create(e.graphics().device().clone()) - .expect("Create PipelineLayout"), - ); - let spc_map = &[ - br::vk::VkSpecializationMapEntry { - constantID: 0, - offset: 0, - size: 4, - }, - br::vk::VkSpecializationMapEntry { - constantID: 1, - offset: 4, - size: 4, - }, - ]; - shader.set_vertex_spec_constants( - Cow::Borrowed(spc_map), - Cow::Borrowed(unsafe { as_u8_slice(&pvg::renderer_pivot::LEFT_TOP[..]) }), - ); - curve_shader.set_vertex_spec_constants( - Cow::Borrowed(spc_map), - Cow::Borrowed(unsafe { as_u8_slice(&pvg::renderer_pivot::LEFT_TOP[..]) }), - ); - - let (color1_emap, color1_values) = VgRendererFragmentFixedColor { - r: 1.0, - g: 0.5, - b: 0.0, - a: 1.0, - } - .as_pair(); - // TODO: このcloneなんとかしたい - shader.set_fragment_spec_constants(color1_emap.clone(), color1_values.clone()); - curve_shader.set_fragment_spec_constants(color1_emap, color1_values); - let interior_vertex_processing = - shader.generate_vps(br::vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST); - let curve_vertex_processing = - curve_shader.generate_vps(br::vk::VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST); - - let mut gpb = br::NonDerivedGraphicsPipelineBuilder::new( - &pl, - render_pass.subpass(0), - interior_vertex_processing, - ); - gpb.multisample_state(Some({ - let mut state = br::MultisampleState::new(); - state.rasterization_samples(msaa_count as _); - - state - })) - .viewport_scissors( - br::DynamicArrayState::Static(&vp), - br::DynamicArrayState::Static(&sc), + .expect("Creating GraphicsPipeline2"), + pl.clone(), + ); + gpb.vertex_processing(curve_vertex_processing); + let gp_curve = LayoutedPipeline::combine( + gpb.create( + e.graphics().device().clone(), + None::<&br::PipelineCacheObject>, ) - .set_attachment_blends(vec![ColorAttachmentBlending::PREMULTIPLIED_ALPHA.into_vk()]); - let gp = LayoutedPipeline::combine( - gpb.create( - e.graphics().device().clone(), - None::<&br::PipelineCacheObject>, - ) - .expect("Create GraphicsPipeline"), - pl.clone(), - ); - - let (color2_layout, color2_values) = VgRendererFragmentFixedColor { - r: 0.0, - g: 0.5, - b: 1.0, - a: 1.0, - } - .as_pair(); - gpb.vertex_processing_mut() - .shader_stages_mut() - .set_fragment_spec_constants(color2_layout.as_ref(), &color2_values); - let gp2 = LayoutedPipeline::combine( - gpb.create( - e.graphics().device().clone(), - None::<&br::PipelineCacheObject>, - ) - .expect("Creating GraphicsPipeline2"), - pl.clone(), - ); - gpb.vertex_processing(curve_vertex_processing); - let gp_curve = LayoutedPipeline::combine( - gpb.create( - e.graphics().device().clone(), - None::<&br::PipelineCacheObject>, - ) - .expect("Create GraphicsPipeline of CurveRender"), - pl.clone(), - ); - gpb.vertex_processing_mut() - .shader_stages_mut() - .set_fragment_spec_constants(&*color2_layout, &color2_values); - let gp2_curve = LayoutedPipeline::combine( - gpb.create( - e.graphics().device().clone(), - None::<&br::PipelineCacheObject>, - ) - .expect("Creating GraphicsPipeline2 for CurveRender"), - pl.clone(), - ); - - let render_vg = RenderVG { - params: vg_renderer_params, - buffer: buffer.0.clone(), - interior_pipeline: gp, - curve_pipeline: gp_curve, - transform_buffer_descriptor_set: desc_interior, - target_pixels: Vector2(screen_size.width as _, screen_size.height as _), - rendering_precision: e.rendering_precision(), - }; - let render_vg2 = RenderVG { - params: vg_renderer_params2, - buffer: buffer.0, - interior_pipeline: gp2, - curve_pipeline: gp2_curve, - transform_buffer_descriptor_set: desc_curve, - target_pixels: Vector2(screen_size.width as _, screen_size.height as _), - - rendering_precision: e.rendering_precision(), - }; - let color_renders = [render_vg2, render_vg]; - - let mut render_cb = CommandBundle::new( - &e.graphics(), - CBSubmissionType::Graphics, - framebuffers.len(), + .expect("Create GraphicsPipeline of CurveRender"), + pl.clone(), + ); + gpb.vertex_processing_mut() + .shader_stages_mut() + .set_fragment_spec_constants(&*color2_layout, &color2_values); + let gp2_curve = LayoutedPipeline::combine( + gpb.create( + e.graphics().device().clone(), + None::<&br::PipelineCacheObject>, ) - .expect("Creating RenderCB"); - for (r, f) in render_cb.iter_mut().zip(&framebuffers) { - let rp = - BeginRenderPass::for_entire_framebuffer(&render_pass, f).with_clear_values(vec![ - br::ClearValue::color([1.0; 4]), - br::ClearValue::color([1.0; 4]), - ]); - - (&color_renders[..]) - .between(rp, EndRenderPass) - .execute_and_finish(unsafe { - r.begin(e.graphics_device()) - .expect("Failed to begin render command recording") - .as_dyn_ref() - }) - .expect("Failed to finish render commands"); - } - - Self { - ph: PhantomData, - memory_manager, - render_pass, - framebuffers, - _bufview: bufview, - _bufview2: bufview2, - _descriptors: (dsl, dp), - render_cb, - render_vgs: color_renders, - target_size: peridot::math::Vector2(screen_size.width as _, screen_size.height as _), - } - } - - fn update( - &mut self, - e: &mut peridot::Engine, - on_back_buffer_of: u32, - _dt: std::time::Duration, - ) { - e.do_render( - on_back_buffer_of, - None::, - br::EmptySubmissionBatch.with_command_buffers( - &self.render_cb[on_back_buffer_of as usize..=on_back_buffer_of as usize], - ), + .expect("Creating GraphicsPipeline2 for CurveRender"), + pl.clone(), + ); + + let render_vg = RenderVG { + params: vg_renderer_params, + buffer: buffer.0.clone(), + interior_pipeline: gp, + curve_pipeline: gp_curve, + transform_buffer_descriptor_set: desc_interior, + target_pixels: Vector2(screen_size.width as _, screen_size.height as _), + rendering_precision: e.rendering_precision(), + }; + let render_vg2 = RenderVG { + params: vg_renderer_params2, + buffer: buffer.0, + interior_pipeline: gp2, + curve_pipeline: gp2_curve, + transform_buffer_descriptor_set: desc_curve, + target_pixels: Vector2(screen_size.width as _, screen_size.height as _), + + rendering_precision: e.rendering_precision(), + }; + let mut color_renders = [render_vg2, render_vg]; + + let mut render_cb = CommandBundle::new( + &e.graphics(), + CBSubmissionType::Graphics, + framebuffers.len(), + ) + .expect("Creating RenderCB"); + for (r, f) in render_cb.iter_mut().zip(&framebuffers) { + let rp = BeginRenderPass::new( + &render_pass, + f, + screen_size.into_rect(br::vk::VkOffset2D::ZERO), ) - .expect("Failed to present"); + .with_clear_values(vec![ + br::ClearValue::color([1.0; 4]), + br::ClearValue::color([1.0; 4]), + ]); + + (&color_renders[..]) + .between(rp, EndRenderPass) + .execute_and_finish(unsafe { + r.begin(e.graphics_device()) + .expect("Failed to begin render command recording") + .as_dyn_ref() + }) + .expect("Failed to finish render commands"); } - fn discard_back_buffer_resources(&mut self) { - self.render_cb.reset().expect("Resetting RenderCB"); - self.framebuffers.clear(); - } - fn on_resize(&mut self, e: &mut peridot::Engine, new_size: Vector2) { - let rt_size = br::vk::VkExtent2D { - width: new_size.0 as _, - height: new_size.1 as _, - }; - - let msaa_count = br::vk::VK_SAMPLE_COUNT_4_BIT; - let msaa_texture = self - .memory_manager - .allocate_device_local_image( - e.graphics(), - br::ImageDesc::new(rt_size.clone(), e.back_buffer_format()) - .as_color_attachment() - .as_transient_attachment() - .sample_counts(msaa_count), - ) - .expect("Failed to create msaa render target"); - let msaa_texture = SharedRef::new( - msaa_texture - .subresource_range(br::AspectMask::COLOR, 0..1, 0..1) - .view_builder() - .create() - .expect("Failed to create msaa render target view"), - ); + let target_size = peridot::math::Vector2(screen_size.width as _, screen_size.height as _); - PipelineBarrier::from( - RangedImage::single_color_plane(msaa_texture.image()) - .barrier(br::ImageLayout::Undefined.to(br::ImageLayout::ColorAttachmentOpt)), - ) - .submit(e) - .expect("Failed to initialize msaa rt"); - - self.framebuffers = e - .iter_back_buffers() - .map(|bb| { - br::FramebufferBuilder::new(&self.render_pass) - .with_attachment(bb.clone()) - .with_attachment(msaa_texture.clone()) - .create() - }) - .collect::, _>>() - .expect("Bind Framebuffer"); + while let Some(ev) = e.event_receivers().wait_for_event().await { + match ev { + peridot::Event::Shutdown => break, + peridot::Event::NextFrame => { + let fd = e.prepare_frame().expect("Failed to prepare frame"); - for r in self.render_vgs.iter_mut() { - r.set_target_pixels(self.target_size.clone()); - } + e.do_render( + fd.backbuffer_index, + None::, + br::EmptySubmissionBatch.with_command_buffers( + &render_cb[fd.backbuffer_index as usize..=fd.backbuffer_index as usize], + ), + ) + .expect("Failed to present"); + } + peridot::Event::Resize(new_size) => { + e.wait_for_last_rendering_completion(); + + render_cb.reset().expect("Resetting RenderCB"); + drop(framebuffers); + drop(backbuffer_resources); + + e.resize_presenter_backbuffers(new_size); + + let rt_size = br::vk::VkExtent2D { + width: new_size.0 as _, + height: new_size.1 as _, + }; + + let msaa_count = br::vk::VK_SAMPLE_COUNT_4_BIT; + let msaa_texture_res = memory_manager + .allocate_device_local_image( + e.graphics(), + br::ImageDesc::new(rt_size.clone(), e.back_buffer_format()) + .as_color_attachment() + .as_transient_attachment() + .sample_counts(msaa_count), + ) + .expect("Failed to create msaa render target"); + msaa_texture = SharedRef::new( + msaa_texture_res + .subresource_range(br::AspectMask::COLOR, 0..1, 0..1) + .view_builder() + .create() + .expect("Failed to create msaa render target view"), + ); - for (r, f) in self.render_cb.iter_mut().zip(&self.framebuffers) { - let rp = BeginRenderPass::for_entire_framebuffer(&self.render_pass, f) - .with_clear_values(vec![ - br::ClearValue::color([1.0; 4]), - br::ClearValue::color([1.0; 4]), - ]); - - (&self.render_vgs[..]) - .between(rp, EndRenderPass) - .execute_and_finish(unsafe { - r.begin(e.graphics_device()) - .expect("Start Recording CB") - .as_dyn_ref() - }) - .expect("Failed to finish render commands"); + PipelineBarrier::from( + RangedImage::single_color_plane(msaa_texture.image()).barrier( + br::ImageLayout::Undefined.to(br::ImageLayout::ColorAttachmentOpt), + ), + ) + .submit(e) + .expect("Failed to initialize msaa rt"); + + backbuffer_resources = e.iter_back_buffers().cloned().collect(); + framebuffers = backbuffer_resources + .iter() + .map(|bb| { + br::FramebufferBuilder::new(&render_pass) + .with_attachment(bb) + .with_attachment(&msaa_texture) + .create() + }) + .collect::, _>>() + .expect("Bind Framebuffer"); + + for r in color_renders.iter_mut() { + r.set_target_pixels(target_size.clone()); + } + + for (r, f) in render_cb.iter_mut().zip(&framebuffers) { + let rp = BeginRenderPass::new( + &render_pass, + f, + br::vk::VkExtent2D::from(new_size).into_rect(br::vk::VkOffset2D::ZERO), + ) + .with_clear_values(vec![ + br::ClearValue::color([1.0; 4]), + br::ClearValue::color([1.0; 4]), + ]); + + (&color_renders[..]) + .between(rp, EndRenderPass) + .execute_and_finish(unsafe { + r.begin(e.graphics_device()) + .expect("Start Recording CB") + .as_dyn_ref() + }) + .expect("Failed to finish render commands"); + } + } } } + + unsafe { + e.graphics().device().wait().expect("Failed to wait works"); + } } diff --git a/modules/command-object/src/graphics_command.rs b/modules/command-object/src/graphics_command.rs index e48d16e5..fc616482 100644 --- a/modules/command-object/src/graphics_command.rs +++ b/modules/command-object/src/graphics_command.rs @@ -402,25 +402,6 @@ impl BeginRenderPass { } } } -impl<'f, R, D> BeginRenderPass> -where - R: br::RenderPass + br::DeviceChild, - D: br::Device, -{ - pub fn for_entire_framebuffer( - render_pass: R, - framebuffer: &'f br::FramebufferObject<'f, D>, - ) -> Self { - Self::new( - render_pass, - framebuffer, - framebuffer - .size() - .clone() - .into_rect(br::vk::VkOffset2D::ZERO), - ) - } -} impl< R: br::RenderPass + br::DeviceChild, F: br::Framebuffer + br::DeviceChild, diff --git a/modules/command-object/src/ranged_resources.rs b/modules/command-object/src/ranged_resources.rs index 2d002971..d706a24b 100644 --- a/modules/command-object/src/ranged_resources.rs +++ b/modules/command-object/src/ranged_resources.rs @@ -236,7 +236,7 @@ impl RangedBuffe ); } } -impl +impl RangedBuffer> { pub fn guard_map( diff --git a/modules/memory-manager/src/lib.rs b/modules/memory-manager/src/lib.rs index ab3b9843..3bd4c7ca 100644 --- a/modules/memory-manager/src/lib.rs +++ b/modules/memory-manager/src/lib.rs @@ -288,7 +288,7 @@ impl MemoryManager { } fn device_local_memory_type(&self, index_mask: u32) -> Option<&MemoryType> { - let mut target_types = self + let target_types = self .device_local_memory_types .iter() .find(|t| (index_mask & t.index_mask()) != 0); diff --git a/modules/memory-manager/src/resource_wrapper.rs b/modules/memory-manager/src/resource_wrapper.rs index 9273ba95..daf39e98 100644 --- a/modules/memory-manager/src/resource_wrapper.rs +++ b/modules/memory-manager/src/resource_wrapper.rs @@ -1,5 +1,5 @@ -use bedrock as br; -use br::{Device, DeviceChild, DeviceMemory, VkHandle, VulkanStructure}; +use bedrock::{self as br, DeviceMemoryMut}; +use br::{Device, DeviceChild, VkHandle, VulkanStructure}; #[allow(unused_imports)] use peridot::mthelper::DynamicMutabilityProvider; use peridot::mthelper::SharedMutableRef; diff --git a/modules/vg/src/rendering.rs b/modules/vg/src/rendering.rs index fb9a62a0..aaf514bf 100644 --- a/modules/vg/src/rendering.rs +++ b/modules/vg/src/rendering.rs @@ -127,7 +127,7 @@ impl ModelData for Context { fn stage_data_into( &self, - mem: &br::MappedMemoryRange, + mem: &br::MappedMemoryRange, offsets: ContextPreallocOffsets, ) -> RendererParams { unsafe { self.write_data_into(mem.get_mut(0) as _, offsets) }