1use std::sync::{Arc, Weak};
4
5use super::frames::{FramePool, HalfPixel};
6use super::half;
7use crate::{RenderError, RenderSize};
8
9#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash)]
11pub(crate) struct PixelBox {
12 pub(crate) x: u32,
13 pub(crate) y: u32,
14 pub(crate) width: u32,
15 pub(crate) height: u32,
16}
17
18impl PixelBox {
19 pub(crate) const EMPTY: Self = Self {
20 x: 0,
21 y: 0,
22 width: 0,
23 height: 0,
24 };
25
26 pub(crate) const fn whole(size: RenderSize) -> Self {
27 Self {
28 x: 0,
29 y: 0,
30 width: size.width,
31 height: size.height,
32 }
33 }
34
35 pub(crate) const fn is_empty(self) -> bool {
36 self.width == 0 || self.height == 0
37 }
38
39 pub(crate) const fn right(self) -> u32 {
40 self.x + self.width
41 }
42
43 pub(crate) const fn bottom(self) -> u32 {
44 self.y + self.height
45 }
46
47 pub(crate) fn pixels(self) -> usize {
48 self.width as usize * self.height as usize
49 }
50
51 pub(crate) const fn contains(self, x: u32, y: u32) -> bool {
52 x >= self.x && x < self.x + self.width && y >= self.y && y < self.y + self.height
53 }
54
55 pub(crate) fn intersect(self, other: Self) -> Self {
57 let x = self.x.max(other.x);
58 let y = self.y.max(other.y);
59 let right = self.right().min(other.right());
60 let bottom = self.bottom().min(other.bottom());
61 if right <= x || bottom <= y {
62 return Self::EMPTY;
63 }
64 Self {
65 x,
66 y,
67 width: right - x,
68 height: bottom - y,
69 }
70 }
71
72 pub(crate) fn union(self, other: Self) -> Self {
74 if self.is_empty() {
75 return other;
76 }
77 if other.is_empty() {
78 return self;
79 }
80 let x = self.x.min(other.x);
81 let y = self.y.min(other.y);
82 Self {
83 x,
84 y,
85 width: self.right().max(other.right()) - x,
86 height: self.bottom().max(other.bottom()) - y,
87 }
88 }
89
90 pub(crate) fn expand(self, margin: u32, size: RenderSize) -> Self {
92 if self.is_empty() {
93 return self;
94 }
95 let x = self.x.saturating_sub(margin);
96 let y = self.y.saturating_sub(margin);
97 let right = self.right().saturating_add(margin).min(size.width);
98 let bottom = self.bottom().saturating_add(margin).min(size.height);
99 Self {
100 x,
101 y,
102 width: right - x,
103 height: bottom - y,
104 }
105 }
106}
107
108#[derive(Clone, Debug)]
110pub(crate) enum Pixels {
111 Half(Vec<[u16; 4]>),
113 Unorm8(Vec<[u8; 4]>),
115}
116
117#[derive(Clone, Debug)]
122pub struct CpuImage {
123 size: RenderSize,
124 bounds: PixelBox,
125 pixels: Pixels,
126 pool: Weak<FramePool>,
128}
129
130impl CpuImage {
131 pub(crate) fn new(size: RenderSize, bounds: PixelBox, pixels: Pixels) -> Self {
132 let bounds = bounds.intersect(PixelBox::whole(size));
133 debug_assert_eq!(
134 match &pixels {
135 Pixels::Half(pixels) => pixels.len(),
136 Pixels::Unorm8(pixels) => pixels.len(),
137 },
138 bounds.pixels()
139 );
140 Self {
141 size,
142 bounds,
143 pixels,
144 pool: Weak::new(),
145 }
146 }
147
148 pub(crate) fn pooled(
150 size: RenderSize,
151 bounds: PixelBox,
152 pixels: Vec<HalfPixel>,
153 pool: &Arc<FramePool>,
154 ) -> Self {
155 let mut image = Self::new(size, bounds, Pixels::Half(pixels));
156 image.pool = Arc::downgrade(pool);
157 image
158 }
159
160 pub(crate) fn transparent(size: RenderSize) -> Self {
162 Self {
163 size,
164 bounds: PixelBox::EMPTY,
165 pixels: Pixels::Half(Vec::new()),
166 pool: Weak::new(),
167 }
168 }
169
170 pub fn from_premultiplied_rgba8(size: RenderSize, rgba8: &[u8]) -> Result<Self, RenderError> {
176 let expected = size.width as usize * size.height as usize * 4;
177 if rgba8.len() != expected {
178 return Err(RenderError::InvalidImageData);
179 }
180 let pixels = rgba8.as_chunks::<4>().0.to_vec();
181 Ok(Self::new(
182 size,
183 PixelBox::whole(size),
184 Pixels::Unorm8(pixels),
185 ))
186 }
187
188 #[must_use]
190 pub const fn size(&self) -> RenderSize {
191 self.size
192 }
193
194 pub(crate) const fn bounds(&self) -> PixelBox {
195 self.bounds
196 }
197
198 pub(crate) const fn pixels(&self) -> &Pixels {
199 &self.pixels
200 }
201
202 #[must_use]
204 pub fn retained_bytes(&self) -> u64 {
205 let pixels = self.bounds.pixels() as u64;
206 match self.pixels {
207 Pixels::Half(_) => pixels * 8,
208 Pixels::Unorm8(_) => pixels * 4,
209 }
210 }
211
212 #[must_use]
214 pub fn read_rgba8(&self) -> Vec<u8> {
215 let width = self.size.width as usize;
216 let mut bytes = vec![0_u8; width * self.size.height as usize * 4];
217 let bounds = self.bounds;
218 for row in 0..bounds.height as usize {
219 let start = ((bounds.y as usize + row) * width + bounds.x as usize) * 4;
220 let out = &mut bytes[start..start + bounds.width as usize * 4];
221 match &self.pixels {
222 Pixels::Half(pixels) => {
223 let line = &pixels[row * bounds.width as usize..][..bounds.width as usize];
224 for (pixel, out) in line.iter().zip(out.as_chunks_mut::<4>().0) {
225 *out = half::load4(*pixel).map(half::unorm8);
226 }
227 }
228 Pixels::Unorm8(pixels) => {
229 let line = &pixels[row * bounds.width as usize..][..bounds.width as usize];
230 out.copy_from_slice(line.as_flattened());
231 }
232 }
233 }
234 bytes
235 }
236
237 #[cfg(test)]
239 pub(crate) fn stored_bits(&self) -> Vec<[u16; 4]> {
240 let mut bits = Vec::with_capacity(self.size.width as usize * self.size.height as usize);
241 for y in 0..self.size.height {
242 for x in 0..self.size.width {
243 bits.push(half::store4(self.texel(x, y)));
244 }
245 }
246 bits
247 }
248
249 #[inline(always)]
251 #[allow(clippy::inline_always)]
252 pub(crate) fn texel(&self, x: u32, y: u32) -> [f32; 4] {
253 self.texels().texel(x, y)
254 }
255
256 #[inline(always)]
258 #[allow(clippy::inline_always)]
259 pub(crate) fn texels(&self) -> Texels<'_> {
260 Texels {
261 storage: match &self.pixels {
262 Pixels::Half(pixels) => Storage::Half(pixels, half::table()),
263 Pixels::Unorm8(pixels) => Storage::Unorm8(pixels),
264 },
265 bounds: self.bounds,
266 whole: self.bounds == PixelBox::whole(self.size),
267 last: [
268 i64::from(self.size.width) - 1,
269 i64::from(self.size.height) - 1,
270 ],
271 #[allow(clippy::cast_precision_loss)]
272 size: [self.size.width as f32, self.size.height as f32],
273 }
274 }
275
276 pub(crate) fn decode_row(&self, y: u32, x0: u32, out: &mut [[f32; 4]]) {
278 let bounds = self.bounds;
279 if y < bounds.y || y >= bounds.bottom() {
280 out.fill([0.0; 4]);
281 return;
282 }
283 let row = (y - bounds.y) as usize * bounds.width as usize;
284 let start = x0.max(bounds.x);
285 #[allow(clippy::cast_possible_truncation)]
286 let end = (x0 + out.len() as u32).min(bounds.right());
287 out.fill([0.0; 4]);
288 if start >= end {
289 return;
290 }
291 let target = &mut out[(start - x0) as usize..(end - x0) as usize];
292 let source = row + (start - bounds.x) as usize..row + (end - bounds.x) as usize;
293 match &self.pixels {
294 Pixels::Half(pixels) => {
295 let table = half::table();
296 for (pixel, bits) in target.iter_mut().zip(&pixels[source]) {
297 *pixel = bits.map(|bits| table[usize::from(bits)]);
298 }
299 }
300 Pixels::Unorm8(pixels) => {
301 for (pixel, codes) in target.iter_mut().zip(&pixels[source]) {
302 *pixel = codes.map(half::unorm8_value);
303 }
304 }
305 }
306 }
307
308 #[inline(always)]
310 #[allow(clippy::inline_always)]
311 pub(crate) fn texel_clamped(&self, x: i64, y: i64) -> [f32; 4] {
312 self.texels().texel_clamped(x, y)
313 }
314
315 #[inline(always)]
317 #[allow(clippy::inline_always)]
318 pub(crate) fn sample(&self, u: f32, v: f32) -> [f32; 4] {
319 self.texels().sample(u, v)
320 }
321}
322
323#[derive(Clone, Copy)]
325enum Storage<'a> {
326 Half(&'a [[u16; 4]], &'static [f32; 65_536]),
327 Unorm8(&'a [[u8; 4]]),
328}
329
330#[derive(Clone, Copy)]
332pub(crate) struct Texels<'a> {
333 storage: Storage<'a>,
334 bounds: PixelBox,
335 whole: bool,
337 last: [i64; 2],
338 size: [f32; 2],
339}
340
341#[allow(clippy::inline_always)]
343impl Texels<'_> {
344 #[inline(always)]
346 pub(crate) fn texel(&self, x: u32, y: u32) -> [f32; 4] {
347 let bounds = self.bounds;
348 if !self.whole && !bounds.contains(x, y) {
349 return [0.0; 4];
350 }
351 debug_assert!(bounds.contains(x, y), "({x}, {y}) is inside the picture");
352 let index = (y - bounds.y) as usize * bounds.width as usize + (x - bounds.x) as usize;
353 match self.storage {
354 Storage::Half(pixels, table) => pixels[index].map(|bits| table[usize::from(bits)]),
355 Storage::Unorm8(pixels) => pixels[index].map(half::unorm8_value),
356 }
357 }
358
359 #[inline(always)]
361 pub(crate) fn texel_clamped(&self, x: i64, y: i64) -> [f32; 4] {
362 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
363 self.texel(
364 x.clamp(0, self.last[0]) as u32,
365 y.clamp(0, self.last[1]) as u32,
366 )
367 }
368
369 #[inline(always)]
371 pub(crate) fn sample(&self, u: f32, v: f32) -> [f32; 4] {
372 let x = (u * self.size[0] - 0.5).clamp(-1.0, self.size[0]);
375 let y = (v * self.size[1] - 0.5).clamp(-1.0, self.size[1]);
376 let x0 = x.floor();
377 let y0 = y.floor();
378 let fx = x - x0;
379 let fy = y - y0;
380 #[allow(clippy::cast_possible_truncation)]
381 let (ix, iy) = (x0 as i64, y0 as i64);
382 let t00 = self.texel_clamped(ix, iy);
383 let t10 = self.texel_clamped(ix + 1, iy);
384 let t01 = self.texel_clamped(ix, iy + 1);
385 let t11 = self.texel_clamped(ix + 1, iy + 1);
386 let mut out = [0.0; 4];
387 for channel in 0..4 {
388 let top = t00[channel] + (t10[channel] - t00[channel]) * fx;
389 let bottom = t01[channel] + (t11[channel] - t01[channel]) * fx;
390 out[channel] = top + (bottom - top) * fy;
391 }
392 out
393 }
394}
395
396impl Drop for CpuImage {
397 fn drop(&mut self) {
398 if let Pixels::Half(pixels) = &mut self.pixels
399 && let Some(pool) = self.pool.upgrade()
400 {
401 pool.give_back(std::mem::take(pixels));
402 }
403 }
404}