1use crate::{
2 AtlasKey, AtlasTextureId, AtlasTextureKind, AtlasTile, Bounds, DevicePixels, PlatformAtlas,
3 Point, Size,
4};
5use anyhow::Result;
6use blade_graphics as gpu;
7use blade_util::{BufferBelt, BufferBeltDescriptor};
8use collections::FxHashMap;
9use etagere::BucketedAtlasAllocator;
10use parking_lot::Mutex;
11use std::{borrow::Cow, ops, sync::Arc};
12
13pub(crate) const PATH_TEXTURE_FORMAT: gpu::TextureFormat = gpu::TextureFormat::R16Float;
14
15pub(crate) struct BladeAtlas(Mutex<BladeAtlasState>);
16
17struct PendingUpload {
18 id: AtlasTextureId,
19 bounds: Bounds<DevicePixels>,
20 data: gpu::BufferPiece,
21}
22
23struct BladeAtlasState {
24 gpu: Arc<gpu::Context>,
25 upload_belt: BufferBelt,
26 storage: BladeAtlasStorage,
27 tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,
28 initializations: Vec<AtlasTextureId>,
29 uploads: Vec<PendingUpload>,
30}
31
32#[cfg(gles)]
33unsafe impl Send for BladeAtlasState {}
34
35impl BladeAtlasState {
36 fn destroy(&mut self) {
37 self.storage.destroy(&self.gpu);
38 self.upload_belt.destroy(&self.gpu);
39 }
40}
41
42pub struct BladeTextureInfo {
43 pub size: gpu::Extent,
44 pub raw_view: gpu::TextureView,
45}
46
47impl BladeAtlas {
48 pub(crate) fn new(gpu: &Arc<gpu::Context>) -> Self {
49 BladeAtlas(Mutex::new(BladeAtlasState {
50 gpu: Arc::clone(gpu),
51 upload_belt: BufferBelt::new(BufferBeltDescriptor {
52 memory: gpu::Memory::Upload,
53 min_chunk_size: 0x10000,
54 alignment: 64, // Vulkan `optimalBufferCopyOffsetAlignment` on Intel XE
55 }),
56 storage: BladeAtlasStorage::default(),
57 tiles_by_key: Default::default(),
58 initializations: Vec::new(),
59 uploads: Vec::new(),
60 }))
61 }
62
63 pub(crate) fn destroy(&self) {
64 self.0.lock().destroy();
65 }
66
67 pub(crate) fn clear_textures(&self, texture_kind: AtlasTextureKind) {
68 let mut lock = self.0.lock();
69 let textures = &mut lock.storage[texture_kind];
70 for texture in textures {
71 texture.clear();
72 }
73 }
74
75 /// Allocate a rectangle and make it available for rendering immediately (without waiting for `before_frame`)
76 pub fn allocate_for_rendering(
77 &self,
78 size: Size<DevicePixels>,
79 texture_kind: AtlasTextureKind,
80 gpu_encoder: &mut gpu::CommandEncoder,
81 ) -> AtlasTile {
82 let mut lock = self.0.lock();
83 let tile = lock.allocate(size, texture_kind);
84 lock.flush_initializations(gpu_encoder);
85 tile
86 }
87
88 pub fn before_frame(&self, gpu_encoder: &mut gpu::CommandEncoder) {
89 let mut lock = self.0.lock();
90 lock.flush(gpu_encoder);
91 }
92
93 pub fn after_frame(&self, sync_point: &gpu::SyncPoint) {
94 let mut lock = self.0.lock();
95 lock.upload_belt.flush(sync_point);
96 }
97
98 pub fn get_texture_info(&self, id: AtlasTextureId) -> BladeTextureInfo {
99 let lock = self.0.lock();
100 let texture = &lock.storage[id];
101 let size = texture.allocator.size();
102 BladeTextureInfo {
103 size: gpu::Extent {
104 width: size.width as u32,
105 height: size.height as u32,
106 depth: 1,
107 },
108 raw_view: texture.raw_view,
109 }
110 }
111}
112
113impl PlatformAtlas for BladeAtlas {
114 fn get_or_insert_with<'a>(
115 &self,
116 key: &AtlasKey,
117 build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
118 ) -> Result<Option<AtlasTile>> {
119 let mut lock = self.0.lock();
120 if let Some(tile) = lock.tiles_by_key.get(key) {
121 Ok(Some(tile.clone()))
122 } else {
123 profiling::scope!("new tile");
124 let Some((size, bytes)) = build()? else {
125 return Ok(None);
126 };
127 let tile = lock.allocate(size, key.texture_kind());
128 lock.upload_texture(tile.texture_id, tile.bounds, &bytes);
129 lock.tiles_by_key.insert(key.clone(), tile.clone());
130 Ok(Some(tile))
131 }
132 }
133}
134
135impl BladeAtlasState {
136 fn allocate(&mut self, size: Size<DevicePixels>, texture_kind: AtlasTextureKind) -> AtlasTile {
137 let textures = &mut self.storage[texture_kind];
138 textures
139 .iter_mut()
140 .rev()
141 .find_map(|texture| texture.allocate(size))
142 .unwrap_or_else(|| {
143 let texture = self.push_texture(size, texture_kind);
144 texture.allocate(size).unwrap()
145 })
146 }
147
148 fn push_texture(
149 &mut self,
150 min_size: Size<DevicePixels>,
151 kind: AtlasTextureKind,
152 ) -> &mut BladeAtlasTexture {
153 const DEFAULT_ATLAS_SIZE: Size<DevicePixels> = Size {
154 width: DevicePixels(1024),
155 height: DevicePixels(1024),
156 };
157
158 let size = min_size.max(&DEFAULT_ATLAS_SIZE);
159 let format;
160 let usage;
161 match kind {
162 AtlasTextureKind::Monochrome => {
163 format = gpu::TextureFormat::R8Unorm;
164 usage = gpu::TextureUsage::COPY | gpu::TextureUsage::RESOURCE;
165 }
166 AtlasTextureKind::Polychrome => {
167 format = gpu::TextureFormat::Bgra8UnormSrgb;
168 usage = gpu::TextureUsage::COPY | gpu::TextureUsage::RESOURCE;
169 }
170 AtlasTextureKind::Path => {
171 format = PATH_TEXTURE_FORMAT;
172 usage = gpu::TextureUsage::COPY
173 | gpu::TextureUsage::RESOURCE
174 | gpu::TextureUsage::TARGET;
175 }
176 }
177
178 let raw = self.gpu.create_texture(gpu::TextureDesc {
179 name: "atlas",
180 format,
181 size: gpu::Extent {
182 width: size.width.into(),
183 height: size.height.into(),
184 depth: 1,
185 },
186 array_layer_count: 1,
187 mip_level_count: 1,
188 dimension: gpu::TextureDimension::D2,
189 usage,
190 });
191 let raw_view = self.gpu.create_texture_view(gpu::TextureViewDesc {
192 name: "",
193 texture: raw,
194 format,
195 dimension: gpu::ViewDimension::D2,
196 subresources: &Default::default(),
197 });
198
199 let textures = &mut self.storage[kind];
200 let atlas_texture = BladeAtlasTexture {
201 id: AtlasTextureId {
202 index: textures.len() as u32,
203 kind,
204 },
205 allocator: etagere::BucketedAtlasAllocator::new(size.into()),
206 format,
207 raw,
208 raw_view,
209 };
210
211 self.initializations.push(atlas_texture.id);
212 textures.push(atlas_texture);
213 textures.last_mut().unwrap()
214 }
215
216 fn upload_texture(&mut self, id: AtlasTextureId, bounds: Bounds<DevicePixels>, bytes: &[u8]) {
217 let data = self.upload_belt.alloc_bytes(bytes, &self.gpu);
218 self.uploads.push(PendingUpload { id, bounds, data });
219 }
220
221 fn flush_initializations(&mut self, encoder: &mut gpu::CommandEncoder) {
222 for id in self.initializations.drain(..) {
223 let texture = &self.storage[id];
224 encoder.init_texture(texture.raw);
225 }
226 }
227
228 fn flush(&mut self, encoder: &mut gpu::CommandEncoder) {
229 self.flush_initializations(encoder);
230
231 let mut transfers = encoder.transfer();
232 for upload in self.uploads.drain(..) {
233 let texture = &self.storage[upload.id];
234 transfers.copy_buffer_to_texture(
235 upload.data,
236 upload.bounds.size.width.to_bytes(texture.bytes_per_pixel()),
237 gpu::TexturePiece {
238 texture: texture.raw,
239 mip_level: 0,
240 array_layer: 0,
241 origin: [
242 upload.bounds.origin.x.into(),
243 upload.bounds.origin.y.into(),
244 0,
245 ],
246 },
247 gpu::Extent {
248 width: upload.bounds.size.width.into(),
249 height: upload.bounds.size.height.into(),
250 depth: 1,
251 },
252 );
253 }
254 }
255}
256
257#[derive(Default)]
258struct BladeAtlasStorage {
259 monochrome_textures: Vec<BladeAtlasTexture>,
260 polychrome_textures: Vec<BladeAtlasTexture>,
261 path_textures: Vec<BladeAtlasTexture>,
262}
263
264impl ops::Index<AtlasTextureKind> for BladeAtlasStorage {
265 type Output = Vec<BladeAtlasTexture>;
266 fn index(&self, kind: AtlasTextureKind) -> &Self::Output {
267 match kind {
268 crate::AtlasTextureKind::Monochrome => &self.monochrome_textures,
269 crate::AtlasTextureKind::Polychrome => &self.polychrome_textures,
270 crate::AtlasTextureKind::Path => &self.path_textures,
271 }
272 }
273}
274
275impl ops::IndexMut<AtlasTextureKind> for BladeAtlasStorage {
276 fn index_mut(&mut self, kind: AtlasTextureKind) -> &mut Self::Output {
277 match kind {
278 crate::AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
279 crate::AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
280 crate::AtlasTextureKind::Path => &mut self.path_textures,
281 }
282 }
283}
284
285impl ops::Index<AtlasTextureId> for BladeAtlasStorage {
286 type Output = BladeAtlasTexture;
287 fn index(&self, id: AtlasTextureId) -> &Self::Output {
288 let textures = match id.kind {
289 crate::AtlasTextureKind::Monochrome => &self.monochrome_textures,
290 crate::AtlasTextureKind::Polychrome => &self.polychrome_textures,
291 crate::AtlasTextureKind::Path => &self.path_textures,
292 };
293 &textures[id.index as usize]
294 }
295}
296
297impl BladeAtlasStorage {
298 fn destroy(&mut self, gpu: &gpu::Context) {
299 for mut texture in self.monochrome_textures.drain(..) {
300 texture.destroy(gpu);
301 }
302 for mut texture in self.polychrome_textures.drain(..) {
303 texture.destroy(gpu);
304 }
305 for mut texture in self.path_textures.drain(..) {
306 texture.destroy(gpu);
307 }
308 }
309}
310
311struct BladeAtlasTexture {
312 id: AtlasTextureId,
313 allocator: BucketedAtlasAllocator,
314 raw: gpu::Texture,
315 raw_view: gpu::TextureView,
316 format: gpu::TextureFormat,
317}
318
319impl BladeAtlasTexture {
320 fn clear(&mut self) {
321 self.allocator.clear();
322 }
323
324 fn allocate(&mut self, size: Size<DevicePixels>) -> Option<AtlasTile> {
325 let allocation = self.allocator.allocate(size.into())?;
326 let tile = AtlasTile {
327 texture_id: self.id,
328 tile_id: allocation.id.into(),
329 padding: 0,
330 bounds: Bounds {
331 origin: allocation.rectangle.min.into(),
332 size,
333 },
334 };
335 Some(tile)
336 }
337
338 fn destroy(&mut self, gpu: &gpu::Context) {
339 gpu.destroy_texture(self.raw);
340 gpu.destroy_texture_view(self.raw_view);
341 }
342
343 fn bytes_per_pixel(&self) -> u8 {
344 self.format.block_info().size
345 }
346}
347
348impl From<Size<DevicePixels>> for etagere::Size {
349 fn from(size: Size<DevicePixels>) -> Self {
350 etagere::Size::new(size.width.into(), size.height.into())
351 }
352}
353
354impl From<etagere::Point> for Point<DevicePixels> {
355 fn from(value: etagere::Point) -> Self {
356 Point {
357 x: DevicePixels::from(value.x),
358 y: DevicePixels::from(value.y),
359 }
360 }
361}
362
363impl From<etagere::Size> for Size<DevicePixels> {
364 fn from(size: etagere::Size) -> Self {
365 Size {
366 width: DevicePixels::from(size.width),
367 height: DevicePixels::from(size.height),
368 }
369 }
370}
371
372impl From<etagere::Rectangle> for Bounds<DevicePixels> {
373 fn from(rectangle: etagere::Rectangle) -> Self {
374 Bounds {
375 origin: rectangle.min.into(),
376 size: rectangle.size().into(),
377 }
378 }
379}