atagen

monolith

public
Star0
Watch0
f0e45b05980877266f927f0802d20103c0939d5b
1
ssh://brewery@pls.lobotomise.me:33/atagen/monolith.git
crates/render-vk/src/image.rsRust245 lines7.4 KB
1
use crate::Error;
2
use crate::device::Shared;
3
use crate::format::{components, vk_format};
4
use ash::vk;
5
use gpu_allocator::MemoryLocation;
6
use gpu_allocator::vulkan::{Allocation, AllocationCreateDesc, AllocationScheme};
7
use smithay::backend::allocator::Fourcc;
8
use smithay::backend::renderer::{Texture, TextureMapping};
9
use std::fmt;
10
use std::marker::PhantomData;
11
use std::sync::{Arc, Mutex};
12
13
pub(crate) enum Memory {
14
    Allocated(Allocation),
15
    /// Memory imported from a dmabuf, owned directly.
16
    Imported(vk::DeviceMemory),
17
}
18
19
pub(crate) struct ImageInner {
20
    pub shared: Arc<Shared>,
21
    pub image: vk::Image,
22
    pub view: vk::ImageView,
23
    pub memory: Mutex<Option<Memory>>,
24
    pub fourcc: Fourcc,
25
    pub format: vk::Format,
26
    pub width: u32,
27
    pub height: u32,
28
    pub usage: vk::ImageUsageFlags,
29
    pub layout: Mutex<vk::ImageLayout>,
30
    /// Shared with other devices or processes through a dmabuf. Every use
31
    /// acquires the image from the foreign queue family and releases it after.
32
    pub external: bool,
33
}
34
35
impl fmt::Debug for ImageInner {
36
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37
        f.debug_struct("ImageInner")
38
            .field("image", &self.image)
39
            .field("fourcc", &self.fourcc)
40
            .field("size", &(self.width, self.height))
41
            .field("external", &self.external)
42
            .finish()
43
    }
44
}
45
46
impl Drop for ImageInner {
47
    fn drop(&mut self) {
48
        let d = &self.shared.device.device;
49
        unsafe {
50
            d.destroy_image_view(self.view, None);
51
            d.destroy_image(self.image, None);
52
        }
53
        match self.memory.lock().unwrap_or_else(|e| e.into_inner()).take() {
54
            Some(Memory::Allocated(a)) => {
55
                let _ = self
56
                    .shared
57
                    .allocator
58
                    .lock()
59
                    .unwrap_or_else(|e| e.into_inner())
60
                    .free(a);
61
            }
62
            Some(Memory::Imported(m)) => unsafe { d.free_memory(m, None) },
63
            None => {}
64
        }
65
    }
66
}
67
68
impl ImageInner {
69
    pub fn create(
70
        shared: &Arc<Shared>,
71
        fourcc: Fourcc,
72
        width: u32,
73
        height: u32,
74
        usage: vk::ImageUsageFlags,
75
    ) -> Result<Arc<Self>, Error> {
76
        let fmt = vk_format(fourcc).ok_or(Error::UnsupportedFormat(fourcc))?;
77
        if width == 0 || height == 0 {
78
            return Err(Error::InvalidSize(width as i32, height as i32));
79
        }
80
        let d = &shared.device.device;
81
        let info = vk::ImageCreateInfo::default()
82
            .image_type(vk::ImageType::TYPE_2D)
83
            .format(fmt.format)
84
            .extent(vk::Extent3D {
85
                width,
86
                height,
87
                depth: 1,
88
            })
89
            .mip_levels(1)
90
            .array_layers(1)
91
            .samples(vk::SampleCountFlags::TYPE_1)
92
            .tiling(vk::ImageTiling::OPTIMAL)
93
            .usage(usage)
94
            .initial_layout(vk::ImageLayout::UNDEFINED);
95
        let image = unsafe { d.create_image(&info, None)? };
96
        let requirements = unsafe { d.get_image_memory_requirements(image) };
97
        let allocation = shared
98
            .allocator
99
            .lock()
100
            .unwrap_or_else(|e| e.into_inner())
101
            .allocate(&AllocationCreateDesc {
102
                name: "image",
103
                requirements,
104
                location: MemoryLocation::GpuOnly,
105
                linear: false,
106
                allocation_scheme: AllocationScheme::GpuAllocatorManaged,
107
            });
108
        let allocation = match allocation {
109
            Ok(a) => a,
110
            Err(e) => {
111
                unsafe { d.destroy_image(image, None) };
112
                return Err(e.into());
113
            }
114
        };
115
        let memory = Memory::Allocated(allocation);
116
        let (mem, offset) = match &memory {
117
            Memory::Allocated(a) => (unsafe { a.memory() }, a.offset()),
118
            Memory::Imported(m) => (*m, 0),
119
        };
120
        Self::finish(
121
            shared, image, memory, mem, offset, fourcc, width, height, usage, false,
122
        )
123
    }
124
125
    /// Binds memory, creates the view and wraps everything up. Takes
126
    /// ownership of `image` and `memory`, releasing both on failure.
127
    #[expect(clippy::too_many_arguments)]
128
    pub fn finish(
129
        shared: &Arc<Shared>,
130
        image: vk::Image,
131
        memory: Memory,
132
        mem: vk::DeviceMemory,
133
        offset: u64,
134
        fourcc: Fourcc,
135
        width: u32,
136
        height: u32,
137
        usage: vk::ImageUsageFlags,
138
        external: bool,
139
    ) -> Result<Arc<Self>, Error> {
140
        let fmt = vk_format(fourcc).ok_or(Error::UnsupportedFormat(fourcc))?;
141
        let d = &shared.device.device;
142
        let mut inner = Self {
143
            shared: shared.clone(),
144
            image,
145
            view: vk::ImageView::null(),
146
            memory: Mutex::new(Some(memory)),
147
            fourcc,
148
            format: fmt.format,
149
            width,
150
            height,
151
            usage,
152
            layout: Mutex::new(if external {
153
                vk::ImageLayout::GENERAL
154
            } else {
155
                vk::ImageLayout::UNDEFINED
156
            }),
157
            external,
158
        };
159
        unsafe { d.bind_image_memory(image, mem, offset)? };
160
        let view_info = vk::ImageViewCreateInfo::default()
161
            .image(image)
162
            .view_type(vk::ImageViewType::TYPE_2D)
163
            .format(fmt.format)
164
            .components(components(fmt.opaque))
165
            .subresource_range(color_range());
166
        inner.view = unsafe { d.create_image_view(&view_info, None)? };
167
        Ok(Arc::new(inner))
168
    }
169
170
    pub fn layout(&self) -> vk::ImageLayout {
171
        *self.layout.lock().unwrap_or_else(|e| e.into_inner())
172
    }
173
174
    pub fn set_layout(&self, layout: vk::ImageLayout) {
175
        *self.layout.lock().unwrap_or_else(|e| e.into_inner()) = layout;
176
    }
177
}
178
179
pub(crate) fn color_range() -> vk::ImageSubresourceRange {
180
    vk::ImageSubresourceRange::default()
181
        .aspect_mask(vk::ImageAspectFlags::COLOR)
182
        .level_count(1)
183
        .layer_count(1)
184
}
185
186
/// A sampled texture.
187
#[derive(Clone, Debug)]
188
pub struct VulkanTexture(pub(crate) Arc<ImageInner>);
189
190
/// An image the renderer can draw into, from [`smithay::backend::renderer::Offscreen`].
191
#[derive(Debug)]
192
pub struct VulkanImage(pub(crate) Arc<ImageInner>);
193
194
impl VulkanImage {
195
    /// The image's contents as a texture, for drawing it elsewhere.
196
    pub fn texture(&self) -> VulkanTexture {
197
        VulkanTexture(self.0.clone())
198
    }
199
}
200
201
/// A bound render target, borrowing whatever it was bound from.
202
#[derive(Debug)]
203
pub struct VulkanTarget<'a>(
204
    pub(crate) Arc<ImageInner>,
205
    pub(crate) PhantomData<&'a mut ()>,
206
);
207
208
/// Pixels read back from the GPU.
209
#[derive(Debug)]
210
pub struct VulkanMapping {
211
    pub(crate) data: Vec<u8>,
212
    pub(crate) width: u32,
213
    pub(crate) height: u32,
214
    pub(crate) fourcc: Fourcc,
215
}
216
217
macro_rules! texture_impl {
218
    ($t:ty, |$s:ident| $inner:expr) => {
219
        impl Texture for $t {
220
            fn width(&self) -> u32 {
221
                let $s = self;
222
                $inner.width
223
            }
224
            fn height(&self) -> u32 {
225
                let $s = self;
226
                $inner.height
227
            }
228
            fn format(&self) -> Option<Fourcc> {
229
                let $s = self;
230
                Some($inner.fourcc)
231
            }
232
        }
233
    };
234
}
235
236
texture_impl!(VulkanTexture, |s| s.0);
237
texture_impl!(VulkanImage, |s| s.0);
238
texture_impl!(VulkanTarget<'_>, |s| s.0);
239
texture_impl!(VulkanMapping, |s| s);
240
241
impl TextureMapping for VulkanMapping {
242
    fn flipped(&self) -> bool {
243
        false
244
    }
245
}