diff --git a/Cargo.lock b/Cargo.lock index 7ac2b46..3f04449 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -577,6 +577,25 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -816,14 +835,19 @@ dependencies = [ [[package]] name = "egui_software_backend" version = "0.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8ca3a47168e93a5cca79b7cb830817acaf07ebc1f8756aa368a6b2d6250f6ae" dependencies = [ "constify", "egui", + "rayon", "strength_reduce", ] +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + [[package]] name = "emath" version = "0.34.3" @@ -2221,7 +2245,7 @@ dependencies = [ [[package]] name = "pdf-presenter" -version = "0.1.53" +version = "0.1.54" dependencies = [ "bytemuck", "chrono", @@ -2531,6 +2555,26 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + [[package]] name = "read-fonts" version = "0.37.0" diff --git a/Cargo.toml b/Cargo.toml index cc0aa89..1c60acf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ default-members = ["crates/pdf-presenter"] resolver = "3" [workspace.package] -version = "0.1.53" +version = "0.1.54" edition = "2024" license = "MIT" repository = "https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter" @@ -17,3 +17,6 @@ strip = true [profile.dev.package."*"] opt-level = 2 + +[patch.crates-io] +egui_software_backend = { path = "vendor/egui_software_backend" } diff --git a/README.md b/README.md index 1b825e3..46dccc5 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,9 @@ pointer near an edge or right-click to recover them. Prepared slides are cached for reuse. The presenter shows loading progress, RAM use and an ETA when available; decks larger than the RAM budget use a rolling buffer. Notes can come from the PDF or picture-folder sidecars. Themes and English/French -controls are available in Menu. +controls are available in Menu. Optional shared slide zoom is available under +**Menu → Preferences → Enable page zoom**; scroll to zoom, drag to pan, double-click +to reset on the current preview or presentation screen. ## Import your notes diff --git a/crates/pdf-presenter/Cargo.toml b/crates/pdf-presenter/Cargo.toml index 0b2a7f5..3ee363a 100644 --- a/crates/pdf-presenter/Cargo.toml +++ b/crates/pdf-presenter/Cargo.toml @@ -14,7 +14,7 @@ font8x8 = "=0.3.1" egui = { version = "=0.34.1", features = ["default_fonts"] } egui-winit = { version = "=0.34.1", default-features = false, features = ["x11", "wayland"] } -egui_software_backend = { version = "=0.0.3", default-features = false, features = ["std"] } +egui_software_backend = { version = "=0.0.3", default-features = false, features = ["std", "rayon"] } bytemuck = "1.25" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/crates/pdf-presenter/src/lib.rs b/crates/pdf-presenter/src/lib.rs index 74a6445..2522e9c 100644 --- a/crates/pdf-presenter/src/lib.rs +++ b/crates/pdf-presenter/src/lib.rs @@ -90,3 +90,5 @@ pub mod timer; /// Editable presentation notes sidecars. pub mod notes; + +pub mod zoom; diff --git a/crates/pdf-presenter/src/localization.rs b/crates/pdf-presenter/src/localization.rs index 2dd4043..2cd92f4 100644 --- a/crates/pdf-presenter/src/localization.rs +++ b/crates/pdf-presenter/src/localization.rs @@ -39,6 +39,24 @@ pub fn tr<'a>(ctx: &egui::Context, text: &'a str) -> &'a str { return text; } match text { + "Enable page zoom" => "Activer le zoom des diapositives", + "Page zoom" => "Zoom de la diapositive", + "Reset zoom" => "Réinitialiser le zoom", + "Disable zoom" => "Désactiver le zoom", + "Keep zoom enabled" => "Garder le zoom activé", + "Zoom performance" => "Performances du zoom", + "Scroll to zoom · drag to pan · double-click to reset" => { + "Molette pour zoomer · glisser pour déplacer · double-clic pour réinitialiser" + } + "Use the current slide preview or a presentation screen. Changing slides resets zoom." => { + "Utilisez l’aperçu actuel ou un écran de présentation. Changer de diapositive réinitialise le zoom." + } + "Zoom reuses buffered images: no extra PDF rendering or image memory. Enlarged slides may look softer. Software drawing can slow down on large or multiple displays." => { + "Le zoom réutilise les images en mémoire, sans rendu PDF ni mémoire d’image supplémentaires. Les diapositives agrandies peuvent être moins nettes. Le dessin logiciel peut ralentir sur des écrans grands ou multiples." + } + "Zoomed frames are taking over 33 ms to draw. Panning may feel slow on this display. Reset or disable zoom to return to normal viewing." => { + "Les images zoomées prennent plus de 33 ms à dessiner. Le déplacement peut sembler lent sur cet écran. Réinitialisez ou désactivez le zoom pour revenir à l’affichage normal." + } "Cancel" => "Annuler", "Preview (first 3 slides)" => "Aperçu (3 premières diapositives)", "Import notes…" => "Importer des notes…", diff --git a/crates/pdf-presenter/src/native.rs b/crates/pdf-presenter/src/native.rs index 3c4feeb..9414956 100644 --- a/crates/pdf-presenter/src/native.rs +++ b/crates/pdf-presenter/src/native.rs @@ -46,6 +46,9 @@ struct NativeWindow { transition: Option<(Instant, bool)>, frames: usize, display_action: Option, + zoom_change: Option, + zoom_watch: crate::zoom::PerformanceWatch, + zoom_slow: bool, #[cfg(target_os = "linux")] browser_parent: Option, } @@ -98,6 +101,9 @@ impl NativeWindow { transition: None, frames: 0, display_action: None, + zoom_change: None, + zoom_watch: Default::default(), + zoom_slow: false, #[cfg(target_os = "linux")] browser_parent: None, }) @@ -166,6 +172,7 @@ impl NativeWindow { blank: bool, setup: Option<&HostState>, ) -> Result<(), Failure> { + let render_started = Instant::now(); let size = self.window.inner_size(); if size.width == 0 || size.height == 0 { return Ok(()); @@ -182,6 +189,7 @@ impl NativeWindow { let ui_state = &mut self.ui; let ctx = self.ctx.clone(); let display_action = &mut self.display_action; + let zoom_change = &mut self.zoom_change; let output = ctx.run_ui(input, |ui| match role { Role::Presenter => { presenter_ui::presenter(ui, studio.as_deref_mut().unwrap(), ui_state) @@ -193,7 +201,7 @@ impl NativeWindow { if let Some(setup) = setup { *display_action = presenter_ui::output_display_recovery( ui, - setup.setup_controls, + setup.setup_controls && !setup.zoom.enabled, setup.route_trial.is_some(), ); } @@ -216,12 +224,43 @@ impl NativeWindow { egui::TextureOptions::LINEAR, ) }); - presenter_ui::paint_slide( + let mut view = setup.map(|s| s.zoom.view).unwrap_or_default(); + if let Some(setup) = setup + && setup.zoom.enabled + && setup.route_trial.is_none() + && setup + .frame + .as_ref() + .is_some_and(|f| f.path == frame.info.path) + { + let target = presenter_ui::fitted_slide( + ui.max_rect(), + [frame.info.width, frame.info.height], + ); + let (next, response) = presenter_ui::zoom_gestures(ui, target, view); + if setup.setup_controls { + response.context_menu(|ui| { + if ui + .button("Swap presenter and presentation displays…") + .clicked() + { + *display_action = Some(DisplayAction::Swap); + ui.close(); + } + }); + } + if next != view { + *zoom_change = Some(next); + view = next; + } + } + presenter_ui::paint_slide_zoomed( ui.painter(), ui.max_rect(), tex.id(), [frame.info.width, frame.info.height], setup.map(|s| s.slide_colors).unwrap_or_default(), + view, ); } } @@ -248,6 +287,19 @@ impl NativeWindow { self.window.pre_present_notify(); buffer.present()?; self.frames += 1; + let zoomed = if role == Role::Presenter { + studio + .as_ref() + .is_some_and(|s| s.zoom.enabled && s.zoom.view.scale > 1.) + } else { + !blank && setup.is_some_and(|s| s.zoom.enabled && s.zoom.view.scale > 1.) + }; + if self.zoom_watch.observe(zoomed, render_started.elapsed()) { + self.zoom_slow = true; + if let Some(s) = studio { + s.zoom_warning = true; + } + } Ok(()) } } @@ -347,6 +399,9 @@ struct Host { presented: HashSet, failed_reads: HashSet, preload_cursor: usize, + zoom_pending: bool, + zoom_slow: bool, + next_zoom_ack: Instant, } // The last visible frame may outlive its cache entry during a working-set change. // Count that allocation and pin it until the requested replacement is available. @@ -656,6 +711,7 @@ impl App { fn poll(&mut self, el: &ActiveEventLoop) { let mut repaint = false; if let Some(s) = &mut self.studio { + repaint |= s.new_zoom; let before = ( s.generation, s.frames.len(), @@ -719,6 +775,20 @@ impl App { } if let Some(output) = &self.output { while let Ok(ack) = output.rx.try_recv() { + if let Some(zoom) = ack.zoom { + if ack.generation == s.buffer_generation() && ack.page == Some(s.requested) + { + if s.zoom.accept_output(zoom) { + repaint = true; + } + if zoom.epoch == s.zoom.epoch { + s.zoom_warning |= ack.zoom_slow; + s.new_zoom = true; // Echo newest serial so output can stop retrying. + repaint |= ack.zoom_slow; + } + } + continue; + } if let Some(action) = ack.display_action { s.display_control(action, ack.route_trial); } @@ -750,6 +820,7 @@ impl App { if s.new_output { s.output_sequence += 1; let state = HostState { + zoom: s.zoom, setup_controls: !s.presentation_started, route_trial: s.route_trial.as_ref().map(|t| t.id), sequence: s.output_sequence, @@ -778,11 +849,27 @@ impl App { }; if output.tx.try_send(state).is_ok() { s.new_output = false; + s.new_zoom = false; } else { s.output_sequence -= 1; } } } + if s.new_zoom + && !s.new_output + && let Some(output) = &self.output + { + let state = HostState { + zoom_only: true, + zoom: s.zoom, + generation: s.buffer_generation(), + page: s.requested, + ..Default::default() + }; + if output.tx.try_send(state).is_ok() { + s.new_zoom = false; + } + } if s.close_requested { el.exit(); } @@ -799,7 +886,7 @@ impl App { } if let Some(host) = &mut self.host { loop { - let state = match host.commands.try_recv() { + let mut state = match host.commands.try_recv() { Ok(state) => state, Err(mpsc::TryRecvError::Empty) => break, Err(mpsc::TryRecvError::Disconnected) => { @@ -809,6 +896,18 @@ impl App { break; } }; + if state.zoom_only { + if state.generation == host.state.generation && state.page == host.state.page { + let before = host.state.zoom; + host.state.zoom.accept_presenter(state.zoom); + host.zoom_pending = host.state.zoom != state.zoom.normalized(); + repaint |= before != host.state.zoom; + } + continue; + } + host.state.zoom.accept_presenter(state.zoom); + host.zoom_pending = host.state.zoom != state.zoom.normalized(); + state.zoom = host.state.zoom; if !state.blanked { host.close_requested = false; } @@ -847,6 +946,16 @@ impl App { } host.state = state; } + if host.zoom_pending && host.parent_connected && Instant::now() >= host.next_zoom_ack { + let _ = host.acks.try_send(Ack { + zoom: Some(host.state.zoom), + zoom_slow: host.zoom_slow, + generation: host.state.generation, + page: Some(host.state.page), + ..Default::default() + }); + host.next_zoom_ack = Instant::now() + Duration::from_millis(33); + } if !host.parent_connected && (host.close_requested || self.windows.is_empty()) { el.exit(); return; @@ -1049,6 +1158,17 @@ impl ApplicationHandler for App { blank, self.host.as_ref().map(|h| &h.state), ); + if let Some(host) = &mut self.host { + if let Some(view) = self.windows[index].zoom_change.take() { + host.state.zoom.gesture(view); + host.zoom_pending = true; + self.windows.iter().for_each(|w| w.window.request_redraw()); + } + if self.windows[index].zoom_slow && !host.zoom_slow { + host.zoom_slow = true; + host.zoom_pending = true; + } + } if let Some(action) = self.windows[index].display_action.take() && let Some(host) = &self.host { @@ -1227,6 +1347,9 @@ pub fn run_output() -> Result<(), Failure> { presented: HashSet::new(), failed_reads: HashSet::new(), preload_cursor: 0, + zoom_pending: false, + zoom_slow: false, + next_zoom_ack: now, }), output: None, lease: Some(SleepLease::new()), diff --git a/crates/pdf-presenter/src/output.rs b/crates/pdf-presenter/src/output.rs index e305e97..bda32ed 100644 --- a/crates/pdf-presenter/src/output.rs +++ b/crates/pdf-presenter/src/output.rs @@ -23,6 +23,10 @@ pub enum DisplayAction { } #[derive(Clone, Default, Debug, Serialize, Deserialize)] pub struct HostState { + #[serde(default)] + pub zoom: crate::zoom::Sync, + #[serde(default)] + pub zoom_only: bool, #[serde(default)] pub slide_colors: crate::settings::SlideColors, #[serde(default)] @@ -44,6 +48,10 @@ pub struct HostState { } #[derive(Clone, Default, Debug, Serialize, Deserialize)] pub struct Ack { + #[serde(default)] + pub zoom: Option, + #[serde(default)] + pub zoom_slow: bool, /// Explicit operator blanking, separate from diagnostic status messages. #[serde(default)] pub request_blank: bool, @@ -60,6 +68,18 @@ pub struct Ack { #[serde(default)] pub buffered: usize, } +/// A lightweight crop update must never discard queued frame/routing state. +pub fn coalesce(latest: &mut Option, command: HostState) { + if command.zoom_only + && let Some(previous) = latest + { + if previous.generation == command.generation && previous.page == command.page { + previous.zoom.accept_presenter(command.zoom); + } + } else { + *latest = Some(command); + } +} pub struct OutputLink { pub tx: SyncSender, pub rx: Receiver, @@ -130,7 +150,7 @@ impl OutputLink { } let mut latest = None; while let Ok(command) = commands.try_recv() { - latest = Some(command); + coalesce(&mut latest, command); } if let Some(command) = latest { if write_json(&mut stdin, &command).is_err() { diff --git a/crates/pdf-presenter/src/presenter_ui.rs b/crates/pdf-presenter/src/presenter_ui.rs index 1521430..43fe67d 100644 --- a/crates/pdf-presenter/src/presenter_ui.rs +++ b/crates/pdf-presenter/src/presenter_ui.rs @@ -18,19 +18,102 @@ pub fn paint_slide( dimensions: [u32; 2], colors: crate::settings::SlideColors, ) { - let [width, height] = dimensions.map(|v| v as f32); + paint_slide_zoomed( + painter, + rect, + texture, + dimensions, + colors, + Default::default(), + ); +} +pub fn fitted_slide(rect: Rect, dimensions: [u32; 2]) -> Rect { + let [width, height] = dimensions.map(|v| v.max(1) as f32); let scale = (rect.width() / width).min(rect.height() / height); - let target = Rect::from_center_size(rect.center(), Vec2::new(width * scale, height * scale)); + Rect::from_center_size(rect.center(), Vec2::new(width * scale, height * scale)) +} +/// Crop UVs, never enlarge geometry or allocate another image for zoom. +pub fn paint_slide_zoomed( + painter: &egui::Painter, + rect: Rect, + texture: egui::TextureId, + dimensions: [u32; 2], + colors: crate::settings::SlideColors, + view: crate::zoom::View, +) { + let target = fitted_slide(rect, dimensions); let [r, g, b] = colors.fit_padding; painter.rect_filled(rect, 0., Color32::from_rgb(r, g, b)); let [r, g, b] = colors.page_background; painter.rect_filled(target, 0., Color32::from_rgb(r, g, b)); - painter.image( - texture, - target, - Rect::from_min_max(Pos2::ZERO, Pos2::new(1., 1.)), - Color32::WHITE, - ); + let uv = view.uv(); + // Separate clip bands keep large moving crops parallel in the bounded CPU + // renderer pool. Every band reads the same texture; no image is duplicated. + let pixels = target.area() * painter.ctx().pixels_per_point().powi(2); + let bands = if view.scale > 1. && pixels > 1_000_000. { + 4 + } else { + 1 + }; + for band in 0..bands { + let a = band as f32 / bands as f32; + let b = (band + 1) as f32 / bands as f32; + let rect = Rect::from_min_max( + Pos2::new(target.left(), target.top() + target.height() * a), + Pos2::new(target.right(), target.top() + target.height() * b), + ); + let crop = Rect::from_min_max( + Pos2::new(uv.left(), uv.top() + uv.height() * a), + Pos2::new(uv.right(), uv.top() + uv.height() * b), + ); + painter + .with_clip_rect(painter.clip_rect().intersect(rect)) + .image(texture, rect, crop, Color32::WHITE); + } +} +/// Shared presenter/output input in normalized slide coordinates; no file I/O. +pub fn zoom_gestures( + ui: &mut Ui, + target: Rect, + view: crate::zoom::View, +) -> (crate::zoom::View, egui::Response) { + let response = ui.interact(target, ui.id().with("page-zoom"), Sense::click_and_drag()); + let mut next = view; + if response.hovered() { + let scroll = ui.input_mut(|i| { + let scroll = i.smooth_scroll_delta.y; + i.smooth_scroll_delta = Vec2::ZERO; + scroll + }); + if scroll != 0. + && let Some(pos) = response.hover_pos() + { + let anchor = (pos - target.min) / target.size(); + next = next.zoom_at( + next.scale * (scroll * 0.002).clamp(-0.7, 0.7).exp(), + [anchor.x, anchor.y], + ); + } + let pinch = ui.input(|i| i.zoom_delta()); + if pinch != 1. { + next = next.zoom_at(next.scale * pinch, [0.5; 2]); + } + } + if response.dragged_by(egui::PointerButton::Primary) { + let delta = ui.input(|i| i.pointer.delta()) / target.size(); + next = next.pan([delta.x, delta.y]); + } + if response.double_clicked() { + next = Default::default(); + } + if response.hovered() || response.dragged() { + ui.ctx().set_cursor_icon(if response.dragged() { + egui::CursorIcon::Grabbing + } else { + egui::CursorIcon::Grab + }); + } + (next, response) } const TEAL: Color32 = Color32::from_rgb(103, 226, 205); pub struct UiState { @@ -51,6 +134,16 @@ impl Default for UiState { } impl UiState { pub fn image(&mut self, ui: &mut Ui, s: &Studio, page: usize, rect: Rect) { + self.image_view(ui, s, page, rect, Default::default()); + } + fn image_view( + &mut self, + ui: &mut Ui, + s: &Studio, + page: usize, + rect: Rect, + view: crate::zoom::View, + ) { let locale = ui.ctx().clone(); ui.painter() .rect_filled(rect, 6., Color32::from_rgb(18, 28, 31)); @@ -66,12 +159,13 @@ impl UiState { TextureOptions::LINEAR, ) }); - paint_slide( + paint_slide_zoomed( ui.painter(), rect, tex.id(), [frame.info.width, frame.info.height], s.settings.slide_colors, + view, ); } else { ui.painter().text( @@ -657,12 +751,25 @@ pub fn presenter(ui: &mut Ui, s: &mut Studio, native: &mut UiState) { ui.visuals().hyperlink_color, ); if let Some(page) = page { - native.image( - ui, - s, - page, - Rect::from_min_max(rect.min + Vec2::new(0., 24.), rect.max), - ); + let area = Rect::from_min_max(rect.min + Vec2::new(0., 24.), rect.max); + if index == 1 && s.settings.zoom_enabled { + native.image_view(ui, s, page, area, s.zoom.view); + if s.route_trial.is_none() + && let Some(frame) = s.frame(page) + { + let target = fitted_slide(area, [frame.info.width, frame.info.height]); + let (view, response) = zoom_gestures(ui, target, s.zoom.view); + response.on_hover_text(tr( + &locale, + "Scroll to zoom · drag to pan · double-click to reset", + )); + if view != s.zoom.view { + s.set_zoom(view); + } + } + } else { + native.image(ui, s, page, area); + } } else if index == 2 && s.count() > 0 && s.requested == s.count() - 1 { // Presenter-only decoration: never create a page, frame or navigation target. let area = Rect::from_min_max(rect.min + Vec2::new(0., 24.), rect.max); @@ -1290,6 +1397,16 @@ pub fn presenter(ui: &mut Ui, s: &mut Studio, native: &mut UiState) { }); s.displays_open &= open; } + if s.settings.zoom_enabled && s.zoom_warning && !s.zoom_warning_dismissed { + egui::Window::new(tr(&ctx, "Zoom performance")) + .collapsible(false).resizable(false).show(&ctx, |ui| { + ui.set_max_width(420.); + ui.label(tr(&ctx, "Zoomed frames are taking over 33 ms to draw. Panning may feel slow on this display. Reset or disable zoom to return to normal viewing.")); + if ui.button(tr(&ctx, "Reset zoom")).clicked() { s.set_zoom(Default::default()); s.zoom_warning_dismissed = true; } + if ui.button(tr(&ctx, "Disable zoom")).clicked() { s.enable_zoom(false); } + if ui.button(tr(&ctx, "Keep zoom enabled")).clicked() { s.zoom_warning_dismissed = true; } + }); + } notes_import_ui(&ctx, s); notes_editor_ui(&ctx, s); } @@ -1860,6 +1977,10 @@ fn menu(ui: &mut Ui, s: &mut Studio) { ui.menu_button(tr(&locale,"Preferences"), |ui| { ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { ui.set_width(370.); + let mut enabled = s.settings.zoom_enabled; + if ui.checkbox(&mut enabled, tr(&locale, "Enable page zoom")).changed() { s.enable_zoom(enabled); } + ui.small(tr(&locale, "Zoom reuses buffered images: no extra PDF rendering or image memory. Enlarged slides may look softer. Software drawing can slow down on large or multiple displays.")); + ui.separator(); if ui.checkbox(&mut s.settings.auto_show,tr(&locale,"Show presentation automatically when opening a document")).changed() {s.save_preferences();} ui.separator(); ui.label(tr(&locale,"RAM budget per process (presenter + output each use this allowance):")); @@ -1873,6 +1994,17 @@ fn menu(ui: &mut Ui, s: &mut Studio) { }); }); }); + if s.settings.zoom_enabled { + ui.menu_button(tr(&locale, "Page zoom"), |ui| { + let mut scale = s.zoom.view.scale; + if ui.add(egui::Slider::new(&mut scale, 1.0..=8.0).text("×")).changed() { + s.set_zoom(s.zoom.view.zoom_at(scale, [0.5; 2])); + } + if ui.button(tr(&locale, "Reset zoom")).clicked() { s.set_zoom(Default::default()); } + ui.small(tr(&locale, "Scroll to zoom · drag to pan · double-click to reset")); + ui.small(tr(&locale, "Use the current slide preview or a presentation screen. Changing slides resets zoom.")); + }); + } ui.separator(); timer_controls(ui, s, true); fullscreen_button(ui, s); diff --git a/crates/pdf-presenter/src/settings.rs b/crates/pdf-presenter/src/settings.rs index a8b8687..015e349 100644 --- a/crates/pdf-presenter/src/settings.rs +++ b/crates/pdf-presenter/src/settings.rs @@ -225,6 +225,7 @@ pub struct Settings { pub thumbnail_size: f32, pub buffer_mib: u32, pub auto_show: bool, + pub zoom_enabled: bool, pub theme: crate::theme::Theme, pub language: crate::localization::Language, } @@ -266,6 +267,7 @@ impl Default for Settings { thumbnail_size: 220., buffer_mib: default_buffer_mib(), auto_show: true, + zoom_enabled: false, theme: Default::default(), language: Default::default(), } diff --git a/crates/pdf-presenter/src/studio.rs b/crates/pdf-presenter/src/studio.rs index ecd7f65..b111e86 100644 --- a/crates/pdf-presenter/src/studio.rs +++ b/crates/pdf-presenter/src/studio.rs @@ -127,6 +127,10 @@ pub struct Studio { pub dirty_routes: bool, pub privacy_hold: bool, pub output_sequence: u64, + pub zoom: crate::zoom::Sync, + pub new_zoom: bool, + pub zoom_warning: bool, + pub zoom_warning_dismissed: bool, pub new_output: bool, pub close_requested: bool, failed: HashSet<(usize, u32)>, @@ -224,6 +228,10 @@ impl Studio { dirty_routes: true, privacy_hold: false, output_sequence: 0, + zoom: Default::default(), + new_zoom: false, + zoom_warning: false, + zoom_warning_dismissed: false, new_output: true, close_requested: false, failed: HashSet::new(), @@ -428,6 +436,9 @@ impl Studio { if !self.blanked && self.routes.presentation.is_empty() { self.slide_played(); } + if self.requested != page { + self.set_zoom(crate::zoom::View::default()); + } self.requested = page; self.jump.clear(); self.new_output = true; @@ -748,6 +759,7 @@ impl Studio { if !self.smoke { self.blanked = !settings.auto_show; self.settings = settings; + self.set_zoom(crate::zoom::View::default()); self.layout = self.settings.for_project(&self.project()); self.routes = Routes::default(); } @@ -864,6 +876,7 @@ impl Studio { self.output_buffered = 0; self.ram_blocked = false; self.failed.clear(); + self.set_zoom(crate::zoom::View::default()); self.requested = 0; self.presentation_started = false; self.timer = crate::timer::Timer::default(); @@ -1104,6 +1117,17 @@ impl Studio { pub fn buffer_generation(&self) -> u64 { (self.generation << 32) | u64::from(self.target_edge) } + pub fn set_zoom(&mut self, view: crate::zoom::View) { + self.zoom.set(self.settings.zoom_enabled, view); + self.new_zoom = true; + } + pub fn enable_zoom(&mut self, enabled: bool) { + self.settings.zoom_enabled = enabled; + self.set_zoom(crate::zoom::View::default()); + self.zoom_warning = false; + self.zoom_warning_dismissed = false; + self.save_preferences(); + } pub fn save_preferences(&mut self) { self.pending_save = true; } diff --git a/crates/pdf-presenter/src/zoom.rs b/crates/pdf-presenter/src/zoom.rs new file mode 100644 index 0000000..76290e2 --- /dev/null +++ b/crates/pdf-presenter/src/zoom.rs @@ -0,0 +1,123 @@ +//! Bounded, resolution-independent crop of an already buffered slide. +use serde::{Deserialize, Serialize}; +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct View { + pub scale: f32, + pub center: [f32; 2], +} +impl Default for View { + fn default() -> Self { + Self { + scale: 1., + center: [0.5; 2], + } + } +} +impl View { + pub fn normalized(self) -> Self { + if !self.scale.is_finite() || self.center.iter().any(|v| !v.is_finite()) { + return Self::default(); + } + let scale = self.scale.clamp(1., 8.); + let half = 0.5 / scale; + Self { + scale, + center: self.center.map(|v| v.clamp(half, 1. - half)), + } + } + pub fn zoom_at(self, scale: f32, anchor: [f32; 2]) -> Self { + let old = self.normalized(); + let scale = if scale.is_finite() { + scale.clamp(1., 8.) + } else { + old.scale + }; + let mut next = Self { scale, ..old }; + for (i, a) in anchor.into_iter().enumerate() { + if a.is_finite() { + next.center[i] += (a.clamp(0., 1.) - 0.5) * (1. / old.scale - 1. / scale); + } + } + next.normalized() + } + /// Drag displacement as a fraction of the fitted slide viewport. + pub fn pan(self, delta: [f32; 2]) -> Self { + let mut next = self.normalized(); + for (i, d) in delta.into_iter().enumerate() { + if d.is_finite() { + next.center[i] -= d / next.scale; + } + } + next.normalized() + } + pub fn uv(self) -> egui::Rect { + let v = self.normalized(); + egui::Rect::from_center_size( + egui::pos2(v.center[0], v.center[1]), + egui::Vec2::splat(1. / v.scale), + ) + } +} +/// Presenter epochs override output gestures. Output serials order local gestures +/// within an epoch, allowing bounded channels to coalesce and retry latest state. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Sync { + pub enabled: bool, + pub view: View, + pub epoch: u64, + pub serial: u64, +} +impl Sync { + pub fn normalized(mut self) -> Self { + self.view = if self.enabled { + self.view.normalized() + } else { + View::default() + }; + self + } + pub fn set(&mut self, enabled: bool, view: View) { + self.enabled = enabled; + self.view = view; + self.epoch = self.epoch.wrapping_add(1); + self.serial = 0; + *self = self.normalized(); + } + pub fn gesture(&mut self, view: View) { + if self.enabled { + self.view = view.normalized(); + self.serial = self.serial.wrapping_add(1); + } + } + pub fn accept_output(&mut self, other: Self) -> bool { + if !self.enabled + || !other.enabled + || other.epoch != self.epoch + || other.serial <= self.serial + { + return false; + } + *self = other.normalized(); + true + } + pub fn accept_presenter(&mut self, other: Self) { + if (other.epoch, other.serial) >= (self.epoch, self.serial) { + *self = other.normalized(); + } + } +} +#[derive(Default)] +pub struct PerformanceWatch { + slow: u8, +} +impl PerformanceWatch { + /// Three consecutive zoomed frames above a 30 Hz frame budget trigger notice. + pub fn observe(&mut self, active: bool, elapsed: std::time::Duration) -> bool { + self.slow = if active && elapsed > std::time::Duration::from_millis(33) { + self.slow.saturating_add(1) + } else { + 0 + }; + self.slow >= 3 + } +} diff --git a/crates/pdf-presenter/tests/native.rs b/crates/pdf-presenter/tests/native.rs index 16eb66c..8a585c0 100644 --- a/crates/pdf-presenter/tests/native.rs +++ b/crates/pdf-presenter/tests/native.rs @@ -204,6 +204,15 @@ fn independent_output_acknowledges_frames_and_blanking() { write_json( &mut input, &HostState { + zoom: pdf_presenter::zoom::Sync { + enabled: true, + view: pdf_presenter::zoom::View { + scale: 2., + center: [0.5; 2], + }, + epoch: sequence * 2, + serial: 0, + }, sequence, page, generation: 99, @@ -226,6 +235,41 @@ fn independent_output_acknowledges_frames_and_blanking() { break; } } + // Zoom-only commands carry no frame, preload, routes or visibility fields. + // They must retain every buffered frame after all source/cache files are gone. + write_json( + &mut input, + &HostState { + zoom_only: true, + generation: 99, + page, + zoom: pdf_presenter::zoom::Sync { + enabled: true, + view: pdf_presenter::zoom::View { + scale: 4., + center: [0.4, 0.6], + }, + epoch: sequence * 2 + 1, + serial: 0, + }, + ..Default::default() + }, + ) + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(5); + loop { + let ack = rx + .recv_timeout(deadline.saturating_duration_since(Instant::now())) + .expect("zoom retained buffer deadline"); + assert!(ack.status.is_empty(), "{}", ack.status); + if ack.sequence == sequence + && ack.generation == 99 + && ack.buffered == 8 + && ack.page == (!blanked).then_some(page) + { + break; + } + } } write_json( &mut input, diff --git a/crates/pdf-presenter/tests/presenter_ui.rs b/crates/pdf-presenter/tests/presenter_ui.rs index 68e5a3f..2bba767 100644 --- a/crates/pdf-presenter/tests/presenter_ui.rs +++ b/crates/pdf-presenter/tests/presenter_ui.rs @@ -1134,3 +1134,46 @@ fn notes_import_review_requires_explicit_save_and_cancel_discards_preview() { assert_eq!(s.deck.as_ref().unwrap().notes, original); } } + +#[test] +fn zoom_is_opt_in_resets_on_slide_change_and_does_not_blank_output() { + let mut s = studio(); + assert!(!s.settings.zoom_enabled); + s.blanked = false; + s.set_zoom(pdf_presenter::zoom::View { + scale: 4., + center: [0.3, 0.6], + }); + assert_eq!(s.zoom.view.scale, 1.); + s.enable_zoom(true); + s.set_zoom(pdf_presenter::zoom::View { + scale: 4., + center: [0.3, 0.6], + }); + let ctx = Context::default(); + let mut state = UiState::default(); + for size in [Vec2::new(1280., 900.), Vec2::new(600., 400.)] { + let _ = ctx.run_ui(input(size), |ui| { + presenter_ui::presenter(ui, &mut s, &mut state) + }); + assert_eq!(s.zoom.view.scale, 4.); + } + let epoch = s.zoom.epoch; + s.execute(Action::Go(1)); + assert_eq!(s.zoom.view.scale, 1.); + assert!(s.zoom.epoch > epoch); + assert!(!s.blanked); + s.set_zoom(pdf_presenter::zoom::View { + scale: 8., + center: [0.5; 2], + }); + s.zoom_warning = true; + let _ = ctx.run_ui(input(Vec2::new(900., 700.)), |ui| { + presenter_ui::presenter(ui, &mut s, &mut state) + }); + assert!(!s.zoom_warning_dismissed); + s.enable_zoom(false); + assert_eq!(s.zoom.view, Default::default()); + assert!(!s.zoom_warning); + assert!(!s.blanked); +} diff --git a/crates/pdf-presenter/tests/zoom.rs b/crates/pdf-presenter/tests/zoom.rs new file mode 100644 index 0000000..16b5b1c --- /dev/null +++ b/crates/pdf-presenter/tests/zoom.rs @@ -0,0 +1,441 @@ +use egui::{Context, Pos2, RawInput, Rect, TextureOptions, Vec2}; +use egui_software_backend::{BufferMutRef, ColorFieldOrder, EguiSoftwareRender}; +use pdf_presenter::{ + output::{HostState, coalesce}, + settings::Settings, + zoom::{PerformanceWatch, Sync, View}, +}; +use std::time::{Duration, Instant}; +#[test] +fn crop_anchor_pan_and_limits() { + let start = View::default(); + let zoom = start.zoom_at(2., [0.25, 0.75]); + assert_eq!(zoom.center, [0.375, 0.625]); + assert_eq!(zoom.uv().size(), Vec2::splat(0.5)); + let panned = zoom.pan([0.1, -0.1]); + assert!((panned.center[0] - 0.325).abs() < 0.00001); + let edge = panned.pan([100., -100.]); + assert_eq!(edge.center, [0.25, 0.75]); + assert_eq!(edge.zoom_at(1., [0., 0.]), start); + assert_eq!(start.zoom_at(100., [0.5; 2]).scale, 8.); + assert_eq!( + View { + scale: f32::NAN, + center: [f32::INFINITY, 0.] + } + .normalized(), + start + ); + assert_eq!(start.pan([f32::NAN, f32::INFINITY]), start); +} +#[test] +fn synchronization_rejects_stale_gestures_and_coalesces_without_losing_frames() { + let mut presenter = Sync::default(); + presenter.set(true, View::default()); + let mut host = presenter; + host.gesture(host.view.zoom_at(3., [0.5; 2])); + let old = host; + host.gesture(host.view.pan([0.1, 0.])); + assert!(presenter.accept_output(host)); + assert!(!presenter.accept_output(old)); + host.accept_presenter(old); + assert_eq!(host, presenter); + presenter.set(true, View::default()); + assert!(!presenter.accept_output(host)); + host.accept_presenter(presenter); + assert_eq!(host.view, View::default()); + presenter.set(false, host.view.zoom_at(4., [0.5; 2])); + assert_eq!(presenter.view, View::default()); + let mut pending = Some(HostState { + generation: 4, + page: 2, + sequence: 12, + monitors: vec!["screen".into()], + zoom: host, + ..Default::default() + }); + host.gesture(host.view.zoom_at(4., [0.5; 2])); + coalesce( + &mut pending, + HostState { + zoom_only: true, + zoom: host, + generation: 4, + page: 2, + ..Default::default() + }, + ); + let state = pending.as_ref().unwrap(); + assert_eq!(state.monitors, vec!["screen"]); + assert_eq!(state.sequence, 12); + assert!(!state.zoom_only); + assert_eq!(state.zoom, host); + coalesce( + &mut pending, + HostState { + zoom_only: true, + generation: 3, + ..Default::default() + }, + ); + assert_eq!(pending.as_ref().unwrap().zoom, host); + coalesce( + &mut pending, + HostState { + quit: true, + ..Default::default() + }, + ); + assert!(pending.unwrap().quit); +} +#[test] +fn settings_default_opt_out_roundtrip_and_warning_threshold() { + assert!(!Settings::default().zoom_enabled); + let old: Settings = toml::from_str("version=1").unwrap(); + assert!(!old.zoom_enabled); + let enabled = Settings { + zoom_enabled: true, + ..Default::default() + }; + let restored: Settings = toml::from_str(&toml::to_string(&enabled).unwrap()).unwrap(); + assert!(restored.zoom_enabled); + let mut watch = PerformanceWatch::default(); + assert!(!watch.observe(false, Duration::from_secs(1))); + assert!(!watch.observe(true, Duration::from_millis(40))); + assert!(!watch.observe(true, Duration::from_millis(40))); + assert!(watch.observe(true, Duration::from_millis(40))); + assert!(!watch.observe(true, Duration::from_millis(20))); + assert!(!watch.observe(true, Duration::from_millis(40))); +} +#[test] +fn zoom_paints_existing_texture_crop_with_constant_geometry_and_no_new_uploads() { + let ctx = Context::default(); + let mut rgba = vec![0; 64 * 32 * 4]; + for y in 0..32 { + for x in 0..64 { + let color = if x < 32 { + [255, 0, 0, 255] + } else { + [0, 0, 255, 255] + }; + rgba[(y * 64 + x) * 4..(y * 64 + x + 1) * 4].copy_from_slice(&color); + } + } + let texture = ctx.load_texture( + "slide", + egui::ColorImage::from_rgba_unmultiplied([64, 32], &rgba), + TextureOptions::NEAREST, + ); + let mut renderer = EguiSoftwareRender::new(ColorFieldOrder::Bgra); + let rect = Rect::from_min_size(Pos2::ZERO, Vec2::splat(200.)); + let mut pixels = vec![0u32; 200 * 200]; + for (index, view) in [ + View::default(), + View { + scale: 2., + center: [0.25, 0.5], + }, + View { + scale: 2., + center: [0.75, 0.5], + }, + ] + .into_iter() + .enumerate() + { + let output = ctx.run_ui( + RawInput { + screen_rect: Some(rect), + ..Default::default() + }, + |ui| { + pdf_presenter::presenter_ui::paint_slide_zoomed( + ui.painter(), + rect, + texture.id(), + [64, 32], + Default::default(), + view, + ); + }, + ); + if index > 0 { + assert!( + output.textures_delta.set.is_empty(), + "zoom uploaded another image" + ); + } + let primitives = ctx.tessellate(output.shapes, output.pixels_per_point); + for primitive in &primitives { + if let egui::epaint::Primitive::Mesh(mesh) = &primitive.primitive + && mesh.texture_id == texture.id() + { + assert!( + mesh.vertices.iter().all(|v| rect.contains(v.pos)), + "zoom enlarged draw geometry" + ); + } + } + renderer.render( + &mut BufferMutRef::new(bytemuck::cast_slice_mut(&mut pixels), 200, 200), + &primitives, + &output.textures_delta, + output.pixels_per_point, + ); + assert_eq!(pixels[5 * 200 + 5] & 0xffffff, 0); // Padding unchanged. + if index > 0 { + let expected = if index == 1 { 0xff0000 } else { 0x0000ff }; + assert_eq!(pixels[100 * 200 + 30] & 0xffffff, expected); + assert_eq!(pixels[100 * 200 + 170] & 0xffffff, expected); + } + } +} +#[test] +#[ignore = "Manual Linux software drawing measurement; not a timing-sensitive CI assertion"] +fn buffered_zoom_drawing_measurement() { + for [width, height] in [[1920usize, 1080usize], [3840, 2160]] { + let ctx = Context::default(); + let rgba: Vec = (0..1920 * 1080) + .flat_map(|p| [(p % 256) as u8, ((p / 1920) % 256) as u8, 128, 255]) + .collect(); + let texture = ctx.load_texture( + "benchmark", + egui::ColorImage::from_rgba_unmultiplied([1920, 1080], &rgba), + TextureOptions::LINEAR, + ); + let mut renderer = EguiSoftwareRender::new(ColorFieldOrder::Bgra); + let mut pixels = vec![0u32; width * height]; + let rect = Rect::from_min_size(Pos2::ZERO, Vec2::new(width as f32, height as f32)); + for scale in [1., 4., 8.] { + let mut times = Vec::new(); + for i in 0..12 { + let start = Instant::now(); + let view = View { + scale, + center: [0.4 + i as f32 * 0.01, 0.5], + } + .normalized(); + let output = ctx.run_ui( + RawInput { + screen_rect: Some(rect), + ..Default::default() + }, + |ui| { + pdf_presenter::presenter_ui::paint_slide_zoomed( + ui.painter(), + rect, + texture.id(), + [1920, 1080], + Default::default(), + view, + ); + }, + ); + let primitives = ctx.tessellate(output.shapes, output.pixels_per_point); + renderer.render( + &mut BufferMutRef::new(bytemuck::cast_slice_mut(&mut pixels), width, height), + &primitives, + &output.textures_delta, + output.pixels_per_point, + ); + if i > 1 { + times.push(start.elapsed().as_secs_f64() * 1000.); + } + } + times.sort_by(f64::total_cmp); + println!( + "{width}x{height} {scale}x: median {:.2} ms, max {:.2} ms", + times[times.len() / 2], + times.last().unwrap() + ); + } + } +} + +#[test] +fn wheel_drag_and_double_click_operate_in_slide_coordinates() { + let ctx = Context::default(); + let target = Rect::from_min_max(Pos2::new(40., 40.), Pos2::new(440., 240.)); + let mut view = View::default(); + let mut time = 0.; + let mut render = |events: Vec| { + time += 0.04; + let _ = ctx.run_ui( + RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, Vec2::new(500., 300.))), + events, + time: Some(time), + ..Default::default() + }, + |ui| { + view = pdf_presenter::presenter_ui::zoom_gestures(ui, target, view).0; + }, + ); + view + }; + let center = target.center(); + render(vec![egui::Event::PointerMoved(center)]); + render(vec![egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + phase: egui::TouchPhase::Move, + delta: Vec2::new(0., 300.), + modifiers: egui::Modifiers::NONE, + }]); + let mut zoom = View::default(); + for _ in 0..30 { + zoom = render(vec![]); + } + assert!(zoom.scale > 1.2); + let click = |pos, pressed| egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }; + render(vec![click(center, true)]); + let moved = center + Vec2::new(40., 10.); + let panned = render(vec![egui::Event::PointerMoved(moved)]); + assert!(panned.center[0] < zoom.center[0]); + render(vec![click(moved, false)]); + for _ in 0..20 { + render(vec![]); + } + for _ in 0..2 { + render(vec![click(moved, true)]); + zoom = render(vec![click(moved, false)]); + } + assert_eq!(zoom, View::default()); +} + +#[test] +fn optimized_crop_matches_general_renderer_with_alpha_clipping_and_dpi() { + for dpi in [1., 2.] { + let ctx = Context::default(); + ctx.set_pixels_per_point(dpi); + let rgba: Vec = (0..64 * 32) + .flat_map(|p| { + [ + (p % 64 * 4) as u8, + (p / 64 * 8) as u8, + 80, + (40 + p % 64 * 3) as u8, + ] + }) + .collect(); + let texture = ctx.load_texture( + "alpha", + egui::ColorImage::from_rgba_unmultiplied([64, 32], &rgba), + TextureOptions::LINEAR, + ); + let mut fast = EguiSoftwareRender::new(ColorFieldOrder::Bgra); + let mut reference = + EguiSoftwareRender::new(ColorFieldOrder::Bgra).with_allow_raster_opt(false); + let rect = Rect::from_min_size(Pos2::ZERO, Vec2::new(320., 240.)); + let mut actual = vec![0u32; (320. * dpi) as usize * (240. * dpi) as usize]; + let mut expected = actual.clone(); + for view in [ + View { + scale: 2., + center: [0.25, 0.25], + }, + View { + scale: 3.1, + center: [0.7, 0.4], + }, + ] { + let output = ctx.run_ui( + RawInput { + screen_rect: Some(rect), + ..Default::default() + }, + |ui| { + let painter = ui.painter().with_clip_rect(rect.shrink(20.)); + pdf_presenter::presenter_ui::paint_slide_zoomed( + &painter, + rect, + texture.id(), + [64, 32], + Default::default(), + view, + ); + }, + ); + let primitives = ctx.tessellate(output.shapes, output.pixels_per_point); + let width = (320. * output.pixels_per_point) as usize; + let height = (240. * output.pixels_per_point) as usize; + // egui applies a requested DPI change on a subsequent frame. + actual.resize(width * height, 0); + expected.resize(width * height, 0); + actual.fill(0); + expected.fill(0); + fast.render( + &mut BufferMutRef::new(bytemuck::cast_slice_mut(&mut actual), width, height), + &primitives, + &output.textures_delta, + output.pixels_per_point, + ); + reference.render( + &mut BufferMutRef::new(bytemuck::cast_slice_mut(&mut expected), width, height), + &primitives, + &output.textures_delta, + output.pixels_per_point, + ); + for (a, b) in actual.iter().zip(&expected) { + for (a, b) in a.to_le_bytes().iter().zip(b.to_le_bytes()) { + assert!( + a.abs_diff(b) <= 2, + "crop pixel mismatch: {a} vs {b} at DPI {dpi}" + ); + } + } + } + } +} + +#[test] +fn parallel_crop_bands_have_no_seams_at_fractional_boundaries() { + let ctx = Context::default(); + let texture = ctx.load_texture( + "solid", + egui::ColorImage::from_rgba_unmultiplied([64, 32], &[255, 180, 60, 255].repeat(64 * 32)), + TextureOptions::LINEAR, + ); + let rect = Rect::from_min_size(Pos2::ZERO, Vec2::new(1931., 1087.)); + let output = ctx.run_ui( + RawInput { + screen_rect: Some(rect), + ..Default::default() + }, + |ui| { + pdf_presenter::presenter_ui::paint_slide_zoomed( + ui.painter(), + rect, + texture.id(), + [64, 32], + Default::default(), + View { + scale: 3.7, + center: [0.4, 0.6], + }, + ); + }, + ); + let primitives = ctx.tessellate(output.shapes, output.pixels_per_point); + assert_eq!(primitives.iter().filter(|p| matches!(&p.primitive, egui::epaint::Primitive::Mesh(m) if m.texture_id == texture.id())).count(),4); + let mut pixels = vec![0u32; 1931 * 1087]; + EguiSoftwareRender::new(ColorFieldOrder::Bgra).render( + &mut BufferMutRef::new(bytemuck::cast_slice_mut(&mut pixels), 1931, 1087), + &primitives, + &output.textures_delta, + output.pixels_per_point, + ); + for y in 62..1025 { + for x in [50, 965, 1880] { + assert_eq!( + pixels[y * 1931 + x] & 0xffffff, + 0xffb43c, + "band seam at {x},{y}" + ); + } + } +} diff --git a/docs/changelog.md b/docs/changelog.md index 8380f49..616ba69 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -2,6 +2,18 @@ ## Unreleased +### 0.1.54 + +- Add globally saved, default-off page zoom (1×–8×), wheel/pinch zoom, drag panning + and double-click reset from the presenter/current preview or any output. Mirror + the crop with lightweight ordered messages; reset on slide changes and preserve + visibility. Reuse buffered textures without new rendering, file I/O or image + allocations. Explain sharpness/CPU tradeoffs and warn on repeated slow frames. + Bundle a licensed renderer patch for bounded scanline sampling and parallel crop + bands (four threads maximum). Local software-drawing medians: ~5 ms at 1080p, + ~16 ms at 4K; physical multicreen/OS acceptance remains separate. + Linux checks cover input, pixels, opt-in migration and disk-free output buffering. + ### 0.1.53 - Import UTF-8 TXT notes separated by hyphen lines or Markdown notes separated by diff --git a/docs/development/native-implementation.md b/docs/development/native-implementation.md index 7358734..186bd5f 100644 --- a/docs/development/native-implementation.md +++ b/docs/development/native-implementation.md @@ -292,3 +292,48 @@ formatting, warnings-denied Clippy/rustdoc and 13 Python tests pass; whole-app X11 coverage is 86.38%. Niri is unavailable here, so this verifies hint delivery, not Niri placement or physical multi-monitor acceptance. Windows/macOS were not built or runtime-tested for this Linux-only change. + + +## Buffered page zoom — 0.1.54 + +Opt-in zoom crops UVs of the current cached texture, with bounded normalized panning +and no oversized draw rectangle. All views share crop state via small coalesced IPC; +page/epoch/serial checks prevent stale gestures from undoing navigation or reset. +The output host updates its mirrors locally and retries the latest crop at 30 Hz +until echoed. Full slide-buffer manifests are not resent for zoom-only updates. +Tests cover anchor math, bounds, pointer gestures, settings migration, software +pixels/unchanged texture uploads and host buffer preservation after deleting source +and cache files. The manual software-drawing measurement is run with: + +```sh +cargo test --release --test zoom buffered_zoom_drawing_measurement -- --ignored --nocapture +``` + +This synthetic measurement excludes OS presentation/compositor and physical mirror +acceptance. Validate real pointer/trackpad input and simultaneous displays on each OS; +only Linux development checks were run for this subject. + + +The software renderer is bundled with a narrow cropped-quad optimization; see +[`vendor/egui_software_backend/PDF-PRESENTER-PATCH.md`](../../vendor/egui_software_backend/PDF-PRESENTER-PATCH.md) +for provenance and the precise changes. Fixed-point bilinear scanlines reuse two +filtered rows and bounded coordinate tables. Large crops use four disjoint bands +on a lazily initialized pool capped at four CPU threads per native process. This +keeps image buffers shared, avoids PDF jobs and bounds additional scratch memory +by viewport width. Font/tinted/general geometry keeps the original raster path. + + +Local release-mode measurement (2026-11-20, Intel Core i5-8500, six logical CPUs, +renderer pool capped at four): 1920×1080 source image, changing crop center every +frame, two warm-up frames then ten timed frames per case. Median software drawing: + +| Output size | Fitted/static 1× | Panning at 4× | Panning at 8× | +| --- | ---: | ---: | ---: | +| 1920×1080 | 0.79 ms | 4.83 ms | 4.29 ms | +| 3840×2160 | 4.11 ms | 16.07 ms | 15.76 ms | + +Maximum measured moving-frame time was 17.02 ms. The 1× case benefits from an +unchanged cached primitive; moving crops deliberately invalidate that cache. +These numbers include egui tessellation and software buffer drawing, exclude native +surface/compositor/monitor latency, and are not a guaranteed display frame rate. +The in-app watcher measures the actual native window draw/presentation call. diff --git a/docs/interfaces/examples/settings-v1.toml b/docs/interfaces/examples/settings-v1.toml index 44d0a19..e0aff72 100644 --- a/docs/interfaces/examples/settings-v1.toml +++ b/docs/interfaces/examples/settings-v1.toml @@ -1,5 +1,6 @@ version = 1 auto_show = true +zoom_enabled = false theme = "midra" language = "system" presenter_fullscreen = true diff --git a/docs/interfaces/process-protocol.md b/docs/interfaces/process-protocol.md index bd3da78..1e7a424 100644 --- a/docs/interfaces/process-protocol.md +++ b/docs/interfaces/process-protocol.md @@ -136,3 +136,35 @@ merges notes and writes atomically, returning the existing `Reply.notes` snapsho Both notes jobs use the dedicated 30-second bridge, bounded JSON messages and source generations. Notes picker results carry the source generation too. These messages are private same-executable presenter/worker traffic, never output-host traffic. + + +## Shared zoom in 0.1.54 + +HostState adds `zoom {enabled, view {scale, center}, epoch, serial}` and +`zoom_only` (false by default). Scale is bounded to 1–8 and center is normalized +page UV coordinates, clamped to keep the full crop inside the page. Disabled or +invalid views normalize to a complete fitted page. The viewport keeps the slide's +aspect ratio and draws a cropped texture rectangle with constant-sized geometry. +No higher-resolution request, texture upload or image buffer is created by zoom. +Large crops split into disjoint clip bands on a pool capped at four CPU threads; +scanline interpolation uses O(viewport width) scratch memory. + +Presenter gestures, enable/disable and slide changes advance `epoch`, reset serial +to zero and invalidate prior output gestures. Output gestures increment `serial` +within that epoch, sharing the crop immediately among output mirrors. Ack adds +optional `zoom` and boolean `zoom_slow`; crop ACKs include generation and page. +Presenter accepts only current-generation/current-page/current-epoch newer serials. +The output retains newer local serials against delayed presenter states. Pending +output changes retry at most every 33 ms until the presenter echoes the crop; pipe +queues remain bounded and the latest absolute crop replaces intermediate gestures. + +Zoom-only messages contain only crop/page/generation metadata and must not replace +frame, preload, monitor, fullscreen or visibility state. Coalescing retains queued +full state and merges same-page zoom metadata. The host validates page/generation +before applying a lightweight update, without touching its RAM cache or textures. +Full state also carries zoom for recovery. Notes and other operator data remain +absent. No zoom state is persisted except the opt-in boolean in settings. + +The performance watcher counts three consecutive zoomed window draws above 33 ms, +including software drawing/presentation. The presenter shows the warning locally; +output hosts report only a boolean. It does not alter visibility or navigation. diff --git a/docs/interfaces/settings.md b/docs/interfaces/settings.md index 877f364..b531f58 100644 --- a/docs/interfaces/settings.md +++ b/docs/interfaces/settings.md @@ -12,6 +12,11 @@ with an error, without rewriting the bad file. Missing files use defaults. Reads bounded to 4 MiB. Writes validate then atomically replace using a same-directory flushed temporary file. Unknown fields are ignored and not preserved on round trip. +- `zoom_enabled`: boolean, default false, added in 0.1.54. Global opt-in for + presenter/current-slide and output zoom gestures. Missing fields in older v1 + files retain normal non-zoom behavior. Menu → Preferences saves this setting + immediately. Crop/scale, gesture serials and warning state are transient and are + never saved in global/project layouts; each newly opened slide starts fitted. - `slide_colors.page_background` and `slide_colors.fit_padding`: opaque sRGB arrays of exactly three integers, each 0–255, added in 0.1.26. Defaults are `[255, 255, 255]` (white beneath transparent slide pixels) and `[0, 0, 0]` diff --git a/docs/user-guide.md b/docs/user-guide.md index 71137d8..50e7af7 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -317,3 +317,32 @@ file onto the presenter. Review the destination and slide count, then choose **Import and save notes** to create/update the presentation's `.notes.toml` file. Cancel leaves files unchanged. See the [README examples](../README.md#import-your-notes) and [format contract](interfaces/presentation-notes.md#importing-txt-and-markdown). + + +## Zoom and move around a slide + +Zoom is **off by default**. Enable **Menu → Preferences → Enable page zoom**. +The preference is saved globally; it does not change presentation visibility. + +- On the **current slide preview** or any **presentation screen**, scroll up/down + to zoom in/out (1×–8×). The point under the mouse stays anchored when possible. +- Hold the left mouse button and drag to move the enlarged image. Movement stops + at the page edges. Double-click to reset to the complete fitted slide. +- **Menu → Page zoom** also has a zoom slider and **Reset zoom** button. If the + current preview is hidden, show it in Layout to pan from the presenter. +- All mirrored presenter/current previews and presentation outputs share the crop. + Previous/next previews, All slides thumbnails and browser previews stay unzoomed. + Moving to another slide or opening another presentation resets zoom. Display + swaps/fullscreen changes preserve it. Zoom gestures pause during display trials. + +Zoom uses the already buffered image: no PDF re-render, additional image buffer, +cache rewrite or disk access is triggered by changing the zoom. This prioritizes +response time; text/images may look softer when enlarged, especially while only a +low-resolution preview is available. Normal background preparation continues. + +The Preferences disclaimer explains that software drawing can slow down on large +or multiple displays. If three consecutive zoomed frames take over 33 ms each to +render/present on a window, a **Zoom performance** warning appears on the presenter +with reset, disable and keep-enabled choices. This is a detected frame-budget +warning, not proof that zoom caused the delay. It does not blank or interrupt the +output. It cannot predict compositor/hardware delays or guarantee a frame rate. diff --git a/vendor/egui_software_backend/Cargo.toml b/vendor/egui_software_backend/Cargo.toml new file mode 100644 index 0000000..d916f4c --- /dev/null +++ b/vendor/egui_software_backend/Cargo.toml @@ -0,0 +1,156 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2024" +name = "egui_software_backend" +version = "0.0.3" +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = "A CPU software render backend for egui." +homepage = "https://github.com/DGriffin91/egui_software_backend" +readme = "README.md" +keywords = [ + "egui", + "raster", + "software", + "render", + "softbuffer", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/DGriffin91/egui_software_backend" + +[features] +default = [ + "std", + "winit", +] +log = ["dep:log"] +raster_stats = ["std"] +rayon = ["dep:rayon"] +std = [] +test_render = [ + "dep:image", + "dep:egui_kittest", +] +winit = [ + "dep:winit", + "softbuffer", + "egui-winit", + "bytemuck", +] + +[lib] +name = "egui_software_backend" +path = "src/lib.rs" + +[dependencies.bytemuck] +version = "1.25" +optional = true + +[dependencies.constify] +version = "0.0.1" + +[dependencies.egui] +version = "0.34" +default-features = false + +[dependencies.egui-winit] +version = "0.34" +optional = true +default-features = false + +[dependencies.egui_kittest] +version = "0.34" +optional = true + +[dependencies.image] +version = "0.25" +optional = true + +[dependencies.log] +version = "0.4" +optional = true + +[dependencies.rayon] +version = "1.11.0" +optional = true + +[dependencies.softbuffer] +version = "0.4" +optional = true + +[dependencies.strength_reduce] +version = "0.2.4" + +[dependencies.winit] +version = "0.30" +optional = true + +[dev-dependencies.argh] +version = "0.1" + +[dev-dependencies.bytemuck] +version = "1.25" + +[dev-dependencies.dify] +version = "0.7" + +[dev-dependencies.eframe] +version = "0.34" + +[dev-dependencies.egui] +version = "0.34" +features = ["default_fonts"] + +[dev-dependencies.egui-winit] +version = "0.34" +default-features = false + +[dev-dependencies.egui_demo_lib] +version = "0.34" + +[dev-dependencies.egui_extras] +version = "0.34" +features = ["all_loaders"] + +[dev-dependencies.egui_kittest] +version = "0.34" +features = [ + "snapshot", + "wgpu", +] + +[dev-dependencies.epaint_default_fonts] +version = "0.34" + +[dev-dependencies.image] +version = "0.25" +features = [ + "jpeg", + "png", +] + +[dev-dependencies.softbuffer] +version = "0.4" + +[dev-dependencies.winit] +version = "0.30" + +[profile.dev] +opt-level = 3 + +[profile.dev.package."*"] +opt-level = 3 diff --git a/vendor/egui_software_backend/LICENSE-APACHE b/vendor/egui_software_backend/LICENSE-APACHE new file mode 100644 index 0000000..d9a10c0 --- /dev/null +++ b/vendor/egui_software_backend/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/vendor/egui_software_backend/LICENSE-MIT b/vendor/egui_software_backend/LICENSE-MIT new file mode 100644 index 0000000..9cf1062 --- /dev/null +++ b/vendor/egui_software_backend/LICENSE-MIT @@ -0,0 +1,19 @@ +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/egui_software_backend/PDF-PRESENTER-PATCH.md b/vendor/egui_software_backend/PDF-PRESENTER-PATCH.md new file mode 100644 index 0000000..d7361e8 --- /dev/null +++ b/vendor/egui_software_backend/PDF-PRESENTER-PATCH.md @@ -0,0 +1,31 @@ +# Local renderer patch + +Upstream: crates.io `egui_software_backend` 0.0.3, MIT OR Apache-2.0. Source and +license texts were copied from the Cargo registry for reproducible offline builds. +The Cargo example entries were removed because those example files are not bundled. +No generated binaries or downloaded runtime components are included. + +Local changes: + +- `fast_image.rs`, registered in lib.rs and called from render.rs: guarded scanline + sampling for axis-aligned, white, clamped cropped image quads. Other geometry, + font texture, full images and tint/wrapping keep the upstream raster path. +- Sampling caches two horizontally filtered rows and O(viewport width) index data. + Fixed-point bilinear interpolation preserves premultiplied color/alpha, with at + most two channel values of rounding difference versus the floating-point path. + No separate slide/zoom image is allocated. +- egui_texture.rs records opacity at upload; lib.rs conservatively clears it for + transparent partial updates. Opaque scanlines avoid unnecessary blending. +- lib.rs initializes the optional Rayon pool lazily, bounded to at most four + available CPU threads per process. Renderer workers are not created by PDF/IO + worker processes. The application splits large moving crops into four disjoint + clip bands; all bands reference the same texture. +- Tile occupancy lookup uses binary search in the existing row-major sorted list. + Cached primitives, alpha compositing, canvas buffers and general UI drawing keep + their upstream representation. No new coverage exclusions were added. + +Tests: `crates/pdf-presenter/tests/zoom.rs`, `slide_colors.rs`, and native tests. +They compare optimized pixels with the general raster path, exercise clipping/DPI, +alpha and crop bounds, and check that panning does not upload another texture. +Benchmark: `cargo test --release --test zoom buffered_zoom_drawing_measurement -- +--ignored --nocapture`. Physical multicreen acceptance is separate. diff --git a/vendor/egui_software_backend/README.md b/vendor/egui_software_backend/README.md new file mode 100644 index 0000000..2eb84ca --- /dev/null +++ b/vendor/egui_software_backend/README.md @@ -0,0 +1,73 @@ +# CPU software render backend for [egui](https://github.com/emilk/egui) +![License](https://img.shields.io/badge/license-MIT%2FApache-blue.svg) [![Crates.io](https://img.shields.io/crates/v/egui_software_backend.svg)](https://crates.io/crates/egui_software_backend) +[![Docs](https://docs.rs/egui_software_backend/badge.svg)](https://docs.rs/egui_software_backend/latest/egui_software_backend/) + +![demo](demo.png) + +```rs +use egui_software_backend::{BufferMutRef, ColorFieldOrder, EguiSoftwareRender}; +let buffer = &mut vec![[0u8; 4]; 512 * 512]; +let mut buffer_ref = BufferMutRef::new(buffer, 512, 512); +let ctx = egui::Context::default(); +let mut demo = egui_demo_lib::DemoWindows::default(); +let mut sw_render = EguiSoftwareRender::new(ColorFieldOrder::Bgra); + +let out = ctx.run(egui::RawInput::default(), |ctx| { + demo.ui(ctx); +}); + +let primitives = ctx.tessellate(out.shapes, out.pixels_per_point); + +sw_render.render( + &mut buffer_ref, + &primitives, + &out.textures_delta, + out.pixels_per_point, +); +``` + +## winit quickstart +```rust +use egui::vec2; +use egui_software_backend::{SoftwareBackend, SoftwareBackendAppConfiguration}; + +struct EguiApp {} + +impl EguiApp { + fn new(context: egui::Context) -> Self { + egui_extras::install_image_loaders(&context); + EguiApp {} + } +} + +impl egui_software_backend::App for EguiApp { + fn ui(&mut self, ui: &mut egui::Ui, _backend: &mut SoftwareBackend) { + egui::CentralPanel::default().show_inside(ui, |ui| { + ui.label("Hello World!"); + }); + } +} + +fn main() { + let settings = SoftwareBackendAppConfiguration::new() + .inner_size(Some(vec2(500.0, 300.0))) + .title(Some("Simple example".to_string())); + + egui_software_backend::run_app_with_software_backend(settings, EguiApp::new) + //Can fail if winit fails to create the window + .expect("Failed to run app") +} +``` + +[egui_backend_selector](https://github.com/AlexanderSchuetz97/egui_backend_selector) can be used in conjunction with this crate to automatically fallback to using this software renderer at runtime. + +## Other examples +- bevy + softbuffer see examples/bevy_example folder + +## egui version mapping +| egui_software_backend | egui | +|-----------------------|--------| +| 0.0.3 | 0.34.X | +| 0.0.2 | 0.33.X | +| 0.0.1 | 0.33.X | + diff --git a/vendor/egui_software_backend/src/color/avx2.rs b/vendor/egui_software_backend/src/color/avx2.rs new file mode 100644 index 0000000..49262ef --- /dev/null +++ b/vendor/egui_software_backend/src/color/avx2.rs @@ -0,0 +1,321 @@ +#![allow(unsafe_code)] + +use core::ptr::write_unaligned; +use core::{arch::x86_64::*, ptr::read_unaligned}; + +use crate::color::sse41::Sse41Impl; +use crate::color::{GenericImpl, SelectedImpl}; + +type U8x4x4 = __m128i; +type U16x4x2 = __m128i; +type U16x4x4 = __m256i; + +#[derive(Clone, Copy)] +pub(crate) struct Avx2Impl { + sse41: Sse41Impl, +} + +impl Avx2Impl { + /// `std::arch::is_x86_feature_detected!("avx2")` MUST be true + /// `std::arch::is_x86_feature_detected!("sse4.1")` MUST be true + pub(crate) const unsafe fn new() -> Self { + Self { + sse41: unsafe { Sse41Impl::new() }, + } + } +} + +impl Avx2Impl { + #[inline] + #[target_feature(enable = "avx2")] + fn dispatch_avx2(self, f: impl FnOnce(Self) -> R) -> R { + f(self) + } + + // https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html + /// dst[i] = blend(src[i], dst[i]) // As unorm + /// blend fn is (ONE, ONE_MINUS_SRC_ALPHA) + #[target_feature(enable = "avx2")] + fn egui_blend_u8_slice_avx2(self, src: &[[u8; 4]], dst: &mut [[u8; 4]]) { + assert_eq!(src.len(), dst.len()); + + let n = dst.len(); + if n == 0 { + return; + } + + let mut i = 0; + while i + 3 < n { + // Load 4 src pixels + let src_ptr = unsafe { src.as_ptr().add(i) }.cast::<__m128i>(); + let src8: U8x4x4 = unsafe { read_unaligned(src_ptr) }; + let src16: U16x4x4 = x8_zeroextend16(src8); + + // Load 4 dst pixels + let dst_ptr = unsafe { dst.as_mut_ptr().add(i) }.cast::<__m128i>(); + let dst8: U8x4x4 = unsafe { read_unaligned(dst_ptr) }; + let dst16: U16x4x4 = x8_zeroextend16(dst8); + + let dst8: U8x4x4 = egui_blend_4_u16x4(src8, src16, dst16); + + unsafe { write_unaligned(dst_ptr, dst8) }; + i += 4; + } + + while i < n { + dst[i] = self.egui_blend_u8(src[i], dst[i]); + i += 1; + } + } + + // https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html + /// dst[i] = blend(src[i], dst[i]) // As unorm + /// blend fn is (ONE, ONE_MINUS_SRC_ALPHA) + #[target_feature(enable = "avx2")] + fn egui_blend_u8_slice_one_src_tinted_fn_avx2( + self, + src: [u8; 4], + mut tint_fn: impl FnMut() -> [u8; 4], + dst: &mut [[u8; 4]], + ) { + let n = dst.len(); + if n == 0 { + return; + } + + let src8 = _mm_set1_epi32(i32::from_le_bytes(src)); + let src16 = x8_zeroextend16(src8); + + let mut i = 0usize; + while i + 3 < n { + // Load 4 tint values + let tint_a = i32::from_le_bytes(tint_fn()); + let tint_b = i32::from_le_bytes(tint_fn()); + let tint_c = i32::from_le_bytes(tint_fn()); + let tint_d = i32::from_le_bytes(tint_fn()); + let tint8: U8x4x4 = _mm_set_epi32(tint_d, tint_c, tint_b, tint_a); + let tint16: U16x4x4 = x8_zeroextend16(tint8); + + // Load 4 dst pixels + let dst_ptr = unsafe { dst.as_mut_ptr().add(i) }.cast::<__m128i>(); + let dst8: U8x4x4 = unsafe { read_unaligned(dst_ptr) }; + let dst16 = x8_zeroextend16(dst8); + + // src_tinted = (src16 * vert16 + 128) * 257 >> 16 (rounded /255) + let src_tinted16 = x16_div_255_approx(a16_times_b16_plus_128(src16, tint16)); + let src_tinted8 = x16_pack8(src_tinted16); + + let dst8 = egui_blend_4_u16x4(src_tinted8, src_tinted16, dst16); + + unsafe { write_unaligned(dst_ptr, dst8) }; + i += 4; + } + + // Tail: handle the last pixels (if any) in scalar + while i < n { + dst[i] = self.egui_blend_u8(self.unorm_mult4x4(src, tint_fn()), dst[i]); + i += 1; + } + } + + #[target_feature(enable = "avx2")] + fn egui_blend_u8_slice_tinted_avx2(self, src: &[[u8; 4]], tint: [u8; 4], dst: &mut [[u8; 4]]) { + assert_eq!(src.len(), dst.len()); + let n = dst.len(); + if n == 0 { + return; + } + + let tint8: U8x4x4 = _mm_set1_epi32(i32::from_le_bytes(tint)); + let tint16: U16x4x4 = x8_zeroextend16(tint8); + + let mut i = 0usize; + while i + 3 < n { + // Load 4 src pixels + let src = unsafe { src.as_ptr().add(i) }.cast::<__m128i>(); + let src8 = unsafe { read_unaligned(src) }; + let src16 = x8_zeroextend16(src8); + + // Load 4 dst pixels + let dst = unsafe { dst.as_mut_ptr().add(i) }.cast::<__m128i>(); + let dst8 = unsafe { read_unaligned(dst) }; + let dst16 = x8_zeroextend16(dst8); + + // src_tinted = (src16 * vert16 + 128) * 257 >> 16 (rounded /255) + let src_tinted16 = x16_div_255_approx(a16_times_b16_plus_128(src16, tint16)); + let src_tinted8 = x16_pack8(src_tinted16); + + let dst8 = egui_blend_4_u16x4(src_tinted8, src_tinted16, dst16); + + unsafe { write_unaligned(dst, dst8) }; + i += 4; + } + + // Tail: handle the last pixels (if any) in scalar + while i < n { + dst[i] = self.egui_blend_u8(self.unorm_mult4x4(src[i], tint), dst[i]); + i += 1; + } + } + + #[target_feature(enable = "avx2")] + fn egui_blend_u8_slice_one_src_avx2(self, src: [u8; 4], dst: &mut [[u8; 4]]) { + let n = dst.len(); + if n == 0 { + return; + } + + let a = src[3]; + + let alpha = src[3] as i32; + let alpha_compl = 0xFF ^ alpha; + + // (255 - a) in all u16 lanes + let alpha_compl16 = _mm256_set1_epi16(alpha_compl as i16); + + let mut i = 0; + if a == 0 { + // Only need to saturating_add src to dst. We can do 8 at a time in this case. + let src8 = _mm256_set1_epi32(i32::from_le_bytes(src)); + while i + 7 < n { + let dst_ptr = unsafe { dst.as_mut_ptr().add(i) }.cast::<__m256i>(); + let dst8 = unsafe { read_unaligned(dst_ptr) }; + let dst8 = _mm256_adds_epu8(dst8, src8); + unsafe { write_unaligned(dst_ptr, dst8) }; + i += 8; + } + } else { + let src8 = _mm_set1_epi32(i32::from_le_bytes(src)); + while i + 3 < n { + // Load 4 dst pixels + let dst_ptr = unsafe { dst.as_mut_ptr().add(i) }.cast::<__m128i>(); + let dst8: U8x4x4 = unsafe { read_unaligned(dst_ptr) }; + let dst16 = x8_zeroextend16(dst8); + + // dst * alpha_compl + 0x0080008000800080 + let res16 = a16_times_b16_plus_128(dst16, alpha_compl16); + let res16 = x16_div_255_approx(res16); + let dst8 = x16_pack8(res16); + + // dst.saturating_add(src) + let dst8 = a8_saturatingadd_b8(dst8, src8); + + unsafe { write_unaligned(dst_ptr, dst8) }; + i += 4; + } + } + + while i < n { + dst[i] = self.egui_blend_u8(src, dst[i]); + i += 1; + } + } +} + +impl SelectedImpl for Avx2Impl { + #[inline] + fn dispatch(self, f: impl FnOnce(Self) -> R) -> R { + unsafe { self.dispatch_avx2(f) } + } + + #[inline] + fn egui_blend_u8_slice(self, src: &[[u8; 4]], dst: &mut [[u8; 4]]) { + unsafe { self.egui_blend_u8_slice_avx2(src, dst) } + } + + #[inline] + fn egui_blend_u8_slice_one_src_tinted_fn( + self, + src: [u8; 4], + tint_fn: impl FnMut() -> [u8; 4], + dst: &mut [[u8; 4]], + ) { + unsafe { self.egui_blend_u8_slice_one_src_tinted_fn_avx2(src, tint_fn, dst) } + } + + #[inline] + fn egui_blend_u8_slice_tinted(self, src: &[[u8; 4]], tint: [u8; 4], dst: &mut [[u8; 4]]) { + unsafe { self.egui_blend_u8_slice_tinted_avx2(src, tint, dst) } + } + + #[inline] + fn egui_blend_u8_slice_one_src(self, src: [u8; 4], dst: &mut [[u8; 4]]) { + unsafe { self.egui_blend_u8_slice_one_src_avx2(src, dst) } + } + + #[inline] + fn egui_blend_u8(self, src: [u8; 4], dst: [u8; 4]) -> [u8; 4] { + self.sse41.egui_blend_u8(src, dst) + } + + #[inline] + fn unorm_mult4x4(self, a: [u8; 4], b: [u8; 4]) -> [u8; 4] { + GenericImpl.unorm_mult4x4(a, b) + } +} + +/// src_u8x4x4 should have four 8 bit per channel rgba samples stored in the low bits +/// src_u16x4x4 should have four 16 bit per channel rgba samples +/// dst_u16x4x4 should have four 16 bit per channel rgba samples +#[inline] +#[target_feature(enable = "avx2")] +fn egui_blend_4_u16x4(src8: __m128i, src16: __m256i, dst16: __m256i) -> __m128i { + let ones_u16x4x4 = _mm256_set1_epi16(0x00FF); + + // Broadcast alpha within each pixel's 4 lanes + let a_broadcast_lo = _mm256_shufflelo_epi16(src16, 0b11111111); + let a_broadcast = _mm256_shufflehi_epi16(a_broadcast_lo, 0b11111111); + + // simd_alpha_compl = 255 - A for each lane, per pixel + let simd_alpha_compl = _mm256_xor_si256(ones_u16x4x4, a_broadcast); + + // dst * alpha_compl + 0x0080008000800080 + let res16 = a16_times_b16_plus_128(dst16, simd_alpha_compl); + let res16 = x16_div_255_approx(res16); + let dst8 = x16_pack8(res16); + + a8_saturatingadd_b8(dst8, src8) +} + +/// a.saturating_add(b) +#[inline] +#[target_feature(enable = "avx2")] +fn a8_saturatingadd_b8(a: U8x4x4, b: U8x4x4) -> U8x4x4 { + _mm_adds_epu8(a, b) +} + +/// x as u16 +#[inline] +#[target_feature(enable = "avx2")] +fn x8_zeroextend16(x: U8x4x4) -> U16x4x4 { + _mm256_cvtepu8_epi16(x) +} + +/// a + b + 128 +#[inline] +#[target_feature(enable = "avx2")] +fn a16_times_b16_plus_128(a: U16x4x4, b: U16x4x4) -> U16x4x4 { + let mul = _mm256_mullo_epi16(a, b); + _mm256_add_epi16(mul, _mm256_set1_epi16(128)) +} + +/// Fast approximation of x / 255 +/// ((x >> 8) + x) >> x +#[inline] +#[target_feature(enable = "avx2")] +fn x16_div_255_approx(x: U16x4x4) -> U16x4x4 { + // This mulhi is equivalent to the ((x >> 8) + x) >> 8 operation + // 1 256 1 257 + // ((x >> 8) + x) >> 8 = (x + x---)/256 = (x--- + x---)/256 = (x-----) = x*257 >> 16 + // 256 256 256 65536 + _mm256_mulhi_epu16(x, _mm256_set1_epi16(257)) +} + +// Converts packed 16-bit integers from `x` to packed 8-bit integers using unsigned saturation. +#[inline] +#[target_feature(enable = "avx2")] +fn x16_pack8(x: U16x4x4) -> U8x4x4 { + let hi: U16x4x2 = _mm256_extracti128_si256(x, 1); + let lo: U16x4x2 = _mm256_castsi256_si128(x); + _mm_packus_epi16(lo, hi) +} diff --git a/vendor/egui_software_backend/src/color/mod.rs b/vendor/egui_software_backend/src/color/mod.rs new file mode 100644 index 0000000..a5300e1 --- /dev/null +++ b/vendor/egui_software_backend/src/color/mod.rs @@ -0,0 +1,238 @@ +use crate::math::vec4::{Vec4, vec4}; + +#[cfg(all(target_arch = "x86_64", feature = "std"))] +pub(crate) mod avx2; +#[cfg(all(target_arch = "aarch64", feature = "std"))] +pub(crate) mod neon; +#[cfg(all(target_arch = "x86_64", feature = "std"))] +pub(crate) mod sse41; + +/// An available to run on this processor implementation +/// +/// This enum doesn't implement `SelectedImpl` by choice, thus forcing compiler monomorphisation +/// a the call tree up to the closest [`dispatch_simd_impl!`] +/// +/// This enum values can only be created from [`available_instrs()`], so there is no way to select +/// a non supported by the current processor implementation +#[derive(Clone, Copy)] +pub(crate) enum AvailableImpl { + Generic(GenericImpl), + #[cfg(all(target_arch = "x86_64", feature = "std"))] + Sse41(sse41::Sse41Impl), + #[cfg(all(target_arch = "x86_64", feature = "std"))] + Avx2(avx2::Avx2Impl), + #[cfg(all(target_arch = "aarch64", feature = "std"))] + Neon(neon::NeonImpl), +} + +/// Non empty, order from most performant to least one list of supported by the current processor +/// implementations +pub(crate) fn available_instrs() -> &'static [AvailableImpl] { + const GENERIC: GenericImpl = GenericImpl; + #[cfg(all(target_arch = "x86_64", feature = "std"))] + if std::arch::is_x86_feature_detected!("sse4.1") { + const SSE41: sse41::Sse41Impl = unsafe { sse41::Sse41Impl::new() }; + if std::arch::is_x86_feature_detected!("avx2") { + const AVX2: avx2::Avx2Impl = unsafe { avx2::Avx2Impl::new() }; + return &[ + AvailableImpl::Avx2(AVX2), + AvailableImpl::Sse41(SSE41), + AvailableImpl::Generic(GENERIC), + ]; + } else { + return &[AvailableImpl::Sse41(SSE41), AvailableImpl::Generic(GENERIC)]; + } + } + + #[cfg(all(target_arch = "aarch64", feature = "std"))] + if std::arch::is_aarch64_feature_detected!("neon") { + const NEON: neon::NeonImpl = unsafe { neon::NeonImpl::new() }; + return &[AvailableImpl::Neon(NEON), AvailableImpl::Generic(GENERIC)]; + } + + &[AvailableImpl::Generic(GENERIC)] +} + +impl Default for AvailableImpl { + /// Returns the most performant available implementation + fn default() -> Self { + *available_instrs().first().expect("at least one impl") + } +} + +impl core::fmt::Display for AvailableImpl { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Generic(_) => f.write_str("Generic"), + #[cfg(all(target_arch = "x86_64", feature = "std"))] + Self::Sse41(_) => f.write_str("Sse41"), + #[cfg(all(target_arch = "x86_64", feature = "std"))] + Self::Avx2(_) => f.write_str("Avx2"), + #[cfg(all(target_arch = "aarch64", feature = "std"))] + Self::Neon(_) => f.write_str("Neon"), + } + } +} + +impl core::fmt::Debug for AvailableImpl { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + core::fmt::Display::fmt(&self, f) + } +} + +#[doc(hidden)] +#[macro_export] +macro_rules! dispatch_simd_impl { + (|$simd_impl:ident| $body:expr) => { + $crate::dispatch_simd_impl!($crate::color::AvailableImpl::default(), |$simd_impl| $body) + }; + ($available_impl:expr, |$simd_impl:ident| $body:expr) => { + match $available_impl { + $crate::color::AvailableImpl::Generic(i) => { + i.dispatch(|$simd_impl: $crate::color::GenericImpl| $body) + } + #[cfg(all(target_arch = "x86_64", feature = "std"))] + $crate::color::AvailableImpl::Sse41(i) => { + i.dispatch(|$simd_impl: $crate::color::sse41::Sse41Impl| $body) + } + #[cfg(all(target_arch = "x86_64", feature = "std"))] + $crate::color::AvailableImpl::Avx2(i) => { + i.dispatch(|$simd_impl: $crate::color::avx2::Avx2Impl| $body) + } + #[cfg(all(target_arch = "aarch64", feature = "std"))] + $crate::color::AvailableImpl::Neon(i) => { + i.dispatch(|$simd_impl: $crate::color::neon::NeonImpl| $body) + } + } + }; +} + +/// This trait holds performance sensitive methods that often can be writing in more architecture +/// dependent specialized versions +/// +/// All methods of this trait contains a generic implementation +pub(crate) trait SelectedImpl: Copy + Sync + Send + 'static { + /// Trick the compiler into compiling `f` with the same target_feature as this impl. + #[inline] + fn dispatch(self, f: impl FnOnce(Self) -> R) -> R { + f(self) + } + + fn egui_blend_u8_slice(self, src: &[[u8; 4]], dst: &mut [[u8; 4]]) { + for (pixel, src) in dst.iter_mut().zip(src) { + *pixel = self.egui_blend_u8(*src, *pixel); + } + } + /// dst[i] = blend(src * tint_fn(), dst[i]) // As unorm + /// blend fn is (ONE, ONE_MINUS_SRC_ALPHA) + fn egui_blend_u8_slice_one_src_tinted_fn( + self, + src: [u8; 4], + mut tint_fn: impl FnMut() -> [u8; 4], + dst: &mut [[u8; 4]], + ) { + for pixel in dst.iter_mut() { + *pixel = self.egui_blend_u8(self.unorm_mult4x4(tint_fn(), src), *pixel); + } + } + + /// dst[i] = blend(src[i] * tint, dst[i]) // As unorm + /// blend fn is (ONE, ONE_MINUS_SRC_ALPHA) + fn egui_blend_u8_slice_tinted(self, src: &[[u8; 4]], tint: [u8; 4], dst: &mut [[u8; 4]]) { + for (pixel, tex_color) in dst.iter_mut().zip(src) { + *pixel = self.egui_blend_u8(self.unorm_mult4x4(tint, *tex_color), *pixel); + } + } + + /// dst[i] = blend(src, dst[i]) + /// blend fn is (ONE, ONE_MINUS_SRC_ALPHA) + fn egui_blend_u8_slice_one_src(self, src: [u8; 4], dst: &mut [[u8; 4]]) { + for pixel in dst { + *pixel = self.egui_blend_u8(src, *pixel); + } + } + + // https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html + /// blend fn is (ONE, ONE_MINUS_SRC_ALPHA) + #[inline(always)] + fn egui_blend_u8(self, src: [u8; 4], mut dst: [u8; 4]) -> [u8; 4] { + let a = src[3]; + if a == 255 { + return src; + } + if a != 0 { + let alpha = a as u64; + let alpha_compl = 0xFF ^ alpha; + let dst64 = as_color16(u32::from_le_bytes(dst)); + + let res16 = dst64 * alpha_compl + 0x0080008000800080; + let res8 = res16 + ((res16 >> 8) & 0x00FF00FF00FF00FF); + + // transform the result back to 32 bytes + let res = (res8 >> 8) & 0x00FF00FF00FF00FF; + let res = (res | (res >> 8)) & 0x0000FFFF0000FFFF; + let res = res | (res >> 16); + dst = u32::to_le_bytes((res & 0x00000000FFFFFFFF) as u32); + } + + [ + dst[0].saturating_add(src[0]), + dst[1].saturating_add(src[1]), + dst[2].saturating_add(src[2]), + dst[3].saturating_add(src[3]), + ] + } + + #[inline(always)] + fn unorm_mult4x4(self, a: [u8; 4], b: [u8; 4]) -> [u8; 4] { + [ + unorm_mult(a[0] as u32, b[0] as u32) as u8, + unorm_mult(a[1] as u32, b[1] as u32) as u8, + unorm_mult(a[2] as u32, b[2] as u32) as u8, + unorm_mult(a[3] as u32, b[3] as u32) as u8, + ] + } +} +#[derive(Clone, Copy)] +pub(crate) struct GenericImpl; + +impl SelectedImpl for GenericImpl {} + +#[inline(always)] +pub fn vec4_to_u8x4(v: &Vec4) -> [u8; 4] { + let v = v.clamp(Vec4::ZERO, Vec4::ONE) * 255.0 + 0.5; + [v.x as u8, v.y as u8, v.z as u8, v.w as u8] +} + +#[inline(always)] +pub fn u8x4_to_vec4(v: &[u8; 4]) -> Vec4 { + vec4( + v[0] as f32 / 255.0, + v[1] as f32 / 255.0, + v[2] as f32 / 255.0, + v[3] as f32 / 255.0, + ) +} + +/// transforms 4 bytes RGBA into 8 bytes 0R0G0B0A +#[inline(always)] +pub fn as_color16(color: u32) -> u64 { + let x = color as u64; + let x = ((x & 0xFFFF0000) << 16) | (x & 0xFFFF); + ((x & 0x0000FF000000FF00) << 8) | (x & 0x000000FF000000FF) +} + +#[inline(always)] +// Jerry R. Van Aken - Alpha Blending with No Division Operations https://arxiv.org/pdf/2202.02864 +// Input should be 0..255, is multiplied as if it were 0..1f +pub fn unorm_mult(mut a: u32, b: u32) -> u32 { + a *= b; + a += 0x80; + a += a >> 8; + a >> 8 +} + +#[inline(always)] +pub fn swizzle_rgba_bgra(a: [u8; 4]) -> [u8; 4] { + [a[2], a[1], a[0], a[3]] +} diff --git a/vendor/egui_software_backend/src/color/neon.rs b/vendor/egui_software_backend/src/color/neon.rs new file mode 100644 index 0000000..bfd8ec5 --- /dev/null +++ b/vendor/egui_software_backend/src/color/neon.rs @@ -0,0 +1,349 @@ +#![allow(unsafe_code)] + +use core::arch::aarch64::*; + +use crate::color::SelectedImpl; + +#[derive(Clone, Copy)] +pub(crate) struct NeonImpl(()); + +impl NeonImpl { + /// `std::arch::is_aarch64_feature_detected!("neon")` MUST be true + pub(crate) const unsafe fn new() -> Self { + Self(()) + } + + #[inline] + #[target_feature(enable = "neon")] + fn dispatch_neon(self, f: impl FnOnce(Self) -> R) -> R { + f(self) + } +} + +impl SelectedImpl for NeonImpl { + #[inline] + fn dispatch(self, f: impl FnOnce(Self) -> R) -> R { + unsafe { self.dispatch_neon(f) } + } + + #[inline] + fn egui_blend_u8_slice(self, src: &[[u8; 4]], dst: &mut [[u8; 4]]) { + unsafe { egui_blend_u8_slice(src, dst) } + } + + #[inline] + fn egui_blend_u8_slice_one_src_tinted_fn( + self, + src: [u8; 4], + tint_fn: impl FnMut() -> [u8; 4], + dst: &mut [[u8; 4]], + ) { + unsafe { egui_blend_u8_slice_one_src_tinted_fn(src, tint_fn, dst) } + } + + #[inline] + fn egui_blend_u8_slice_tinted(self, src: &[[u8; 4]], tint: [u8; 4], dst: &mut [[u8; 4]]) { + unsafe { egui_blend_u8_slice_tinted(src, tint, dst) } + } + + #[inline] + fn egui_blend_u8_slice_one_src(self, src: [u8; 4], dst: &mut [[u8; 4]]) { + unsafe { egui_blend_u8_slice_one_src(src, dst) } + } + + #[inline] + fn egui_blend_u8(self, src: [u8; 4], dst: [u8; 4]) -> [u8; 4] { + unsafe { egui_blend_u8(src, dst) } + } + + #[inline] + fn unorm_mult4x4(self, a: [u8; 4], b: [u8; 4]) -> [u8; 4] { + unsafe { unorm_mult4x4(a, b) } + } +} + +/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA) +#[inline] +#[target_feature(enable = "neon")] +fn egui_blend_u8(src: [u8; 4], dst: [u8; 4]) -> [u8; 4] { + let a = src[3]; + + let alpha_compl = vdupq_n_u16((0xFFu16) ^ (a as u16)); + let e1 = vdupq_n_u16(0x0080); + + let dst8 = vreinterpret_u8_u32(vdup_n_u32(u32::from_le_bytes(dst))); + let mut dst = vmovl_u8(dst8); + + // dst * alpha_compl + 0x0080 + dst = vaddq_u16(vmulq_u16(dst, alpha_compl), e1); + + // ((x >> 8) + x) >> 8 + dst = vaddq_u16(dst, vshrq_n_u16(dst, 8)); + dst = vshrq_n_u16(dst, 8); + + // Pack to back to u8 + let dst = vqmovn_u16(dst); + + let src32x2 = vdup_n_u32(u32::from_le_bytes(src)); + let src8 = vreinterpret_u8_u32(src32x2); + + // saturating add + let out8 = vqadd_u8(dst, src8); + + let out32 = vget_lane_u32(vreinterpret_u32_u8(out8), 0); + out32.to_le_bytes() +} + +// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html +/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA) +#[target_feature(enable = "neon")] +pub fn egui_blend_u8_slice_one_src(src: [u8; 4], dst: &mut [[u8; 4]]) { + let n = dst.len(); + if n == 0 { + return; + } + + let a = src[3]; + + let src32 = u32::from_le_bytes(src); + + let alpha = src[3] as i32; + let alpha_compl = 0xFF ^ alpha; + + let e1 = vdupq_n_u16(0x0080); + + // (255 - a) in all u16 lanes + let simd_alpha_compl = vdupq_n_u16(alpha_compl as u16); + + let mut i = 0; + if a == 0 { + let src8_q = vreinterpretq_u8_u32(vdupq_n_u32(src32)); + // Only need to saturating_add src to dst. We can do 4 at a time in this case. + while i + 3 < n { + let p = unsafe { dst.as_mut_ptr().add(i) } as *mut u8; + let d128 = unsafe { vld1q_u8(p) }; + let out = vqaddq_u8(d128, src8_q); + unsafe { vst1q_u8(p, out) }; + i += 4; + } + } else { + let src8 = vreinterpret_u8_u32(vdup_n_u32(src32)); + while i + 1 < n { + let dst_p = unsafe { dst.as_mut_ptr().add(i) } as *mut u8; + // Load two dst pixels + let d8 = unsafe { vld1_u8(dst_p) }; + // [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a] + let dst16 = vmovl_u8(d8); + + // dst * alpha_compl + 0x0080008000800080 + let res16 = vaddq_u16(vmulq_u16(dst16, simd_alpha_compl), e1); + + // ((x >> 8) + x) >> 8 + let res16 = vshrq_n_u16(vaddq_u16(res16, vshrq_n_u16(res16, 8)), 8); + let mut dst8 = vqmovn_u16(res16); + + // dst.saturating_add(src) + dst8 = vqadd_u8(dst8, src8); + + unsafe { vst1_u8(dst_p, dst8) }; + i += 2; + } + } + + while i < n { + dst[i] = egui_blend_u8(src, dst[i]); + i += 1; + } +} + +// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html +/// dst[i] = blend(src[i], dst[i]) // As unorm +/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA) +#[target_feature(enable = "neon")] +fn egui_blend_u8_slice(src: &[[u8; 4]], dst: &mut [[u8; 4]]) { + assert_eq!(src.len(), dst.len()); + + let n = dst.len(); + if n == 0 { + return; + } + + let mut i = 0; + while i + 1 < n { + let src_p = unsafe { src.as_ptr().add(i) } as *mut u8; + // Load two src pixels + let src8 = unsafe { vld1_u8(src_p) }; + // [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a] + let src16 = vmovl_u8(src8); + + // Load two dst pixels + let dst_p = unsafe { dst.as_mut_ptr().add(i) } as *mut u8; + // Load two dst pixels + let d8 = unsafe { vld1_u8(dst_p) }; + // [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a] + let dst16 = vmovl_u8(d8); + + let dst8 = egui_blend_two_u16x4(src8, src16, dst16); + + unsafe { vst1_u8(dst_p, dst8) }; + i += 2; + } + + if i < n { + dst[i] = egui_blend_u8(src[i], dst[i]); + } +} + +// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html +/// dst[i] = blend(src[i] * vert, dst[i]) // As unorm +/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA) +#[target_feature(enable = "neon")] +fn egui_blend_u8_slice_tinted(src: &[[u8; 4]], tint: [u8; 4], dst: &mut [[u8; 4]]) { + assert_eq!(src.len(), dst.len()); + let n = dst.len(); + if n == 0 { + return; + } + + let e1 = vdupq_n_u16(0x0080); + + let tint32 = u32::from_le_bytes(tint); + let tint8 = vreinterpret_u8_u32(vdup_n_u32(tint32)); + let tint16 = vmovl_u8(tint8); + + let mut i = 0usize; + while i + 1 < n { + let src_p = unsafe { src.as_ptr().add(i) } as *mut u8; + // Load two src pixels + let src8 = unsafe { vld1_u8(src_p) }; + // [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a] + let src16 = vmovl_u8(src8); + + // Load two dst pixels + let dst_p = unsafe { dst.as_mut_ptr().add(i) } as *mut u8; + let d8 = unsafe { vld1_u8(dst_p) }; + // [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a] + let dst16 = vmovl_u8(d8); + + // src_tinted = (src16 * vert16 + 128) * 257 >> 16 (rounded /255) + let mut t = vaddq_u16(vmulq_u16(src16, tint16), e1); + t = vaddq_u16(t, vshrq_n_u16(t, 8)); + let src_tinted16 = vshrq_n_u16(t, 8); + let src_tinted8 = vqmovn_u16(src_tinted16); + + let dst8 = egui_blend_two_u16x4(src_tinted8, src_tinted16, dst16); + + unsafe { vst1_u8(dst_p, dst8) }; + i += 2; + } + + // Tail: handle the last pixel (if any) in scalar + if i < n { + dst[i] = egui_blend_u8(unorm_mult4x4(src[i], tint), dst[i]); + } +} + +// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html +/// dst[i] = blend(src * tint_fn(), dst[i]) // As unorm +/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA) +#[target_feature(enable = "neon")] +fn egui_blend_u8_slice_one_src_tinted_fn( + src: [u8; 4], + mut tint_fn: impl FnMut() -> [u8; 4], + dst: &mut [[u8; 4]], +) { + let n = dst.len(); + if n == 0 { + return; + } + + let src32 = u32::from_le_bytes(src); + let src8 = vreinterpret_u8_u32(vdup_n_u32(src32)); + let src16 = vmovl_u8(src8); + + let e1 = vdupq_n_u16(0x0080); + + let mut i = 0usize; + while i + 1 < n { + // Load two tint values + + let mut t32x2 = vdup_n_u32(0); + t32x2 = vset_lane_u32(u32::from_le_bytes(tint_fn()), t32x2, 0); + t32x2 = vset_lane_u32(u32::from_le_bytes(tint_fn()), t32x2, 1); + let tint8 = vreinterpret_u8_u32(t32x2); + let tint16 = vmovl_u8(tint8); + + // Load two dst pixels + let dst_p = unsafe { dst.as_mut_ptr().add(i) } as *mut u8; + let d8 = unsafe { vld1_u8(dst_p) }; + // [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a] + let dst16 = vmovl_u8(d8); + + // src_tinted = (src16 * vert16 + 128) * 257 >> 16 (rounded /255) + let mut t = vaddq_u16(vmulq_u16(src16, tint16), e1); + t = vaddq_u16(t, vshrq_n_u16(t, 8)); + let src_tinted16 = vshrq_n_u16(t, 8); + let src_tinted8 = vqmovn_u16(src_tinted16); + + let dst8 = egui_blend_two_u16x4(src_tinted8, src_tinted16, dst16); + + unsafe { vst1_u8(dst_p, dst8) }; + i += 2; + } + + // Tail: handle the last pixel (if any) in scalar + if i < n { + dst[i] = egui_blend_u8(unorm_mult4x4(src, tint_fn()), dst[i]); + } +} + +#[inline] +#[target_feature(enable = "neon")] +fn unorm_mult4x4(a: [u8; 4], b: [u8; 4]) -> [u8; 4] { + let e1 = vdupq_n_u16(0x0080); + let a = vmovl_u8(vreinterpret_u8_u32(vdup_n_u32(u32::from_le_bytes(a)))); + let b = vmovl_u8(vreinterpret_u8_u32(vdup_n_u32(u32::from_le_bytes(b)))); + + // a * b + 0x0080 + let mut dst = vaddq_u16(vmulq_u16(a, b), e1); + + // ((a >> 8) + a) >> 8 + dst = vaddq_u16(dst, vshrq_n_u16(dst, 8)); + dst = vshrq_n_u16(dst, 8); + + // Pack to back to u8 + let dst = vqmovn_u16(dst); + + vget_lane_u32(vreinterpret_u32_u8(dst), 0).to_le_bytes() // Return first element of dst +} + +#[inline] +/// src8 should have two 8 bit per channel rgba samples stored in the low bits +/// src16 should have two 16 bit per channel rgba samples +/// dst16 should have two 16 bit per channel rgba samples +#[target_feature(enable = "neon")] +fn egui_blend_two_u16x4(src8: uint8x8_t, src16: uint16x8_t, dst16: uint16x8_t) -> uint8x8_t { + let ones = vdupq_n_u16(0x00FF); + let e1 = vdupq_n_u16(0x0080); + + // Broadcast alpha within each pixel's 4 lanes + let a_lo4 = vdup_n_u16(vgetq_lane_u16(src16, 3)); + let a_hi4 = vdup_n_u16(vgetq_lane_u16(src16, 7)); + let a_broadcast = vcombine_u16(a_lo4, a_hi4); + + // simd_alpha_compl = 255 - A for each lane, per pixel + let simd_alpha_compl = vsubq_u16(ones, a_broadcast); + + // dst * alpha_compl + 0x0080008000800080 + let dst_term = vmulq_u16(dst16, simd_alpha_compl); + let res16 = vaddq_u16(dst_term, e1); + + // ((x >> 8) + x) >> 8 + let res16 = vaddq_u16(res16, vshrq_n_u16(res16, 8)); + let res16 = vshrq_n_u16(res16, 8); + let dst8 = vqmovn_u16(res16); + // Pack back to u8 + + // dst.saturating_add(src) + vqadd_u8(dst8, src8) +} diff --git a/vendor/egui_software_backend/src/color/sse41.rs b/vendor/egui_software_backend/src/color/sse41.rs new file mode 100644 index 0000000..6ff4785 --- /dev/null +++ b/vendor/egui_software_backend/src/color/sse41.rs @@ -0,0 +1,346 @@ +#![allow(unsafe_code)] + +use core::{arch::x86_64::*, ptr::read_unaligned}; + +use crate::color::SelectedImpl; + +#[derive(Clone, Copy)] +pub struct Sse41Impl(()); + +impl Sse41Impl { + /// `std::arch::is_x86_feature_detected!("sse4.1")` MUST be true + pub const unsafe fn new() -> Self { + Self(()) + } + + #[inline] + #[target_feature(enable = "sse4.1")] + fn dispatch_sse41(self, f: impl FnOnce(Self) -> R) -> R { + f(self) + } +} + +impl SelectedImpl for Sse41Impl { + #[inline] + fn dispatch(self, f: impl FnOnce(Self) -> R) -> R { + unsafe { self.dispatch_sse41(f) } + } + + #[inline] + fn egui_blend_u8_slice(self, src: &[[u8; 4]], dst: &mut [[u8; 4]]) { + unsafe { egui_blend_u8_slice(src, dst) } + } + + #[inline] + fn egui_blend_u8_slice_one_src_tinted_fn( + self, + src: [u8; 4], + tint_fn: impl FnMut() -> [u8; 4], + dst: &mut [[u8; 4]], + ) { + unsafe { egui_blend_u8_slice_one_src_tinted_fn(src, tint_fn, dst) } + } + + #[inline] + fn egui_blend_u8_slice_tinted(self, src: &[[u8; 4]], tint: [u8; 4], dst: &mut [[u8; 4]]) { + unsafe { egui_blend_u8_slice_tinted(src, tint, dst) } + } + + #[inline] + fn egui_blend_u8_slice_one_src(self, src: [u8; 4], dst: &mut [[u8; 4]]) { + unsafe { egui_blend_u8_slice_one_src(src, dst) } + } + + #[inline] + fn egui_blend_u8(self, src: [u8; 4], dst: [u8; 4]) -> [u8; 4] { + unsafe { egui_blend_u8(src, dst) } + } + + #[inline] + fn unorm_mult4x4(self, a: [u8; 4], b: [u8; 4]) -> [u8; 4] { + unsafe { unorm_mult4x4(a, b) } + } +} + +/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA) +#[inline] +#[target_feature(enable = "sse4.1")] +fn egui_blend_u8(src: [u8; 4], dst: [u8; 4]) -> [u8; 4] { + let alpha = src[3]; + + let alpha_compl = _mm_set1_epi16(0xFFi16 ^ (alpha as i16)); + let e1 = _mm_set1_epi16(0x0080); + let mut dst = _mm_cvtsi32_si128(i32::from_le_bytes(dst)); // Load dst into element a + dst = _mm_cvtepu8_epi16(dst); // [0,0,0,0,0,0,0,rgba] -> [0,0,0,0,r,g,b,a] + + // dst * alpha_compl + 0x0080 + dst = _mm_add_epi16(_mm_mullo_epi16(dst, alpha_compl), e1); + + // ((x >> 8) + x) >> 8 + dst = _mm_add_epi16(dst, _mm_srli_epi16(dst, 8)); + dst = _mm_srli_epi16(dst, 8); + + // Pack to back to u8 + let dst = _mm_packus_epi16(dst, _mm_setzero_si128()); + + let src = _mm_cvtsi32_si128(i32::from_le_bytes(src)); // Load src into element a + let dst = _mm_adds_epu8(dst, src); // dst.saturating_add(src) + + i32::to_le_bytes(_mm_cvtsi128_si32(dst)) // Return first element of dst +} + +// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html +/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA) +#[target_feature(enable = "sse4.1")] +fn egui_blend_u8_slice_one_src(src: [u8; 4], dst: &mut [[u8; 4]]) { + let n = dst.len(); + if n == 0 { + return; + } + + let a = src[3]; + + let src32 = u32::from_le_bytes(src); + let src64 = (src32 as u64) | ((src32 as u64) << 32); + let src8 = _mm_set1_epi64x(src64 as i64); + + let alpha = src[3] as i32; + let alpha_compl = 0xFF ^ alpha; + + let e1 = _mm_set1_epi16(0x0080); + let e2 = _mm_set1_epi16(0x0101); + + // (255 - a) in all u16 lanes + let simd_alpha_compl = _mm_set1_epi16(alpha_compl as i16); + + let mut i = 0; + if a == 0 { + // Only need to saturating_add src to dst. We can do 4 at a time in this case. + while i + 3 < n { + let p = unsafe { dst.as_mut_ptr().add(i) } as *mut __m128i; + let d128 = unsafe { _mm_loadu_si128(p) }; + let out = _mm_adds_epu8(d128, src8); + unsafe { _mm_storeu_si128(p, out) }; + i += 4; + } + } else { + while i + 1 < n { + let dst = unsafe { dst.as_mut_ptr().add(i) }.cast::(); + // Load two dst pixels + let d8 = _mm_cvtsi64_si128(unsafe { read_unaligned(dst) } as i64); + // [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a] + let dst16 = _mm_cvtepu8_epi16(d8); + + // dst * alpha_compl + 0x0080008000800080 + let res16 = _mm_add_epi16(_mm_mullo_epi16(dst16, simd_alpha_compl), e1); + + // This mulhi is equivalent to the ((x >> 8) + x) >> 8 operation. (can you see why?) + let res16 = _mm_mulhi_epu16(res16, e2); + let mut dst8 = _mm_packus_epi16(res16, res16); // Pack back to u8 + + // dst.saturating_add(src) + dst8 = _mm_adds_epu8(dst8, src8); + + let lo64 = _mm_cvtsi128_si64(dst8) as u64; + unsafe { core::ptr::write_unaligned(dst, lo64) }; + i += 2; + } + } + + while i < n { + dst[i] = egui_blend_u8(src, dst[i]); + i += 1; + } +} + +// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html +/// dst[i] = blend(src[i], dst[i]) // As unorm +/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA) +#[target_feature(enable = "sse4.1")] +fn egui_blend_u8_slice(src: &[[u8; 4]], dst: &mut [[u8; 4]]) { + assert_eq!(src.len(), dst.len()); + + let n = dst.len(); + if n == 0 { + return; + } + + let mut i = 0; + while i + 1 < n { + // Load two src pixels + let src = unsafe { src.as_ptr().add(i) }.cast::(); + let src8 = _mm_cvtsi64_si128(unsafe { read_unaligned(src) } as i64); + // [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a] + let src16 = _mm_cvtepu8_epi16(src8); + + // Load two dst pixels + let dst = unsafe { dst.as_mut_ptr().add(i) }.cast::(); + let d8 = _mm_cvtsi64_si128(unsafe { read_unaligned(dst) } as i64); + let dst16 = _mm_cvtepu8_epi16(d8); + + let dst8 = egui_blend_two_u16x4(src8, src16, dst16); + + let lo64 = _mm_cvtsi128_si64(dst8) as u64; + unsafe { core::ptr::write_unaligned(dst, lo64) }; + i += 2; + } + + if i < n { + dst[i] = egui_blend_u8(src[i], dst[i]); + } +} + +// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html +/// dst[i] = blend(src[i] * vert, dst[i]) // As unorm +/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA) +#[target_feature(enable = "sse4.1")] +fn egui_blend_u8_slice_tinted(src: &[[u8; 4]], tint: [u8; 4], dst: &mut [[u8; 4]]) { + assert_eq!(src.len(), dst.len()); + let n = dst.len(); + if n == 0 { + return; + } + + let e1 = _mm_set1_epi16(0x0080); + let e2 = _mm_set1_epi16(0x0101); + + let t32 = _mm_set1_epi32(i32::from_le_bytes(tint)); + let tint16 = _mm_cvtepu8_epi16(t32); + + let mut i = 0usize; + while i + 1 < n { + // Load two src pixels + let src = unsafe { src.as_ptr().add(i) }.cast::(); + let src8 = _mm_cvtsi64_si128(unsafe { read_unaligned(src) } as i64); + // [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a] + let src16 = _mm_cvtepu8_epi16(src8); + + // Load two dst pixels + let dst = unsafe { dst.as_mut_ptr().add(i) }.cast::(); + let dst8 = _mm_cvtsi64_si128(unsafe { read_unaligned(dst) } as i64); + let dst16 = _mm_cvtepu8_epi16(dst8); + + // src_tinted = (src16 * vert16 + 128) * 257 >> 16 (rounded /255) + let tint_mul = _mm_mullo_epi16(src16, tint16); + let tint_rounded = _mm_add_epi16(tint_mul, e1); + let src_tinted16 = _mm_mulhi_epu16(tint_rounded, e2); + let src_tinted8 = _mm_packus_epi16(src_tinted16, src_tinted16); + + let dst8 = egui_blend_two_u16x4(src_tinted8, src_tinted16, dst16); + + let lo64 = _mm_cvtsi128_si64(dst8) as u64; + unsafe { core::ptr::write_unaligned(dst, lo64) }; + i += 2; + } + + // Tail: handle the last pixel (if any) in scalar + if i < n { + dst[i] = egui_blend_u8(unorm_mult4x4(src[i], tint), dst[i]); + } +} + +// https://www.lgfae.com/posts/2025-09-01-AlphaBlendWithSIMD.html +/// dst[i] = blend(src * tint_fn(), dst[i]) // As unorm +/// blend fn is (ONE, ONE_MINUS_SRC_ALPHA) +#[target_feature(enable = "sse4.1")] +fn egui_blend_u8_slice_one_src_tinted_fn( + src: [u8; 4], + mut tint_fn: impl FnMut() -> [u8; 4], + dst: &mut [[u8; 4]], +) { + let n = dst.len(); + if n == 0 { + return; + } + + let src32 = u32::from_le_bytes(src); + let src64 = (src32 as u64) | ((src32 as u64) << 32); + + let e1 = _mm_set1_epi16(0x0080); + let e2 = _mm_set1_epi16(0x0101); + + let mut i = 0usize; + while i + 1 < n { + // Load two tint values + let tint_a = u32::from_le_bytes(tint_fn()) as i64; + let tint_b = u32::from_le_bytes(tint_fn()) as i64; + let tint_simd = _mm_cvtsi64_si128((tint_b << 32) | tint_a); + let tint16 = _mm_cvtepu8_epi16(tint_simd); + + let src8 = _mm_cvtsi64_si128(src64 as i64); + // [0,0,0,0,rg,ba,rg,ba] -> [r,g,b,a,r,g,b,a] + let src16 = _mm_cvtepu8_epi16(src8); + + // Load two dst pixels + let dst = unsafe { dst.as_mut_ptr().add(i) }.cast::(); + let dst8 = _mm_cvtsi64_si128(unsafe { read_unaligned(dst) } as i64); + let dst16 = _mm_cvtepu8_epi16(dst8); + + // src_tinted = (src16 * vert16 + 128) * 257 >> 16 (rounded /255) + let tint_mul = _mm_mullo_epi16(src16, tint16); + let tint_rounded = _mm_add_epi16(tint_mul, e1); + let src_tinted16 = _mm_mulhi_epu16(tint_rounded, e2); + let src_tinted8 = _mm_packus_epi16(src_tinted16, src_tinted16); + + let dst8 = egui_blend_two_u16x4(src_tinted8, src_tinted16, dst16); + + let lo64 = _mm_cvtsi128_si64(dst8) as u64; + unsafe { core::ptr::write_unaligned(dst, lo64) }; + i += 2; + } + + // Tail: handle the last pixel (if any) in scalar + if i < n { + dst[i] = egui_blend_u8(unorm_mult4x4(src, tint_fn()), dst[i]); + } +} + +#[inline] +#[target_feature(enable = "sse4.1")] +fn unorm_mult4x4(a: [u8; 4], b: [u8; 4]) -> [u8; 4] { + let e1 = _mm_set1_epi16(0x0080); + let a = _mm_cvtepu8_epi16(_mm_cvtsi32_si128(i32::from_le_bytes(a))); + let b = _mm_cvtepu8_epi16(_mm_cvtsi32_si128(i32::from_le_bytes(b))); + + // a * b + 0x0080 + let mut dst = _mm_add_epi16(_mm_mullo_epi16(a, b), e1); + + // ((a >> 8) + a) >> 8 + dst = _mm_add_epi16(dst, _mm_srli_epi16(dst, 8)); + dst = _mm_srli_epi16(dst, 8); + + // Pack to back to u8 + let dst = _mm_packus_epi16(dst, _mm_setzero_si128()); + + i32::to_le_bytes(_mm_cvtsi128_si32(dst)) // Return first element of dst +} + +#[inline] +/// src8 should have two 8 bit per channel rgba samples stored in the low bits +/// src16 should have two 16 bit per channel rgba samples +/// dst16 should have two 16 bit per channel rgba samples +#[target_feature(enable = "sse4.1")] +fn egui_blend_two_u16x4(src8: __m128i, src16: __m128i, dst16: __m128i) -> __m128i { + let ones = _mm_set1_epi16(0x00FF); + let e1 = _mm_set1_epi16(0x0080); + let e2 = _mm_set1_epi16(0x0101); + + // Broadcast alpha within each pixel's 4 lanes + let a_broadcast_lo = _mm_shufflelo_epi16(src16, 0b11111111); + let a_broadcast = _mm_shufflehi_epi16(a_broadcast_lo, 0b11111111); + + // simd_alpha_compl = 255 - A for each lane, per pixel + let simd_alpha_compl = _mm_sub_epi16(ones, a_broadcast); + + // dst * alpha_compl + 0x0080008000800080 + let dst_term = _mm_mullo_epi16(dst16, simd_alpha_compl); + let res16 = _mm_add_epi16(dst_term, e1); + + // This mulhi is equivalent to the ((x >> 8) + x) >> 8 operation. (can you see why?) + let res16 = _mm_mulhi_epu16(res16, e2); + let dst8 = _mm_packus_epi16(res16, res16); + // Pack back to u8 + + // dst.saturating_add(src) + _mm_adds_epu8(dst8, src8) +} diff --git a/vendor/egui_software_backend/src/egui_texture.rs b/vendor/egui_software_backend/src/egui_texture.rs new file mode 100644 index 0000000..f36867c --- /dev/null +++ b/vendor/egui_software_backend/src/egui_texture.rs @@ -0,0 +1,121 @@ +use alloc::vec::Vec; +use egui::{Color32, TextureFilter, TextureOptions, Vec2, vec2}; + +use crate::{ + ColorFieldOrder, + color::{swizzle_rgba_bgra, u8x4_to_vec4, vec4_to_u8x4}, +}; + +pub struct EguiTexture { + pub opaque: bool, + pub data: Vec<[u8; 4]>, + // Common case: The default egui texture has the top-left corner pixel fully white. + // https://github.com/emilk/egui/blob/c97c065a575ec6e657bb42872890a00d0fb391c1/crates/epaint/src/lib.rs#L92 + pub uv_zero_val: [u8; 4], + /// width - 1 + pub width_extent: i32, + /// height - 1 + pub height_extent: i32, + pub width: usize, + #[allow(dead_code)] + pub height: usize, + pub fsize: Vec2, + pub options: TextureOptions, +} + +impl EguiTexture { + pub fn new( + field_order: ColorFieldOrder, + options: TextureOptions, + size: [usize; 2], + pixels: &[Color32], + ) -> EguiTexture { + let data = pixels + .iter() + .map(|p| match field_order { + ColorFieldOrder::Rgba => p.to_array(), + ColorFieldOrder::Bgra => swizzle_rgba_bgra(p.to_array()), + }) + .collect::>(); + let uv_zero_val = data[0]; + EguiTexture { + opaque: data.iter().all(|p| p[3] == 255), + data, + width_extent: size[0] as i32 - 1, + height_extent: size[1] as i32 - 1, + width: size[0], + height: size[1], + fsize: vec2(size[0] as f32, size[1] as f32), + options, + uv_zero_val, + } + } + + #[allow(dead_code)] + pub fn sample_nearest(&self, uv: Vec2) -> [u8; 4] { + let ss_x = ((uv.x * self.fsize.x) as i32).max(0).min(self.width_extent); + let ss_y = ((uv.y * self.fsize.y) as i32) + .max(0) + .min(self.height_extent); + self.data[ss_x as usize + ss_y as usize * self.width] + } + + pub fn sample_bilinear(&self, uv: Vec2) -> [u8; 4] { + if uv == Vec2::ZERO { + return self.uv_zero_val; + } + + let w = self.fsize.x; + let h = self.fsize.y; + + #[inline(always)] + fn mirror(v: f32) -> f32 { + ((v * 0.5 + 0.5).fract() - 0.5) * 2.0 + } + + let uv = match self.options.wrap_mode { + egui::TextureWrapMode::ClampToEdge => uv, + egui::TextureWrapMode::Repeat => vec2(uv.x.fract(), uv.y.fract()), + egui::TextureWrapMode::MirroredRepeat => vec2(mirror(uv.x), mirror(uv.y)), + }; + + let sx = uv.x * w - 0.5; + let sy = uv.y * h - 0.5; + + let x0 = sx.floor() as i32; + let y0 = sy.floor() as i32; + let x1 = x0 + 1; + let y1 = y0 + 1; + + let fx = sx - x0 as f32; + let fy = sy - y0 as f32; + + let x0c = x0.max(0).min(self.width_extent); + let y0c = y0.max(0).min(self.height_extent); + let x1c = x1.max(0).min(self.width_extent); + let y1c = y1.max(0).min(self.height_extent); + + let c00 = self.data[(x0c as usize) + (y0c as usize) * self.width]; + + if self.options.magnification == TextureFilter::Nearest || (fx == 0.0 && fy == 0.0) { + // if these are 0 the px at 0,0 will have full influence. Equivalent to nearest sampling. + return c00; + } + + let c10 = self.data[(x1c as usize) + (y0c as usize) * self.width]; + let c01 = self.data[(x0c as usize) + (y1c as usize) * self.width]; + let c11 = self.data[(x1c as usize) + (y1c as usize) * self.width]; + + let v00 = u8x4_to_vec4(&c00); + let v10 = u8x4_to_vec4(&c10); + let v01 = u8x4_to_vec4(&c01); + let v11 = u8x4_to_vec4(&c11); + + let w00 = (1.0 - fx) * (1.0 - fy); + let w10 = fx * (1.0 - fy); + let w01 = (1.0 - fx) * fy; + let w11 = fx * fy; + + vec4_to_u8x4(&(v00 * w00 + v01 * w01 + v10 * w10 + v11 * w11)) + } +} diff --git a/vendor/egui_software_backend/src/fast_image.rs b/vendor/egui_software_backend/src/fast_image.rs new file mode 100644 index 0000000..e544155 --- /dev/null +++ b/vendor/egui_software_backend/src/fast_image.rs @@ -0,0 +1,175 @@ +//! PDF Presenter patch: bounded scanline sampling for cropped, untinted image quads. +//! Keep general meshes, fonts, wrapping, full images and tinting on the upstream path. +use crate::{BufferMutRef, EguiTexture}; +use alloc::vec::Vec; +use egui::{Color32, Mesh, Rect, TextureFilter, TextureWrapMode, Vec2}; + +pub(crate) fn draw( + buffer: &mut BufferMutRef<'_>, + clip: &Rect, + mesh: &Mesh, + offset: Vec2, + texture: &EguiTexture, +) -> bool { + if mesh.texture_id == egui::TextureId::Managed(0) + || mesh.vertices.len() != 4 + || mesh.indices.len() != 6 + || texture.options.wrap_mode != TextureWrapMode::ClampToEdge + || mesh + .vertices + .iter() + .any(|v| v.color != Color32::WHITE || !v.pos.is_finite() || !v.uv.is_finite()) + { + return false; + } + let mut rect = Rect::NOTHING; + let mut uv = Rect::NOTHING; + for v in &mesh.vertices { + rect.extend_with(v.pos); + uv.extend_with(v.uv); + } + if rect.width() <= 0. + || rect.height() <= 0. + || uv.width() <= 0. + || uv.height() <= 0. + || uv.min.x < 0. + || uv.min.y < 0. + || uv.max.x > 1. + || uv.max.y > 1. + || (uv.width() >= 0.99999 && uv.height() >= 0.99999) + { + return false; + } + let mut corners = [0usize; 4]; + let mut seen = 0u8; + for (i, v) in mesh.vertices.iter().enumerate() { + if (v.pos.x != rect.min.x && v.pos.x != rect.max.x) + || (v.pos.y != rect.min.y && v.pos.y != rect.max.y) + { + return false; + } + let x = usize::from(v.pos.x == rect.max.x); + let y = usize::from(v.pos.y == rect.max.y); + let c = x + y * 2; + if seen & (1 << c) != 0 + || v.uv.x != if x == 0 { uv.min.x } else { uv.max.x } + || v.uv.y != if y == 0 { uv.min.y } else { uv.max.y } + { + return false; + } + seen |= 1 << c; + corners[i] = c; + } + let mut triangles = [[0usize; 3]; 2]; + for (t, indices) in triangles.iter_mut().zip(mesh.indices.chunks_exact(3)) { + for (c, i) in t.iter_mut().zip(indices) { + let Some(corner) = corners.get(*i as usize) else { + return false; + }; + *c = *corner; + } + t.sort_unstable(); + } + triangles.sort_unstable(); + if triangles != [[0, 1, 2], [1, 2, 3]] && triangles != [[0, 1, 3], [0, 2, 3]] { + return false; + } + rect = rect.translate(offset); + let visible = rect.intersect(*clip); + if !visible.is_positive() { + return true; + } + let bound = |v: f32, max: usize| (v - 0.5).ceil().clamp(0., max as f32) as usize; + let x0 = bound(visible.min.x, buffer.width); + let x1 = bound(visible.max.x, buffer.width); + let y0 = bound(visible.min.y, buffer.height); + let y1 = bound(visible.max.y, buffer.height); + if x0 >= x1 || y0 >= y1 { + return true; + } + let step = uv.size() / rect.size(); + let linear = texture.options.magnification != TextureFilter::Nearest; + let axis = |value: f32, size: usize| { + if !linear { + let i = (value * size as f32).floor().clamp(0., (size - 1) as f32) as usize; + return (i, i, 0u32); + } + let p = value * size as f32 - 0.5; + let lo = p.floor(); + let a = lo.clamp(0., (size - 1) as f32) as usize; + let b = (lo + 1.).clamp(0., (size - 1) as f32) as usize; + (a, b, ((p - lo) * 256.).round().clamp(0., 256.) as u32) + }; + // O(viewport width) scratch, reused across every scanline; no image allocation. + let columns: Vec<_> = (x0..x1) + .map(|x| { + axis( + uv.min.x + (x as f32 + 0.5 - rect.min.x) * step.x, + texture.width, + ) + }) + .collect(); + let mut row0 = alloc::vec![[0u8;4]; columns.len()]; + let mut row1 = row0.clone(); + let mut cached0 = usize::MAX; + let mut cached1 = usize::MAX; + let horizontal = |row: &mut [[u8; 4]], source_y: usize| { + let source = &texture.data[source_y * texture.width..(source_y + 1) * texture.width]; + for (dst, &(a, b, w)) in row.iter_mut().zip(&columns) { + let a = source[a]; + let b = source[b]; + for c in 0..4 { + dst[c] = ((u32::from(a[c]) * (256 - w) + u32::from(b[c]) * w + 128) >> 8) as u8; + } + } + }; + for y in y0..y1 { + let (ya, yb, wy) = axis( + uv.min.y + (y as f32 + 0.5 - rect.min.y) * step.y, + texture.height, + ); + if ya == cached1 { + core::mem::swap(&mut row0, &mut row1); + core::mem::swap(&mut cached0, &mut cached1); + } + if ya != cached0 { + horizontal(&mut row0, ya); + cached0 = ya; + } + if yb != cached1 { + horizontal(&mut row1, yb); + cached1 = yb; + } + let destination = buffer.get_mut_span(x0, x1, y); + if texture.opaque { + // Contiguous arithmetic: LLVM vectorizes this hot loop. Enlarged rows + // reuse horizontally filtered samples instead of sampling four texels + // and recalculating X coordinates for every screen pixel. + let weight = wy as u16; + for ((dst, a), b) in destination.iter_mut().zip(&row0).zip(&row1) { + for c in 0..4 { + dst[c] = ((u16::from(a[c]) * (256 - weight) + u16::from(b[c]) * weight + 128) + >> 8) as u8; + } + } + } else { + for ((dst, a), b) in destination.iter_mut().zip(&row0).zip(&row1) { + let mut src = [0u8; 4]; + for c in 0..4 { + src[c] = + ((u32::from(a[c]) * (256 - wy) + u32::from(b[c]) * wy + 128) >> 8) as u8; + } + if src[3] == 255 { + *dst = src; + } else if src[3] != 0 { + let alpha = 255 - u32::from(src[3]); + for c in 0..4 { + dst[c] = (u32::from(src[c]) + (u32::from(dst[c]) * alpha + 127) / 255) + .min(255) as u8; + } + } + } + } + } + true +} diff --git a/vendor/egui_software_backend/src/hash.rs b/vendor/egui_software_backend/src/hash.rs new file mode 100644 index 0000000..b62d681 --- /dev/null +++ b/vendor/egui_software_backend/src/hash.rs @@ -0,0 +1,39 @@ +pub struct Hash32(pub u32); + +impl Hash32 { + #[inline(always)] + pub fn new_fnv() -> Self { + Hash32(0x811c9dc5) // FNV offset basis + } + + #[inline(always)] + pub fn hash_wrap(&mut self, v: u32) { + self.hash(v); + self.fnv_wrap(); + } + + #[inline(always)] + pub fn hash(&mut self, v: u32) { + self.0 ^= hash32(v); + } + + #[inline(always)] + pub fn fnv_wrap(&mut self) { + self.0 = self.0.wrapping_mul(0x01000193); // FNV prime + } + + pub fn finalize(&self) -> u32 { + self.0 + } +} + +#[inline(always)] +fn hash32(x: u32) -> u32 { + // from https://nullprogram.com/blog/2018/07/31/ + let mut x = x ^ (x >> 16); + x = x.overflowing_mul(0x7feb352d).0; + x = x ^ (x >> 15); + x = x.overflowing_mul(0x846ca68b).0; + x = x ^ (x >> 16); + x +} diff --git a/vendor/egui_software_backend/src/lib.rs b/vendor/egui_software_backend/src/lib.rs new file mode 100644 index 0000000..41e95ba --- /dev/null +++ b/vendor/egui_software_backend/src/lib.rs @@ -0,0 +1,1206 @@ +//! CPU software render backend for egui +//! +//! ## Basic example usage: +//! ```rust +//!use egui_software_backend::{BufferMutRef, ColorFieldOrder, EguiSoftwareRender}; +//!let buffer = &mut vec![[0u8; 4]; 512 * 512]; +//!let mut buffer_ref = BufferMutRef::new(buffer, 512, 512); +//!let ctx = egui::Context::default(); +//!let mut demo = egui_demo_lib::DemoWindows::default(); +//!let mut sw_render = EguiSoftwareRender::new(ColorFieldOrder::Bgra); +//! +//!let out = ctx.run_ui(egui::RawInput::default(), |ui| { +//! demo.ui(ui); +//!}); +//! +//!let primitives = ctx.tessellate(out.shapes, out.pixels_per_point); +//! +//!sw_render.render( +//! &mut buffer_ref, +//! &primitives, +//! &out.textures_delta, +//! out.pixels_per_point, +//!); +//!``` +//! +//! ## Usage with optional winit backend: +//! ```rust +//!#[cfg(all(feature = "std", feature = "winit"))] +//!mod example { +//! use egui::vec2; +//! use egui_software_backend::{SoftwareBackend, SoftwareBackendAppConfiguration}; +//! +//! struct EguiApp {} +//! +//! impl EguiApp { +//! fn new(context: egui::Context) -> Self { +//! egui_extras::install_image_loaders(&context); +//! EguiApp {} +//! } +//! } +//! +//! impl egui_software_backend::App for EguiApp { +//! fn ui(&mut self, ui: &mut egui::Ui, _backend: &mut SoftwareBackend) { +//! egui::CentralPanel::default().show_inside(ui, |ui| { +//! ui.label("Hello World!"); +//! }); +//! } +//! } +//! +//! fn main() { +//! let settings = SoftwareBackendAppConfiguration::new() +//! .inner_size(Some(vec2(500.0, 300.0))) +//! .title(Some("Simple example".to_string())); +//! +//! egui_software_backend::run_app_with_software_backend(settings, EguiApp::new) +//! //Can fail if winit fails to create the window +//! .expect("Failed to run app") +//! } +//!} +//!``` +//! +//! Performance will be very poor without compiler optimizations. Run in release or use (Cargo.toml): +//!```toml +//!# Enable high optimizations for dependencies +//![profile.dev.package."*"] +//!opt-level = 3 +//!``` +//! + +#![allow(clippy::needless_doctest_main)] +#![no_std] +extern crate alloc; + +#[cfg(feature = "std")] +extern crate std; + +use core::ops::Range; + +use alloc::{borrow::Cow, vec, vec::Vec}; + +use egui::{Color32, Mesh, Pos2, Vec2, ahash::HashMap, vec2}; + +#[cfg(feature = "raster_stats")] +use crate::stats::RasterStats; +use crate::{ + color::{AvailableImpl, SelectedImpl, swizzle_rgba_bgra}, + egui_texture::EguiTexture, + hash::Hash32, + render::{draw_egui_mesh, egui_orient2df}, +}; + +pub(crate) mod color; +pub(crate) mod egui_texture; +pub(crate) mod hash; +pub(crate) mod math; +pub(crate) mod raster; +pub(crate) mod render; +#[cfg(feature = "raster_stats")] +pub mod stats; +#[cfg(feature = "test_render")] +pub mod test_render; + +#[cfg(feature = "winit")] +mod winit; + +#[cfg(feature = "winit")] +pub use winit::{ + App, SoftwareBackend, SoftwareBackendAppConfiguration, run_app_with_software_backend, +}; + +#[inline(always)] +#[allow(dead_code)] +pub(crate) fn sse41() -> bool { + #[cfg(all(target_arch = "x86_64", feature = "std"))] + return std::arch::is_x86_feature_detected!("sse4.1"); + #[cfg(any(not(target_arch = "x86_64"), not(feature = "std")))] + return false; +} + +#[inline(always)] +#[allow(dead_code)] +pub(crate) fn neon() -> bool { + #[cfg(all(target_arch = "aarch64", feature = "std"))] + // This should always be true on aarch64 + return std::arch::is_aarch64_feature_detected!("neon"); + #[cfg(any(not(target_arch = "aarch64"), not(feature = "std")))] + return false; +} + +const TILE_SIZE: usize = 64; + +/// Used to define the color swizzle order. Some backends require Rgba and others require Bgra. The renderer swizzles +/// textures as they are loaded so they can later be rasterized directly onto the frame buffer. +#[derive(Copy, Clone, Default)] +pub enum ColorFieldOrder { + #[default] + Rgba, + Bgra, +} + +/// Software render backend for egui. +pub struct EguiSoftwareRender { + textures: HashMap, + cached_primitives: HashMap, + tiles_dim: [usize; 2], + dirty_tiles: Vec, + target_size: Vec2, + prims_updated_this_frame: usize, + output_field_order: ColorFieldOrder, + canvas: Canvas, + redraw_everything_this_frame: bool, + convert_tris_to_rects: bool, + allow_raster_opt: bool, + cacheing_enabled: bool, + simd_impl: AvailableImpl, + #[cfg(feature = "raster_stats")] + pub stats: RasterStats, +} + +impl EguiSoftwareRender { + /// # Arguments + /// * `output_field_order` - egui textures and vertex colors will be swizzled before rendering to match the desired + /// output buffer order. + pub fn new(output_field_order: ColorFieldOrder) -> Self { + #[cfg(all(feature = "std", feature = "rayon"))] + { + static POOL: std::sync::Once = std::sync::Once::new(); + POOL.call_once(|| { + let count = std::thread::available_parallelism().map_or(1, |n| n.get()).min(4); + let _ = rayon::ThreadPoolBuilder::new().num_threads(count).build_global(); + }); + } + EguiSoftwareRender { + textures: Default::default(), + cached_primitives: Default::default(), + tiles_dim: Default::default(), + dirty_tiles: Default::default(), + target_size: Default::default(), + prims_updated_this_frame: Default::default(), + output_field_order, + canvas: Default::default(), + redraw_everything_this_frame: Default::default(), + convert_tris_to_rects: true, + allow_raster_opt: true, + cacheing_enabled: true, + simd_impl: Default::default(), + #[cfg(feature = "raster_stats")] + stats: Default::default(), + } + } + + /// If true: attempts to optimize by converting suitable triangle pairs into rectangles for faster rendering. + /// Things *should* look the same with this set to `true` while rendering faster. + pub fn with_convert_tris_to_rects(mut self, set: bool) -> Self { + self.convert_tris_to_rects = set; + self + } + + /// If false: Rasterize everything with triangles, always calculate vertex colors, uvs, use bilinear + /// everywhere, etc... Things *should* look the same with this set to `true` while rendering faster. + pub fn with_allow_raster_opt(mut self, set: bool) -> Self { + self.allow_raster_opt = set; + self + } + + /// If true: rasterized ClippedPrimitives are cached and rendered to an intermediate tiled canvas. That canvas is + /// then rendered over the frame buffer. If false ClippedPrimitives are rendered directly to the frame buffer. + /// Rendering without caching is much slower and primarily intended for testing. + pub fn with_caching(mut self, set: bool) -> Self { + self.cacheing_enabled = set; + self + } + + /// Renders the given paint jobs to buffer_ref. Alternatively, when using caching + /// EguiSoftwareRender::render_to_canvas() and subsequently EguiSoftwareRender::blit_canvas_to_buffer() can be run + /// separately so that the primary rendering in render_to_canvas() can happen without a lock on the frame buffer. + /// + /// + /// # Arguments + /// * `paint_jobs` - List of `egui::ClippedPrimitive` from egui to be rendered. + /// * `textures_delta` - The change in egui textures since last frame + /// * `pixels_per_point` - The number of physical pixels for each logical point. + pub fn render( + &mut self, + buffer_ref: &mut BufferMutRef, + paint_jobs: &[egui::ClippedPrimitive], + textures_delta: &egui::TexturesDelta, + pixels_per_point: f32, + ) { + if self.cacheing_enabled { + self.render_to_canvas( + buffer_ref.width, + buffer_ref.height, + paint_jobs, + textures_delta, + pixels_per_point, + ); + self.blit_canvas_to_buffer(buffer_ref); + } else { + self.render_direct(buffer_ref, paint_jobs, textures_delta, pixels_per_point); + } + } + + /// Renders the given paint jobs to an intermediate canvas. + /// + /// # Arguments + /// * `width` - The width of the output in pixels. Must match final output buffer dimensions. + /// * `height` - The height of the output in pixels. Must match final output buffer dimensions. + /// * `paint_jobs` - List of `egui::ClippedPrimitive` from egui to be rendered. + /// * `textures_delta` - The change in egui textures since last frame + /// * `pixels_per_point` - The number of physical pixels for each logical point. + pub fn render_to_canvas( + &mut self, + width: usize, + height: usize, + paint_jobs: &[egui::ClippedPrimitive], + textures_delta: &egui::TexturesDelta, + pixels_per_point: f32, + ) { + // TODO: need to deal with user textures. Either make the fields of EguiUserTextures pub or need to come up with a replacement. + + #[cfg(feature = "raster_stats")] + self.stats.clear(); + + assert!(width > 0); + assert!(height > 0); + assert!(pixels_per_point > 0.0); + + self.redraw_everything_this_frame = self.canvas.resize(width, height); + + if self.redraw_everything_this_frame { + self.canvas.clear(); + self.cached_primitives.clear(); + } + + for (_hash, prim) in self.cached_primitives.iter_mut() { + prim.seen_this_frame = false; + } + + self.target_size = vec2(width as f32, height as f32); + self.tiles_dim = [width.div_ceil(TILE_SIZE), height.div_ceil(TILE_SIZE)]; + + self.set_textures(textures_delta); + + self.render_prims_to_cache(paint_jobs, pixels_per_point); + + self.update_dirty_tiles(); + self.clear_unused_cached_prims(); + + let mut reinit_canvas = self.redraw_everything_this_frame; + + if self.prims_updated_this_frame > 0 { + // TODO use tiles + reinit_canvas = true; + } + + if reinit_canvas { + self.update_canvas_from_cached(); + } + + self.free_textures(textures_delta); + } + + /// Draw canvas alpha over given buffer. + /// Only run after EguiSoftwareRender::render_to_canvas(), or use EguiSoftwareRender::render() to run both. + /// Only writes tile regions that contain pixels that are not fully transparent. + pub fn blit_canvas_to_buffer(&mut self, buffer: &mut BufferMutRef) { + #[cfg(feature = "raster_stats")] + let start = std::time::Instant::now(); + + // Simple tile-less version + // buffer.data.iter_mut().zip(self.canvas.iter()).for_each(|(pixel, src)| { + // *pixel = egui_blend_u8(*src, *pixel); + // }); + + if self.canvas.data.is_empty() { + #[cfg(feature = "log")] + log::error!( + "Canvas not initialized, call EguiSoftwareRender::blit_canvas_to_buffer() only after EguiSoftwareRender::render_to_canvas()" + ); + return; + } + + let width = self.canvas.width; + let height = self.canvas.height; + assert_eq!(self.canvas.data.len(), width * height); + assert_eq!(buffer.data.len(), width * height); + + + + let tiles_x = self.tiles_dim[0]; + + #[cfg(feature = "rayon")] + { + use rayon::{ + iter::{IndexedParallelIterator, ParallelIterator}, + slice::ParallelSliceMut, + }; + // blit rows of tiles in parallel + + let width = buffer.width; + let px_per_row_of_tiles = width * TILE_SIZE; + + buffer + .data + .par_chunks_mut(px_per_row_of_tiles) + .enumerate() + .for_each(|(tile_row, tile_height_row)| { + let height = tile_height_row.len() / width; // Might be less than TILE_SIZE + let buffer_tile_row = &mut BufferMutRef::new(tile_height_row, width, height); + + for (tile_idx, &mask) in self.dirty_tiles.iter().enumerate() { + if mask & Self::OCCUPIED_TILE_MASK == 0 { + continue; + } + + let tile_y = tile_idx / tiles_x; + if tile_y != tile_row { + continue; + } + + let tile_x = tile_idx % tiles_x; + + let x_start = tile_x * TILE_SIZE; + let y_start = 0; + let x_end = (x_start + TILE_SIZE).min(width); + let y_end = TILE_SIZE.min(height); + + let canvas_row_offset = tile_row * TILE_SIZE; + + dispatch_simd_impl!(self.simd_impl, |simd_impl| self.blit_tile( + simd_impl, + buffer_tile_row, + x_start, + y_start, + x_end, + y_end, + canvas_row_offset, + )); + } + }); + } + #[cfg(not(feature = "rayon"))] + { + for (tile_idx, &mask) in self.dirty_tiles.iter().enumerate() { + if mask & Self::OCCUPIED_TILE_MASK == 0 { + continue; + } + + let tile_x = tile_idx % tiles_x; + let tile_y = tile_idx / tiles_x; + + let x_start = tile_x * TILE_SIZE; + let y_start = tile_y * TILE_SIZE; + let x_end = (x_start + TILE_SIZE).min(width); + let y_end = (y_start + TILE_SIZE).min(height); + + dispatch_simd_impl!(self.simd_impl, |simd_impl| self + .blit_tile(simd_impl, buffer, x_start, y_start, x_end, y_end, 0)); + } + } + + #[cfg(feature = "raster_stats")] + { + self.stats.blit_canvas_to_buffer = start.elapsed().as_secs_f32(); + } + } + + #[allow(clippy::too_many_arguments)] + fn blit_tile( + &self, + simd_impl: impl SelectedImpl, + buffer: &mut BufferMutRef, + x_start: usize, + y_start: usize, + x_end: usize, + y_end: usize, + canvas_row_offset: usize, + ) { + for y in y_start..y_end { + let src_row = self.canvas.get_span(x_start, x_end, y + canvas_row_offset); + let dst_row = &mut buffer.get_mut_span(x_start, x_end, y); + simd_impl.egui_blend_u8_slice(src_row, dst_row); + } + } + + /// Render directly into buffer without cache. This is much slower and mainly intended for testing. + fn render_direct( + &mut self, + direct_draw_buffer: &mut BufferMutRef, + paint_jobs: &[egui::ClippedPrimitive], + textures_delta: &egui::TexturesDelta, + pixels_per_point: f32, + ) { + #[cfg(feature = "raster_stats")] + self.stats.clear(); + + self.set_textures(textures_delta); + + self.target_size = vec2( + direct_draw_buffer.width as f32, + direct_draw_buffer.height as f32, + ); + + #[cfg(feature = "raster_stats")] + let start = std::time::Instant::now(); + + for egui::ClippedPrimitive { + clip_rect, + primitive, + } in paint_jobs.iter() + { + let input_mesh = match primitive { + egui::epaint::Primitive::Mesh(input_mesh) => input_mesh, + egui::epaint::Primitive::Callback(_) => { + #[cfg(feature = "log")] + log::error!("egui::epaint::Primitive::Callback(PaintCallback) not supported"); + continue; + } + }; + + if input_mesh.vertices.is_empty() || input_mesh.indices.is_empty() { + continue; + } + + let clip_rect = egui::Rect { + min: clip_rect.min * pixels_per_point, + max: clip_rect.max * pixels_per_point, + }; + + let mut mesh_min = egui::Vec2::splat(f32::MAX); + let mut mesh_max = egui::Vec2::splat(-f32::MAX); + + let px_mesh = + self.prepare_px_mesh(pixels_per_point, input_mesh, &mut mesh_min, &mut mesh_max); + + let mesh_size = mesh_max - mesh_min; + if mesh_size.x > 8192.0 || mesh_size.y > 8192.0 { + // TODO it occasionally tries to make giant buffers in the first couple frames initially for some reason. + continue; + } + + let render_in_low_precision = mesh_size.x > 4096.0 || mesh_size.y > 4096.0; + if render_in_low_precision { + draw_egui_mesh::<2>( + self.simd_impl, + &self.textures, + direct_draw_buffer, + &clip_rect, + &px_mesh, + Vec2::ZERO, + self.allow_raster_opt, + self.convert_tris_to_rects, + #[cfg(all(feature = "raster_stats", not(feature = "rayon")))] + &mut self.stats, + ); + } else { + draw_egui_mesh::<8>( + self.simd_impl, + &self.textures, + direct_draw_buffer, + &clip_rect, + &px_mesh, + Vec2::ZERO, + self.allow_raster_opt, + self.convert_tris_to_rects, + #[cfg(all(feature = "raster_stats", not(feature = "rayon")))] + &mut self.stats, + ); + } + } + + #[cfg(feature = "raster_stats")] + { + self.stats.render_direct = start.elapsed().as_secs_f32(); + } + self.free_textures(textures_delta); + } + + fn prepare_px_mesh( + &self, + pixels_per_point: f32, + mesh: &egui::Mesh, + mesh_min: &mut Vec2, + mesh_max: &mut Vec2, + ) -> Mesh { + let mut px_mesh = mesh.clone(); + + for v in px_mesh.vertices.iter_mut() { + v.pos *= pixels_per_point; + + match self.output_field_order { + ColorFieldOrder::Rgba => (), // egui uses rgba + ColorFieldOrder::Bgra => { + let d = swizzle_rgba_bgra(v.color.to_array()); + v.color = Color32::from_rgba_premultiplied(d[0], d[1], d[2], d[3]); + } + } + + *mesh_min = mesh_min.min(v.pos.to_vec2()); + *mesh_max = mesh_max.max(v.pos.to_vec2()); + } + + // Make all the tris face forward (ccw) to simplify rasterization. + // TODO perf: could store the area so it's not recomputed later. + for i in (0..px_mesh.indices.len()).step_by(3) { + let i0 = px_mesh.indices[i] as usize; + let i1 = px_mesh.indices[i + 1] as usize; + let i2 = px_mesh.indices[i + 2] as usize; + let v0 = px_mesh.vertices[i0]; + let v1 = px_mesh.vertices[i1]; + let v2 = px_mesh.vertices[i2]; + let area = egui_orient2df(&v0.pos, &v1.pos, &v2.pos); + if area < 0.0 { + px_mesh.indices.swap(i + 1, i + 2); + } + } + px_mesh + } + + fn render_prims_to_cache( + &mut self, + paint_jobs: &[egui::ClippedPrimitive], + pixels_per_point: f32, + ) { + #[cfg(feature = "raster_stats")] + let start = std::time::Instant::now(); + + struct CacheReuse { + seen_this_frame: bool, + z_order: usize, + min_x: usize, + min_y: usize, + rendered_this_frame: bool, + hash: u32, + } + + enum CacheUpdate { + CacheReuse(CacheReuse), + New(u32, CachedPrimitive), + None, + } + + // Render paint jobs in parallel + #[cfg(feature = "rayon")] + use rayon::iter::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator}; + #[cfg(feature = "rayon")] + let iter = paint_jobs.par_iter().enumerate(); + + #[cfg(not(feature = "rayon"))] + let iter = paint_jobs.iter().enumerate(); + + let updates: Vec = iter + .map( + |( + prim_idx, + egui::ClippedPrimitive { + clip_rect, + primitive, + }, + )| { + let input_mesh = match primitive { + egui::epaint::Primitive::Mesh(input_mesh) => input_mesh, + egui::epaint::Primitive::Callback(_) => { + #[cfg(feature = "log")] + log::error!( + "egui::epaint::Primitive::Callback(PaintCallback) not supported" + ); + return CacheUpdate::None; + } + }; + + if input_mesh.vertices.is_empty() || input_mesh.indices.is_empty() { + return CacheUpdate::None; + } + + let clip_rect = egui::Rect { + min: clip_rect.min * pixels_per_point, + max: clip_rect.max * pixels_per_point, + }; + + let mut mesh_min = egui::Vec2::splat(f32::MAX); + let mut mesh_max = egui::Vec2::splat(-f32::MAX); + + let px_mesh = self.prepare_px_mesh( + pixels_per_point, + input_mesh, + &mut mesh_min, + &mut mesh_max, + ); + + let cropped_min = mesh_min.max(clip_rect.min.to_vec2()); + let cropped_max = mesh_max.min(clip_rect.max.to_vec2()); + let clip_rect = egui::Rect { + min: Pos2::ZERO, + max: (cropped_max - cropped_min).to_pos2() + egui::Vec2::splat(0.5), + }; + + let hash = { + let mut hasher = Hash32::new_fnv(); + + hasher.hash_wrap(clip_rect.min.x.to_bits()); + hasher.hash_wrap(clip_rect.min.y.to_bits()); + hasher.hash_wrap(clip_rect.max.x.to_bits()); + hasher.hash_wrap(clip_rect.max.y.to_bits()); + hasher.hash_wrap(match px_mesh.texture_id { + egui::TextureId::Managed(id) => id as u32, + egui::TextureId::User(id) => id as u32 + 9358476, + }); + for ind in &px_mesh.indices { + let v = px_mesh.vertices[*ind as usize]; + + // Tried to do this to avoid full redraws when moving a window but it was resulting in some + // meshes to be matches incorrectly in the ui gradient portion of the egui color test: + //let pos = v.pos - cropped_min; + + // It's much faster to not wrap for every field. General ordering should be sufficiently preserved. + hasher.hash(v.pos.x.to_bits()); + hasher.hash(v.pos.y.to_bits()); + hasher.hash(v.uv.x.to_bits()); + hasher.hash(v.uv.y.to_bits()); + hasher.hash(u32::from_le_bytes(v.color.to_array())); + hasher.fnv_wrap(); + } + hasher.hash_wrap(px_mesh.indices.len() as u32); + hasher.finalize() + }; + + if self.cached_primitives.contains_key(&hash) { + CacheUpdate::CacheReuse(CacheReuse { + hash, + seen_this_frame: true, + z_order: prim_idx, + min_x: cropped_min.x as usize, + min_y: cropped_min.y as usize, + rendered_this_frame: false, + }) + } else { + let min_x = cropped_min.x as usize; + let min_y = cropped_min.y as usize; + let width = (cropped_max.x.ceil() as usize) - min_x; + let height = (cropped_max.y.ceil() as usize) - min_y; + + if width > 8192 || height > 8192 { + // TODO it occasionally tries to make giant buffers in the first couple frames initially for some reason. + return CacheUpdate::None; + } + + if width == 0 || height == 0 { + return CacheUpdate::None; + } + + let render_in_low_precision = width > 4096 || height > 4096; + + let mut prim = CachedPrimitive::new(min_x, min_y, width, height, prim_idx); + let mut buffer_ref = BufferMutRef { + data: &mut prim.buffer, + width, + height, + width_extent: width - 1, + height_extent: height - 1, + }; + + let offset = -vec2(cropped_min.x.floor(), cropped_min.y.floor()); + + if render_in_low_precision { + // Seems to not be an issue in direct draw? Seems like a bug. + draw_egui_mesh::<2>( + self.simd_impl, + &self.textures, + &mut buffer_ref, + &clip_rect, + &px_mesh, + offset, + self.allow_raster_opt, + self.convert_tris_to_rects, + #[cfg(all(feature = "raster_stats", not(feature = "rayon")))] + &mut self.stats, + ); + } else { + draw_egui_mesh::<8>( + self.simd_impl, + &self.textures, + &mut buffer_ref, + &clip_rect, + &px_mesh, + offset, + self.allow_raster_opt, + self.convert_tris_to_rects, + #[cfg(all(feature = "raster_stats", not(feature = "rayon")))] + &mut self.stats, + ); + } + prim.update_occupied_tiles(self.tiles_dim[0], self.tiles_dim[1]); + CacheUpdate::New(hash, prim) + } + }, + ) + .collect::>(); + + updates.into_iter().for_each(|update| match update { + CacheUpdate::CacheReuse(cache_reuse) => { + if let Some(cached_primitive) = self.cached_primitives.get_mut(&cache_reuse.hash) { + cached_primitive.seen_this_frame = cache_reuse.seen_this_frame; + cached_primitive.z_order = cache_reuse.z_order; + cached_primitive.min_x = cache_reuse.min_x; + cached_primitive.min_y = cache_reuse.min_y; + cached_primitive.rendered_this_frame = cache_reuse.rendered_this_frame; + } + } + CacheUpdate::New(hash, prim) => { + self.prims_updated_this_frame += 1; + self.cached_primitives.insert(hash, prim); + } + CacheUpdate::None => (), + }); + + #[cfg(feature = "raster_stats")] + { + self.stats.render_prims_to_cache = start.elapsed().as_secs_f32(); + } + } + + fn update_canvas_from_cached(&mut self) { + let simd_impl = self.simd_impl; + #[cfg(feature = "raster_stats")] + let start = std::time::Instant::now(); + + let mut sorted_prim_cache = self.cached_primitives.values().collect::>(); + sorted_prim_cache.sort_unstable_by_key(|prim| prim.z_order); + + #[allow(unused_mut)] + let mut canvas = + BufferMutRef::new(&mut self.canvas.data, self.canvas.width, self.canvas.height); + + #[cfg(feature = "rayon")] + { + use rayon::{ + iter::{IndexedParallelIterator, ParallelIterator}, + slice::ParallelSliceMut, + }; + // composite rows of tiles in parallel + + let full_height = self.canvas.height; + + let width = canvas.width; + let px_per_row_of_tiles = width * TILE_SIZE; + + canvas + .data + .par_chunks_mut(px_per_row_of_tiles) + .enumerate() + .for_each(|(tile_row, tile_height_row)| { + let height = tile_height_row.len() / width; // Might be less than TILE_SIZE + let canvas_tile_row = &mut BufferMutRef::new(tile_height_row, width, height); + + let dirty_tile_row_start = tile_row * self.tiles_dim[0]; + let dirty_tile_row_end = dirty_tile_row_start + self.tiles_dim[0]; + + self.dirty_tiles + .iter() + .enumerate() + .skip(dirty_tile_row_start) + .take(dirty_tile_row_end) + .filter(|(_, mask)| **mask & Self::DIRTY_TILE_MASK != 0) + .map(|(idx, _)| idx) + .for_each(|tile_idx| { + let tile_y = tile_idx / self.tiles_dim[0]; + + if tile_y != tile_row { + return; + } + let canvas_row_offset = tile_row * TILE_SIZE; + + let tile_x = tile_idx % self.tiles_dim[0]; + + update_canvas_tile( + simd_impl, + &sorted_prim_cache, + canvas_tile_row, + tile_x, + tile_y, + full_height, + canvas_row_offset, + ); + }); + }); + } + + #[cfg(not(feature = "rayon"))] + { + for tile_idx in self + .dirty_tiles + .iter() + .enumerate() + .filter(|(_, mask)| **mask & Self::DIRTY_TILE_MASK != 0) + .map(|(idx, _)| idx) + { + let tile_x = tile_idx % self.tiles_dim[0]; + let tile_y = tile_idx / self.tiles_dim[0]; + let full_height = canvas.height; + update_canvas_tile( + simd_impl, + &sorted_prim_cache, + &mut canvas, + tile_x, + tile_y, + full_height, + 0, + ); + } + } + #[cfg(feature = "raster_stats")] + { + self.stats.update_canvas_from_cached = start.elapsed().as_secs_f32(); + } + } + + fn clear_unused_cached_prims(&mut self) { + self.cached_primitives + .retain(|_hash, prim| prim.seen_this_frame); + } + + const DIRTY_TILE_MASK: u8 = 0b00000001; + const OCCUPIED_TILE_MASK: u8 = 0b000000010; + fn update_dirty_tiles(&mut self) { + #[cfg(feature = "raster_stats")] + let start = std::time::Instant::now(); + self.dirty_tiles + .resize(self.tiles_dim[0] * self.tiles_dim[1], 0); + self.dirty_tiles.fill(0); + for prim in self.cached_primitives.values() { + for tile in &prim.occupied_tiles { + let mask = + &mut self.dirty_tiles[tile[0] as usize + tile[1] as usize * self.tiles_dim[0]]; + if !prim.seen_this_frame || prim.rendered_this_frame { + *mask |= Self::DIRTY_TILE_MASK; + } + *mask |= Self::OCCUPIED_TILE_MASK; + } + } + #[cfg(feature = "raster_stats")] + { + self.stats.update_dirty_tiles = start.elapsed().as_secs_f32(); + } + } + + fn set_textures(&mut self, textures_delta: &egui::TexturesDelta) { + #[cfg(feature = "raster_stats")] + let start = std::time::Instant::now(); + for (id, delta) in &textures_delta.set { + if delta.options.magnification != delta.options.minification { + // Would need helper lanes to impl? + #[cfg(feature = "log")] + log::warn!( + "TextureOptions magnification and minification not matching is unsupported." + ); + } + let pixels = match &delta.image { + egui::ImageData::Color(image) => { + assert_eq!(image.width() * image.height(), image.pixels.len()); + Cow::Borrowed(&image.pixels) + } + }; + let size = delta.image.size(); + if let Some(pos) = delta.pos { + if let Some(texture) = self.textures.get_mut(id) { + texture.opaque &= pixels.iter().all(|p| p.a() == 255); + for y in 0..size[1] { + for x in 0..size[0] { + let src_pos = x + y * size[0]; + let dest_pos = (x + pos[0]) + (y + pos[1]) * texture.width; + texture.data[dest_pos] = match self.output_field_order { + ColorFieldOrder::Rgba => pixels[src_pos].to_array(), + ColorFieldOrder::Bgra => { + swizzle_rgba_bgra(pixels[src_pos].to_array()) + } + }; + } + } + } + } else { + let new_texture = + EguiTexture::new(self.output_field_order, delta.options, size, &pixels); + + self.textures.insert(*id, new_texture); + } + } + #[cfg(feature = "raster_stats")] + { + self.stats.set_textures = start.elapsed().as_secs_f32(); + } + } + + fn free_textures(&mut self, textures_delta: &egui::TexturesDelta) { + for free in &textures_delta.free { + self.textures.remove(free); + } + } +} + +fn update_canvas_tile( + simd_impl: AvailableImpl, + sorted_prim_cache: &[&CachedPrimitive], + canvas: &mut BufferMutRef, + tile_x: usize, + tile_y: usize, + full_height: usize, + canvas_row_offset: usize, +) { + let tile_x_start = tile_x * TILE_SIZE; + let tile_y_start = tile_y * TILE_SIZE; + let tile_x_end = (tile_x_start + TILE_SIZE).min(canvas.width); + let tile_y_end = (tile_y_start + TILE_SIZE).min(full_height); + + // clear tile + for y in (tile_y_start - canvas_row_offset)..(tile_y_end - canvas_row_offset) { + let row_start = y * canvas.width; + let start = row_start + tile_x_start; + let end = row_start + tile_x_end; + canvas.data[start..end].fill([0; 4]); + } + + let tile_n = [tile_x as u16, tile_y as u16]; + // redraw cached prims on tile + for prim in sorted_prim_cache { + if prim.occupied_tiles.binary_search_by_key(&(tile_n[1], tile_n[0]), |t| (t[1], t[0])).is_err() { + continue; + } + + let mut min_x = prim.min_x; + let mut min_y = prim.min_y; + let mut max_x = min_x + prim.width; + let mut max_y = min_y + prim.height; + + min_x = min_x.max(tile_x_start).min(canvas.width); + min_y = min_y + .max(tile_y_start) + .min(canvas.height + canvas_row_offset); + max_x = max_x.min(tile_x_end).min(canvas.width); + max_y = max_y.min(tile_y_end).min(canvas.height + canvas_row_offset); + + let prim_buf = prim.get_buffer_ref(); + + if max_x <= min_x || max_y <= min_y { + continue; + } + let prim_x_min = (min_x - prim.min_x).min(prim_buf.width); + let prim_x_max = (max_x - prim.min_x).min(prim_buf.width); + + let get_ranges = |y: usize| -> (Range, Range) { + let canvas_row_start = (y - canvas_row_offset).min(canvas.height) * canvas.width; + let canvas_start = canvas_row_start + min_x; + let canvas_end = canvas_row_start + max_x; + + let prim_y = (y - prim.min_y).min(prim_buf.height); + let prim_row_start = prim_y * prim_buf.width; + let prim_start = prim_row_start + prim_x_min; + let prim_end = prim_row_start + prim_x_max; + + (canvas_start..canvas_end, prim_start..prim_end) + }; + + dispatch_simd_impl!(simd_impl, |simd_impl| { + for y in min_y..max_y { + let (canvas_slice, prim_slice) = get_ranges(y); + let src_row = &prim_buf.data[prim_slice]; + let dst_row = &mut canvas.data[canvas_slice]; + simd_impl.egui_blend_u8_slice(src_row, dst_row); + } + }); + } +} + +#[derive(Default)] +struct Canvas { + data: Vec<[u8; 4]>, + width: usize, + height: usize, + width_extent: usize, + height_extent: usize, +} + +impl Canvas { + fn clear(&mut self) { + self.data.iter_mut().for_each(|p| *p = [0; 4]); + } + + /// returns true if wasn't already the given size + fn resize(&mut self, width: usize, height: usize) -> bool { + if width != self.width || height != self.height { + self.data.resize(width * height, [0; 4]); + self.width = width; + self.height = height; + self.width_extent = width - 1; + self.height_extent = height - 1; + true + } else { + false + } + } + + #[inline(always)] + pub fn get_range(&self, start: usize, end: usize, y: usize) -> Range { + let row_start = y * self.width; + let start = row_start + start; + let end = row_start + end; + start..end + } + + #[inline(always)] + pub fn get_span(&self, start: usize, end: usize, y: usize) -> &[[u8; 4]] { + let range = self.get_range(start, end, y); + &self.data[range] + } +} + +/// A region of cached rendered image data that corresponds to a ClippedPrimitive. +pub struct CachedPrimitive { + buffer: Vec<[u8; 4]>, + min_x: usize, + min_y: usize, + width: usize, + height: usize, + z_order: usize, + seen_this_frame: bool, + rendered_this_frame: bool, + occupied_tiles: Vec<[u16; 2]>, +} + +impl CachedPrimitive { + fn get_buffer_ref(&self) -> BufferRef<'_> { + BufferRef { + data: &self.buffer, + width: self.width, + height: self.height, + width_extent: self.width - 1, + height_extent: self.height - 1, + } + } + + fn new(min_x: usize, min_y: usize, width: usize, height: usize, z_order: usize) -> Self { + CachedPrimitive { + buffer: vec![[0; 4]; width * height], + min_x, + min_y, + width, + height, + z_order, + seen_this_frame: true, + rendered_this_frame: true, + occupied_tiles: Vec::with_capacity(64), + } + } + + fn update_occupied_tiles(&mut self, tiles_wide: usize, tiles_tall: usize) { + // list which tiles contain a pixel with that isn't fully transparent (also containing not color info) + self.occupied_tiles.clear(); + let max_x = self.min_x + self.width; + let max_y = self.min_y + self.height; + let first_tile_x = (self.min_x / TILE_SIZE).min(tiles_wide); + let first_tile_y = (self.min_y / TILE_SIZE).min(tiles_tall); + let last_tile_x = max_x.div_ceil(TILE_SIZE).min(tiles_wide); + let last_tile_y = max_y.div_ceil(TILE_SIZE).min(tiles_tall); + + for tile_y in first_tile_y..last_tile_y { + let mut px_start_y = (tile_y * TILE_SIZE).max(self.min_y); + let mut px_end_y = (px_start_y + TILE_SIZE).min(max_y); + px_start_y -= self.min_y; + px_end_y -= self.min_y; + for tile_x in first_tile_x..last_tile_x { + let mut px_start_x = (tile_x * TILE_SIZE).max(self.min_x); + let mut px_end_x = (px_start_x + TILE_SIZE).min(max_x); + px_start_x -= self.min_x; + px_end_x -= self.min_x; + + 'px_outer: for y in px_start_y..px_end_y { + for x in px_start_x..px_end_x { + // Purposefully panicing when out of bounds. If it's out of bounds then the math is wrong and + // the tile is not being calculated correctly. + if u32::from_le_bytes(self.buffer[x + y * self.width]) > 0 { + self.occupied_tiles.push([tile_x as u16, tile_y as u16]); + break 'px_outer; + } + } + } + } + } + } +} + +/// A mutable reference to a slice of image buffer data and corresponding image extents. +#[derive(Debug)] +pub struct BufferMutRef<'a> { + pub data: &'a mut [[u8; 4]], + pub width: usize, + pub height: usize, + pub width_extent: usize, + pub height_extent: usize, +} + +impl<'a> BufferMutRef<'a> { + pub fn new(data: &'a mut [[u8; 4]], width: usize, height: usize) -> Self { + assert!(width > 0); + assert!(height > 0); + BufferMutRef { + data, + width, + height, + width_extent: width - 1, + height_extent: height - 1, + } + } + + #[inline(always)] + pub fn get_range(&self, start: usize, end: usize, y: usize) -> Range { + let row_start = y * self.width; + let start = row_start + start; + let end = row_start + end; + start..end + } + + #[inline(always)] + pub fn get_mut_span(&mut self, start: usize, end: usize, y: usize) -> &mut [[u8; 4]] { + let range = self.get_range(start, end, y); + &mut self.data[range] + } + + #[inline(always)] + pub fn get_mut_clamped(&mut self, x: usize, y: usize) -> &mut [u8; 4] { + let x = x.min(self.width_extent); + let y = y.min(self.height_extent); + &mut self.data[x + y * self.width] + } + + #[inline(always)] + pub fn get_mut(&mut self, x: usize, y: usize) -> &mut [u8; 4] { + &mut self.data[x + y * self.width] + } +} + +/// A reference to a slice of image buffer data and corresponding image extents. +#[derive(Debug)] +pub struct BufferRef<'a> { + pub data: &'a [[u8; 4]], + pub width: usize, + pub height: usize, + pub width_extent: usize, + pub height_extent: usize, +} + +impl<'a> BufferRef<'a> { + #[inline(always)] + pub fn get_ref_clamped(&self, x: usize, y: usize) -> &[u8; 4] { + let x = x.min(self.width_extent); + let y = y.min(self.height_extent); + &self.data[x + y * self.width] + } + + #[inline(always)] + pub fn get_ref(&self, x: usize, y: usize) -> &[u8; 4] { + &self.data[x + y * self.width] + } +} + +mod fast_image; diff --git a/vendor/egui_software_backend/src/math/i64vec2.rs b/vendor/egui_software_backend/src/math/i64vec2.rs new file mode 100644 index 0000000..5f17a1e --- /dev/null +++ b/vendor/egui_software_backend/src/math/i64vec2.rs @@ -0,0 +1,92 @@ +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[repr(C, align(16))] +pub struct I64Vec2 { + pub x: i64, + pub y: i64, +} + +impl I64Vec2 { + #[inline(always)] + pub fn from_vec2(v: egui::Vec2) -> Self { + i64vec2(v.x as i64, v.y as i64) + } + + #[inline(always)] + pub fn min(self, v: Self) -> Self { + i64vec2(self.x.min(v.x), self.y.min(v.y)) + } + + #[inline(always)] + pub fn max(self, v: Self) -> Self { + i64vec2(self.x.max(v.x), self.y.max(v.y)) + } +} + +impl core::ops::Mul for I64Vec2 { + type Output = Self; + #[inline(always)] + fn mul(self, rhs: Self) -> Self { + i64vec2(self.x * rhs.x, self.y * rhs.y) + } +} + +impl core::ops::Add for I64Vec2 { + type Output = Self; + #[inline(always)] + fn add(self, rhs: Self) -> Self { + i64vec2(self.x + rhs.x, self.y + rhs.y) + } +} + +impl core::ops::Sub for I64Vec2 { + type Output = Self; + #[inline(always)] + fn sub(self, rhs: Self) -> Self { + i64vec2(self.x - rhs.x, self.y - rhs.y) + } +} + +impl core::ops::Mul for I64Vec2 { + type Output = Self; + #[inline(always)] + fn mul(self, rhs: i64) -> Self { + i64vec2(self.x * rhs, self.y * rhs) + } +} + +impl core::ops::Add for I64Vec2 { + type Output = Self; + #[inline(always)] + fn add(self, rhs: i64) -> Self { + i64vec2(self.x + rhs, self.y + rhs) + } +} + +impl core::ops::Sub for I64Vec2 { + type Output = Self; + #[inline(always)] + fn sub(self, rhs: i64) -> Self { + i64vec2(self.x - rhs, self.y - rhs) + } +} + +impl core::ops::Shr for I64Vec2 { + type Output = Self; + #[inline(always)] + fn shr(self, rhs: u32) -> Self { + i64vec2(self.x >> rhs, self.y >> rhs) + } +} + +impl core::ops::Shl for I64Vec2 { + type Output = Self; + #[inline(always)] + fn shl(self, rhs: u32) -> Self { + i64vec2(self.x << rhs, self.y << rhs) + } +} + +#[inline(always)] +pub fn i64vec2(x: i64, y: i64) -> I64Vec2 { + I64Vec2 { x, y } +} diff --git a/vendor/egui_software_backend/src/math/mod.rs b/vendor/egui_software_backend/src/math/mod.rs new file mode 100644 index 0000000..7926b83 --- /dev/null +++ b/vendor/egui_software_backend/src/math/mod.rs @@ -0,0 +1,3 @@ +// These exist just to avoid bringing in glam or similar since egui doesn't. +pub(crate) mod i64vec2; +pub(crate) mod vec4; diff --git a/vendor/egui_software_backend/src/math/vec4.rs b/vendor/egui_software_backend/src/math/vec4.rs new file mode 100644 index 0000000..7acbbf4 --- /dev/null +++ b/vendor/egui_software_backend/src/math/vec4.rs @@ -0,0 +1,601 @@ +// This exists just to avoid bringing in glam or similar since egui doesn't. +// Might be able to use ecolor::rgba::Rgba with some additions. +// Based on emath Vec2 + +use core::fmt; +use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}; + +#[repr(C, align(16))] +#[derive(Clone, Copy, Default, PartialEq)] +pub struct Vec4 { + pub x: f32, + pub y: f32, + pub z: f32, + pub w: f32, +} + +/// `vec4(x, y, z, w) == Vec4::new(x, y, z, w)` +#[inline(always)] +pub const fn vec4(x: f32, y: f32, z: f32, w: f32) -> Vec4 { + Vec4 { x, y, z, w } +} + +// ---------------------------------------------------------------------------- +// Compatibility and convenience conversions to and from [f32; 4]: + +impl From<[f32; 4]> for Vec4 { + #[inline(always)] + fn from(v: [f32; 4]) -> Self { + Self { + x: v[0], + y: v[1], + z: v[2], + w: v[3], + } + } +} + +impl From<&[f32; 4]> for Vec4 { + #[inline(always)] + fn from(v: &[f32; 4]) -> Self { + Self { + x: v[0], + y: v[1], + z: v[2], + w: v[3], + } + } +} + +impl From for [f32; 4] { + #[inline(always)] + fn from(v: Vec4) -> Self { + [v.x, v.y, v.z, v.w] + } +} + +impl From<&Vec4> for [f32; 4] { + #[inline(always)] + fn from(v: &Vec4) -> Self { + [v.x, v.y, v.z, v.w] + } +} + +// ---------------------------------------------------------------------------- +// Compatibility and convenience conversions to and from (f32, f32, f32, f32): + +impl From<(f32, f32, f32, f32)> for Vec4 { + #[inline(always)] + fn from(v: (f32, f32, f32, f32)) -> Self { + Self { + x: v.0, + y: v.1, + z: v.2, + w: v.3, + } + } +} + +impl From<&(f32, f32, f32, f32)> for Vec4 { + #[inline(always)] + fn from(v: &(f32, f32, f32, f32)) -> Self { + Self { + x: v.0, + y: v.1, + z: v.2, + w: v.3, + } + } +} + +impl From for (f32, f32, f32, f32) { + #[inline(always)] + fn from(v: Vec4) -> Self { + (v.x, v.y, v.z, v.w) + } +} + +impl From<&Vec4> for (f32, f32, f32, f32) { + #[inline(always)] + fn from(v: &Vec4) -> Self { + (v.x, v.y, v.z, v.w) + } +} + +// ---------------------------------------------------------------------------- + +impl Vec4 { + pub const ZERO: Self = Self { + x: 0.0, + y: 0.0, + z: 0.0, + w: 0.0, + }; + pub const ONE: Self = Self { + x: 1.0, + y: 1.0, + z: 1.0, + w: 1.0, + }; + pub const INFINITY: Self = Self::splat(f32::INFINITY); + pub const NAN: Self = Self::splat(f32::NAN); + + #[inline(always)] + pub const fn new(x: f32, y: f32, z: f32, w: f32) -> Self { + Self { x, y, z, w } + } + + /// Set `x`, `y`, `z`, `w` to the same value. + #[inline(always)] + pub const fn splat(v: f32) -> Self { + Self { + x: v, + y: v, + z: v, + w: v, + } + } + + /// Safe normalize: returns zero if input is zero. + #[must_use] + #[inline(always)] + pub fn normalized(self) -> Self { + let len = self.length(); + if len <= 0.0 { self } else { self / len } + } + + /// Checks if `self` has length `1.0` up to a precision of `1e-6`. + #[inline(always)] + pub fn is_normalized(self) -> bool { + (self.length_sq() - 1.0).abs() < 2e-6 + } + + #[inline(always)] + pub fn length(self) -> f32 { + self.length_sq().sqrt() + } + + #[inline(always)] + pub fn length_sq(self) -> f32 { + self.x * self.x + self.y * self.y + self.z * self.z + self.w * self.w + } + + #[must_use] + #[inline(always)] + pub fn floor(self) -> Self { + vec4( + self.x.floor(), + self.y.floor(), + self.z.floor(), + self.w.floor(), + ) + } + + #[must_use] + #[inline(always)] + pub fn round(self) -> Self { + vec4( + self.x.round(), + self.y.round(), + self.z.round(), + self.w.round(), + ) + } + + #[must_use] + #[inline(always)] + pub fn ceil(self) -> Self { + vec4(self.x.ceil(), self.y.ceil(), self.z.ceil(), self.w.ceil()) + } + + #[must_use] + #[inline] + pub fn abs(self) -> Self { + vec4(self.x.abs(), self.y.abs(), self.z.abs(), self.w.abs()) + } + + /// True if all members are also finite. + #[inline(always)] + pub fn is_finite(self) -> bool { + self.x.is_finite() && self.y.is_finite() && self.z.is_finite() && self.w.is_finite() + } + + /// True if any member is NaN. + #[inline(always)] + pub fn any_nan(self) -> bool { + self.x.is_nan() || self.y.is_nan() || self.z.is_nan() || self.w.is_nan() + } + + #[must_use] + #[inline] + pub fn min(self, other: Self) -> Self { + vec4( + self.x.min(other.x), + self.y.min(other.y), + self.z.min(other.z), + self.w.min(other.w), + ) + } + + #[must_use] + #[inline] + pub fn max(self, other: Self) -> Self { + vec4( + self.x.max(other.x), + self.y.max(other.y), + self.z.max(other.z), + self.w.max(other.w), + ) + } + + /// The dot-product of two vectors. + #[inline] + pub fn dot(self, other: Self) -> f32 { + self.x * other.x + self.y * other.y + self.z * other.z + self.w * other.w + } + + /// Returns the minimum of all elements. + #[must_use] + #[inline(always)] + pub fn min_elem(self) -> f32 { + self.x.min(self.y).min(self.z).min(self.w) + } + + /// Returns the maximum of all elements. + #[inline(always)] + #[must_use] + pub fn max_elem(self) -> f32 { + self.x.max(self.y).max(self.z).max(self.w) + } + + #[must_use] + #[inline] + pub fn clamp(self, min: Self, max: Self) -> Self { + Self { + x: self.x.clamp(min.x, max.x), + y: self.y.clamp(min.y, max.y), + z: self.z.clamp(min.z, max.z), + w: self.w.clamp(min.w, max.w), + } + } +} + +impl core::ops::Index for Vec4 { + type Output = f32; + + #[inline(always)] + fn index(&self, index: usize) -> &f32 { + match index { + 0 => &self.x, + 1 => &self.y, + 2 => &self.z, + 3 => &self.w, + _ => panic!("Vec4 index out of bounds: {index}"), + } + } +} + +impl core::ops::IndexMut for Vec4 { + #[inline(always)] + fn index_mut(&mut self, index: usize) -> &mut f32 { + match index { + 0 => &mut self.x, + 1 => &mut self.y, + 2 => &mut self.z, + 3 => &mut self.w, + _ => panic!("Vec4 index out of bounds: {index}"), + } + } +} + +impl Eq for Vec4 {} + +impl Neg for Vec4 { + type Output = Self; + + #[inline(always)] + fn neg(self) -> Self { + vec4(-self.x, -self.y, -self.z, -self.w) + } +} + +impl AddAssign for Vec4 { + #[inline(always)] + fn add_assign(&mut self, rhs: Self) { + *self = Self { + x: self.x + rhs.x, + y: self.y + rhs.y, + z: self.z + rhs.z, + w: self.w + rhs.w, + }; + } +} + +impl SubAssign for Vec4 { + #[inline(always)] + fn sub_assign(&mut self, rhs: Self) { + *self = Self { + x: self.x - rhs.x, + y: self.y - rhs.y, + z: self.z - rhs.z, + w: self.w - rhs.w, + }; + } +} + +impl Add for Vec4 { + type Output = Self; + + #[inline(always)] + fn add(self, rhs: Self) -> Self { + Self { + x: self.x + rhs.x, + y: self.y + rhs.y, + z: self.z + rhs.z, + w: self.w + rhs.w, + } + } +} + +impl Add for &Vec4 { + type Output = Vec4; + + #[inline(always)] + fn add(self, rhs: Vec4) -> Vec4 { + Vec4 { + x: self.x + rhs.x, + y: self.y + rhs.y, + z: self.z + rhs.z, + w: self.w + rhs.w, + } + } +} + +impl Add<&Vec4> for Vec4 { + type Output = Vec4; + + #[inline(always)] + fn add(self, rhs: &Vec4) -> Vec4 { + Vec4 { + x: self.x + rhs.x, + y: self.y + rhs.y, + z: self.z + rhs.z, + w: self.w + rhs.w, + } + } +} + +impl Sub for Vec4 { + type Output = Self; + + #[inline(always)] + fn sub(self, rhs: Self) -> Self { + Self { + x: self.x - rhs.x, + y: self.y - rhs.y, + z: self.z - rhs.z, + w: self.w - rhs.w, + } + } +} + +/// Element-wise multiplication +impl Mul for Vec4 { + type Output = Self; + + #[inline(always)] + fn mul(self, vec: Self) -> Self { + Self { + x: self.x * vec.x, + y: self.y * vec.y, + z: self.z * vec.z, + w: self.w * vec.w, + } + } +} + +/// Element-wise division +impl Div for Vec4 { + type Output = Self; + + #[inline(always)] + fn div(self, rhs: Self) -> Self { + Self { + x: self.x / rhs.x, + y: self.y / rhs.y, + z: self.z / rhs.z, + w: self.w / rhs.w, + } + } +} + +impl MulAssign for Vec4 { + #[inline(always)] + fn mul_assign(&mut self, rhs: f32) { + self.x *= rhs; + self.y *= rhs; + self.z *= rhs; + self.w *= rhs; + } +} + +impl DivAssign for Vec4 { + #[inline(always)] + fn div_assign(&mut self, rhs: f32) { + self.x /= rhs; + self.y /= rhs; + self.z /= rhs; + self.w /= rhs; + } +} + +impl Mul for Vec4 { + type Output = Self; + + #[inline(always)] + fn mul(self, factor: f32) -> Self { + Self { + x: self.x * factor, + y: self.y * factor, + z: self.z * factor, + w: self.w * factor, + } + } +} + +impl Mul for &Vec4 { + type Output = Vec4; + + #[inline(always)] + fn mul(self, factor: f32) -> Vec4 { + Vec4 { + x: self.x * factor, + y: self.y * factor, + z: self.z * factor, + w: self.w * factor, + } + } +} + +impl Add for Vec4 { + type Output = Self; + + #[inline(always)] + fn add(self, factor: f32) -> Self { + Self { + x: self.x + factor, + y: self.y + factor, + z: self.z + factor, + w: self.w + factor, + } + } +} + +impl Add for &Vec4 { + type Output = Vec4; + + #[inline(always)] + fn add(self, factor: f32) -> Vec4 { + Vec4 { + x: self.x + factor, + y: self.y + factor, + z: self.z + factor, + w: self.w + factor, + } + } +} + +impl Mul for f32 { + type Output = Vec4; + + #[inline(always)] + fn mul(self, vec: Vec4) -> Vec4 { + Vec4 { + x: self * vec.x, + y: self * vec.y, + z: self * vec.z, + w: self * vec.w, + } + } +} + +impl Div for Vec4 { + type Output = Self; + + #[inline(always)] + fn div(self, factor: f32) -> Self { + Self { + x: self.x / factor, + y: self.y / factor, + z: self.z / factor, + w: self.w / factor, + } + } +} + +impl fmt::Debug for Vec4 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if let Some(precision) = f.precision() { + write!( + f, + "[{1:.0$} {2:.0$} {3:.0$} {4:.0$}]", + precision, self.x, self.y, self.z, self.w + ) + } else { + write!( + f, + "[{:.1} {:.1} {:.1} {:.1}]", + self.x, self.y, self.z, self.w + ) + } + } +} + +impl fmt::Display for Vec4 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("[")?; + self.x.fmt(f)?; + f.write_str(" ")?; + self.y.fmt(f)?; + f.write_str(" ")?; + self.z.fmt(f)?; + f.write_str(" ")?; + self.w.fmt(f)?; + f.write_str("]")?; + Ok(()) + } +} + +#[cfg(test)] +mod test { + use super::*; + + macro_rules! almost_eq { + ($left: expr, $right: expr) => { + let left = $left; + let right = $right; + assert!((left - right).abs() < 1e-6, "{} != {}", left, right); + }; + } + + #[test] + fn test_vec4() { + let mut assignment = vec4(1.0, 2.0, 3.0, 4.0); + assignment += vec4(3.0, 4.0, 5.0, 6.0); + assert_eq!(assignment, vec4(4.0, 6.0, 8.0, 10.0)); + + let mut assignment = vec4(4.0, 6.0, 8.0, 10.0); + assignment -= vec4(1.0, 2.0, 3.0, 4.0); + assert_eq!(assignment, vec4(3.0, 4.0, 5.0, 6.0)); + + let mut assignment = vec4(1.0, 2.0, 3.0, 4.0); + assignment *= 2.0; + assert_eq!(assignment, vec4(2.0, 4.0, 6.0, 8.0)); + + let mut assignment = vec4(2.0, 4.0, 6.0, 8.0); + assignment /= 2.0; + assert_eq!(assignment, vec4(1.0, 2.0, 3.0, 4.0)); + } + + #[test] + fn test_vec4_normalized() { + fn generate_spiral(n: usize, start: Vec4, end: Vec4) -> impl Iterator { + let angle_step = 2.0 * core::f32::consts::PI / n as f32; + let radius_step = (end.length() - start.length()) / n as f32; + + (0..n).map(move |i| { + let angle = i as f32 * angle_step; + let radius = start.length() + i as f32 * radius_step; + let x = radius * angle.cos(); + let y = radius * angle.sin(); + vec4(x, y, x, y) + }) + } + + for v in generate_spiral(40, Vec4::splat(0.1), Vec4::splat(2.0)) { + let vn = v.normalized(); + almost_eq!(vn.length(), 1.0); + assert!(vn.is_normalized()); + } + } +} diff --git a/vendor/egui_software_backend/src/raster/bary.rs b/vendor/egui_software_backend/src/raster/bary.rs new file mode 100644 index 0000000..c584168 --- /dev/null +++ b/vendor/egui_software_backend/src/raster/bary.rs @@ -0,0 +1,259 @@ +use core::ops::{Add, AddAssign, Mul, Sub}; + +use egui::Vec2; + +use crate::math::i64vec2::{I64Vec2, i64vec2}; + +// https://fgiesen.wordpress.com/2013/02/17/optimizing-sw-occlusion-culling-index/ +// https://jtsorlinis.github.io/rendering-tutorial/ +// https://www.cs.cornell.edu/courses/cs4620/2011fa/lectures/16rasterizationWeb.pdf + +/// ss for screen space (unit is screen pixel) +/// sp for subpixel space (unit fraction of screen pixel) +/// Here for reference for raster without using span. +#[allow(unused)] +pub fn raster_tri( + ss_bounds: [I64Vec2; 2], + ss_tri: &[Vec2; 3], + // ss_x, ss_y + mut raster: impl FnMut(i64, i64), +) { + let Some((ss_min, ss_max, _sp_inv_area, mut stepper)) = + SingleStepper::from_ss_tri_backface_cull::(ss_bounds, ss_tri) + else { + return; + }; + + for ss_y in ss_min.y..ss_max.y { + stepper.row_start(); + for ss_x in ss_min.x..ss_max.x { + if stepper.inside_tri_pos_area() { + raster(ss_x, ss_y); + } + stepper.col_step(); + } + stepper.row_step(); + } +} + +#[inline(always)] +pub fn is_top_left(a: &I64Vec2, b: &I64Vec2) -> bool { + let dy = b.y - a.y; + (dy > 0) || (dy == 0 && (b.x - a.x) < 0) +} + +pub struct SingleStepper { + /// Edge subpixel barycentric steps. (edges are: 12, 20, 01) + pub step: [SingleStep; 3], + /// Edge subpixel space barycentric weights. Divide by subpixel area for barycentric factors. + pub sp_weight: [i64; 3], + /// Edge subpixel bias for watertightness. These are applied on SingleStepper::row_start(). If you're using + /// something else you'll need to apply them to sp_weight. + pub bias: [i8; 3], +} + +impl SingleStepper { + /// For the given subpixel resolution, calculate the screen space bounds, subpixel inverse area, and subpixel Stepper. + /// returns: ss_min, ss_max, sp_inv_area, stepper + pub fn from_ss_tri_backface_cull( + ss_bounds: [I64Vec2; 2], + ss_tri: &[Vec2; 3], + ) -> Option<(I64Vec2, I64Vec2, f32, SingleStepper)> { + let subpix_bits = SUBPIX_BITS as u32; + let subpix: i64 = 1 << subpix_bits; + let subpix_half: i64 = subpix >> 1; + let fsubpix = subpix as f32; + + let sp0 = I64Vec2::from_vec2(ss_tri[0] * fsubpix); + let sp1 = I64Vec2::from_vec2(ss_tri[1] * fsubpix); + let sp2 = I64Vec2::from_vec2(ss_tri[2] * fsubpix); + + let sp_area = orient2d(&sp0, &sp1, &sp2); + + if sp_area <= 0 { + return None; + } + + let sp_min = sp0.min(sp1).min(sp2); + let sp_max = sp0.max(sp1).max(sp2); + + let ss_min = ((sp_min - subpix_half) >> subpix_bits) + .max(ss_bounds[0]) + .min(ss_bounds[1]); + let ss_max = ((sp_max + subpix_half) >> subpix_bits) + .max(ss_bounds[0]) + .min(ss_bounds[1]); + + let sp_min_p = ss_min * subpix + subpix_half; + let ss_size = ss_max - ss_min; + + if ss_size.x <= 0 || ss_size.y <= 0 { + return None; + } + + let sp_inv_area = 1.0 / (sp_area as f32); + + let stepper = SingleStepper::new(&sp0, &sp1, &sp2, &sp_min_p, subpix); + + Some((ss_min, ss_max, sp_inv_area, stepper)) + } + + pub fn new( + sp0: &I64Vec2, + sp1: &I64Vec2, + sp2: &I64Vec2, + sp_min_p: &I64Vec2, + subpix: i64, + ) -> Self { + SingleStepper { + step: [ + SingleStep::new(sp1, sp2, sp_min_p, subpix), + SingleStep::new(sp2, sp0, sp_min_p, subpix), + SingleStep::new(sp0, sp1, sp_min_p, subpix), + ], + sp_weight: [0; 3], + bias: [ + if is_top_left(sp1, sp2) { 0 } else { -1 }, + if is_top_left(sp2, sp0) { 0 } else { -1 }, + if is_top_left(sp0, sp1) { 0 } else { -1 }, + ], + } + } + + #[inline(always)] + /// Check if the current step of the stepper is inside the triangle. + pub fn inside_tri_pos_area(&self) -> bool { + // None w are negative + let m = + (self.sp_weight[0] as u64) | (self.sp_weight[1] as u64) | (self.sp_weight[2] as u64); + (m & 0x8000_0000_0000_0000) == 0 + } + + #[inline(always)] + /// Take one step along y to the next row. + pub fn row_step(&mut self) { + self.step[0].row += self.step[0].step.y; + self.step[1].row += self.step[1].step.y; + self.step[2].row += self.step[2].step.y; + } + + #[inline(always)] + /// Take one step along x to the next column. + pub fn col_step(&mut self) { + self.sp_weight[0] += self.step[0].step.x; + self.sp_weight[1] += self.step[1].step.x; + self.sp_weight[2] += self.step[2].step.x; + } + + #[inline(always)] + /// Initialize weights to the start of the current row and apply the bias. + pub fn row_start(&mut self) { + self.sp_weight[0] = self.step[0].row + self.bias[0] as i64; + self.sp_weight[1] = self.step[1].row + self.bias[1] as i64; + self.sp_weight[2] = self.step[2].row + self.bias[2] as i64; + } + + /// Generate stepper for float attribute (like vertex UVs or vertex colors) + /// Depends on SingleStepper's initial state. Make sure to run before using SingleStepper::row_step() or + /// SingleStepper::col_step() + pub fn attr(&self, attr: &[T; 3], sp_inv_area: f32) -> AttributeStepper + where + T: Copy + Add + Sub + AddAssign + Mul, + { + // Get attribute value of top left + let w0 = self.step[0].row; + let w1 = self.step[1].row; + let (b0, b1, b2) = subpixel_bary_to_factor(w0, w1, sp_inv_area); + let attr_tl = attr[0] * b0 + attr[1] * b1 + attr[2] * b2; + + // Get attribute value of one x step right from top left + let w0sx = w0 + self.step[0].step.x; + let w1sx = w1 + self.step[1].step.x; + let (b0, b1, b2) = subpixel_bary_to_factor(w0sx, w1sx, sp_inv_area); + let attr_1x = attr[0] * b0 + attr[1] * b1 + attr[2] * b2; + + // Get attribute value of one y step down from top left + let w0sy = w0 + self.step[0].step.y; + let w1sy = w1 + self.step[1].step.y; + let (b0, b1, b2) = subpixel_bary_to_factor(w0sy, w1sy, sp_inv_area); + let attr_1y = attr[0] * b0 + attr[1] * b1 + attr[2] * b2; + + // Compute deltas + let step_x = attr_1x - attr_tl; + let step_y = attr_1y - attr_tl; + + let row = attr_tl; + + AttributeStepper { + step_x, + step_y, + row, + attr: attr_tl, + } + } +} + +pub struct SingleStep { + pub step: I64Vec2, + pub row: i64, +} + +impl SingleStep { + #[inline(always)] + pub fn new(sp0: &I64Vec2, sp1: &I64Vec2, sp_min_p: &I64Vec2, subpix: i64) -> Self { + let a = sp0.y - sp1.y; + let b = sp1.x - sp0.x; + let c = (sp0.x) * (sp1.y) - (sp0.y) * (sp1.x); + + Self { + step: i64vec2(a * subpix, b * subpix), + row: a * sp_min_p.x + b * sp_min_p.y + c, + } + } +} + +#[inline(always)] +/// Returns twice the signed area of triangle abc +pub fn orient2d(a: &I64Vec2, b: &I64Vec2, c: &I64Vec2) -> i64 { + (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) +} + +#[inline(always)] +/// Convert subpixel space barycentric weights to barycentric factors (0..1) +pub fn subpixel_bary_to_factor(sp_w0: i64, sp_w1: i64, inv_area: f32) -> (f32, f32, f32) { + let b0 = (sp_w0 as f32) * inv_area; + let b1 = (sp_w1 as f32) * inv_area; + let b2 = 1.0 - b0 - b1; + (b0, b1, b2) +} + +#[derive(Default)] +pub struct AttributeStepper +where + T: Copy + Add + Sub + AddAssign + Mul, +{ + pub step_x: T, + pub step_y: T, + pub row: T, + pub attr: T, +} + +impl AttributeStepper +where + T: Copy + Add + Sub + AddAssign + Mul, +{ + #[inline(always)] + pub fn row_step(&mut self) { + self.row += self.step_y; + } + + #[inline(always)] + pub fn col_step(&mut self) { + self.attr += self.step_x; + } + + #[inline(always)] + pub fn row_start(&mut self) { + self.attr = self.row; + } +} diff --git a/vendor/egui_software_backend/src/raster/mod.rs b/vendor/egui_software_backend/src/raster/mod.rs new file mode 100644 index 0000000..38a6855 --- /dev/null +++ b/vendor/egui_software_backend/src/raster/mod.rs @@ -0,0 +1,4 @@ +pub(crate) mod bary; +pub(crate) mod rect; +pub(crate) mod span; +pub(crate) mod tri; diff --git a/vendor/egui_software_backend/src/raster/rect.rs b/vendor/egui_software_backend/src/raster/rect.rs new file mode 100644 index 0000000..38220f8 --- /dev/null +++ b/vendor/egui_software_backend/src/raster/rect.rs @@ -0,0 +1,134 @@ +use constify::constify; +use egui::{Vec2, vec2}; + +use crate::{BufferMutRef, color::SelectedImpl, egui_texture::EguiTexture, render::DrawInfo}; + +#[constify] +pub fn draw_rect( + simd_impl: impl SelectedImpl, + buffer: &mut BufferMutRef, + texture: &EguiTexture, + draw: &DrawInfo, + #[constify] vert_col_vary: bool, + #[constify] vert_uvs_vary: bool, + #[constify] alpha_blend: bool, +) { + simd_impl.dispatch(|simd_impl| { + draw_rect_impl::( + simd_impl, buffer, texture, draw, + ) + }) +} + +#[inline] +#[allow(non_upper_case_globals)] +fn draw_rect_impl( + simd_impl: impl SelectedImpl, + buffer: &mut BufferMutRef, + texture: &EguiTexture, + draw: &DrawInfo, +) { + let const_tri_color_u8x4 = draw.const_tri_color_u8x4; + let clip_bounds = &draw.clip_bounds; + let tri_min = draw.tri_min; + let tri_max = draw.tri_max; + let min_x = ((tri_min.x + 0.5) as i64).max(clip_bounds[0].x); + let min_y = ((tri_min.y + 0.5) as i64).max(clip_bounds[0].y); + let max_x = ((tri_max.x + 0.5) as i64).min(clip_bounds[1].x); + let max_y = ((tri_max.y + 0.5) as i64).min(clip_bounds[1].y); + + let sizex = max_x - min_x; + let sizey = max_y - min_y; + + if sizex <= 0 || sizey <= 0 { + return; + } + + let min_x = min_x as usize; + let min_y = min_y as usize; + let max_x = max_x as usize; + let max_y = max_y as usize; + + if !vert_uvs_vary && !vert_col_vary { + for y in min_y..max_y { + if alpha_blend { + simd_impl.egui_blend_u8_slice_one_src( + const_tri_color_u8x4, + buffer.get_mut_span(min_x, max_x, y), + ); + } else { + buffer + .get_mut_span(min_x, max_x, y) + .fill(const_tri_color_u8x4); + } + } + } else { + // TODO could another level of constify make this cleaner (const use_nearest_sampling?) + let mut min_uv = vec2( + draw.uv[0].x.min(draw.uv[1].x).min(draw.uv[2].x), + draw.uv[0].y.min(draw.uv[1].y).min(draw.uv[2].y), + ); + let max_uv = vec2( + draw.uv[0].x.max(draw.uv[1].x).max(draw.uv[2].x), + draw.uv[0].y.max(draw.uv[1].y).max(draw.uv[2].y), + ); + + let uv_step = (max_uv - min_uv) / (tri_max - tri_min); + min_uv += uv_step * (vec2(min_x as f32, min_y as f32) - tri_min).max(Vec2::ZERO); // Offset to account for clip + min_uv += uv_step * 0.5; // Raster at pixel centers + + let ts_min = min_uv * texture.fsize; + let ts_max = max_uv * texture.fsize; + + let use_nearest_sampling = { + let ss_step = uv_step * texture.fsize; + let dist_from_px_center = (ts_min - ts_min.floor() - vec2(0.5, 0.5)).abs(); + let steps_off_from_1px = (ss_step - Vec2::ONE).abs(); + let eps = 0.01; + let steps_are_1px = steps_off_from_1px.x < eps && steps_off_from_1px.y < eps; + let start_on_texture_px_center = + dist_from_px_center.x < eps && dist_from_px_center.y < eps; + + steps_are_1px && start_on_texture_px_center + }; + + let no_texture_wrap_or_overflow = + (ts_max.x as usize) < texture.width && (ts_max.y as usize) < texture.height; + + if use_nearest_sampling && no_texture_wrap_or_overflow { + // Can just directly blend the texture over the dst buffer, no need to sample with uv + let min_uv = [ts_min.x as i32, ts_min.y as i32]; + let mut tex_row = min_uv[1]; + for y in min_y..max_y { + let tex_row_start = tex_row as usize * texture.width; + let tex_start = tex_row_start + min_uv[0] as usize; + let tex_end = tex_start + max_x - min_x; + + let dst = &mut buffer.get_mut_span(min_x, max_x, y); + let src = &texture.data[tex_start..tex_end]; + + simd_impl.egui_blend_u8_slice_tinted(src, draw.const_vert_color_u8x4, dst); + tex_row += 1; + } + } else { + // There's overflow or can't use nearest. So we need to do full sample. + // TODO perf: there could be a situation where we could nearest sample but with wrapping/clipping. + // We don't have a fast path for that and are falling back to the more general solution below. + // This would be (use_nearest_sampling && !no_texture_wrap_or_overflow) which at least never occurs in the + // demo as far as I can tell + let mut uv = min_uv; + for y in min_y..max_y { + uv.x = min_uv.x; + let buf_y = y * buffer.width; + for x in min_x..max_x { + let tex_color = texture.sample_bilinear(uv); + let pixel = &mut buffer.data[x + buf_y]; + let src = simd_impl.unorm_mult4x4(draw.const_vert_color_u8x4, tex_color); + *pixel = simd_impl.egui_blend_u8(src, *pixel); + uv.x += uv_step.x; + } + uv.y += uv_step.y; + } + } + }; +} diff --git a/vendor/egui_software_backend/src/raster/span.rs b/vendor/egui_software_backend/src/raster/span.rs new file mode 100644 index 0000000..f5b669e --- /dev/null +++ b/vendor/egui_software_backend/src/raster/span.rs @@ -0,0 +1,66 @@ +use crate::raster::bary::SingleStepper; +use strength_reduce::StrengthReducedU64; + +/// Returns Some((start, end)) for the current row in the triangle. The end points are defined within the aabb of the +/// triangle so add ss_min.x to each to get the screen space coordinate. Returns None if there is no span intersecting +/// this row. +pub fn calc_row_span( + stepper: &SingleStepper, + max_cols: i64, + step_rcp: &[StrengthReducedU64; 3], +) -> Option<(i64, i64)> { + let mut start = 0; + let mut end = u64::MAX; + let w = &stepper.sp_weight; + let sx = [ + stepper.step[0].step.x, + stepper.step[1].step.x, + stepper.step[2].step.x, + ]; + + for i in 0..3 { + let w = w[i]; + let sx = sx[i]; + let step_rcp = step_rcp[i]; + if w < 0 { + if sx > 0 { + // unoptimized: start = start.max(div_ceil(-w, sx)); + start = start.max(div_ceil_sr(-w as u64, step_rcp)); + } else { + return None; + } + } else if sx < 0 { + // unoptimized: end = end.min(div_floor(w, -sx) + 1); + // sx < 0 and stepper.step_x_rcp is already abs so no need to negate + // w >= 0 due to if condition above so cast to u64 is fine + end = end.min((w as u64 / step_rcp) + 1); + } + } + + end = end.clamp(0, max_cols as u64); + + if start >= end { + return None; + } + Some((start as i64, end as i64)) +} + +// based on https://github.com/rust-lang/rust/blob/e4b521903b3b1a671e26a70b9475bcff385767e5/library/core/src/num/int_macros.rs#L3238 +#[inline(always)] +pub fn div_ceil_sr(lhs: u64, rhs: StrengthReducedU64) -> u64 { + let (d, r) = StrengthReducedU64::div_rem(lhs, rhs); + + // When remainder is non-zero we have a.div_ceil(b) == 1 + a.div_floor(b), + // so we can re-use the algorithm from div_floor, just adding 1. + let correction = 1 + ((lhs ^ rhs.get()) >> (u64::BITS - 1)); + if r != 0 { d + correction } else { d } +} + +pub fn step_rcp(stepper: &SingleStepper) -> [StrengthReducedU64; 3] { + // max(1) is fine here since the element will already be skipped if step.x == 0 + [ + StrengthReducedU64::new(stepper.step[0].step.x.abs().max(1) as u64), + StrengthReducedU64::new(stepper.step[1].step.x.abs().max(1) as u64), + StrengthReducedU64::new(stepper.step[2].step.x.abs().max(1) as u64), + ] +} diff --git a/vendor/egui_software_backend/src/raster/tri.rs b/vendor/egui_software_backend/src/raster/tri.rs new file mode 100644 index 0000000..4e3e73d --- /dev/null +++ b/vendor/egui_software_backend/src/raster/tri.rs @@ -0,0 +1,142 @@ +use constify::constify; + +use crate::{ + BufferMutRef, + color::{SelectedImpl, vec4_to_u8x4}, + egui_texture::EguiTexture, + raster::{ + bary::SingleStepper, + span::{calc_row_span, step_rcp}, + }, + render::DrawInfo, +}; + +#[constify] +pub fn draw_tri( + simd_impl: impl SelectedImpl, + buffer: &mut BufferMutRef, + texture: &EguiTexture, + draw: &DrawInfo, + #[constify] vert_col_vary: bool, + #[constify] vert_uvs_vary: bool, + #[constify] alpha_blend: bool, +) { + simd_impl.dispatch(|simd_impl| { + draw_tri_impl::( + simd_impl, buffer, texture, draw, + ) + }) +} + +#[inline] +#[allow(non_upper_case_globals)] +fn draw_tri_impl< + const SUBPIX_BITS: i32, + const vert_col_vary: bool, + const vert_uvs_vary: bool, + const alpha_blend: bool, +>( + simd_impl: impl SelectedImpl, + buffer: &mut BufferMutRef, + texture: &EguiTexture, + draw: &DrawInfo, +) { + let Some((ss_min, ss_max, sp_inv_area, mut stepper)) = + SingleStepper::from_ss_tri_backface_cull::(draw.clip_bounds, &draw.ss_tri) + else { + return; + }; + + let step_rcp = step_rcp(&stepper); + + let mut vert_col_stepper = if vert_col_vary { + stepper.attr(&draw.colors, sp_inv_area) + } else { + Default::default() + }; + + let mut vert_uv_stepper = if vert_uvs_vary { + stepper.attr(&draw.uv, sp_inv_area) + } else { + Default::default() + }; + + let max_cols = ss_max.x - ss_min.x; + + for ss_y in ss_min.y..ss_max.y { + stepper.row_start(); + if vert_col_vary { + vert_col_stepper.row_start(); + } + if vert_uvs_vary { + vert_uv_stepper.row_start(); + } + + if let Some((start, end)) = calc_row_span(&stepper, max_cols, &step_rcp) { + if vert_col_vary { + vert_col_stepper.attr += vert_col_stepper.step_x * start as f32; + } + if vert_uvs_vary { + vert_uv_stepper.attr += vert_uv_stepper.step_x * start as f32; + } + let ss_start = (ss_min.x + start) as usize; + let ss_end = (ss_min.x + end) as usize; + + if alpha_blend && !vert_uvs_vary { + let dst = buffer.get_mut_span(ss_start, ss_end, ss_y as usize); + if vert_col_vary { + simd_impl.egui_blend_u8_slice_one_src_tinted_fn( + draw.const_tex_color_u8x4, + || { + let v = vec4_to_u8x4(&vert_col_stepper.attr); + vert_col_stepper.col_step(); + v + }, + dst, + ) + } else { + simd_impl.egui_blend_u8_slice_one_src(draw.const_tri_color_u8x4, dst) + } + } else { + for ss_x in ss_start..ss_end { + let src = if vert_uvs_vary || vert_col_vary { + let tex_color = if vert_uvs_vary { + texture.sample_bilinear(vert_uv_stepper.attr) + } else { + draw.const_tex_color_u8x4 + }; + let vert_color = if vert_col_vary { + vec4_to_u8x4(&vert_col_stepper.attr) + } else { + draw.const_vert_color_u8x4 + }; + crate::color::GenericImpl.unorm_mult4x4(vert_color, tex_color) + //^ `simd_impl.unorm_mult4x4` is slower at least in avx2 and sse4.1 + } else { + draw.const_tri_color_u8x4 + }; + let pixel = buffer.get_mut(ss_x, ss_y as usize); + *pixel = if alpha_blend { + simd_impl.egui_blend_u8(src, *pixel) + } else { + src + }; + if vert_col_vary { + vert_col_stepper.col_step(); + } + if vert_uvs_vary { + vert_uv_stepper.col_step(); + } + } + } + }; + + stepper.row_step(); + if vert_col_vary { + vert_col_stepper.row_step(); + } + if vert_uvs_vary { + vert_uv_stepper.row_step(); + } + } +} diff --git a/vendor/egui_software_backend/src/render.rs b/vendor/egui_software_backend/src/render.rs new file mode 100644 index 0000000..b2f10d1 --- /dev/null +++ b/vendor/egui_software_backend/src/render.rs @@ -0,0 +1,325 @@ +#![allow(unsafe_code)] + +use crate::{ + BufferMutRef, EguiTexture, + color::{AvailableImpl, SelectedImpl, u8x4_to_vec4, vec4_to_u8x4}, + math::{ + i64vec2::{I64Vec2, i64vec2}, + vec4::Vec4, + }, + raster::{rect::draw_rect, tri::draw_tri}, +}; +use egui::{Pos2, Vec2, ahash::HashMap, epaint::Vertex, vec2}; + +#[allow(clippy::too_many_arguments)] +pub fn draw_egui_mesh( + simd_impl: AvailableImpl, + textures: &HashMap, + buffer: &mut BufferMutRef, + clip_rect: &egui::Rect, + mesh: &egui::Mesh, + vert_offset: Vec2, + allow_raster_opt: bool, + convert_tris_to_rects: bool, + #[cfg(all(feature = "raster_stats", not(feature = "rayon")))] + stats: &mut crate::stats::RasterStats, +) { + crate::dispatch_simd_impl!(simd_impl, |simd_impl| draw_egui_mesh_impl::( + simd_impl, + textures, + buffer, + clip_rect, + mesh, + vert_offset, + allow_raster_opt, + convert_tris_to_rects, + #[cfg(all(feature = "raster_stats", not(feature = "rayon")))] + stats, + )) +} + +#[allow(clippy::too_many_arguments)] +fn draw_egui_mesh_impl( + simd_impl: impl SelectedImpl, + textures: &HashMap, + buffer: &mut BufferMutRef, + clip_rect: &egui::Rect, + mesh: &egui::Mesh, + vert_offset: Vec2, + allow_raster_opt: bool, + convert_tris_to_rects: bool, + #[cfg(all(feature = "raster_stats", not(feature = "rayon")))] + stats: &mut crate::stats::RasterStats, +) { + if mesh.vertices.is_empty() || mesh.indices.is_empty() { + return; + } + + let Some(texture) = textures.get(&mesh.texture_id) else { + return; + }; + + if allow_raster_opt && crate::fast_image::draw(buffer, clip_rect, mesh, vert_offset, texture) { + return; + } + + let indices = &mesh.indices; + let vertices = &mesh.vertices; + + let clip_bounds = [ + i64vec2( + (clip_rect.min.x as i64).clamp(0, buffer.width as i64), + (clip_rect.min.y as i64).clamp(0, buffer.height as i64), + ), + i64vec2( + (clip_rect.max.x.ceil() as i64).clamp(0, buffer.width as i64), + (clip_rect.max.y.ceil() as i64).clamp(0, buffer.height as i64), + ), + ]; + + if clip_bounds[1].x - clip_bounds[0].x <= 0 || clip_bounds[1].y - clip_bounds[0].y <= 0 { + return; + } + + let mut i = 0; + // Get texture + while i < indices.len() { + let mut tri = [ + vertices[indices[i] as usize], + vertices[indices[i + 1] as usize], + vertices[indices[i + 2] as usize], + ]; + tri[0].pos += vert_offset; + tri[1].pos += vert_offset; + tri[2].pos += vert_offset; + + let tri_min = vec2( + tri[0].pos.x.min(tri[1].pos.x).min(tri[2].pos.x), + tri[0].pos.y.min(tri[1].pos.y).min(tri[2].pos.y), + ); + let tri_max = vec2( + tri[0].pos.x.max(tri[1].pos.x).max(tri[2].pos.x), + tri[0].pos.y.max(tri[1].pos.y).max(tri[2].pos.y), + ); + + let fsize = tri_max - tri_min; + if fsize.x <= 0.0 || fsize.y <= 0.0 { + i += 3; + continue; + } + + let color0_u8x4 = tri[0].color.to_array(); + let color1_u8x4 = tri[1].color.to_array(); + let color2_u8x4 = tri[2].color.to_array(); + + let mut draw = DrawInfo::new( + clip_bounds, + [ + u8x4_to_vec4(&color0_u8x4), + u8x4_to_vec4(&color1_u8x4), + u8x4_to_vec4(&color2_u8x4), + ], + [ + tri[0].pos.to_vec2(), + tri[1].pos.to_vec2(), + tri[2].pos.to_vec2(), + ], + [ + vec2(tri[0].uv.x, tri[0].uv.y), + vec2(tri[1].uv.x, tri[1].uv.y), + vec2(tri[2].uv.x, tri[2].uv.y), + ], + tri_min, + tri_max, + ); + + if !allow_raster_opt { + draw_tri::(simd_impl, buffer, texture, &draw, true, true, true); + i += 3; + continue; + } + + let mut vert_uvs_vary = !(draw.uv[0] == draw.uv[1] && draw.uv[0] == draw.uv[2]); + let mut vert_col_vary = !(color0_u8x4 == color1_u8x4 && color0_u8x4 == color2_u8x4); + let mut alpha_blend = true; + + if !vert_uvs_vary { + draw.const_tex_color_u8x4 = texture.sample_bilinear(draw.uv[0]); + draw.const_tex_color = u8x4_to_vec4(&draw.const_tex_color_u8x4); + } + + if !vert_col_vary { + draw.const_vert_color = draw.colors[0]; + draw.const_vert_color_u8x4 = color0_u8x4; + } + + if !vert_uvs_vary && !vert_col_vary { + let const_tri_color = draw.const_vert_color * draw.const_tex_color; + draw.const_tri_color_u8x4 = vec4_to_u8x4(&const_tri_color); + if draw.const_tri_color_u8x4[3] == 255 { + alpha_blend = false; + } + } + + if !vert_uvs_vary + && vert_col_vary + && draw.const_tex_color_u8x4[3] == 255 + && color0_u8x4[3] == 255 + && color1_u8x4[3] == 255 + && color2_u8x4[3] == 255 + { + alpha_blend = false; + } + + let find_rects = convert_tris_to_rects && !vert_col_vary && i + 6 < indices.len(); + let mut found_rect = false; + + if find_rects { + let mut tri2 = [ + vertices[indices[i + 3] as usize], + vertices[indices[i + 4] as usize], + vertices[indices[i + 5] as usize], + ]; + tri2[0].pos += vert_offset; + tri2[1].pos += vert_offset; + tri2[2].pos += vert_offset; + + found_rect = tri_verts_match_corners(tri_min, tri_max, tri, tri2); + + if found_rect { + let tri_area = egui_orient2df(&tri[0].pos, &tri[1].pos, &tri[2].pos).abs(); + let rect_area = (tri_max.x - tri_min.x) * (tri_max.y - tri_min.y); + let areas_match = (tri_area - rect_area).abs() < 0.5; + + if areas_match { + if rect_area.abs() < 0.25 { + i += 6; // Skip both tris + continue; // early out of rects smaller than quarter px + } + + if !vert_uvs_vary { + let tri2_uvs_match = tri[0].uv == tri2[0].uv + && tri[0].uv == tri2[1].uv + && tri[0].uv == tri2[2].uv; + vert_uvs_vary = vert_uvs_vary && tri2_uvs_match; + } + + if !vert_col_vary { + let tri2_colors_match = tri[0].color == tri2[0].color + && tri[0].color == tri2[1].color + && tri[0].color == tri2[2].color; + vert_col_vary = vert_col_vary && tri2_colors_match; + } + } else { + found_rect = false; + } + } + } + + let rect = found_rect && !vert_col_vary; // vert_col_vary not supported by rect render + + #[cfg(all(feature = "raster_stats", not(feature = "rayon")))] + stats.start_raster(); + if rect { + draw_rect( + simd_impl, + buffer, + texture, + &draw, + vert_col_vary, + vert_uvs_vary, + alpha_blend, + ); + + #[cfg(all(feature = "raster_stats", not(feature = "rayon")))] + stats.finish_rect(fsize, vert_uvs_vary, vert_col_vary, alpha_blend); + i += 6; + } else { + draw_tri::( + simd_impl, + buffer, + texture, + &draw, + vert_col_vary, + vert_uvs_vary, + alpha_blend, + ); + + #[cfg(all(feature = "raster_stats", not(feature = "rayon")))] + stats.finish_tri(fsize, vert_uvs_vary, vert_col_vary, alpha_blend); + i += 3; + } + } +} + +pub struct DrawInfo { + pub clip_bounds: [I64Vec2; 2], + pub colors: [Vec4; 3], + pub ss_tri: [Vec2; 3], + pub uv: [Vec2; 3], + pub tri_min: Vec2, + pub tri_max: Vec2, + pub const_tex_color: Vec4, + pub const_tex_color_u8x4: [u8; 4], + pub const_vert_color: Vec4, + pub const_vert_color_u8x4: [u8; 4], + pub const_tri_color_u8x4: [u8; 4], +} + +impl DrawInfo { + fn new( + clip_bounds: [I64Vec2; 2], + colors: [Vec4; 3], + ss_tri: [Vec2; 3], + uv: [Vec2; 3], + tri_min: Vec2, + tri_max: Vec2, + ) -> Self { + Self { + clip_bounds, + colors, + ss_tri, + uv, + tri_min, + tri_max, + const_tex_color: Vec4::ONE, + const_tex_color_u8x4: [255; 4], + const_vert_color: Vec4::ONE, + const_vert_color_u8x4: [255; 4], + const_tri_color_u8x4: [255; 4], + } + } +} + +#[inline(always)] +/// Returns twice the signed area of triangle abc +pub fn egui_orient2df(a: &Pos2, b: &Pos2, c: &Pos2) -> f32 { + (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) +} + +fn tri_verts_match_corners( + tri_min: Vec2, + tri_max: Vec2, + tri: [Vertex; 3], + tri2: [Vertex; 3], +) -> bool { + #[inline(always)] + fn close(a: f32, b: f32) -> bool { + //(a - b).abs() <= 0.1 + a == b + } + + // https://github.com/emilk/imgui_software_renderer/blob/b5ae63a9e42eccf7db3bf64696761a53424c53dd/src/imgui_sw.cpp#L577 + (close(tri[0].pos.x, tri_min.x) || close(tri[0].pos.x, tri_max.x)) + && (close(tri[0].pos.y, tri_min.y) || close(tri[0].pos.y, tri_max.y)) + && (close(tri[1].pos.x, tri_min.x) || close(tri[1].pos.x, tri_max.x)) + && (close(tri[1].pos.y, tri_min.y) || close(tri[1].pos.y, tri_max.y)) + && (close(tri[2].pos.x, tri_min.x) || close(tri[2].pos.x, tri_max.x)) + && (close(tri[2].pos.y, tri_min.y) || close(tri[2].pos.y, tri_max.y)) + && (close(tri2[0].pos.x, tri_min.x) || close(tri2[0].pos.x, tri_max.x)) + && (close(tri2[0].pos.y, tri_min.y) || close(tri2[0].pos.y, tri_max.y)) + && (close(tri2[1].pos.x, tri_min.x) || close(tri2[1].pos.x, tri_max.x)) + && (close(tri2[1].pos.y, tri_min.y) || close(tri2[1].pos.y, tri_max.y)) + && (close(tri2[2].pos.x, tri_min.x) || close(tri2[2].pos.x, tri_max.x)) + && (close(tri2[2].pos.y, tri_min.y) || close(tri2[2].pos.y, tri_max.y)) +} diff --git a/vendor/egui_software_backend/src/stats.rs b/vendor/egui_software_backend/src/stats.rs new file mode 100644 index 0000000..e311f0a --- /dev/null +++ b/vendor/egui_software_backend/src/stats.rs @@ -0,0 +1,258 @@ +use crate::alloc::string::ToString; +use alloc::format; +use alloc::vec::Vec; +use egui::ahash::HashMap; +use std::time::Instant; + +#[allow(unused_imports)] +use egui::{Ui, Vec2, Vec2b}; + +#[derive(Clone, Copy)] +pub struct Stat { + pub count: u32, + pub time: f32, + pub sum_area: f32, +} + +pub struct RasterStats { + pub tri_width_buckets: HashMap, // Key is tri width + pub tri_height_buckets: HashMap, // Key is tri height + pub rect_width_buckets: HashMap, // Key is rect width + pub rect_height_buckets: HashMap, // Key is rect height + pub tri_vert_col_vary: u32, // Count of tris where the vertex colors varied + pub tri_vert_uvs_vary: u32, // Count of tris where the vertex uvs varied + pub tri_alpha_blend: u32, // Count of tris that required alpha blending + pub rect_vert_col_vary: u32, // Count of rects where the vertex colors varied + pub rect_vert_uvs_vary: u32, // Count of rects where the vertex uvs varied + pub rect_alpha_blend: u32, // Count of rects that required alpha blending + pub tris: u32, // Total tris drawn + pub rects: u32, // Total rects drawn + pub start: Instant, // Time just before latest rasterization + pub set_textures: f32, + pub update_dirty_tiles: f32, + pub update_canvas_from_cached: f32, + pub render_prims_to_cache: f32, + pub render_direct: f32, + pub blit_canvas_to_buffer: f32, +} + +impl Default for RasterStats { + fn default() -> Self { + Self { + tri_width_buckets: Default::default(), + tri_height_buckets: Default::default(), + tri_vert_col_vary: Default::default(), + tri_vert_uvs_vary: Default::default(), + tri_alpha_blend: Default::default(), + rect_width_buckets: Default::default(), + rect_height_buckets: Default::default(), + rect_vert_col_vary: Default::default(), + rect_vert_uvs_vary: Default::default(), + rect_alpha_blend: Default::default(), + rects: Default::default(), + tris: Default::default(), + set_textures: Default::default(), + update_dirty_tiles: Default::default(), + update_canvas_from_cached: Default::default(), + render_prims_to_cache: Default::default(), + render_direct: Default::default(), + blit_canvas_to_buffer: Default::default(), + start: Instant::now(), + } + } +} + +#[cfg(not(feature = "rayon"))] +fn insert_or_increment(long_side_size: u32, elapsed: f32, area: f32, map: &mut HashMap) { + if let Some(stat) = map.get_mut(&long_side_size) { + stat.count += 1; + stat.time += elapsed; + stat.sum_area += area; + } else { + map.insert( + long_side_size, + Stat { + count: 1, + time: elapsed, + sum_area: area, + }, + ); + } +} + +impl RasterStats { + pub(crate) fn clear(&mut self) { + *self = RasterStats::default(); + } + + #[cfg(not(feature = "rayon"))] + pub(crate) fn start_raster(&mut self) { + self.start = Instant::now(); + } + + #[cfg(not(feature = "rayon"))] + pub(crate) fn finish_rect( + &mut self, + fsize: Vec2, + vert_uvs_vary: bool, + vert_col_vary: bool, + alpha_blend: bool, + ) { + let elapsed = self.start.elapsed().as_secs_f32(); + self.rects += 1; + let tri_area = (fsize.x * fsize.y) * 0.5; + insert_or_increment( + (fsize.x as u32).max(1), + elapsed, + tri_area, + &mut self.rect_width_buckets, + ); + insert_or_increment( + (fsize.y as u32).max(1), + elapsed, + tri_area, + &mut self.rect_height_buckets, + ); + self.rect_vert_col_vary += vert_col_vary as u32; + self.rect_vert_uvs_vary += vert_uvs_vary as u32; + self.rect_alpha_blend += alpha_blend as u32; + } + + #[cfg(not(feature = "rayon"))] + pub(crate) fn finish_tri( + &mut self, + fsize: Vec2, + vert_uvs_vary: bool, + vert_col_vary: bool, + alpha_blend: bool, + ) { + let elapsed = self.start.elapsed().as_secs_f32(); + self.tris += 1; + let rect_area = fsize.x * fsize.y; + insert_or_increment( + (fsize.x as u32).max(1), + elapsed, + rect_area, + &mut self.tri_width_buckets, + ); + insert_or_increment( + (fsize.y as u32).max(1), + elapsed, + rect_area, + &mut self.tri_height_buckets, + ); + self.tri_vert_col_vary += vert_col_vary as u32; + self.tri_vert_uvs_vary += vert_uvs_vary as u32; + self.tri_alpha_blend += alpha_blend as u32; + } + + pub fn render(&self, ui: &mut Ui) { + egui::ScrollArea::both() + .auto_shrink(Vec2b::new(false, false)) + .min_scrolled_width(900.0) + .show(ui, |ui| { + egui::Grid::new("stats_grid").striped(true).show(ui, |ui| { + let mut stat = |label: &str, val: f32| { + ui.label(label); + ui.label(format!("{:.2}ms", val * 1000.0)); + ui.end_row(); + }; + stat("set_textures", self.set_textures); + stat("render_prims_to_cache", self.render_prims_to_cache); + stat("update_dirty_tiles", self.update_dirty_tiles); + stat("update_canvas_from_cached", self.update_canvas_from_cached); + stat("blit_canvas_to_buffer", self.blit_canvas_to_buffer); + stat("render_direct", self.render_direct); + + ui.heading(""); + ui.heading("Tri"); + ui.heading("Rect"); + ui.end_row(); + let mut stat = |label: &str, val: u32, val2: u32| { + ui.label(label); + ui.label(val.to_string()); + ui.label(val2.to_string()); + ui.end_row(); + }; + stat( + "Vertex colors vary", + self.tri_vert_col_vary, + self.rect_vert_col_vary, + ); + stat( + "Vertex uvs vary", + self.tri_vert_uvs_vary, + self.rect_vert_uvs_vary, + ); + stat( + "Requires alpha blend", + self.tri_alpha_blend, + self.rect_alpha_blend, + ); + }); + + ui.label(""); + ui.end_row(); + + fn collect_and_sort(map: &HashMap) -> Vec<(u32, Stat)> { + let mut v: Vec<_> = map.iter().map(|(&k, &s)| (k, s)).collect(); + v.sort_by_key(|&(_, s)| std::cmp::Reverse((s.time * 1000000.0) as u32)); // Seconds to microseconds + v + } + + let tri_width_bucket = collect_and_sort(&self.tri_width_buckets); + let tri_height_bucket = collect_and_sort(&self.tri_height_buckets); + let rect_width_bucket = collect_and_sort(&self.rect_width_buckets); + let rect_height_bucket = collect_and_sort(&self.rect_height_buckets); + + let max_rows = tri_width_bucket + .len() + .max(tri_height_bucket.len()) + .max(rect_width_bucket.len()) + .max(rect_height_bucket.len()); + + egui::Grid::new("stats_grid2").striped(true).show(ui, |ui| { + ui.heading("Tris"); + ui.heading(format!("{}", self.tris)); + (0..=5).for_each(|_| _ = ui.heading("")); + ui.heading(" "); + ui.heading("Rects"); + ui.heading(format!("{}", self.rects)); + (0..=5).for_each(|_| _ = ui.heading("")); + ui.end_row(); + + let headers = ["W", "Qty", "μs", "area"]; + + headers.iter().for_each(|s| _ = ui.heading(*s)); + headers.iter().for_each(|s| _ = ui.heading(*s)); + ui.heading(" "); + headers.iter().for_each(|s| _ = ui.heading(*s)); + headers.iter().for_each(|s| _ = ui.heading(*s)); + ui.end_row(); + + fn row(ui: &mut Ui, i: usize, v: &[(u32, Stat)]) { + if let Some((size, stat)) = v.get(i) { + ui.label(format!("{size}")); + ui.label(format!("{}", stat.count)); + ui.label(format!("{:.0}", stat.time * 1000000.0)); // Seconds to microseconds + ui.label(format!("{}", stat.sum_area as u32)); + } else { + ui.label(""); + ui.label(""); + ui.label(""); + ui.label(""); + } + } + + for i in 0..max_rows { + row(ui, i, &tri_width_bucket); + row(ui, i, &tri_height_bucket); + ui.label(" "); + row(ui, i, &rect_width_bucket); + row(ui, i, &rect_height_bucket); + ui.end_row(); + } + }); + }); + } +} diff --git a/vendor/egui_software_backend/src/test_render.rs b/vendor/egui_software_backend/src/test_render.rs new file mode 100644 index 0000000..be5fdbe --- /dev/null +++ b/vendor/egui_software_backend/src/test_render.rs @@ -0,0 +1,42 @@ +use alloc::{string::String, vec, vec::Vec}; +use egui::TexturesDelta; +use egui_kittest::TestRenderer; +use image::ImageBuffer; + +use crate::{BufferMutRef, EguiSoftwareRender}; + +impl TestRenderer for EguiSoftwareRender { + fn handle_delta(&mut self, delta: &TexturesDelta) { + self.set_textures(delta); + self.free_textures(delta); + } + + fn render( + &mut self, + ctx: &egui::Context, + output: &egui::FullOutput, + ) -> Result { + let paint_jobs = ctx.tessellate(output.shapes.clone(), output.pixels_per_point); + + let width = (ctx.content_rect().width() * output.pixels_per_point).ceil() as usize; + let height = (ctx.content_rect().height() * output.pixels_per_point).ceil() as usize; + + let mut buffer = vec![[0u8; 4]; width * height]; + + let mut buffer_ref = BufferMutRef::new(&mut buffer, width as usize, height as usize); + + self.render( + &mut buffer_ref, + &paint_jobs, + &output.textures_delta, + output.pixels_per_point, + ); + + Ok(ImageBuffer::, Vec<_>>::from_raw( + width as u32, + height as u32, + buffer.iter().flatten().cloned().collect::>(), + ) + .unwrap()) + } +} diff --git a/vendor/egui_software_backend/src/winit.rs b/vendor/egui_software_backend/src/winit.rs new file mode 100644 index 0000000..3461313 --- /dev/null +++ b/vendor/egui_software_backend/src/winit.rs @@ -0,0 +1,1166 @@ +use crate::{BufferMutRef, ColorFieldOrder, EguiSoftwareRender}; +use egui::{ + Context, CursorGrab, IconData, Pos2, SystemTheme, Vec2, ViewportBuilder, ViewportCommand, + WindowLevel, X11WindowType, +}; +use softbuffer::SoftBufferError; +use std::boxed::Box; +use std::error::Error; +use std::fmt::{Display, Formatter}; +use std::mem; +use std::num::NonZeroU32; +use std::ops::Deref; +use std::rc::Rc; +use std::string::String; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use std::vec::Vec; +use winit::application::ApplicationHandler; +use winit::event::{Event, WindowEvent}; +use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop, OwnedDisplayHandle}; +use winit::window::{CursorGrabMode, Fullscreen, Icon, Theme, Window, WindowButtons, WindowId}; + +/// Errors that can occur when using the egui software backend with winit. +#[derive(Debug)] +pub enum SoftwareBackendAppError { + /// A softbuffer error has occurred. + /// The softbuffer crate is used to manage the pixel buffer of the window. + SoftBuffer { + soft_buffer_error: Box, + function: &'static str, + }, + + /// Some event loop error has occurred. + EventLoop(Box), + + /// The event loop has errored in addition to an error from the software renderer + SuppressedEventLoop { + event_loop_error: Box, + suppressed: Box, + }, + + /// Error when calling winit create_window + CreateWindowOs(Box), +} + +impl Display for SoftwareBackendAppError { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { + match self { + SoftwareBackendAppError::SoftBuffer { function, .. } => { + f.write_str("error calling ")?; + f.write_str(function) + } + SoftwareBackendAppError::EventLoop(_) => f.write_str("winit event loop has errored"), + SoftwareBackendAppError::SuppressedEventLoop { .. } => { + f.write_str("software renderer and winit event loop have both errored") + } + SoftwareBackendAppError::CreateWindowOs(_) => { + f.write_str("os error calling winit::create_window") + } + } + } +} + +impl Error for SoftwareBackendAppError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + SoftwareBackendAppError::SuppressedEventLoop { suppressed, .. } => { + Some(suppressed as &dyn Error) + } + _ => None, + } + } +} + +impl SoftwareBackendAppError { + fn soft_buffer( + function: &'static str, + ) -> impl FnOnce(SoftBufferError) -> SoftwareBackendAppError { + move |error| Self::SoftBuffer { + soft_buffer_error: Box::new(error), + function, + } + } +} + +// Doing what clippy suggests would make it impossible for the compiler to optimize the layout of this enum, causing +// state machine transitions to be more expensive! +#[allow(clippy::large_enum_variant)] +/// Winit App State machine, that handles all states of our application. +enum WinitAppStateMachine EguiApp> { + /// The app has died, either without or with some sort of error. + Dead(Option), + + /// The app is configured, but the window has not been created yet. + /// Transitions into WindowInitialized (resume). + Configured(ConfiguredAppState), + + /// The window has been initialized. + /// Transitions into Dead (error) or Running (resume). + WindowInitialized(WindowInitializedAppState), + + /// The app is running. + /// Transitions into Dead (quit/error) or WindowInitialized (suspend) + Running(RunningEguiAppState), +} + +struct ConfiguredAppState EguiApp> { + /////////// DANGER ZONE DO NOT CHANGE THE ORDER OF THOSE FIELDS //////////////////// + // WAYLAND BUG: The wayland clipboard blows up with a segmentation fault if + // If the fields are dropped in the wrong order. Other platforms are not affected by drop order. + // Fields of a struct are dropped in declaration order. https://doc.rust-lang.org/reference/destructors.html + egui_context: Context, + softbuffer_context: softbuffer::Context, + /////////////////// END OF DANGER ZONE////////////////////////////////////// + config: SoftwareBackendAppConfiguration, + software_backend: SoftwareBackend, + renderer: EguiSoftwareRender, + egui_app_factory: EguiAppFactory, +} + +struct WindowInitializedAppState EguiApp> { + /////////// DANGER ZONE DO NOT CHANGE THE ORDER OF THOSE FIELDS //////////////////// + // WAYLAND BUG: The wayland clipboard blows up with a segmentation fault if + // If the fields are dropped in the wrong order. Other platforms are not affected by drop order. + // Fields of a struct are dropped in declaration order. https://doc.rust-lang.org/reference/destructors.html + egui_context: Context, + softbuffer_context: softbuffer::Context, + window: Rc, + /////////////////// END OF DANGER ZONE////////////////////////////////////// + config: SoftwareBackendAppConfiguration, + software_backend: SoftwareBackend, + renderer: EguiSoftwareRender, + egui_app_factory: EguiAppFactory, +} + +struct RunningEguiAppState EguiApp> { + /////////// DANGER ZONE DO NOT CHANGE THE ORDER OF THOSE FIELDS //////////////////// + // WAYLAND BUG: The wayland clipboard blows up with a segmentation fault if + // If the fields are dropped in the wrong order. Other platforms are not affected by drop order. + // Fields of a struct are dropped in declaration order. https://doc.rust-lang.org/reference/destructors.html + egui_context: Context, + surface: softbuffer::Surface>, + egui_winit: egui_winit::State, + window: Rc, + /////////////////// END OF DANGER ZONE////////////////////////////////////// + config: SoftwareBackendAppConfiguration, + software_backend: SoftwareBackend, + renderer: EguiSoftwareRender, + egui_app_factory: EguiAppFactory, + softbuffer_context: softbuffer::Context, + egui_app: EguiApp, + fullscreen: bool, + visible: bool, + input_events: Vec, +} + +impl EguiApp> Default + for WinitAppStateMachine +{ + fn default() -> Self { + Self::Dead(None) + } +} + +impl EguiApp> + ConfiguredAppState +{ + pub(crate) fn create_window( + mut self, + elwt: &ActiveEventLoop, + ) -> Result, SoftwareBackendAppError> { + // !BUG IN WAYLAND! + // If resizable is false during window creation you can never make the window resizable again. + // We always force None before we call into egui_winit and set it on the window object later. + let resizable = self + .config + .viewport_builder + .resizable + .take() + .unwrap_or(true); + + let window = + egui_winit::create_window(&self.egui_context, elwt, &self.config.viewport_builder); + + self.config.viewport_builder.resizable = Some(resizable); + + let window = window + .map_err(|ose| SoftwareBackendAppError::CreateWindowOs(Box::new(ose))) + .map(Rc::new)?; + + window.set_resizable(resizable); + + Ok(WindowInitializedAppState { + config: self.config, + software_backend: self.software_backend, + renderer: self.renderer, + egui_context: self.egui_context, + egui_app_factory: self.egui_app_factory, + softbuffer_context: self.softbuffer_context, + window, + }) + } +} + +impl EguiApp> + WindowInitializedAppState +{ + pub(crate) fn create_surface( + mut self, + ) -> Result, SoftwareBackendAppError> { + let surface = softbuffer::Surface::new(&self.softbuffer_context, self.window.clone()) + .map_err(SoftwareBackendAppError::soft_buffer( + "softbuffer::Surface::new", + ))?; + + let egui_winit = egui_winit::State::new( + self.egui_context.clone(), + egui::ViewportId::ROOT, + &self.window, + Some(self.window.scale_factor() as f32), + None, + None, + ); + + let egui_app = (self.egui_app_factory)(self.egui_context.clone()); + let fullscreen = self.config.viewport_builder.fullscreen.unwrap_or_default(); + let visible = self.config.viewport_builder.visible.unwrap_or(true); + + Ok(RunningEguiAppState { + config: self.config, + renderer: self.renderer, + egui_context: self.egui_context, + egui_app_factory: self.egui_app_factory, + softbuffer_context: self.softbuffer_context, + window: self.window, + surface, + egui_winit, + egui_app, + fullscreen, + visible, + input_events: Vec::new(), + software_backend: self.software_backend, + }) + } +} + +impl EguiApp> + WinitAppStateMachine +{ + /// Create a new application. + pub(crate) fn new( + config: SoftwareBackendAppConfiguration, + renderer: EguiSoftwareRender, + softbuffer_context: softbuffer::Context, + egui_app_factory: EguiAppFactory, + egui_context: Context, + ) -> Self { + Self::Configured(ConfiguredAppState { + config, + software_backend: SoftwareBackend { + capture_frame_time: false, + last_frame_time: None, + }, + renderer, + softbuffer_context, + egui_context, + egui_app_factory, + }) + } +} + +enum UserEvent { + RequestRepaint { + /// What to repaint. + viewport_id: egui::ViewportId, + + /// When to repaint. + when: Instant, + + /// What the cumulative pass number was when the repaint was _requested_. + cumulative_pass_nr: u64, + }, +} + +impl EguiApp> ApplicationHandler + for WinitAppStateMachine +{ + fn resumed(&mut self, el: &ActiveEventLoop) { + if el.exiting() { + return; + } + + match mem::take(self) { + Self::Configured(state) => match state.create_window(el) { + Ok(ss) => { + *self = Self::WindowInitialized(ss); + self.resumed(el); + } + Err(e) => { + *self = Self::Dead(Some(e)); + el.exit(); + } + }, + Self::WindowInitialized(state) => match state.create_surface() { + Ok(ss) => { + *self = Self::Running(ss); + } + Err(e) => { + *self = Self::Dead(Some(e)); + el.exit(); + } + }, + Self::Running(state) => { + *self = Self::Running(state); + self.suspended(el); + self.resumed(el); + } + Self::Dead(err) => { + *self = Self::Dead(err); + el.exit(); + } + } + } + + fn user_event(&mut self, event_loop: &ActiveEventLoop, event: UserEvent) { + if event_loop.exiting() { + return; + } + if let Self::Running(state) = self { + match event { + UserEvent::RequestRepaint { + viewport_id, + when, + cumulative_pass_nr, + } => { + let current_pass_nr = state.egui_context.cumulative_pass_nr_for(viewport_id); + if current_pass_nr == cumulative_pass_nr + || current_pass_nr == cumulative_pass_nr + 1 + { + state.request_redraw(); + } + event_loop.set_control_flow(ControlFlow::WaitUntil(when)); + } + } + } + } + + fn window_event( + &mut self, + event_loop: &ActiveEventLoop, + window_id: WindowId, + event: WindowEvent, + ) { + if event_loop.exiting() { + return; + } + + match self { + Self::Configured(_) | Self::WindowInitialized(_) => { + event_loop.set_control_flow(ControlFlow::Wait); + } + Self::Running(state) => { + if let Err(e) = + state.handle_event(Event::WindowEvent { window_id, event }, event_loop) + { + *self = Self::Dead(Some(e)); + event_loop.exit(); + } + } + Self::Dead(_) => { + event_loop.exit(); + } + } + } + + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + if event_loop.exiting() { + return; + } + + match self { + Self::Configured(_) | Self::WindowInitialized(_) => { + event_loop.set_control_flow(ControlFlow::Wait); + } + Self::Running(state) => { + if let Err(e) = state.handle_event(Event::AboutToWait, event_loop) { + *self = Self::Dead(Some(e)); + event_loop.exit(); + } + } + Self::Dead(_) => { + event_loop.exit(); + } + } + } + + fn suspended(&mut self, event_loop: &ActiveEventLoop) { + if event_loop.exiting() { + return; + } + + match mem::take(self) { + Self::Dead(e) => { + *self = Self::Dead(e); + event_loop.exit(); + } + Self::Configured(state) => { + *self = Self::Configured(state); + } + Self::WindowInitialized(window) => { + *self = Self::WindowInitialized(window); + } + Self::Running(state) => { + *self = Self::WindowInitialized(state.suspend()); + } + } + } +} + +impl EguiApp> + RunningEguiAppState +{ + pub(crate) fn suspend(self) -> WindowInitializedAppState { + WindowInitializedAppState { + config: self.config, + software_backend: self.software_backend, + renderer: self.renderer, + egui_context: self.egui_context, + egui_app_factory: self.egui_app_factory, + softbuffer_context: self.softbuffer_context, + window: self.window, + } + } + pub(crate) fn request_redraw(&self) { + self.window.request_redraw(); + } + + pub(crate) fn handle_event( + &mut self, + event: Event<()>, + elwt: &ActiveEventLoop, + ) -> Result<(), SoftwareBackendAppError> { + let start = if self.software_backend.capture_frame_time { + Some(Instant::now()) + } else { + None + }; + + elwt.set_control_flow(ControlFlow::Wait); + + let Event::WindowEvent { + window_id, + event: window_event, + } = event + else { + return Ok(()); + }; + + if window_id != self.window.id() { + return Ok(()); + } + + match window_event { + WindowEvent::RedrawRequested => { + let size = self.window.inner_size(); + let width = NonZeroU32::new(size.width).unwrap_or(ONE_PIXEL); + let height = NonZeroU32::new(size.height).unwrap_or(ONE_PIXEL); + + self.surface.resize(width, height).map_err( + SoftwareBackendAppError::soft_buffer("softbuffer::Surface::resize"), + )?; + + let mut raw_input = self.egui_winit.take_egui_input(self.window.deref()); + + raw_input + .events + .extend_from_slice(self.input_events.as_slice()); + self.input_events.clear(); + + let full_output = self.egui_context.run_ui(raw_input, |ui| { + self.egui_app.ui(ui, &mut self.software_backend); + + self.egui_context.viewport(|r| { + let mut die = false; + for command in &r.commands { + match command { + ViewportCommand::Close => { + die = true; + } + ViewportCommand::CancelClose => { + die = false; + } + ViewportCommand::Title(title) => self.window.set_title(title), + ViewportCommand::Transparent(trans) => { + self.window.set_transparent(*trans) + } + ViewportCommand::Visible(true) => { + self.visible = true; + self.window.set_visible(true); + if self.fullscreen { + self.window + .set_fullscreen(Some(Fullscreen::Borderless(None))); + } else { + self.window.set_fullscreen(None); + } + } + ViewportCommand::Visible(false) => { + self.visible = false; + // Needed because otherwise fullscreen mode never works again. + self.window.set_fullscreen(None); + + // Needed because otherwise cursor grab needs to be manually set to none before it + // can be enabled again + _ = self.window.set_cursor_grab(CursorGrabMode::None); + + self.window.set_visible(false) + } + ViewportCommand::OuterPosition(state) => { + self.window.set_outer_position( + winit::dpi::LogicalPosition::new(state.x, state.y), + ); + } + ViewportCommand::InnerSize(state) => { + _ = self.window.request_inner_size( + winit::dpi::LogicalSize::new(state.x, state.y), + ); + } + ViewportCommand::MinInnerSize(state) => { + self.window.set_min_inner_size(Some( + winit::dpi::LogicalSize::new(state.x, state.y), + )); + } + ViewportCommand::MaxInnerSize(state) => { + self.window.set_max_inner_size(Some( + winit::dpi::LogicalSize::new(state.x, state.y), + )); + } + ViewportCommand::ResizeIncrements(None) => { + self.window + .set_resize_increments::>( + None, + ); + } + ViewportCommand::ResizeIncrements(Some(state)) => { + let size = winit::dpi::LogicalSize::new(state.x, state.y); + self.window.set_resize_increments(Some(size)); + } + ViewportCommand::Resizable(state) => { + self.window.set_resizable(*state); + } + ViewportCommand::EnableButtons { + close, + maximize, + minimized, + } => { + let mut button_state = WindowButtons::empty(); + if *close { + button_state.set(WindowButtons::CLOSE, true); + } + if *maximize { + button_state.set(WindowButtons::MAXIMIZE, true); + } + if *minimized { + button_state.set(WindowButtons::MINIMIZE, true); + } + + self.window.set_enabled_buttons(button_state); + } + ViewportCommand::Minimized(state) => { + self.window.set_minimized(*state); + } + ViewportCommand::Maximized(state) => { + self.window.set_maximized(*state); + } + ViewportCommand::Fullscreen(false) => { + self.fullscreen = false; + if self.visible { + self.window.set_fullscreen(None) + } + } + ViewportCommand::Fullscreen(true) => { + self.fullscreen = true; + if self.visible { + self.window + .set_fullscreen(Some(Fullscreen::Borderless(None))) + } + } + ViewportCommand::Decorations(dec) => { + self.window.set_decorations(*dec) + } + ViewportCommand::WindowLevel(WindowLevel::Normal) => { + self.window + .set_window_level(winit::window::WindowLevel::Normal); + } + ViewportCommand::WindowLevel(WindowLevel::AlwaysOnBottom) => { + self.window.set_window_level( + winit::window::WindowLevel::AlwaysOnBottom, + ); + } + ViewportCommand::WindowLevel(WindowLevel::AlwaysOnTop) => { + self.window + .set_window_level(winit::window::WindowLevel::AlwaysOnTop); + } + ViewportCommand::Icon(ico) => { + self.window.set_window_icon( + ico.as_ref() + .map(|i| { + Icon::from_rgba(i.rgba.clone(), i.width, i.height) + .ok() + }) + .unwrap_or(None), + ); + } + ViewportCommand::Focus => self.window.focus_window(), + ViewportCommand::SetTheme(SystemTheme::Dark) => { + self.window.set_theme(Some(Theme::Dark)) + } + ViewportCommand::SetTheme(SystemTheme::Light) => { + self.window.set_theme(Some(Theme::Light)) + } + ViewportCommand::SetTheme(SystemTheme::SystemDefault) => { + // Winit has no default... + // we will just use light as that is the default + // of most operating systems. + self.window.set_theme(Some(Theme::Light)) + } + + //Wtf, I don't think DXGI, or reading the X11 backbuffer cares about this. + ViewportCommand::ContentProtected(x) => { + self.window.set_content_protected(*x); + } + + ViewportCommand::CursorGrab(CursorGrab::Confined) => { + _ = self.window.set_cursor_grab(CursorGrabMode::Confined); + } + ViewportCommand::CursorGrab(CursorGrab::Locked) => { + _ = self.window.set_cursor_grab(CursorGrabMode::Locked); + } + ViewportCommand::CursorGrab(CursorGrab::None) => { + _ = self.window.set_cursor_grab(CursorGrabMode::None); + } + ViewportCommand::CursorVisible(visible) => { + self.window.set_cursor_visible(*visible); + } + ViewportCommand::RequestCut => { + self.input_events.push(egui::Event::Cut); + } + ViewportCommand::RequestCopy => { + self.input_events.push(egui::Event::Copy); + } + ViewportCommand::RequestPaste => { + if let Some(content) = self.egui_winit.clipboard_text() { + self.input_events.push(egui::Event::Paste(content)); + } + } + ViewportCommand::MousePassthrough(_) => { + //UNSUPPORTED + } + ViewportCommand::Screenshot(_) => { + //UNSUPPORTED (YET) + } + ViewportCommand::BeginResize(_) => { + //UNSUPPORTED + } + ViewportCommand::IMERect(_) => { + //UNSUPPORTED + } + ViewportCommand::IMEAllowed(_) => { + //UNSUPPORTED + } + ViewportCommand::IMEPurpose(_) => { + //UNSUPPORTED + } + ViewportCommand::CursorPosition(_) => { + //UNSUPPORTED + } + ViewportCommand::RequestUserAttention(_) => { + //UNSUPPORTED + } + ViewportCommand::StartDrag => { + //UNSUPPORTED + } + } + + if die { + self.window.set_visible(false); //I wish eframe did this. + elwt.exit(); + } + } + }); + }); + + //Makes the clipboard work. + self.egui_winit + .handle_platform_output(self.window.deref(), full_output.platform_output); + + let clipped_primitives = self + .egui_context + .tessellate(full_output.shapes, full_output.pixels_per_point); + + let mut buffer = + self.surface + .buffer_mut() + .map_err(SoftwareBackendAppError::soft_buffer( + "softbuffer::Surface::buffer_mut", + ))?; + buffer.fill(0); // CLEAR + + let buffer_ref = &mut BufferMutRef::new( + bytemuck::cast_slice_mut(&mut buffer), + width.get() as usize, + height.get() as usize, + ); + + self.renderer.render( + buffer_ref, + &clipped_primitives, + &full_output.textures_delta, + full_output.pixels_per_point, + ); + + buffer + .present() + .map_err(SoftwareBackendAppError::soft_buffer( + "softbuffer::Buffer::present", + ))?; + + self.software_backend.last_frame_time = start.map(|a| a.elapsed()); + } + + WindowEvent::CloseRequested => { + self.egui_app.on_exit(&self.egui_context); + elwt.exit(); + } + _ => { + let response = self + .egui_winit + .on_window_event(self.window.deref(), &window_event); + + if response.repaint { + // Redraw when egui says it's necessary (e.g., mouse move, key press): + self.window.request_redraw(); + } + } + }; + + Ok(()) + } +} + +/// This struct contains statistics as well as possible interactions with the software renderer. +/// +/// # Example +/// ```rust +/// use egui_software_backend::{App, SoftwareBackend}; +/// +/// struct MyApp { +/// +/// } +/// +/// impl App for MyApp { +/// fn ui(&mut self, ui: &mut egui::Ui, backend: &mut SoftwareBackend) { +/// backend.set_capture_frame_time(true); +/// +/// +/// egui::CentralPanel::default().show_inside(ui, |ui| { +/// ui.label(format!( +/// "Frame Time {}ms", +/// backend.last_frame_time().unwrap_or_default().as_millis() +/// )); +/// }); +/// } +/// } +/// +/// ``` +pub struct SoftwareBackend { + capture_frame_time: bool, + last_frame_time: Option, +} + +impl SoftwareBackend { + /// Returns true if the frame time for the next frame is captured. + pub fn is_capture_frame_time(&self) -> bool { + self.capture_frame_time + } + + /// Enables or disables capturing the frame time. + /// Note that once this is called, the value persists until this function is called again. + /// Calling this with true will not affect the current frame, so once this is called with true, + /// you will need to wait for 2 more frames until you get a value. + pub fn set_capture_frame_time(&mut self, capture: bool) { + self.capture_frame_time = capture; + } + + /// Returns the rendering duration of the last frame if this information is available. + /// Returns none otherwise. Note that this information is only captured is `set_capture_frame_time` + /// is called with true. + pub fn last_frame_time(&self) -> Option { + self.last_frame_time + } +} + +/// Implement this trait to write apps using the optional winit backend similarly to eframe's App. +pub trait App { + fn ui(&mut self, ui: &mut egui::Ui, software_backend: &mut SoftwareBackend); + + fn on_exit(&mut self, _ctx: &Context) {} +} + +/// Used to initialize the software render backend app, renderer, and winit configuration. +#[derive(Debug, Clone)] +pub struct SoftwareBackendAppConfiguration { + /// The underlying egui viewport builder that is used to create the window with winit. + pub viewport_builder: ViewportBuilder, + + /// If true: rasterized ClippedPrimitives are cached and rendered to an intermediate tiled canvas. That canvas is + /// then rendered over the frame buffer. If false ClippedPrimitives are rendered directly to the frame buffer. + /// Rendering without caching is much slower and primarily intended for testing. + /// + /// Default is true! + pub allow_raster_opt: bool, + + /// If true: attempts to optimize by converting suitable triangle pairs into rectangles for faster rendering. + /// Things *should* look the same with this set to `true` while rendering faster. + /// + /// Default is true! + pub convert_tris_to_rects: bool, + + /// If true: rasterized ClippedPrimitives are cached and rendered to an intermediate tiled canvas. That canvas is + /// then rendered over the frame buffer. If false ClippedPrimitives are rendered directly to the frame buffer. + /// Rendering without caching is much slower and primarily intended for testing. + /// + /// Default is true! + pub caching: bool, +} + +impl SoftwareBackendAppConfiguration { + /// Creates a new SoftwareBackendAppConfiguration using the default configuration. + pub const fn new() -> Self { + //The constructor is not const. + let vp = ViewportBuilder { + override_redirect: None, + title: None, + app_id: None, + position: None, + //CGA + inner_size: Some(Vec2::new(320f32, 200f32)), + min_inner_size: None, + max_inner_size: None, + clamp_size_to_monitor_size: None, + fullscreen: None, + maximized: None, + resizable: None, + transparent: None, + decorations: None, + icon: None, + active: None, + visible: None, + fullsize_content_view: None, + movable_by_window_background: None, + title_shown: None, + titlebar_buttons_shown: None, + titlebar_shown: None, + has_shadow: None, + drag_and_drop: None, + taskbar: None, + close_button: None, + minimize_button: None, + maximize_button: None, + window_level: None, + mouse_passthrough: None, + window_type: None, + }; + + Self { + viewport_builder: vp, + + allow_raster_opt: true, + convert_tris_to_rects: true, + caching: true, + } + } + + /// This sets the egui viewport builder to the given builder. This replaces most settings. + pub fn viewport_builder(mut self, viewport_builder: ViewportBuilder) -> Self { + self.viewport_builder = viewport_builder; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub fn title(mut self, title: Option) -> Self { + self.viewport_builder.title = title; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub fn app_id(mut self, app_id: Option) -> Self { + self.viewport_builder.app_id = app_id; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub const fn position(mut self, position: Option) -> Self { + self.viewport_builder.position = position; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub const fn inner_size(mut self, inner_size: Option) -> Self { + self.viewport_builder.inner_size = inner_size; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub const fn min_inner_size(mut self, min_inner_size: Option) -> Self { + self.viewport_builder.min_inner_size = min_inner_size; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub const fn max_inner_size(mut self, max_inner_size: Option) -> Self { + self.viewport_builder.max_inner_size = max_inner_size; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub const fn clamp_size_to_monitor_size( + mut self, + clamp_size_to_monitor_size: Option, + ) -> Self { + self.viewport_builder.clamp_size_to_monitor_size = clamp_size_to_monitor_size; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub const fn fullscreen(mut self, fullscreen: Option) -> Self { + self.viewport_builder.fullscreen = fullscreen; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub const fn maximized(mut self, maximized: Option) -> Self { + self.viewport_builder.maximized = maximized; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub const fn resizable(mut self, resizable: Option) -> Self { + self.viewport_builder.resizable = resizable; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub const fn transparent(mut self, transparent: Option) -> Self { + self.viewport_builder.transparent = transparent; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub const fn decorations(mut self, decorations: Option) -> Self { + self.viewport_builder.decorations = decorations; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub fn icon(mut self, icon: Option>) -> Self { + self.viewport_builder.icon = icon; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub fn active(mut self, active: Option) -> Self { + self.viewport_builder.active = active; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub fn visible(mut self, visible: Option) -> Self { + self.viewport_builder.visible = visible; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub fn fullsize_content_view(mut self, fullsize_content_view: Option) -> Self { + self.viewport_builder.fullsize_content_view = fullsize_content_view; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub fn movable_by_window_background( + mut self, + movable_by_window_background: Option, + ) -> Self { + self.viewport_builder.movable_by_window_background = movable_by_window_background; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub fn title_shown(mut self, title_shown: Option) -> Self { + self.viewport_builder.title_shown = title_shown; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub fn titlebar_buttons_shown(mut self, titlebar_buttons_shown: Option) -> Self { + self.viewport_builder.titlebar_buttons_shown = titlebar_buttons_shown; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub fn titlebar_shown(mut self, titlebar_shown: Option) -> Self { + self.viewport_builder.titlebar_shown = titlebar_shown; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub fn has_shadow(mut self, has_shadow: Option) -> Self { + self.viewport_builder.has_shadow = has_shadow; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub fn drag_and_drop(mut self, drag_and_drop: Option) -> Self { + self.viewport_builder.has_shadow = drag_and_drop; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub fn taskbar(mut self, taskbar: Option) -> Self { + self.viewport_builder.has_shadow = taskbar; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub const fn close_button(mut self, close_button: Option) -> Self { + self.viewport_builder.close_button = close_button; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub const fn minimize_button(mut self, minimize_button: Option) -> Self { + self.viewport_builder.minimize_button = minimize_button; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub const fn maximize_button(mut self, maximize_button: Option) -> Self { + self.viewport_builder.maximize_button = maximize_button; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub const fn window_level(mut self, window_level: Option) -> Self { + self.viewport_builder.window_level = window_level; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub const fn mouse_passthrough(mut self, mouse_passthrough: Option) -> Self { + self.viewport_builder.mouse_passthrough = mouse_passthrough; + self + } + + /// See egui::viewport::ViewportBuilder. This is a convenience function that sets the field. + pub const fn window_type(mut self, window_type: Option) -> Self { + self.viewport_builder.window_type = window_type; + self + } + + /// If false: Rasterize everything with triangles, always calculate vertex colors, uvs, use bilinear + /// everywhere, etc... Things *should* look the same with this set to `true` while rendering faster. + /// + /// Default is true! + pub const fn allow_raster_opt(mut self, allow_raster_opt: bool) -> Self { + self.allow_raster_opt = allow_raster_opt; + self + } + + /// If true: attempts to optimize by converting suitable triangle pairs into rectangles for faster rendering. + /// Things *should* look the same with this set to `true` while rendering faster. + /// + /// Default is true! + pub const fn convert_tris_to_rects(mut self, convert_tris_to_rects: bool) -> Self { + self.convert_tris_to_rects = convert_tris_to_rects; + self + } + + /// If true: rasterized ClippedPrimitives are cached and rendered to an intermediate tiled canvas. That canvas is + /// then rendered over the frame buffer. If false ClippedPrimitives are rendered directly to the frame buffer. + /// Rendering without caching is much slower and primarily intended for testing. + /// + /// Default is true! + pub const fn caching(mut self, caching: bool) -> Self { + self.caching = caching; + self + } +} + +impl Default for SoftwareBackendAppConfiguration { + fn default() -> Self { + Self::new() + } +} + +const ONE_PIXEL: NonZeroU32 = NonZeroU32::new(1).unwrap(); + +/// Starts the app. +pub fn run_app_with_software_backend( + settings: SoftwareBackendAppConfiguration, + egui_app_factory: impl FnMut(Context) -> T, +) -> Result<(), SoftwareBackendAppError> { + let egui_software_render = EguiSoftwareRender::new(ColorFieldOrder::Bgra) + .with_allow_raster_opt(settings.allow_raster_opt) + .with_convert_tris_to_rects(settings.convert_tris_to_rects) + .with_caching(settings.caching); + + let event_loop: EventLoop = EventLoop::with_user_event() + .build() + .map_err(|e| SoftwareBackendAppError::EventLoop(Box::new(e)))?; + + let softbuffer_context = softbuffer::Context::new(event_loop.owned_display_handle()).map_err( + SoftwareBackendAppError::soft_buffer("softbuffer::Context::new"), + )?; + + let egui_ctx = Context::default(); + + let event_loop_proxy = event_loop.create_proxy(); + egui_ctx.set_request_repaint_callback(move |info| { + let when = Instant::now() + info.delay; + let cumulative_pass_nr = info.current_cumulative_pass_nr; + event_loop_proxy + .send_event(UserEvent::RequestRepaint { + viewport_id: info.viewport_id, + when, + cumulative_pass_nr, + }) + .ok(); + }); + + let mut app = WinitAppStateMachine::new( + settings.clone(), + egui_software_render, + softbuffer_context, + egui_app_factory, + egui_ctx, + ); + + if let Err(event_loop_error) = event_loop.run_app(&mut app) { + if let WinitAppStateMachine::Dead(Some(app_err)) = app { + return Err(SoftwareBackendAppError::SuppressedEventLoop { + event_loop_error: Box::new(event_loop_error), + suppressed: Box::new(app_err), + }); + } + + return Err(SoftwareBackendAppError::EventLoop(Box::new( + event_loop_error, + ))); + } + + if let WinitAppStateMachine::Dead(Some(app_err)) = app { + return Err(app_err); + } + + Ok(()) +}