1use astrelis_core::profiling::profile_function;
29
30use crate::GraphicsContext;
31use crate::extension::AsWgpu;
32use crate::types::GpuTexture;
33use ahash::HashMap;
34use std::sync::Arc;
35
36#[derive(Debug, Clone, Copy, PartialEq)]
42pub struct AtlasRect {
43 pub x: f32,
44 pub y: f32,
45 pub width: f32,
46 pub height: f32,
47}
48
49impl AtlasRect {
50 pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
52 Self {
53 x,
54 y,
55 width,
56 height,
57 }
58 }
59}
60
61type Rect = AtlasRect;
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
66pub struct AtlasKey(u64);
67
68impl AtlasKey {
69 pub fn new(s: &str) -> Self {
71 use std::collections::hash_map::DefaultHasher;
72 use std::hash::{Hash, Hasher};
73
74 let mut hasher = DefaultHasher::new();
75 s.hash(&mut hasher);
76 Self(hasher.finish())
77 }
78
79 pub fn from_u64(id: u64) -> Self {
81 Self(id)
82 }
83
84 pub fn as_u64(&self) -> u64 {
86 self.0
87 }
88}
89
90#[derive(Debug, Clone, Copy)]
92pub struct AtlasEntry {
93 pub rect: Rect,
95 pub uv_rect: Rect,
97}
98
99impl AtlasEntry {
100 pub fn new(rect: Rect, atlas_size: f32) -> Self {
102 let uv_rect = Rect {
103 x: rect.x / atlas_size,
104 y: rect.y / atlas_size,
105 width: rect.width / atlas_size,
106 height: rect.height / atlas_size,
107 };
108
109 Self { rect, uv_rect }
110 }
111}
112
113#[derive(Debug, Clone)]
115#[allow(dead_code)]
116enum PackerNode {
117 Empty { rect: Rect },
119 Filled { rect: Rect, key: AtlasKey },
121 Split {
123 rect: Rect,
124 left: Box<PackerNode>,
125 right: Box<PackerNode>,
126 },
127}
128
129impl PackerNode {
130 fn new(rect: Rect) -> Self {
132 Self::Empty { rect }
133 }
134
135 fn insert(&mut self, key: AtlasKey, width: f32, height: f32) -> Option<Rect> {
137 match self {
138 PackerNode::Empty { rect } => {
139 if width > rect.width || height > rect.height {
141 return None;
142 }
143
144 if width == rect.width && height == rect.height {
146 let result = *rect;
147 *self = PackerNode::Filled { rect: *rect, key };
148 return Some(result);
149 }
150
151 let rect_copy = *rect;
153
154 let horizontal_waste = rect.width - width;
156 let vertical_waste = rect.height - height;
157
158 let (left_rect, right_rect) = if horizontal_waste > vertical_waste {
159 (
161 Rect {
162 x: rect.x,
163 y: rect.y,
164 width,
165 height: rect.height,
166 },
167 Rect {
168 x: rect.x + width,
169 y: rect.y,
170 width: rect.width - width,
171 height: rect.height,
172 },
173 )
174 } else {
175 (
177 Rect {
178 x: rect.x,
179 y: rect.y,
180 width: rect.width,
181 height,
182 },
183 Rect {
184 x: rect.x,
185 y: rect.y + height,
186 width: rect.width,
187 height: rect.height - height,
188 },
189 )
190 };
191
192 let mut left = Box::new(PackerNode::new(left_rect));
193 let right = Box::new(PackerNode::new(right_rect));
194
195 let result = left.insert(key, width, height);
197
198 *self = PackerNode::Split {
199 rect: rect_copy,
200 left,
201 right,
202 };
203
204 result
205 }
206 PackerNode::Filled { .. } => None,
207 PackerNode::Split { left, right, .. } => {
208 left.insert(key, width, height)
210 .or_else(|| right.insert(key, width, height))
211 }
212 }
213 }
214}
215
216pub struct TextureAtlas {
218 texture: GpuTexture,
220 entries: HashMap<AtlasKey, AtlasEntry>,
221 packer: PackerNode,
222 context: Arc<GraphicsContext>,
223 pending_uploads: Vec<(AtlasKey, Vec<u8>, Rect)>,
225 dirty: bool,
226}
227
228impl TextureAtlas {
229 pub fn new(context: Arc<GraphicsContext>, size: u32, format: wgpu::TextureFormat) -> Self {
237 profile_function!();
238 let texture = GpuTexture::new_2d(
239 context.device(),
240 Some("TextureAtlas"),
241 size,
242 size,
243 format,
244 wgpu::TextureUsages::TEXTURE_BINDING
245 | wgpu::TextureUsages::COPY_DST
246 | wgpu::TextureUsages::RENDER_ATTACHMENT,
247 );
248
249 let packer = PackerNode::new(Rect {
250 x: 0.0,
251 y: 0.0,
252 width: size as f32,
253 height: size as f32,
254 });
255
256 Self {
257 texture,
258 entries: HashMap::default(),
259 packer,
260 context,
261 pending_uploads: Vec::new(),
262 dirty: false,
263 }
264 }
265
266 pub fn insert(
277 &mut self,
278 key: AtlasKey,
279 image_data: &[u8],
280 width: u32,
281 height: u32,
282 ) -> Option<AtlasEntry> {
283 profile_function!();
284 if let Some(entry) = self.entries.get(&key) {
286 return Some(*entry);
287 }
288
289 let rect = self.packer.insert(key, width as f32, height as f32)?;
291
292 let entry = AtlasEntry::new(rect, self.texture.width() as f32);
294 self.entries.insert(key, entry);
295
296 self.pending_uploads.push((key, image_data.to_vec(), rect));
298 self.dirty = true;
299
300 Some(entry)
301 }
302
303 pub fn get(&self, key: &AtlasKey) -> Option<&AtlasEntry> {
305 self.entries.get(key)
306 }
307
308 pub fn contains(&self, key: &AtlasKey) -> bool {
310 self.entries.contains_key(key)
311 }
312
313 pub fn upload(&mut self) {
315 profile_function!();
316 if !self.dirty {
317 return;
318 }
319
320 let format = self.texture.format();
321 for (_, data, rect) in &self.pending_uploads {
322 let bytes_per_pixel = match format {
323 wgpu::TextureFormat::Rgba8UnormSrgb | wgpu::TextureFormat::Rgba8Unorm => 4,
324 wgpu::TextureFormat::Bgra8UnormSrgb | wgpu::TextureFormat::Bgra8Unorm => 4,
325 wgpu::TextureFormat::R8Unorm => 1,
326 _ => 4, };
328
329 self.context.queue().write_texture(
330 wgpu::TexelCopyTextureInfo {
331 texture: self.texture.as_wgpu(),
332 mip_level: 0,
333 origin: wgpu::Origin3d {
334 x: rect.x as u32,
335 y: rect.y as u32,
336 z: 0,
337 },
338 aspect: wgpu::TextureAspect::All,
339 },
340 data,
341 wgpu::TexelCopyBufferLayout {
342 offset: 0,
343 bytes_per_row: Some(rect.width as u32 * bytes_per_pixel),
344 rows_per_image: Some(rect.height as u32),
345 },
346 wgpu::Extent3d {
347 width: rect.width as u32,
348 height: rect.height as u32,
349 depth_or_array_layers: 1,
350 },
351 );
352 }
353
354 self.pending_uploads.clear();
355 self.dirty = false;
356 }
357
358 pub fn texture_view(&self) -> &wgpu::TextureView {
360 self.texture.view()
361 }
362
363 pub fn texture(&self) -> &wgpu::Texture {
365 self.texture.as_wgpu()
366 }
367
368 pub fn size(&self) -> u32 {
370 self.texture.width()
371 }
372
373 pub fn format(&self) -> wgpu::TextureFormat {
375 self.texture.format()
376 }
377
378 pub fn len(&self) -> usize {
380 self.entries.len()
381 }
382
383 pub fn is_empty(&self) -> bool {
385 self.entries.is_empty()
386 }
387
388 pub fn clear(&mut self) {
390 self.entries.clear();
391 self.pending_uploads.clear();
392 let size = self.texture.width();
393 self.packer = PackerNode::new(Rect {
394 x: 0.0,
395 y: 0.0,
396 width: size as f32,
397 height: size as f32,
398 });
399 self.dirty = false;
400 }
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406
407 #[test]
408 fn test_atlas_key() {
409 let key1 = AtlasKey::new("test");
410 let key2 = AtlasKey::new("test");
411 let key3 = AtlasKey::new("other");
412
413 assert_eq!(key1, key2);
414 assert_ne!(key1, key3);
415 }
416
417 #[test]
418 fn test_atlas_entry_uv() {
419 let rect = Rect {
420 x: 0.0,
421 y: 0.0,
422 width: 64.0,
423 height: 64.0,
424 };
425 let entry = AtlasEntry::new(rect, 256.0);
426
427 assert_eq!(entry.uv_rect.x, 0.0);
428 assert_eq!(entry.uv_rect.y, 0.0);
429 assert_eq!(entry.uv_rect.width, 0.25);
430 assert_eq!(entry.uv_rect.height, 0.25);
431 }
432
433 #[test]
434 fn test_packer_insertion() {
435 let mut packer = PackerNode::new(Rect {
436 x: 0.0,
437 y: 0.0,
438 width: 256.0,
439 height: 256.0,
440 });
441
442 let key1 = AtlasKey::new("rect1");
443 let rect1 = packer.insert(key1, 64.0, 64.0);
444 assert!(rect1.is_some());
445
446 let key2 = AtlasKey::new("rect2");
447 let rect2 = packer.insert(key2, 32.0, 32.0);
448 assert!(rect2.is_some());
449
450 let key3 = AtlasKey::new("rect3");
452 let rect3 = packer.insert(key3, 512.0, 512.0);
453 assert!(rect3.is_none());
454 }
455
456 #[test]
457 fn test_atlas_basic() {
458 let context = GraphicsContext::new_owned_sync().expect("Failed to create graphics context");
459 let mut atlas = TextureAtlas::new(context, 256, wgpu::TextureFormat::Rgba8UnormSrgb);
460
461 assert_eq!(atlas.size(), 256);
462 assert_eq!(atlas.len(), 0);
463 assert!(atlas.is_empty());
464
465 let mut image_data = vec![0u8; 32 * 32 * 4];
467 for i in 0..(32 * 32) {
468 image_data[i * 4] = 255; image_data[i * 4 + 1] = 0; image_data[i * 4 + 2] = 0; image_data[i * 4 + 3] = 255; }
473
474 let key = AtlasKey::new("red_square");
475 let entry = atlas.insert(key, &image_data, 32, 32);
476 assert!(entry.is_some());
477 assert_eq!(atlas.len(), 1);
478
479 let retrieved = atlas.get(&key);
481 assert!(retrieved.is_some());
482
483 atlas.upload();
485 }
486
487 #[test]
488 fn test_atlas_multiple_inserts() {
489 let context = GraphicsContext::new_owned_sync().expect("Failed to create graphics context");
490 let mut atlas = TextureAtlas::new(context, 256, wgpu::TextureFormat::Rgba8UnormSrgb);
491
492 for i in 0..10 {
494 let image_data = vec![0u8; 16 * 16 * 4];
495 let key = AtlasKey::new(&format!("image_{}", i));
496 let entry = atlas.insert(key, &image_data, 16, 16);
497 assert!(entry.is_some());
498 }
499
500 assert_eq!(atlas.len(), 10);
501 atlas.upload();
502 }
503
504 #[test]
505 fn test_atlas_duplicate_key() {
506 let context = GraphicsContext::new_owned_sync().expect("Failed to create graphics context");
507 let mut atlas = TextureAtlas::new(context, 256, wgpu::TextureFormat::Rgba8UnormSrgb);
508
509 let image_data = vec![0u8; 32 * 32 * 4];
510 let key = AtlasKey::new("duplicate");
511
512 let entry1 = atlas.insert(key, &image_data, 32, 32);
513 assert!(entry1.is_some());
514
515 let entry2 = atlas.insert(key, &image_data, 32, 32);
516 assert!(entry2.is_some());
517
518 assert_eq!(atlas.len(), 1);
520 }
521
522 #[test]
523 fn test_atlas_clear() {
524 let context = GraphicsContext::new_owned_sync().expect("Failed to create graphics context");
525 let mut atlas = TextureAtlas::new(context, 256, wgpu::TextureFormat::Rgba8UnormSrgb);
526
527 let image_data = vec![0u8; 32 * 32 * 4];
528 let key = AtlasKey::new("test");
529 atlas.insert(key, &image_data, 32, 32);
530
531 assert_eq!(atlas.len(), 1);
532
533 atlas.clear();
534
535 assert_eq!(atlas.len(), 0);
536 assert!(atlas.is_empty());
537 }
538}