1mod color;
21mod loader;
22mod pixels;
23#[cfg(feature = "svg")]
24mod svg;
25#[cfg(feature = "svg")]
26mod svg_paint;
27
28use std::collections::HashMap;
29use std::fmt;
30use std::path::{Path, PathBuf};
31use std::rc::{Rc, Weak};
32use std::sync::Arc;
33use std::time::Duration;
34
35use animation::Curve;
36use reactive::{Effect, Signal, signal, untracked};
37use scene::{AtlasUpdate, Color, ColorMatrix, DisplayList, IMAGE_ATLAS_LEVELS, ImageData, ImageEncoding, ImageUpdate, Quad, max_atlas_size};
38
39use crate::property::Property;
40use crate::element::Element;
41use crate::geometry::Affine;
42use crate::gradient::Fill;
43
44use crate::property::{IntoProp, PropId, Prop};
45use crate::geometry::Rect;
46use crate::tree::{NodeId, Tree, TreeRef};
47
48pub(crate) use loader::{ImageRef, Status, acquire};
49use pixels::Frames;
50#[cfg(feature = "svg")]
51pub(crate) use svg_paint::SvgTarget;
52
53pub fn image<V: Into<ImageSource> + 'static>(source: impl IntoProp<V>) -> Element {
73 Element::from_kind(ImageBlock::default()).set(crate::property::SOURCE, source)
74}
75
76#[derive(Clone)]
78pub struct ImageSource {
79 pub(crate) kind: SourceKind,
80 pub(crate) max_size: Option<u32>,
81 pub(crate) revision: u64,
83}
84
85#[derive(Clone)]
86pub(crate) enum SourceKind {
87 File(Arc<Path>),
88 Bytes(Arc<[u8]>),
89 Static(&'static [u8]),
90 Rgba { width: u32, height: u32, pixels: Arc<[u8]> },
91 RgbaF32 { width: u32, height: u32, pixels: Arc<[f32]> },
92}
93
94#[derive(Clone, PartialEq, Eq, Hash, Debug)]
96pub(crate) struct SourceKey {
97 kind: KeyKind,
98 max_size: Option<u32>,
99 revision: u64,
100}
101
102#[derive(Clone, PartialEq, Eq, Hash, Debug)]
103enum KeyKind {
104 File(Arc<Path>),
105 Memory(usize, usize),
106 Rgba(usize, usize, u32),
107}
108
109impl ImageSource {
110 pub fn file(path: impl AsRef<Path>) -> Self {
112 Self { kind: SourceKind::File(path.as_ref().into()), max_size: None, revision: 0 }
113 }
114
115 pub fn bytes(bytes: impl Into<Arc<[u8]>>) -> Self {
118 Self { kind: SourceKind::Bytes(bytes.into()), max_size: None, revision: 0 }
119 }
120
121 pub fn from_static(bytes: &'static [u8]) -> Self {
123 Self { kind: SourceKind::Static(bytes), max_size: None, revision: 0 }
124 }
125
126 pub fn rgba(width: u32, height: u32, pixels: impl Into<Arc<[u8]>>) -> Self {
128 Self { kind: SourceKind::Rgba { width, height, pixels: pixels.into() }, max_size: None, revision: 0 }
129 }
130
131 pub fn rgba_f32(width: u32, height: u32, pixels: impl Into<Arc<[f32]>>) -> Self {
135 Self { kind: SourceKind::RgbaF32 { width, height, pixels: pixels.into() }, max_size: None, revision: 0 }
136 }
137
138 pub fn max_size(mut self, pixels: u32) -> Self {
141 self.max_size = Some(pixels.max(1));
142 self
143 }
144
145 pub(crate) fn key(&self) -> SourceKey {
146 let kind = match &self.kind {
147 SourceKind::File(path) => KeyKind::File(path.clone()),
148 SourceKind::Bytes(bytes) => KeyKind::Memory(bytes.as_ptr() as usize, bytes.len()),
149 SourceKind::Static(bytes) => KeyKind::Memory(bytes.as_ptr() as usize, bytes.len()),
150 SourceKind::Rgba { width, pixels, .. } => KeyKind::Rgba(pixels.as_ptr() as usize, pixels.len(), *width),
151 SourceKind::RgbaF32 { width, pixels, .. } => KeyKind::Rgba(pixels.as_ptr() as usize, pixels.len() * 4, *width),
152 };
153 SourceKey { kind, max_size: self.max_size, revision: self.revision }
154 }
155}
156
157impl PartialEq for ImageSource {
158 fn eq(&self, other: &Self) -> bool {
159 self.key() == other.key()
160 }
161}
162
163impl fmt::Debug for ImageSource {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 match &self.kind {
166 SourceKind::File(path) => write!(f, "ImageSource::file({path:?})")?,
167 SourceKind::Bytes(bytes) => write!(f, "ImageSource::bytes({} 字节)", bytes.len())?,
168 SourceKind::Static(bytes) => write!(f, "ImageSource::from_static({} 字节)", bytes.len())?,
169 SourceKind::Rgba { width, height, .. } => write!(f, "ImageSource::rgba({width}x{height})")?,
170 SourceKind::RgbaF32 { width, height, .. } => write!(f, "ImageSource::rgba_f32({width}x{height})")?,
171 }
172 if let Some(max) = self.max_size {
173 write!(f, ".max_size({max})")?;
174 }
175 Ok(())
176 }
177}
178
179impl From<&str> for ImageSource {
180 fn from(path: &str) -> Self {
181 Self::file(path)
182 }
183}
184
185impl From<String> for ImageSource {
186 fn from(path: String) -> Self {
187 Self::file(path)
188 }
189}
190
191impl From<PathBuf> for ImageSource {
192 fn from(path: PathBuf) -> Self {
193 Self::file(path)
194 }
195}
196
197impl From<&Path> for ImageSource {
198 fn from(path: &Path) -> Self {
199 Self::file(path)
200 }
201}
202
203impl IntoProp<ImageSource> for ImageSource {
204 fn into_prop(self) -> Prop<ImageSource> {
205 Prop::Static(self)
206 }
207}
208
209#[derive(Clone, PartialEq, Eq)]
220pub struct RgbaImage {
221 pub width: u32,
223 pub height: u32,
225 pub pixels: Arc<[u8]>,
227}
228
229impl RgbaImage {
230 pub fn new(width: u32, height: u32, pixels: impl Into<Arc<[u8]>>) -> Self {
232 Self { width, height, pixels: pixels.into() }
233 }
234}
235
236impl fmt::Debug for RgbaImage {
237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238 write!(f, "RgbaImage({}×{}, {} 字节)", self.width, self.height, self.pixels.len())
239 }
240}
241
242impl From<RgbaImage> for ImageSource {
243 fn from(image: RgbaImage) -> Self {
244 Self::rgba(image.width, image.height, image.pixels)
245 }
246}
247
248impl From<&RgbaImage> for ImageSource {
249 fn from(image: &RgbaImage) -> Self {
250 Self::rgba(image.width, image.height, image.pixels.clone())
251 }
252}
253
254impl IntoProp<RgbaImage> for RgbaImage {
255 fn into_prop(self) -> Prop<RgbaImage> {
256 Prop::Static(self)
257 }
258}
259
260impl IntoProp<PathBuf> for PathBuf {
263 fn into_prop(self) -> Prop<PathBuf> {
264 Prop::Static(self)
265 }
266}
267
268#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
270#[non_exhaustive]
271pub enum ImageFit {
272 #[default]
274 Stretch,
275 Contain,
277 Cover,
279 None,
281 ScaleDown,
283}
284
285impl IntoProp<ImageFit> for ImageFit {
286 fn into_prop(self) -> Prop<ImageFit> {
287 Prop::Static(self)
288 }
289}
290
291#[derive(Clone, Debug, PartialEq)]
293pub enum ImageState {
294 Loading,
296 Ready {
298 width: u32,
300 height: u32,
302 },
303 Error(Arc<str>),
305}
306
307impl ImageState {
308 pub fn is_ready(&self) -> bool {
310 matches!(self, Self::Ready { .. })
311 }
312
313 pub fn size(&self) -> Option<[u32; 2]> {
315 match *self {
316 Self::Ready { width, height } => Some([width, height]),
317 _ => None,
318 }
319 }
320}
321
322type RevisionSource = fn(&std::path::Path) -> u64;
324
325thread_local! {
326 static REVISION_SOURCE: std::cell::Cell<Option<RevisionSource>> = const { std::cell::Cell::new(None) };
327}
328
329pub fn set_image_revision_source(source: RevisionSource) {
332 REVISION_SOURCE.with(|s| s.set(Some(source)));
333}
334
335fn image_revision(path: &std::path::Path) -> u64 {
337 REVISION_SOURCE.with(std::cell::Cell::get).map_or(0, |source| source(path))
338}
339
340#[derive(Clone, Copy, Debug, Default, PartialEq)]
342pub struct ImageCacheStats {
343 pub images: usize,
345 pub loading_images: usize,
347 pub bytes: u64,
349 pub retained_images: usize,
351 pub retained_bytes: u64,
353 pub decoded_images: usize,
355 pub decode_time: Duration,
357}
358
359pub fn image_cache_stats() -> ImageCacheStats {
361 loader::stats()
362}
363
364pub fn set_image_cache_budget(bytes: u64) {
366 loader::set_budget(bytes as usize);
367}
368
369pub fn wait_idle(stall: Duration) -> Result<(), Vec<String>> {
372 loader::wait_idle(stall)
373}
374
375#[derive(Clone, Copy, Debug, PartialEq)]
390pub struct PlaybackHandle {
391 playing: Signal<Option<bool>>,
393 restarts: Signal<u64>,
394 pub(crate) finished: Signal<bool>,
395}
396
397impl PlaybackHandle {
398 pub fn new() -> Self {
400 Self { playing: signal(None), restarts: signal(0), finished: signal(false) }
401 }
402
403 pub fn play(self) {
405 self.playing.set(Some(true));
406 }
407
408 pub fn pause(self) {
410 self.playing.set(Some(false));
411 }
412
413 pub fn toggle(self) {
415 let playing = self.is_playing_untracked();
416 self.playing.set(Some(!playing));
417 }
418
419 pub fn restart(self) {
421 self.restarts.update(|n| *n += 1);
422 }
423
424 pub fn is_playing(self) -> bool {
427 self.playing.get().unwrap_or_else(|| !crate::system::is_motion_reduced())
428 }
429
430 fn is_playing_untracked(self) -> bool {
431 untracked(|| self.is_playing())
432 }
433
434 pub fn is_finished(self) -> bool {
436 self.finished.get()
437 }
438}
439
440impl Default for PlaybackHandle {
441 fn default() -> Self {
442 Self::new()
443 }
444}
445
446#[derive(Default)]
448pub(crate) struct ImageExtras {
449 fade_in: bool,
450 state: Option<Signal<ImageState>>,
451 player: Option<PlaybackHandle>,
452}
453
454impl Element {
455 fn image_extras(&mut self) -> &mut ImageExtras {
457 if self.kind.is_none() {
458 self.kind = Some(Box::new(ImageBlock::default()));
459 }
460 self.image.get_or_insert_with(Box::default)
461 }
462
463 pub fn image_position(self, x: impl IntoProp<f32>, y: impl IntoProp<f32>) -> Self {
466 self.image_position_x(x).image_position_y(y)
467 }
468
469 pub fn image_fade(mut self, curve: impl Into<Curve>) -> Self {
472 self.image_extras().fade_in = true;
473 self.transition(Property::Opacity, curve)
474 }
475
476 pub fn report_load_state(mut self, state: Signal<ImageState>) -> Self {
478 self.image_extras().state = Some(state);
479 self
480 }
481
482 pub fn playback_handle(mut self, player: PlaybackHandle) -> Self {
485 self.image_extras().player = Some(player);
486 self
487 }
488}
489
490pub(crate) fn bind_source(tree: &TreeRef, id: NodeId, source: crate::property::registry::Slot) {
492 bind(tree, id, Some(source), None, false);
493}
494
495pub(crate) fn bind(tree: &TreeRef, id: NodeId, source: Option<crate::property::registry::Slot>, extras: Option<Box<ImageExtras>>, has_playing: bool) -> Option<Signal<bool>> {
498 let ImageExtras { fade_in, state, player } = extras.map(|e| *e).unwrap_or_default();
499 if let Some(player) = player {
500 if !has_playing {
502 crate::tree::bind(tree, Some(Prop::Dynamic(Box::new(move || player.playing.get()))), move |tree, intent| tree.set_playing(id, intent));
503 }
504 tree.borrow_mut().update_image(id, |block| block.handle = Some(player));
505 let weak: Weak<std::cell::RefCell<Tree>> = Rc::downgrade(tree);
507 let mut first = true;
508 Effect::new(move || {
509 player.restarts.get();
510 if std::mem::take(&mut first) {
511 return;
512 }
513 player.finished.set(false);
514 if let Some(tree) = weak.upgrade() {
515 tree.borrow_mut().restart_image(id);
516 }
517 });
518 }
519
520 let loaded = fade_in.then(|| signal(false));
522 if let Some(source) = source {
523 let tick = signal(0u64);
525 let weak: Weak<std::cell::RefCell<Tree>> = Rc::downgrade(tree);
526 Effect::new(move || {
527 tick.get();
528 let Some(mut source) = source.get::<ImageSource>() else { return };
529 if let SourceKind::File(path) = &source.kind {
531 source.revision = image_revision(path);
532 }
533 let source = match weak.upgrade() {
535 Some(tree) => match tree.borrow_mut().hold_back(id, PropId::SOURCE, source) {
536 Some(source) => source,
537 None => return,
538 },
539 None => source,
540 };
541 let image = untracked(|| loader::acquire(&source));
542 image.listen(tick);
543 let status = image.state();
544 let shown = weak.upgrade().is_some_and(|tree| tree.borrow_mut().set_image(id, image));
545 if let Some(state) = state {
546 state.set_if_changed(status);
547 }
548 if let Some(loaded) = loaded {
549 loaded.set_if_changed(shown);
550 }
551 });
552 }
553 loaded
554}
555
556pub(crate) struct ImageBlock {
558 requested: Option<ImageRef>,
560 shown: Option<ImageRef>,
562 pub fit: ImageFit,
563 pub position: [f32; 2],
564 pub tint: Color,
566 pub player: Option<Player>,
568 pub intent: Option<bool>,
571 pub handle: Option<PlaybackHandle>,
573}
574
575impl Default for ImageBlock {
576 fn default() -> Self {
577 Self {
578 requested: None,
579 shown: None,
580 fit: ImageFit::Stretch,
581 position: [0.5, 0.5],
582 tint: Color::TRANSPARENT,
583 player: None,
584 intent: None,
585 handle: None,
586 }
587 }
588}
589
590impl ImageBlock {
591 pub fn showing(&self) -> bool {
592 self.shown.is_some()
593 }
594
595 pub fn source_label(&self) -> Option<String> {
597 self.requested.as_ref().map(|image| format!("{:?}", image.source()))
598 }
599
600 pub fn intrinsic(&self) -> [f32; 2] {
602 match self.shown.as_ref().map(ImageRef::status) {
603 Some(Status::Ready { natural, .. }) => [natural[0] as f32, natural[1] as f32],
604 #[cfg(feature = "svg")]
605 Some(Status::Vector { document }) => document.size,
606 _ => [0.0; 2],
607 }
608 }
609
610 #[cfg(feature = "svg")]
612 pub fn document(&self) -> Option<Arc<svg::SvgDocument>> {
613 match self.shown.as_ref().map(ImageRef::status) {
614 Some(Status::Vector { document }) => Some(document),
615 _ => None,
616 }
617 }
618
619 #[cfg(feature = "svg")]
621 pub fn paint_document(&self, document: &svg::SvgDocument, area: &ImageArea, target: SvgTarget) {
622 svg_paint::paint(document, self, area, target);
623 }
624}
625
626pub(crate) struct Player {
629 key: Key,
631 frames: Arc<Frames>,
632 pub frame: usize,
634 pub due: Option<f64>,
636 played: u32,
638 pub finished: bool,
639}
640
641pub(crate) struct Stepped {
643 pub changed: bool,
645 pub finished: bool,
647}
648
649impl Player {
650 pub fn frames(&self) -> usize {
651 self.frames.frames.len()
652 }
653
654 pub fn delay(&self) -> f64 {
656 self.frames.delays[self.frame] as f64
657 }
658
659 pub fn step(&mut self, now: f64) -> Stepped {
662 let mut out = Stepped { changed: false, finished: false };
663 let Some(mut due) = self.due else {
664 self.due = Some(now + self.delay());
665 return out;
666 };
667 let count = self.frames();
668 while now >= due && !self.finished {
669 if self.frame + 1 < count {
670 self.frame += 1;
671 } else {
672 self.played += 1;
673 if self.frames.loops.is_some_and(|n| self.played >= n) {
674 self.finished = true;
675 out.finished = true;
676 break;
677 }
678 self.frame = 0;
679 }
680 out.changed = true;
681 due += self.delay();
682 if now - due > 1.0 {
683 due = now + self.delay();
684 }
685 }
686 self.due = Some(due);
687 out
688 }
689
690 pub fn rewind(&mut self) -> bool {
692 let changed = self.frame != 0;
693 self.frame = 0;
694 self.played = 0;
695 self.finished = false;
696 self.due = None;
697 changed
698 }
699
700 pub fn current(&self) -> Arc<ImageData> {
702 self.frames.frames[self.frame].clone()
703 }
704}
705
706#[derive(Clone, Copy, Debug)]
708enum Slot {
709 Atlas([u32; 2]),
711 Texture(u32),
713}
714
715#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
718pub(crate) enum Key {
719 Image(u64),
720 Player(u64),
721 #[cfg(feature = "svg")]
722 Embedded(u64),
723}
724
725struct TreeImage {
727 image: ImageRef,
728 users: u32,
730 slot: Option<Slot>,
731 frame: Option<Arc<ImageData>>,
733}
734
735impl TreeImage {
736 fn data(&self) -> Option<Arc<ImageData>> {
738 match (&self.frame, self.image.status()) {
739 (Some(frame), _) => Some(frame.clone()),
740 (None, Status::Ready { frames: Some(_), .. }) => None,
741 (None, Status::Ready { data, .. }) => Some(data),
742 _ => None,
743 }
744 }
745}
746
747#[derive(Default)]
749pub(crate) struct ImageSystem {
750 images: HashMap<Key, TreeImage>,
751 atlas_size: u32,
753 shelves: Shelves,
754 spare: Vec<([u32; 2], [u32; 2])>,
756 next_texture: u32,
757 next_player: u64,
758 updates: Vec<AtlasUpdate>,
759 dirty: bool,
761}
762
763const ATLAS_START: u32 = 1024;
765
766impl ImageSystem {
767 pub fn update(&mut self, block: &mut ImageBlock, image: ImageRef) -> bool {
769 if !block.requested.as_ref().is_some_and(|r| r.same(&image)) {
770 self.retain(&image);
771 if let Some(old) = block.requested.replace(image.clone()) {
772 self.release(&old);
773 }
774 }
775 match image.status() {
776 Status::Ready { frames, .. } => {
777 if block.shown.as_ref().is_some_and(|s| s.same(&image)) {
778 return false;
779 }
780 self.retain(&image);
781 if let Some(old) = block.shown.replace(image.clone()) {
782 self.release_shown(&old);
783 }
784 self.stop(block);
786 if let Some(frames) = frames {
787 self.next_player += 1;
788 let key = Key::Player(self.next_player);
789 let first = frames.frames[0].clone();
790 self.images.insert(key, TreeImage { image, users: 1, slot: None, frame: Some(first) });
791 block.player = Some(Player { key, frames, frame: 0, due: None, played: 0, finished: false });
792 }
793 self.dirty = true;
794 true
795 }
796 #[cfg(feature = "svg")]
797 Status::Vector { document } => {
798 if block.shown.as_ref().is_some_and(|s| s.same(&image)) {
799 return false;
800 }
801 self.retain(&image);
802 if let Some(old) = block.shown.replace(image.clone()) {
803 self.release_shown(&old);
804 }
805 self.stop(block);
806 self.show_embedded(&document, &image);
807 true
808 }
809 Status::Loading => false,
810 Status::Error(_) => match block.shown.take() {
811 Some(old) => {
812 self.release_shown(&old);
813 self.stop(block);
814 true
815 }
816 None => false,
817 },
818 }
819 }
820
821 pub fn detach(&mut self, block: &mut ImageBlock) {
823 self.stop(block);
824 if let Some(image) = block.requested.take() {
825 self.release(&image);
826 }
827 if let Some(image) = block.shown.take() {
828 self.release_shown(&image);
829 }
830 }
831
832 fn release_shown(&mut self, image: &ImageRef) {
834 #[cfg(feature = "svg")]
835 if let Status::Vector { document } = image.status() {
836 self.hide_embedded(&document);
837 }
838 self.release(image);
839 }
840
841 #[cfg(feature = "svg")]
843 fn show_embedded(&mut self, document: &svg::SvgDocument, owner: &ImageRef) {
844 for embedded in &document.images {
845 let entry = TreeImage { image: owner.clone(), users: 0, slot: None, frame: Some(embedded.data.clone()) };
846 self.images.entry(Key::Embedded(embedded.id)).or_insert(entry).users += 1;
847 self.dirty = true;
848 }
849 }
850
851 #[cfg(feature = "svg")]
853 fn hide_embedded(&mut self, document: &svg::SvgDocument) {
854 for embedded in &document.images {
855 let key = Key::Embedded(embedded.id);
856 let Some(entry) = self.images.get_mut(&key) else { continue };
857 entry.users -= 1;
858 if entry.users == 0
859 && let Some(entry) = self.images.remove(&key)
860 && let Some(Slot::Texture(id)) = entry.slot
861 {
862 self.updates.push(AtlasUpdate::Image(ImageUpdate::Release { id }));
863 }
864 }
865 }
866
867 #[cfg(feature = "svg")]
869 fn embedded_slot(&self, id: u64) -> Option<Slot> {
870 self.images.get(&Key::Embedded(id))?.slot
871 }
872
873 fn stop(&mut self, block: &mut ImageBlock) {
875 let Some(player) = block.player.take() else { return };
876 let Some(entry) = self.images.remove(&player.key) else { return };
877 match entry.slot {
878 Some(Slot::Texture(id)) => self.updates.push(AtlasUpdate::Image(ImageUpdate::Release { id })),
879 Some(Slot::Atlas(at)) => {
880 if let Some(frame) = entry.frame {
881 self.spare.push((frame.storage(), at));
882 }
883 }
884 None => {}
885 }
886 }
887
888 pub fn show_frame(&mut self, player: &Player) {
890 let Some(entry) = self.images.get_mut(&player.key) else { return };
891 let data = player.current();
892 entry.frame = Some(data.clone());
893 match entry.slot {
894 Some(Slot::Atlas([x, y])) => self.updates.push(AtlasUpdate::Image(ImageUpdate::Atlas { x, y, image: data })),
895 Some(Slot::Texture(id)) => self.updates.push(AtlasUpdate::Image(ImageUpdate::Write { id, image: data })),
896 None => {}
898 }
899 }
900
901 fn retain(&mut self, image: &ImageRef) {
902 let entry = TreeImage { image: image.clone(), users: 0, slot: None, frame: None };
903 self.images.entry(Key::Image(image.id())).or_insert(entry).users += 1;
904 }
905
906 fn release(&mut self, image: &ImageRef) {
908 let key = Key::Image(image.id());
909 let Some(entry) = self.images.get_mut(&key) else { return };
910 entry.users -= 1;
911 if entry.users == 0 {
912 let entry = self.images.remove(&key).expect("刚查到");
913 if let Some(Slot::Texture(id)) = entry.slot {
914 self.updates.push(AtlasUpdate::Image(ImageUpdate::Release { id }));
915 }
916 }
917 }
918
919 pub fn prepare(&mut self) {
922 if !std::mem::take(&mut self.dirty) {
923 return;
924 }
925 let mut pending: Vec<Key> = self.images.iter().filter(|(_, e)| e.slot.is_none() && e.data().is_some()).map(|(&k, _)| k).collect();
926 pending.sort_unstable();
927 let mut repack = Vec::new();
928 for key in pending {
929 let data = self.images[&key].data().expect("刚检查过");
930 if !fits_atlas(&data) {
931 self.create_texture(key, data);
932 continue;
933 }
934 let [w, h] = data.storage();
935 let spare = matches!(key, Key::Player(_)).then(|| self.spare.iter().position(|(size, _)| *size == [w, h])).flatten();
937 let at = match spare {
938 Some(i) => Some(self.spare.swap_remove(i).1),
939 None => self.shelves.allocate(w, h),
940 };
941 match at {
942 Some(at) if self.atlas_size > 0 => {
943 self.updates.push(AtlasUpdate::Image(ImageUpdate::Atlas { x: at[0], y: at[1], image: data }));
944 self.images.get_mut(&key).expect("刚查到").slot = Some(Slot::Atlas(at));
945 }
946 _ => repack.push(key),
947 }
948 }
949 if !repack.is_empty() {
950 self.repack(repack);
951 }
952 }
953
954 fn create_texture(&mut self, key: Key, data: Arc<ImageData>) {
955 self.next_texture += 1;
956 let texture = self.next_texture;
957 self.updates.push(AtlasUpdate::Image(ImageUpdate::Create { id: texture, image: data }));
958 self.images.get_mut(&key).expect("刚查到").slot = Some(Slot::Texture(texture));
959 }
960
961 fn repack(&mut self, new: Vec<Key>) {
964 let mut keys: Vec<Key> = self.images.iter().filter(|(_, e)| matches!(e.slot, Some(Slot::Atlas(_)))).map(|(&k, _)| k).collect();
965 keys.extend(new);
966 let data: HashMap<Key, Arc<ImageData>> = keys.iter().map(|&k| (k, self.images[&k].data().expect("图集里的都解码好了"))).collect();
967 keys.sort_by_key(|k| (std::cmp::Reverse(data[k].storage()[1]), *k));
969 let mut size = self.atlas_size.max(ATLAS_START);
970 let placed = loop {
971 let mut shelves = Shelves::new(size);
972 let placed: Vec<Option<[u32; 2]>> = keys.iter().map(|k| shelves.allocate(data[k].storage()[0], data[k].storage()[1])).collect();
973 if placed.iter().all(Option::is_some) || size >= max_atlas_size() {
974 self.shelves = shelves;
975 break placed;
976 }
977 size = (size * 2).min(max_atlas_size());
978 };
979 self.atlas_size = size;
980 self.spare.clear();
982 self.updates.push(AtlasUpdate::Image(ImageUpdate::ResetAtlas { size }));
983 for (key, at) in keys.into_iter().zip(placed) {
984 let image = data[&key].clone();
985 match at {
986 Some(at) => {
987 self.updates.push(AtlasUpdate::Image(ImageUpdate::Atlas { x: at[0], y: at[1], image }));
988 self.images.get_mut(&key).expect("刚查到").slot = Some(Slot::Atlas(at));
989 }
990 None => self.create_texture(key, image),
991 }
992 }
993 }
994
995 pub fn take_updates(&mut self) -> Vec<AtlasUpdate> {
997 std::mem::take(&mut self.updates)
998 }
999
1000 pub fn snapshot(&self) -> Vec<AtlasUpdate> {
1002 let mut out = Vec::new();
1003 if self.atlas_size > 0 {
1004 out.push(AtlasUpdate::Image(ImageUpdate::ResetAtlas { size: self.atlas_size }));
1005 }
1006 for entry in self.images.values() {
1007 let (Some(slot), Some(data)) = (entry.slot, entry.data()) else { continue };
1008 out.push(AtlasUpdate::Image(match slot {
1009 Slot::Atlas([x, y]) => ImageUpdate::Atlas { x, y, image: data },
1010 Slot::Texture(id) => ImageUpdate::Create { id, image: data },
1011 }));
1012 }
1013 out
1014 }
1015
1016 pub fn push(&self, block: &ImageBlock, area: &ImageArea, list: &mut DisplayList) {
1019 let Some(shown) = &block.shown else { return };
1020 let key = block.player.as_ref().map_or(Key::Image(shown.id()), |p| p.key);
1021 let Some(entry) = self.images.get(&key) else { return };
1022 let (Some(slot), Status::Ready { natural, data, .. }) = (entry.slot, shown.status()) else { return };
1023 let content = area.content;
1024 if content.width <= 0.0 || content.height <= 0.0 || natural[0] == 0 || natural[1] == 0 {
1025 return;
1026 }
1027 let [dx, dy, dw, dh] = fit_rect(block.fit, block.position, [natural[0] as f32, natural[1] as f32], [content.width, content.height]);
1028 let (bounds, kind) = self.texture_range(slot, &data);
1029 let u = |x: f32| bounds[0] + (x - dx) / dw * (bounds[2] - bounds[0]);
1031 let v = |y: f32| bounds[1] + (y - dy) / dh * (bounds[3] - bounds[1]);
1032
1033 let [cx, cy] = area.local.apply(content.center());
1034 let mut quad = Quad::new(cx - content.width * 0.5, cy - content.height * 0.5, content.width, content.height);
1035 quad.transform = area.local.linear;
1036 quad.radii = [area.inner_radius; 4];
1037 quad.uv = [u(0.0), v(0.0), u(content.width), v(content.height)];
1038 quad.shadow_offset = [bounds[0], bounds[1]];
1039 quad.shadow_blur = bounds[2];
1040 quad.border_width = bounds[3];
1041 quad.kind = kind;
1042 quad.opacity = area.opacity;
1043 if !block.tint.is_transparent() {
1044 quad.gradient = list.push_filter(&ColorMatrix::tint(block.tint));
1045 }
1046 if let Slot::Texture(texture) = slot {
1047 list.quad_effects.push(scene::QuadEffect::Image { quad: list.quads.len() as u32, texture });
1048 }
1049 list.extended |= data.encoding != ImageEncoding::Srgb8;
1051 list.quads.push(quad);
1052 area.push_border(list);
1053 }
1054
1055 fn texture_range(&self, slot: Slot, data: &ImageData) -> ([f32; 4], u32) {
1057 let [sw, sh] = data.storage();
1058 match slot {
1059 Slot::Atlas([x, y]) => {
1060 let s = self.atlas_size as f32;
1061 ([x as f32 / s, y as f32 / s, (x + data.size[0]) as f32 / s, (y + data.size[1]) as f32 / s], Quad::IMAGE)
1062 }
1063 Slot::Texture(_) => ([0.0, 0.0, data.size[0] as f32 / sw as f32, data.size[1] as f32 / sh as f32], Quad::IMAGE_TEXTURE),
1064 }
1065 }
1066}
1067
1068pub(crate) struct ImageArea {
1070 pub bounds: Rect,
1072 pub content: Rect,
1073 pub local: Affine,
1075 pub opacity: f32,
1076 pub radius: f32,
1077 pub inner_radius: f32,
1079 pub border: Option<(f32, Fill)>,
1081}
1082
1083pub(crate) fn push_external(texture: u32, area: &ImageArea, list: &mut DisplayList) {
1086 let content = area.content;
1087 if content.width <= 0.0 || content.height <= 0.0 {
1088 return;
1089 }
1090 let [cx, cy] = area.local.apply(content.center());
1091 let mut quad = Quad::new(cx - content.width * 0.5, cy - content.height * 0.5, content.width, content.height);
1092 quad.transform = area.local.linear;
1093 quad.radii = [area.inner_radius; 4];
1094 quad.uv = [0.0, 0.0, 1.0, 1.0];
1095 quad.shadow_offset = [0.0, 0.0];
1097 quad.shadow_blur = 1.0;
1098 quad.border_width = 1.0;
1099 quad.kind = Quad::IMAGE_TEXTURE;
1100 quad.opacity = area.opacity;
1101 list.quad_effects.push(scene::QuadEffect::Image { quad: list.quads.len() as u32, texture });
1102 list.quads.push(quad);
1103 area.push_border(list);
1104}
1105
1106impl ImageArea {
1107 fn push_border(&self, list: &mut DisplayList) {
1109 let Some((width, color)) = &self.border else { return };
1110 let b = self.bounds;
1111 let [cx, cy] = self.local.apply(b.center());
1112 let mut border = Quad::new(cx - b.width * 0.5, cy - b.height * 0.5, b.width, b.height)
1113 .radius(self.radius)
1114 .fill(Color::TRANSPARENT)
1115 .border(*width, color.color())
1116 .opacity(self.opacity);
1117 border.transform = self.local.linear;
1118 if let Fill::Gradient(gradient) = color {
1119 border = border.with_border_gradient(gradient.push_local(list, [b.width, b.height]));
1120 }
1121 list.quads.push(border);
1122 }
1123}
1124
1125fn fits_atlas(data: &ImageData) -> bool {
1127 let [w, h] = data.storage();
1128 data.encoding == ImageEncoding::Srgb8 && data.levels.len() == IMAGE_ATLAS_LEVELS as usize && w.max(h) <= max_atlas_size() / 2
1129}
1130
1131pub(crate) fn fit_rect(fit: ImageFit, position: [f32; 2], natural: [f32; 2], area: [f32; 2]) -> [f32; 4] {
1133 let [iw, ih] = natural;
1134 let [w, h] = area;
1135 let contain = (w / iw).min(h / ih);
1136 let scale = match fit {
1137 ImageFit::Stretch => return [0.0, 0.0, w, h],
1138 ImageFit::Contain => contain,
1139 ImageFit::Cover => (w / iw).max(h / ih),
1140 ImageFit::None => 1.0,
1141 ImageFit::ScaleDown => contain.min(1.0),
1142 };
1143 let (dw, dh) = (iw * scale, ih * scale);
1144 [(w - dw) * position[0], (h - dh) * position[1], dw, dh]
1145}
1146
1147#[derive(Default)]
1149struct Shelves {
1150 size: u32,
1151 shelves: Vec<[u32; 3]>,
1153 next_y: u32,
1154}
1155
1156impl Shelves {
1157 fn new(size: u32) -> Self {
1158 Self { size, shelves: Vec::new(), next_y: 0 }
1159 }
1160
1161 fn allocate(&mut self, width: u32, height: u32) -> Option<[u32; 2]> {
1162 if width > self.size || height > self.size {
1163 return None;
1164 }
1165 let size = self.size;
1167 if let Some(shelf) = self.shelves.iter_mut().find(|[_, h, x]| *h >= height && *h <= height + height / 2 && x + width <= size) {
1168 let x = shelf[2];
1169 shelf[2] += width;
1170 return Some([x, shelf[0]]);
1171 }
1172 if self.next_y + height > self.size {
1173 return None;
1174 }
1175 let y = self.next_y;
1176 self.next_y += height;
1177 self.shelves.push([y, height, width]);
1178 Some([0, y])
1179 }
1180}