1use std::sync::Arc;
2
3use crate::{
4 emath::NumExt, mutex::RwLock, textures::TextureOptions, ImageData, ImageDelta, TextureId,
5 TextureManager,
6};
7
8#[must_use]
20pub struct TextureHandle {
21 tex_mngr: Arc<RwLock<TextureManager>>,
22 id: TextureId,
23}
24
25impl Drop for TextureHandle {
26 fn drop(&mut self) {
27 self.tex_mngr.write().free(self.id);
28 }
29}
30
31impl Clone for TextureHandle {
32 fn clone(&self) -> Self {
33 self.tex_mngr.write().retain(self.id);
34 Self {
35 tex_mngr: self.tex_mngr.clone(),
36 id: self.id,
37 }
38 }
39}
40
41impl PartialEq for TextureHandle {
42 #[inline]
43 fn eq(&self, other: &Self) -> bool {
44 self.id == other.id
45 }
46}
47
48impl Eq for TextureHandle {}
49
50impl std::hash::Hash for TextureHandle {
51 #[inline]
52 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
53 self.id.hash(state);
54 }
55}
56
57impl TextureHandle {
58 pub fn new(tex_mngr: Arc<RwLock<TextureManager>>, id: TextureId) -> Self {
60 Self { tex_mngr, id }
61 }
62
63 #[inline]
64 pub fn id(&self) -> TextureId {
65 self.id
66 }
67
68 pub fn set(&mut self, image: impl Into<ImageData>, options: TextureOptions) {
70 self.tex_mngr
71 .write()
72 .set(self.id, ImageDelta::full(image.into(), options));
73 }
74
75 pub fn set_partial(
77 &mut self,
78 pos: [usize; 2],
79 image: impl Into<ImageData>,
80 options: TextureOptions,
81 ) {
82 self.tex_mngr
83 .write()
84 .set(self.id, ImageDelta::partial(pos, image.into(), options));
85 }
86
87 pub fn size(&self) -> [usize; 2] {
89 self.tex_mngr
90 .read()
91 .meta(self.id)
92 .map_or([0, 0], |tex| tex.size)
93 }
94
95 pub fn size_vec2(&self) -> crate::Vec2 {
97 let [w, h] = self.size();
98 crate::Vec2::new(w as f32, h as f32)
99 }
100
101 pub fn byte_size(&self) -> usize {
103 self.tex_mngr
104 .read()
105 .meta(self.id)
106 .map_or(0, |tex| tex.bytes_used())
107 }
108
109 pub fn aspect_ratio(&self) -> f32 {
111 let [w, h] = self.size();
112 w as f32 / h.at_least(1) as f32
113 }
114
115 pub fn name(&self) -> String {
117 self.tex_mngr
118 .read()
119 .meta(self.id)
120 .map_or_else(|| "<none>".to_owned(), |tex| tex.name.clone())
121 }
122}
123
124impl From<&TextureHandle> for TextureId {
125 #[inline(always)]
126 fn from(handle: &TextureHandle) -> Self {
127 handle.id()
128 }
129}
130
131impl From<&mut TextureHandle> for TextureId {
132 #[inline(always)]
133 fn from(handle: &mut TextureHandle) -> Self {
134 handle.id()
135 }
136}