1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
//! Textured quad rendering for images with transform support.
//!
//! This module renders images as textured quads with full transform support
//! (rotation, scale, translate). Textures are cached for performance.
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use rustc_hash::FxHashMap;
use wgpu::util::DeviceExt;
use wgpu::{
BindGroup, Buffer as WgpuBuffer, Device, Extent3d, Queue, RenderPass, Texture,
TextureDimension, TextureFormat, TextureUsages,
};
use super::commands::DrawCommand;
use super::constants::{IMAGE_HASH_SAMPLE_SIZE, SVG_QUALITY_MULTIPLIER};
use super::flatten::FlattenedCommand;
use super::textured_quad::{QuadDraw, TexturedQuadPipeline};
use super::textured_vertex::{QuadClip, TexturedVertex};
use crate::widgets::Rect;
use crate::widgets::image::{ContentFit, ImageSource};
/// A prepared image quad ready for rendering.
pub struct PreparedImageQuad {
#[allow(dead_code)] // Kept alive for GPU usage
texture: Arc<CachedTexture>,
bind_group: BindGroup,
/// Vertex buffer with pre-computed vertices in NDC
vertex_buffer: WgpuBuffer,
}
impl QuadDraw for PreparedImageQuad {
fn bind_group(&self) -> &BindGroup {
&self.bind_group
}
fn vertex_buffer(&self) -> &WgpuBuffer {
&self.vertex_buffer
}
}
/// Cached texture data.
struct CachedTexture {
#[allow(dead_code)] // Kept alive for GPU usage
texture: Texture,
view: wgpu::TextureView,
/// Original intrinsic dimensions
intrinsic_width: u32,
intrinsic_height: u32,
/// Last frame this texture was used
last_used_frame: u64,
}
/// Cache key for image textures.
#[derive(Clone, Debug)]
struct CacheKey {
/// Hash of the source
source_hash: u64,
/// Rasterization variant (for SVGs): quantized scale + target size.
/// Raster images always use 0 — they decode at intrinsic size.
svg_variant: u64,
}
impl PartialEq for CacheKey {
fn eq(&self, other: &Self) -> bool {
self.source_hash == other.source_hash && self.svg_variant == other.svg_variant
}
}
impl Eq for CacheKey {}
impl Hash for CacheKey {
fn hash<H: Hasher>(&self, state: &mut H) {
self.source_hash.hash(state);
self.svg_variant.hash(state);
}
}
/// Renderer for images as textured quads.
pub struct ImageQuadRenderer {
/// Pipeline, layout, sampler and index buffer — shared with the text
/// renderer, which draws the same quad from a different texture.
quad: TexturedQuadPipeline,
// Texture cache
texture_cache: FxHashMap<CacheKey, Arc<CachedTexture>>,
current_frame: u64,
max_cache_size: usize,
}
impl ImageQuadRenderer {
pub fn new(device: &Device, format: TextureFormat) -> Self {
Self {
quad: TexturedQuadPipeline::new(device, format, "ImageQuad"),
texture_cache: FxHashMap::default(),
current_frame: 0,
max_cache_size: 64,
}
}
/// Update screen dimensions for NDC conversion.
pub fn set_screen_size(&mut self, width: f32, height: f32) {
self.quad.set_screen_size(width, height);
}
/// Begin a new frame (for cache management).
pub fn begin_frame(&mut self) {
self.current_frame += 1;
// Evict old entries if cache is too large
if self.texture_cache.len() > self.max_cache_size {
self.evict_oldest();
}
}
/// Evict the least recently used entries until under the limit.
fn evict_oldest(&mut self) {
let target_size = self.max_cache_size / 2;
while self.texture_cache.len() > target_size {
let oldest_key = self
.texture_cache
.iter()
.min_by_key(|(_, v)| v.last_used_frame)
.map(|(k, _)| k.clone());
if let Some(key) = oldest_key {
self.texture_cache.remove(&key);
} else {
break;
}
}
}
/// Hash bytes with improved sampling for collision resistance.
fn hash_bytes(bytes: &[u8], hasher: &mut impl Hasher) {
bytes.len().hash(hasher);
if bytes.len() < 1024 {
bytes.hash(hasher);
return;
}
// Sample: first + middle + last bytes for collision resistance
let sample = IMAGE_HASH_SAMPLE_SIZE;
bytes[..sample].hash(hasher);
let mid = bytes.len() / 2 - sample / 2;
bytes[mid..mid + sample].hash(hasher);
bytes[bytes.len() - sample..].hash(hasher);
}
/// Hash an image source for cache lookup.
fn hash_source(source: &ImageSource) -> u64 {
use std::collections::hash_map::DefaultHasher;
let mut hasher = DefaultHasher::new();
match source {
ImageSource::Path(path) => {
"path".hash(&mut hasher);
path.hash(&mut hasher);
}
ImageSource::Bytes(bytes) => {
"bytes".hash(&mut hasher);
Self::hash_bytes(bytes, &mut hasher);
}
ImageSource::Rgba {
width,
height,
pixels,
} => {
"rgba".hash(&mut hasher);
width.hash(&mut hasher);
height.hash(&mut hasher);
Self::hash_bytes(pixels, &mut hasher);
}
ImageSource::SvgPath(path) => {
"svg_path".hash(&mut hasher);
path.hash(&mut hasher);
}
ImageSource::SvgBytes(bytes) => {
"svg_bytes".hash(&mut hasher);
Self::hash_bytes(bytes, &mut hasher);
}
}
hasher.finish()
}
/// Get or create a cached texture for the given source.
///
/// `svg_target` is the widget rect the SVG will be displayed in
/// (logical pixels): the rasterization is sized to it instead of the
/// SVG's intrinsic size, so a 16px icon costs a 16px raster no matter
/// how large its viewBox is. `None` (ContentFit::None) keeps the
/// intrinsic size, which is what that fit mode displays.
fn get_or_create_texture(
&mut self,
device: &Device,
queue: &Queue,
source: &ImageSource,
transform_scale: f32,
scale_factor: f32,
svg_target: Option<(f32, f32)>,
) -> Option<Arc<CachedTexture>> {
let is_svg = source.is_svg();
let render_scale = if is_svg {
transform_scale * scale_factor * SVG_QUALITY_MULTIPLIER
} else {
1.0
};
// Quantize scale to reduce cache entries (round to 0.25 increments)
let quantized_scale = (render_scale * 4.0).round() as u32;
let source_hash = Self::hash_source(source);
// SVG rasterization variant: scale + quantized target size (the
// same icon shown at 16px and 48px needs two textures).
let svg_variant = if is_svg {
let (qw, qh) = match svg_target {
Some((w, h)) => (w.round().max(1.0) as u64, h.round().max(1.0) as u64),
None => (0, 0),
};
(quantized_scale as u64) << 40 | qw << 20 | qh
} else {
0
};
let key = CacheKey {
source_hash,
svg_variant,
};
// Check if we already have this texture cached
if let Some(cached) = self.texture_cache.get_mut(&key) {
// Update last used frame via Arc::get_mut if possible
if let Some(inner) = Arc::get_mut(cached) {
inner.last_used_frame = self.current_frame;
}
return Some(cached.clone());
}
// Load and create texture
let texture = self.load_texture(device, queue, source, render_scale, svg_target)?;
let cached = Arc::new(texture);
self.texture_cache.insert(key, cached.clone());
Some(cached)
}
/// Load and upload a texture to the GPU.
fn load_texture(
&self,
device: &Device,
queue: &Queue,
source: &ImageSource,
render_scale: f32,
svg_target: Option<(f32, f32)>,
) -> Option<CachedTexture> {
// Use Rgba8Unorm to pass colors through without sRGB conversion
let format = TextureFormat::Rgba8Unorm;
match source {
ImageSource::Path(path) => {
// Decode failures must be loud: a missing decoder feature
// (e.g. `webp` disabled) or a bad file otherwise degrades to
// a silently empty box.
let img = match image::open(path) {
Ok(img) => img,
Err(e) => {
log::warn!("Failed to decode image {}: {e}", path.display());
return None;
}
};
let rgba = img.to_rgba8();
let (width, height) = rgba.dimensions();
self.upload_raster(device, queue, &format, width, height, rgba.as_raw())
}
ImageSource::Bytes(bytes) => {
let img = match image::load_from_memory(bytes) {
Ok(img) => img,
Err(e) => {
log::warn!("Failed to decode in-memory image: {e}");
return None;
}
};
let rgba = img.to_rgba8();
let (width, height) = rgba.dimensions();
self.upload_raster(device, queue, &format, width, height, rgba.as_raw())
}
ImageSource::Rgba {
width,
height,
pixels,
} => {
let expected = (*width as usize)
.checked_mul(*height as usize)
.and_then(|v| v.checked_mul(4));
if Some(pixels.len()) != expected {
log::warn!(
"Rgba image source size mismatch: {}x{} expects {:?} bytes, got {}",
width,
height,
expected,
pixels.len()
);
return None;
}
self.upload_raster(device, queue, &format, *width, *height, pixels)
}
ImageSource::SvgPath(path) => {
let data = match std::fs::read(path) {
Ok(data) => data,
Err(e) => {
log::warn!("Failed to read SVG {}: {e}", path.display());
return None;
}
};
self.load_svg(device, queue, &format, &data, render_scale, svg_target)
}
ImageSource::SvgBytes(bytes) => {
self.load_svg(device, queue, &format, bytes, render_scale, svg_target)
}
}
}
/// Upload raw RGBA8 pixel data to GPU.
fn upload_raster(
&self,
device: &Device,
queue: &Queue,
format: &TextureFormat,
width: u32,
height: u32,
rgba: &[u8],
) -> Option<CachedTexture> {
if width == 0 || height == 0 {
return None;
}
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Image Texture"),
size: Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: *format,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
rgba,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(4 * width),
rows_per_image: Some(height),
},
Extent3d {
width,
height,
depth_or_array_layers: 1,
},
);
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
Some(CachedTexture {
texture,
view,
intrinsic_width: width,
intrinsic_height: height,
last_used_frame: self.current_frame,
})
}
/// Fallback when the `svg` feature is disabled: SVG sources fail to
/// decode with a warning instead of failing to compile.
#[cfg(not(feature = "svg"))]
fn load_svg(
&self,
_device: &Device,
_queue: &Queue,
_format: &TextureFormat,
_bytes: &[u8],
_scale: f32,
_target: Option<(f32, f32)>,
) -> Option<CachedTexture> {
log::warn!("SVG image used but the `svg` feature is disabled");
None
}
/// Load and rasterize an SVG.
///
/// With a `target` (the widget rect in logical pixels) the raster is
/// sized to what will actually be displayed rather than the SVG's
/// intrinsic size — a 16px weather icon with a 104px viewBox costs a
/// 16px raster, not a 104px one. This is both faster (rasterization
/// cost scales with pixels) and sharper (no GPU minification).
#[cfg(feature = "svg")]
fn load_svg(
&self,
device: &Device,
queue: &Queue,
format: &TextureFormat,
bytes: &[u8],
scale: f32,
target: Option<(f32, f32)>,
) -> Option<CachedTexture> {
let tree = resvg::usvg::Tree::from_data(bytes, &resvg::usvg::Options::default()).ok()?;
let size = tree.size();
let intrinsic_width = size.width() as u32;
let intrinsic_height = size.height() as u32;
// Fit the raster to the display target, preserving aspect ratio
// (contain). `scale` already carries transform scale, HiDPI factor
// and the quality multiplier.
let scale = match target {
Some((tw, th)) if tw >= 1.0 && th >= 1.0 => {
scale * (tw / size.width()).min(th / size.height())
}
_ => scale,
};
// Calculate scaled dimensions
let scaled_width = (size.width() * scale).ceil() as u32;
let scaled_height = (size.height() * scale).ceil() as u32;
if scaled_width == 0 || scaled_height == 0 {
return None;
}
// Create a pixmap for rendering
let mut pixmap = resvg::tiny_skia::Pixmap::new(scaled_width, scaled_height)?;
// Create transform for scaling
let transform = resvg::tiny_skia::Transform::from_scale(scale, scale);
// Render the SVG
resvg::render(&tree, transform, &mut pixmap.as_mut());
// Upload to GPU
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("SVG Texture"),
size: Extent3d {
width: scaled_width,
height: scaled_height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: *format,
usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
pixmap.data(),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(4 * scaled_width),
rows_per_image: Some(scaled_height),
},
Extent3d {
width: scaled_width,
height: scaled_height,
depth_or_array_layers: 1,
},
);
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
Some(CachedTexture {
texture,
view,
intrinsic_width,
intrinsic_height,
last_used_frame: self.current_frame,
})
}
/// Prepare image commands for rendering, appending them to `out`.
///
/// The caller's buffer rather than one of ours: every group's quads end up
/// in the same frame-long `Vec` addressed by range, so a `Vec` returned
/// here would be allocated per group only to be drained into that one.
pub fn prepare(
&mut self,
device: &Device,
queue: &Queue,
commands: &[FlattenedCommand],
scale_factor: f32,
out: &mut Vec<PreparedImageQuad>,
) {
out.extend(
commands
.iter()
.filter_map(|cmd| self.prepare_single(device, queue, cmd, scale_factor)),
);
}
/// Prepare a single image command.
fn prepare_single(
&mut self,
device: &Device,
queue: &Queue,
cmd: &FlattenedCommand,
scale_factor: f32,
) -> Option<PreparedImageQuad> {
let (source, rect, content_fit) = match &*cmd.command {
DrawCommand::Image {
source,
rect,
content_fit,
} => (source, rect, content_fit),
_ => return None,
};
// Extract scale from transform for SVG quality
let transform_scale = cmd.world_transform.extract_scale().max(1.0);
// Rasterize SVGs at the size they are displayed at; ContentFit::None
// shows the image at intrinsic size, so no target there.
let svg_target = (*content_fit != ContentFit::None).then_some((rect.width, rect.height));
// Get or create the texture
let cached = self.get_or_create_texture(
device,
queue,
source,
transform_scale,
scale_factor,
svg_target,
)?;
// Create bind group
let bind_group = self
.quad
.bind_texture(device, &cached.view, "ImageQuad Bind Group");
// Calculate display rect and UV coordinates based on content fit
let (display_rect, uv) = self.calculate_display_rect_and_uv(
rect,
cached.intrinsic_width,
cached.intrinsic_height,
*content_fit,
);
// An image is cut in the clip's own space, so a turned clip cuts the
// turned shape.
let clip = cmd
.clip()
.map_or(QuadClip::NONE, |clip| QuadClip::shape(&clip, scale_factor));
let vertices =
self.compute_vertices(&display_rect, &cmd.world_transform, uv, scale_factor, clip);
// Create vertex buffer
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("ImageQuad Vertex Buffer"),
contents: bytemuck::cast_slice(&vertices),
usage: wgpu::BufferUsages::VERTEX,
});
Some(PreparedImageQuad {
texture: cached,
bind_group,
vertex_buffer,
})
}
/// Calculate the display rect and UV coordinates based on content fit.
fn calculate_display_rect_and_uv(
&self,
rect: &Rect,
intrinsic_width: u32,
intrinsic_height: u32,
content_fit: ContentFit,
) -> (Rect, (f32, f32, f32, f32)) {
let img_width = intrinsic_width as f32;
let img_height = intrinsic_height as f32;
let img_aspect = img_width / img_height;
let widget_aspect = rect.width / rect.height;
match content_fit {
ContentFit::Fill => {
// Stretch to fill - use full rect and full UV
(*rect, (0.0, 0.0, 1.0, 1.0))
}
ContentFit::Contain => {
// Fit within bounds, preserving aspect ratio (letterbox/pillarbox)
let (scaled_w, scaled_h) = if widget_aspect > img_aspect {
// Widget is wider - fit to height, center horizontally
(rect.height * img_aspect, rect.height)
} else {
// Widget is taller - fit to width, center vertically
(rect.width, rect.width / img_aspect)
};
let offset_x = (rect.width - scaled_w) / 2.0;
let offset_y = (rect.height - scaled_h) / 2.0;
(
Rect::new(rect.x + offset_x, rect.y + offset_y, scaled_w, scaled_h),
(0.0, 0.0, 1.0, 1.0),
)
}
ContentFit::Cover => {
// Cover bounds, cropping as needed (adjust UV to crop)
let (u_min, v_min, u_max, v_max) = if widget_aspect > img_aspect {
// Widget is wider - crop top/bottom
let visible_height = img_aspect / widget_aspect;
let v_offset = (1.0 - visible_height) / 2.0;
(0.0, v_offset, 1.0, v_offset + visible_height)
} else {
// Widget is taller - crop left/right
let visible_width = widget_aspect / img_aspect;
let u_offset = (1.0 - visible_width) / 2.0;
(u_offset, 0.0, u_offset + visible_width, 1.0)
};
(*rect, (u_min, v_min, u_max, v_max))
}
ContentFit::None => {
// Use intrinsic size, centered in widget
let offset_x = (rect.width - img_width) / 2.0;
let offset_y = (rect.height - img_height) / 2.0;
(
Rect::new(rect.x + offset_x, rect.y + offset_y, img_width, img_height),
(0.0, 0.0, 1.0, 1.0),
)
}
}
}
/// Compute vertex positions by applying world transform to local corners.
fn compute_vertices(
&self,
rect: &Rect,
world_transform: &crate::transform::Transform,
uv: (f32, f32, f32, f32),
scale_factor: f32,
clip: QuadClip,
) -> [TexturedVertex; 4] {
// Get local rect corners
let local_corners = [
(rect.x, rect.y), // top-left
(rect.x + rect.width, rect.y), // top-right
(rect.x, rect.y + rect.height), // bottom-left
(rect.x + rect.width, rect.y + rect.height), // bottom-right
];
// Apply world_transform to get screen coordinates (in logical pixels)
// Then multiply by scale_factor to get physical pixels
let screen_corners: [(f32, f32); 4] = [
{
let (sx, sy) =
world_transform.transform_point(local_corners[0].0, local_corners[0].1);
(sx * scale_factor, sy * scale_factor)
},
{
let (sx, sy) =
world_transform.transform_point(local_corners[1].0, local_corners[1].1);
(sx * scale_factor, sy * scale_factor)
},
{
let (sx, sy) =
world_transform.transform_point(local_corners[2].0, local_corners[2].1);
(sx * scale_factor, sy * scale_factor)
},
{
let (sx, sy) =
world_transform.transform_point(local_corners[3].0, local_corners[3].1);
(sx * scale_factor, sy * scale_factor)
},
];
let (u_min, v_min, u_max, v_max) = uv;
let uvs = [
[u_min, v_min],
[u_max, v_min],
[u_min, v_max],
[u_max, v_max],
];
std::array::from_fn(|i| {
let (x, y) = screen_corners[i];
TexturedVertex::corner(self.quad.to_ndc(x, y), uvs[i], (x, y), &clip)
})
}
/// Render the prepared image quads.
pub fn render<'a>(&'a self, render_pass: &mut RenderPass<'a>, quads: &'a [PreparedImageQuad]) {
self.quad.draw(render_pass, quads);
}
}