1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
//! Resource allocation helpers

use failure::Fallible;
use gfx_hal::format::Format;
use gfx_hal::image::{self, Kind, Level, Tiling, ViewCapabilities};
use gfx_hal::memory::Properties;
use gfx_hal::{buffer, Adapter, Backend, Device, Graphics, QueueGroup};

use crate::allocator::{
    Allocation as _, AllocationSpec, Allocator, Hint, HybridAllocation as Allocation,
    HybridAllocator,
};

use crate::resources::Resource;

/// Dull factory helping with resource allocation.
pub struct Factory<B: Backend> {
    alloc: HybridAllocator<B>,
    pub device: B::Device,
    pub physical_device: B::PhysicalDevice,
    pub queue_group: QueueGroup<B, Graphics>,
}

impl<B: Backend> Factory<B> {
    /// Create a new factory using the specified `Adapter`. The graphics queue is immediately opened.
    pub fn new(adapter: Adapter<B>) -> Fallible<Factory<B>> {
        let (device, queue_group) = adapter.open_with(1, |_| true)?;
        let alloc = HybridAllocator::new(&adapter.physical_device);

        Ok(Factory {
            alloc,
            device,
            queue_group,
            physical_device: adapter.physical_device,
        })
    }
}

/// Buffer allocated by the `Factory`.
pub struct Buffer<B: Backend> {
    pub buffer: B::Buffer,
    memory: Allocation<B>,
}

impl<B: Backend> Buffer<B> {
    pub fn plan(size: u64, usage: buffer::Usage) -> BufferPlan {
        BufferPlan {
            size,
            usage,
            hint: Hint::ShortTerm,
            required_flags: Properties::empty(),
            preferred_flags: Properties::empty(),
        }
    }
}

impl<B: Backend> Resource<B> for Buffer<B> {
    type Plan = BufferPlan;

    fn create(factory: &mut Factory<B>, plan: &Self::Plan) -> Buffer<B> {
        plan.create(factory).unwrap()
    }

    fn destroy(self, factory: &mut Factory<B>) {
        unsafe { factory.device.destroy_buffer(self.buffer) };
        factory.alloc.free(&factory.device, self.memory);
    }
}

/// Buffer plan
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct BufferPlan {
    pub size: u64,
    pub usage: buffer::Usage,
    pub hint: Hint,
    pub required_flags: Properties,
    pub preferred_flags: Properties,
}

impl BufferPlan {
    /// Create `COHERENT` buffer, if supported by the driver.
    pub fn coherent(&mut self) -> &mut BufferPlan {
        self.preferred_flags |= Properties::COHERENT;
        self
    }

    /// Create `CPU_CACHED` buffer, if supported by the driver.
    pub fn cached(&mut self) -> &mut BufferPlan {
        self.preferred_flags |= Properties::CPU_CACHED;
        self
    }

    /// Create `DEVICE_LOCAL` buffer, if supported by the driver.
    pub fn device_local(&mut self) -> &mut BufferPlan {
        self.preferred_flags |= Properties::DEVICE_LOCAL;
        self
    }

    /// Require a buffer to be `CPU_VISIBLE`.
    pub fn cpu_visible(&mut self) -> &mut BufferPlan {
        self.required_flags |= Properties::CPU_VISIBLE;
        self
    }

    /// Hint the allocator that the buffer will live for a long time.
    ///
    /// By default, allocator assumes the buffer is a short-lived object.
    pub fn permanent(&mut self) -> &mut BufferPlan {
        self.hint = Hint::ShortTerm;
        self
    }

    /// Build the buffer, allocating the memory and binding it to the buffer.
    pub fn create<B: Backend>(&self, factory: &mut Factory<B>) -> Fallible<Buffer<B>> {
        let device = &factory.device;

        unsafe {
            let mut buffer = device.create_buffer(self.size, self.usage)?;
            let req = device.get_buffer_requirements(&buffer);

            let spec = AllocationSpec {
                hint: self.hint,
                required_flags: self.required_flags,
                preferred_flags: self.preferred_flags,
            };

            let memory = factory.alloc.alloc(device, req, spec)?;
            device.bind_buffer_memory(memory.memory(), memory.range().start, &mut buffer)?;

            Ok(Buffer { buffer, memory })
        }
    }
}

/// Image allocated by the `Factory`.
pub struct Image<B: Backend> {
    pub image: B::Image,
    memory: Allocation<B>,
}

impl<B: Backend> Image<B> {
    pub fn plan(kind: Kind, usage: image::Usage) -> ImagePlan {
        ImagePlan {
            kind,
            mip_levels: 0,
            format: Format::Bgra8Srgb,
            tiling: Tiling::Optimal,
            usage,
            view_caps: ViewCapabilities::empty(),
            hint: Hint::ShortTerm,
            required_flags: Properties::empty(),
            preferred_flags: Properties::empty(),
        }
    }
}

impl<B: Backend> Resource<B> for Image<B> {
    type Plan = ImagePlan;

    fn create(factory: &mut Factory<B>, plan: &Self::Plan) -> Image<B> {
        plan.create(factory).unwrap()
    }

    fn destroy(self, factory: &mut Factory<B>) {
        unsafe { factory.device.destroy_image(self.image) };
        factory.alloc.free(&factory.device, self.memory);
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct ImagePlan {
    pub kind: Kind,
    pub mip_levels: Level,
    pub format: Format,
    pub tiling: Tiling,
    pub usage: image::Usage,
    pub view_caps: ViewCapabilities,
    pub hint: Hint,
    pub required_flags: Properties,
    pub preferred_flags: Properties,
}

impl ImagePlan {
    /// Create `COHERENT` image, if supported by the driver.
    pub fn coherent(&mut self) -> &mut ImagePlan {
        self.preferred_flags |= Properties::COHERENT;
        self
    }

    /// Create `CPU_CACHED` image, if supported by the driver.
    pub fn cached(&mut self) -> &mut ImagePlan {
        self.preferred_flags |= Properties::CPU_CACHED;
        self
    }

    /// Create `DEVICE_LOCAL` image, if supported by the driver.
    pub fn device_local(&mut self) -> &mut ImagePlan {
        self.preferred_flags |= Properties::DEVICE_LOCAL;
        self
    }

    /// Require a image to be `CPU_VISIBLE`.
    pub fn cpu_visible(&mut self) -> &mut ImagePlan {
        self.required_flags |= Properties::CPU_VISIBLE;
        self
    }

    /// Hint the allocator that the image will live for a long time.
    ///
    /// By default, allocator assumes the image is a short-lived object.
    pub fn permanent(&mut self) -> &mut ImagePlan {
        self.hint = Hint::ShortTerm;
        self
    }

    pub fn create<B: Backend>(&self, factory: &mut Factory<B>) -> Fallible<Image<B>> {
        let device = &factory.device;

        unsafe {
            let mut image = device.create_image(
                self.kind,
                self.mip_levels,
                self.format,
                self.tiling,
                self.usage,
                self.view_caps,
            )?;

            let req = device.get_image_requirements(&image);

            let spec = AllocationSpec {
                hint: self.hint,
                required_flags: self.required_flags,
                preferred_flags: self.preferred_flags,
            };

            let memory = factory.alloc.alloc(device, req, spec)?;
            device.bind_image_memory(memory.memory(), memory.range().start, &mut image)?;

            Ok(Image { image, memory })
        }
    }
}