1use std::rc::Rc;
16use std::sync::atomic::{AtomicU32, Ordering};
17
18use crate::id::ElementId;
19use crate::paint::{PaintCommand, PaintList, TextureFrameMeta};
20use crate::render_object::{BoxConstraints, LayoutContext, RenderObject};
21use crate::{Color, Point, Rect, Size};
22
23static NEXT_IMAGE_ID: AtomicU32 = AtomicU32::new(1);
25
26pub fn next_image_id() -> u32 {
28 NEXT_IMAGE_ID.fetch_add(1, Ordering::Relaxed)
29}
30
31#[derive(Clone)]
38pub struct ImageData {
39 pub rgba: Vec<u8>,
40 pub width: u32,
41 pub height: u32,
42 pub stride: usize,
44}
45
46impl ImageData {
47 pub fn new(rgba: Vec<u8>, width: u32, height: u32) -> Self {
49 Self { rgba, width, height, stride: 0 }
50 }
51
52 pub fn with_stride(rgba: Vec<u8>, width: u32, height: u32, stride: usize) -> Self {
57 debug_assert!(stride >= width as usize * 4, "stride({stride}) 小于 width*4,行会互相覆盖");
58 debug_assert!(rgba.len() >= stride.saturating_mul(height as usize), "rgba 长度不足 stride*height");
59 Self { rgba, width, height, stride }
60 }
61
62 pub fn row_bytes(&self) -> usize {
64 if self.stride == 0 {
65 (self.width as usize) * 4
66 } else {
67 self.stride
68 }
69 }
70
71 pub fn is_packed(&self) -> bool {
73 self.row_bytes() == (self.width as usize) * 4
74 }
75
76 pub fn min_len(&self) -> usize {
78 self.row_bytes().saturating_mul(self.height as usize)
79 }
80
81 pub fn row(&self, y: usize) -> &[u8] {
83 let pitch = self.row_bytes();
84 let start = y.checked_mul(pitch);
85 match start {
86 Some(s) if s + pitch <= self.rgba.len() && y < self.height as usize => &self.rgba[s..s + pitch],
87 _ => &[],
88 }
89 }
90
91 pub fn solid(width: u32, height: u32, color: Color) -> Self {
93 let mut rgba = Vec::with_capacity((width * height * 4) as usize);
94 for _ in 0..width * height {
95 rgba.extend_from_slice(&[
96 (color.r * 255.0) as u8,
97 (color.g * 255.0) as u8,
98 (color.b * 255.0) as u8,
99 (color.a * 255.0) as u8,
100 ]);
101 }
102 Self { rgba, width, height, stride: 0 }
103 }
104
105 pub fn pixel_count(&self) -> u32 {
107 self.width * self.height
108 }
109}
110
111impl std::fmt::Debug for ImageData {
112 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113 f.debug_struct("ImageData")
114 .field("width", &self.width)
115 .field("height", &self.height)
116 .field("bytes", &self.rgba.len())
117 .field("stride", &self.row_bytes())
118 .finish()
119 }
120}
121
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum TextureUpdate {
133 Reuse,
135 UpdateContent,
137 Recreate,
139}
140
141pub fn image_identity(data: &Rc<ImageData>) -> usize {
144 Rc::as_ptr(data) as *const u8 as usize
145}
146
147pub fn plan_texture_update(have: Option<(usize, u32, u32)>, want: (usize, u32, u32)) -> TextureUpdate {
155 let Some((prev_id, prev_w, prev_h)) = have else {
156 return TextureUpdate::Recreate;
157 };
158 let (_, w, h) = want;
159 if prev_id == want.0 {
160 return if prev_w == w && prev_h == h { TextureUpdate::Reuse } else { TextureUpdate::Recreate };
162 }
163 if prev_w == w && prev_h == h {
164 TextureUpdate::UpdateContent
165 } else {
166 TextureUpdate::Recreate
167 }
168}
169
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
172pub enum BoxFit {
173 #[default]
175 Fill,
176 Contain,
178}
179
180pub struct ImageRenderObject {
186 pub image: Rc<ImageData>,
187 pub texture_id: u32,
188 pub width: Option<f32>,
189 pub height: Option<f32>,
190 pub fit: BoxFit,
191 pub element_id: Option<ElementId>,
192 pub cached_size: Size,
194 pub dst_rect: Rect,
196 pub meta: Option<TextureFrameMeta>,
198}
199
200impl ImageRenderObject {
201 pub fn new(image: Rc<ImageData>, texture_id: u32, width: Option<f32>, height: Option<f32>, fit: BoxFit) -> Self {
202 Self {
203 image,
204 texture_id,
205 width,
206 height,
207 fit,
208 element_id: None,
209 cached_size: Size::ZERO,
210 dst_rect: Rect::new(0.0, 0.0, 0.0, 0.0),
211 meta: None,
212 }
213 }
214
215 pub fn paint_with_latest_seq(&self, offset: Point, painter: &mut PaintList, latest_seq: u64) {
221 self.paint_impl(offset, painter, Some(latest_seq));
222 }
223
224 fn paint_impl(&self, offset: Point, painter: &mut PaintList, latest_seq: Option<u64>) {
225 let d = self.dst_rect;
226 if d.width <= 0.0 || d.height <= 0.0 {
227 return;
228 }
229 let meta = self.meta.map(|mut m| {
231 if let Some(s) = latest_seq {
232 m.latest_seq = s;
233 }
234 m
235 });
236 match meta {
237 Some(m) => painter.push_texture_with_meta(self.texture_id, Rc::clone(&self.image), m),
238 None => painter.push_texture(self.texture_id, Rc::clone(&self.image)),
239 }
240 painter.push(PaintCommand::TexturedRect {
242 rect: Rect::new(offset.x + d.x, offset.y + d.y, d.width, d.height),
243 color: Color::WHITE,
244 uv: [0.0, 0.0, 1.0, 1.0],
245 texture_id: self.texture_id,
246 mode: crate::paint::TextureMode::Color,
247 });
248 }
249}
250
251impl RenderObject for ImageRenderObject {
252 fn layout(&mut self, constraints: BoxConstraints, _ctx: &mut LayoutContext) -> Size {
253 let natural_w = self.image.width as f32;
254 let natural_h = self.image.height as f32;
255 let want = Size::new(self.width.unwrap_or(natural_w), self.height.unwrap_or(natural_h));
256 self.cached_size = constraints.constrain(want);
257
258 self.dst_rect = match self.fit {
260 BoxFit::Fill => Rect::new(0.0, 0.0, self.cached_size.width, self.cached_size.height),
261 BoxFit::Contain => {
262 if natural_w <= 0.0
263 || natural_h <= 0.0
264 || self.cached_size.width <= 0.0
265 || self.cached_size.height <= 0.0
266 {
267 Rect::new(0.0, 0.0, 0.0, 0.0)
268 } else {
269 let scale = (self.cached_size.width / natural_w).min(self.cached_size.height / natural_h);
270 let dw = natural_w * scale;
271 let dh = natural_h * scale;
272 Rect::new((self.cached_size.width - dw) / 2.0, (self.cached_size.height - dh) / 2.0, dw, dh)
273 }
274 }
275 };
276 self.cached_size
277 }
278
279 fn content_size(&self) -> Size {
280 self.cached_size
281 }
282
283 fn paint(&self, offset: Point, painter: &mut PaintList) {
284 self.paint_impl(offset, painter, None);
285 }
286
287 fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
288 let rect = Rect::new(
290 offset.x + self.dst_rect.x,
291 offset.y + self.dst_rect.y,
292 self.dst_rect.width,
293 self.dst_rect.height,
294 );
295 if rect.contains(position) {
296 self.element_id
297 } else {
298 None
299 }
300 }
301
302 fn set_element_id(&mut self, id: ElementId) {
303 self.element_id = Some(id);
304 }
305
306 fn element_id(&self) -> Option<ElementId> {
307 self.element_id
308 }
309
310 fn children_count(&self) -> usize {
311 0
312 }
313}
314
315