2020-02-26 12:34:34 +01:00
|
|
|
use guillotiere::{AtlasAllocator, Size};
|
|
|
|
|
|
|
|
|
|
pub struct Allocator {
|
|
|
|
|
raw: AtlasAllocator,
|
2020-02-26 20:10:19 +01:00
|
|
|
allocations: usize,
|
2020-02-26 12:34:34 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Allocator {
|
|
|
|
|
pub fn new(size: u32) -> Allocator {
|
|
|
|
|
let raw = AtlasAllocator::new(Size::new(size as i32, size as i32));
|
|
|
|
|
|
2020-02-26 20:10:19 +01:00
|
|
|
Allocator {
|
|
|
|
|
raw,
|
|
|
|
|
allocations: 0,
|
|
|
|
|
}
|
2020-02-26 12:34:34 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn allocate(&mut self, width: u32, height: u32) -> Option<Region> {
|
2020-02-26 20:10:19 +01:00
|
|
|
let allocation =
|
|
|
|
|
self.raw.allocate(Size::new(width as i32, height as i32))?;
|
|
|
|
|
|
|
|
|
|
self.allocations += 1;
|
|
|
|
|
|
|
|
|
|
Some(Region { allocation })
|
2020-02-26 12:34:34 +01:00
|
|
|
}
|
|
|
|
|
|
2020-02-26 20:10:19 +01:00
|
|
|
pub fn deallocate(&mut self, region: &Region) {
|
2020-02-26 18:49:46 +01:00
|
|
|
self.raw.deallocate(region.allocation.id);
|
2020-02-26 20:10:19 +01:00
|
|
|
|
|
|
|
|
self.allocations = self.allocations.saturating_sub(1);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn is_empty(&self) -> bool {
|
|
|
|
|
self.allocations == 0
|
2020-02-26 12:34:34 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-02-26 18:49:46 +01:00
|
|
|
pub struct Region {
|
|
|
|
|
allocation: guillotiere::Allocation,
|
|
|
|
|
}
|
2020-02-26 12:34:34 +01:00
|
|
|
|
|
|
|
|
impl Region {
|
|
|
|
|
pub fn position(&self) -> (u32, u32) {
|
2020-02-26 18:49:46 +01:00
|
|
|
let rectangle = &self.allocation.rectangle;
|
2020-02-26 12:34:34 +01:00
|
|
|
|
2020-02-26 20:10:19 +01:00
|
|
|
(rectangle.min.x as u32, rectangle.min.y as u32)
|
2020-02-26 12:34:34 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn size(&self) -> (u32, u32) {
|
2020-02-26 18:49:46 +01:00
|
|
|
let size = self.allocation.rectangle.size();
|
2020-02-26 12:34:34 +01:00
|
|
|
|
2020-02-26 20:10:19 +01:00
|
|
|
(size.width as u32, size.height as u32)
|
2020-02-26 12:34:34 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl std::fmt::Debug for Allocator {
|
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
|
write!(f, "Allocator")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl std::fmt::Debug for Region {
|
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
2020-02-26 18:49:46 +01:00
|
|
|
f.debug_struct("Region")
|
|
|
|
|
.field("id", &self.allocation.id)
|
|
|
|
|
.field("rectangle", &self.allocation.rectangle)
|
|
|
|
|
.finish()
|
2020-02-26 12:34:34 +01:00
|
|
|
}
|
|
|
|
|
}
|