From 35576f92143958346c51a8530a77d7fd6eb50f2c Mon Sep 17 00:00:00 2001 From: Jonathan Johnson Date: Sat, 9 Dec 2023 13:18:46 -0800 Subject: [PATCH] Image widget Closes #23 (Feels good to close a 3 year old issue!) --- Cargo.lock | 6 +- Cargo.toml | 2 +- examples/image.rs | 84 +++++++++++++++ examples/tilemap.rs | 8 +- src/animation.rs | 12 ++- src/value.rs | 6 ++ src/widgets.rs | 2 + src/widgets/custom.rs | 2 +- src/widgets/image.rs | 229 ++++++++++++++++++++++++++++++++++++++++ src/widgets/layers.rs | 3 +- src/widgets/progress.rs | 2 +- src/widgets/scroll.rs | 2 +- src/window.rs | 2 +- 13 files changed, 344 insertions(+), 16 deletions(-) create mode 100644 examples/image.rs create mode 100644 src/widgets/image.rs diff --git a/Cargo.lock b/Cargo.lock index 86b737a..2f7ec83 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1062,7 +1062,7 @@ checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" [[package]] name = "kludgine" version = "0.1.0" -source = "git+https://github.com/khonsulabs/kludgine#924198daa5fc9fe758efd7c56084f8a05ef783d1" +source = "git+https://github.com/khonsulabs/kludgine#a9c9335df7c40f695c82b4ac74c63330d8021885" dependencies = [ "ahash", "alot", @@ -1942,9 +1942,9 @@ checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" [[package]] name = "rustix" -version = "0.38.27" +version = "0.38.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfeae074e687625746172d639330f1de242a178bf3189b51e35a7a21573513ac" +checksum = "72e572a5e8ca657d7366229cdde4bd14c4eb5499a9573d4d366fe1b599daa316" dependencies = [ "bitflags 2.4.1", "errno", diff --git a/Cargo.toml b/Cargo.toml index 11a2cb0..7f40e3e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,7 @@ unicode-segmentation = "1.10.1" # [patch."https://github.com/khonsulabs/figures"] # figures = { path = "../figures" } -[patch.crates-io] +# [patch.crates-io] # alot = { git = "https://github.com/khonsulabs/alot" } # kempt = { path = "../objectmap" } diff --git a/examples/image.rs b/examples/image.rs new file mode 100644 index 0000000..7ac677c --- /dev/null +++ b/examples/image.rs @@ -0,0 +1,84 @@ +use gooey::animation::ZeroToOne; +use gooey::value::{Dynamic, MapEachCloned}; +use gooey::widget::MakeWidget; +use gooey::widgets::image::{Aspect, ImageScaling}; +use gooey::widgets::slider::Slidable; +use gooey::widgets::Image; +use gooey::Run; +use kludgine::figures::Size; +use kludgine::include_texture; + +fn main() -> gooey::Result { + let mode = Dynamic::::default(); + let scale = Dynamic::new(1f32); + let orientation_width = Dynamic::::default(); + let orientation_height = Dynamic::::default(); + let orientation = (&orientation_width, &orientation_height) + .map_each_cloned(|(width, height)| Size::new(width, height)); + let aspect_mode = Dynamic::::default(); + let image_scaling = (&mode, &scale, &aspect_mode, &orientation).map_each_cloned( + |(mode, scale, aspect_mode, orientation)| match mode { + ScalingMode::Aspect => ImageScaling::Aspect { + mode: aspect_mode, + orientation, + }, + ScalingMode::Stretch => ImageScaling::Stretch, + ScalingMode::Scale => ImageScaling::Scale(scale), + }, + ); + let hide_scale_editor = mode.map_each(|scale| !matches!(scale, ScalingMode::Scale)); + let scale_editor = scale + .slider_between(0., 3.) + .contain() + .collapse_vertically(hide_scale_editor); + + let image = Image::new(include_texture!("assets/ferris-happy.png").expect("valid image")); + + let origin_select = "Origin" + .h3() + .and("Width Orientation") + .and(orientation_width.slider()) + .and("Height Orientation") + .and(orientation_height.slider()) + .into_rows(); + + let apsect_mode_select = "Mode" + .h3() + .and(aspect_mode.new_radio(Aspect::Fit, "Fit")) + .and(aspect_mode.new_radio(Aspect::Fill, "Fill")) + .into_rows(); + + let hide_aspect_editor = mode.map_each(|scale| !matches!(scale, ScalingMode::Aspect)); + let aspect_editor = origin_select + .and(apsect_mode_select) + .into_rows() + .contain() + .collapse_vertically(hide_aspect_editor); + + let mode_select = "Scaling Mode" + .h1() + .and(mode.new_radio(ScalingMode::Scale, "Scale")) + .and(scale_editor) + .and( + mode.new_radio(ScalingMode::Aspect, "Aspect") + .and(aspect_editor) + .into_rows(), + ) + .and(mode.new_radio(ScalingMode::Stretch, "Stretch")) + .into_rows(); + + mode_select + .and(image.scaling(image_scaling).expand().contain()) + .into_columns() + .pad() + .expand() + .run() +} + +#[derive(Default, Debug, PartialEq, Eq, Clone, Copy)] +enum ScalingMode { + Aspect, + Stretch, + #[default] + Scale, +} diff --git a/examples/tilemap.rs b/examples/tilemap.rs index 4fcb31f..c839ad6 100644 --- a/examples/tilemap.rs +++ b/examples/tilemap.rs @@ -7,7 +7,9 @@ use gooey::kludgine::figures::units::Px; use gooey::kludgine::figures::{Point, Rect, Size}; use gooey::kludgine::render::Renderer; use gooey::kludgine::shapes::Shape; -use gooey::kludgine::tilemap::{Object, ObjectLayer, TileKind, TileMapFocus, Tiles, TILE_SIZE}; +use gooey::kludgine::tilemap::{ + DebugGrid, Object, ObjectLayer, TileArray, TileKind, TileMapFocus, TILE_SIZE, +}; use gooey::kludgine::Color; use gooey::value::Dynamic; use gooey::widgets::TileMap; @@ -35,12 +37,12 @@ fn main() -> gooey::Result { let sprite = include_aseprite_sprite!("assets/grass").unwrap(); let layers = Dynamic::new(( - Tiles::new( - 8, + TileArray::new( 8, array::from_fn::<_, 64, _>(|_| TileKind::Sprite(sprite.clone())), ), characters, + DebugGrid, )); let tilemap = TileMap::dynamic(layers.clone()) diff --git a/src/animation.rs b/src/animation.rs index 2a404c7..ad47e9c 100644 --- a/src/animation.rs +++ b/src/animation.rs @@ -52,7 +52,7 @@ use alot::{LotId, Lots}; use intentional::Cast; use kempt::Set; use kludgine::figures::units::{Lp, Px, UPx}; -use kludgine::figures::{Ranged, UnscaledUnit}; +use kludgine::figures::{Ranged, UnscaledUnit, Zero}; use kludgine::Color; use crate::animation::easings::Linear; @@ -1074,8 +1074,6 @@ pub struct ZeroToOne(f32); impl ZeroToOne { /// The maximum value this type can contain. pub const ONE: Self = Self(1.); - /// The minimum type this type can contain. - pub const ZERO: Self = Self(0.); /// Returns a new instance after clamping `value` between +0.0 and 1.0. /// @@ -1108,6 +1106,14 @@ impl ZeroToOne { } } +impl Zero for ZeroToOne { + const ZERO: Self = Self(0.); + + fn is_zero(&self) -> bool { + *self == 0. + } +} + impl Display for ZeroToOne { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { Display::fmt(&self.0, f) diff --git a/src/value.rs b/src/value.rs index 583bbfe..eeb0f01 100644 --- a/src/value.rs +++ b/src/value.rs @@ -1756,6 +1756,12 @@ impl IntoValue for Dynamic { } } +impl IntoValue for &'_ Dynamic { + fn into_value(self) -> Value { + Value::Dynamic(self.clone()) + } +} + impl IntoValue for Value { fn into_value(self) -> Value { self diff --git a/src/widgets.rs b/src/widgets.rs index 680a9ee..a0e395c 100644 --- a/src/widgets.rs +++ b/src/widgets.rs @@ -10,6 +10,7 @@ mod custom; mod data; mod expand; pub mod grid; +pub mod image; pub mod input; pub mod label; pub mod layers; @@ -37,6 +38,7 @@ pub use container::Container; pub use custom::Custom; pub use data::Data; pub use expand::Expand; +pub use image::Image; pub use input::Input; pub use label::Label; pub use layers::Layers; diff --git a/src/widgets/custom.rs b/src/widgets/custom.rs index 1f7b365..2f60f18 100644 --- a/src/widgets/custom.rs +++ b/src/widgets/custom.rs @@ -19,7 +19,7 @@ use crate::ConstraintLimit; /// A callback-based custom widget. /// /// This type can be used to create inline widgets without defining a new type -/// and implementing [`Widget`]/[`WrapperWidget`] for it. +/// and implementing [`Widget`](crate::widget::Widget)/[`WrapperWidget`] for it. #[must_use] pub struct Custom { child: WidgetRef, diff --git a/src/widgets/image.rs b/src/widgets/image.rs new file mode 100644 index 0000000..5d0a943 --- /dev/null +++ b/src/widgets/image.rs @@ -0,0 +1,229 @@ +//! A widget that displays an image/texture. + +use kludgine::figures::units::UPx; +use kludgine::figures::{FloatConversion, IntoSigned, Point, Rect, Size, Zero}; +use kludgine::{AnyTexture, CollectedTexture, SharedTexture, Texture, TextureRegion}; + +use crate::animation::ZeroToOne; +use crate::context::LayoutContext; +use crate::value::{IntoValue, Value}; +use crate::widget::Widget; +use crate::ConstraintLimit; + +/// A widget that displays an image/texture. +#[derive(Debug)] +pub struct Image { + /// The texture to render. + pub contents: Value, + /// The scaling strategy to apply. + pub scaling: Value, +} + +impl Image { + /// Returns a new image widget that renders `contents`, using the default + /// [`ImageScaling`] strategy. + pub fn new(contents: impl IntoValue) -> Self { + Self { + contents: contents.into_value(), + scaling: Value::default(), + } + } + + /// Applies the `scaling` strategies and returns self. + #[must_use] + pub fn scaling(mut self, scaling: impl IntoValue) -> Self { + self.scaling = scaling.into_value(); + self + } + + /// Applies the aspect-fit scaling strategy and returns self. + /// + /// The aspect-fit scaling strategy scales the image to be the largest size + /// it can be without clipping. Any remaining whitespace will be at the + /// right or bottom edge. + /// + /// To apply a different orientation for the whitespace, use + /// [`Self::aspect_fit_around`]. + #[must_use] + pub fn aspect_fit(self) -> Self { + self.aspect_fit_around(Size::ZERO) + } + + /// Applies the aspect-fit scaling strategy and returns self. + /// + /// The aspect-fit scaling strategy scales the image to be the largest size + /// it can be without clipping. Any remaining whitespace will be divided + /// using the ratio `orientation`. + #[must_use] + pub fn aspect_fit_around(self, orientation: Size) -> Self { + self.scaling(ImageScaling::Aspect { + mode: Aspect::Fit, + orientation, + }) + } + + /// Applies the aspect-fill scaling strategy and returns self. + /// + /// The aspect-fill scaling strategy scales the image to be the smallest + /// size it can be to cover the entire surface. The bottom or right sides of + /// the image will be clipped. + /// + /// To apply a different orientation for the clipping, use + /// [`Self::aspect_fill_around`]. + #[must_use] + pub fn aspect_fill(self) -> Self { + self.aspect_fill_around(Size::ZERO) + } + + /// Applies the aspect-fill scaling strategy and returns self. + /// + /// The aspect-fill scaling strategy scales the image to be the smallest + /// size it can be to cover the entire surface. The side that is cropped + /// will be positioned using `orientation`. + #[must_use] + pub fn aspect_fill_around(self, orientation: Size) -> Self { + self.scaling(ImageScaling::Aspect { + mode: Aspect::Fill, + orientation, + }) + } + + /// Applies the stretch scaling strategy and returns self. + /// + /// The stretch scaling strategy stretches the image to fill the surface, + /// ignoring the aspect ratio. + #[must_use] + pub fn stretch(self) -> Self { + self.scaling(ImageScaling::Stretch) + } + + /// Applies a scaling factor strategy and returns self. + /// + /// The image will be displayed at a scaling factor of `amount`. In this + /// mode, the widget will request that its size be the size of the contained + /// image. + #[must_use] + pub fn scaled(self, amount: impl IntoValue) -> Self { + self.scaling(match amount.into_value() { + Value::Constant(amount) => Value::Constant(ImageScaling::Scale(amount)), + Value::Dynamic(amount) => Value::Dynamic(amount.map_each_cloned(ImageScaling::Scale)), + }) + } +} + +impl Widget for Image { + fn redraw(&mut self, context: &mut crate::context::GraphicsContext<'_, '_, '_, '_, '_>) { + self.contents.map(|texture| { + let size = texture.size().into_signed(); + let rect = match self.scaling.get() { + ImageScaling::Aspect { mode, orientation } => { + let scale_width = + context.gfx.region().size.width.into_float() / size.width.into_float(); + let scale_height = + context.gfx.region().size.height.into_float() / size.height.into_float(); + + let effective_scale = match mode { + Aspect::Fill => scale_width.max(scale_height), + Aspect::Fit => scale_width.min(scale_height), + }; + let scaled = size * effective_scale; + + let x = (context.gfx.region().size.width - scaled.width) * *orientation.width; + let y = + (context.gfx.region().size.height - scaled.height) * *orientation.height; + + Rect::new(Point::new(x, y), scaled) + } + ImageScaling::Stretch => context.gfx.region().size.into(), + ImageScaling::Scale(factor) => { + let size = size.map(|px| px * factor); + size.into() + } + }; + context.gfx.draw_texture(texture, rect); + }); + } + + fn layout( + &mut self, + available_space: Size, + context: &mut LayoutContext<'_, '_, '_, '_, '_>, + ) -> Size { + self.scaling.invalidate_when_changed(context); + + match self.scaling.get() { + ImageScaling::Aspect { .. } | ImageScaling::Stretch => { + available_space.map(ConstraintLimit::min) + } + ImageScaling::Scale(factor) => { + self.contents.invalidate_when_changed(context); + self.contents.map(AnyTexture::size).map(|px| px * factor) + } + } + } +} + +/// A scaling strategy for an [`Image`] widget. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum ImageScaling { + /// Scales the image keeping the aspect ratio the same. + Aspect { + /// The strategy to use to pick a scaling factor. + mode: Aspect, + /// The orientation to either crop or align using. + orientation: Size, + }, + + /// The stretch scaling strategy stretches the image to fill the surface, + /// ignoring the aspect ratio. + Stretch, + + /// The image will be displayed at a scaling factor of the contained `f32`. + /// In this mode, the widget will request that its size be the size of the + /// contained image. + Scale(f32), +} + +impl Default for ImageScaling { + /// Returns `ImageScaling::Scale(1.)`. + fn default() -> Self { + Self::Scale(1.) + } +} + +impl IntoValue for Texture { + fn into_value(self) -> Value { + Value::Constant(AnyTexture::from(self)) + } +} + +impl IntoValue for SharedTexture { + fn into_value(self) -> Value { + Value::Constant(AnyTexture::from(self)) + } +} + +impl IntoValue for CollectedTexture { + fn into_value(self) -> Value { + Value::Constant(AnyTexture::from(self)) + } +} + +impl IntoValue for TextureRegion { + fn into_value(self) -> Value { + Value::Constant(AnyTexture::from(self)) + } +} + +/// An aspect mode for scaling an [`Image`]. +#[derive(Default, Debug, Clone, Copy, Eq, PartialEq)] +pub enum Aspect { + /// The aspect-fit scaling strategy scales the image to be the largest size + /// it can be without clipping. + #[default] + Fit, + + /// The aspect-fill scaling strategy scales the image to be the smallest + /// size it can be to cover the entire surface. + Fill, +} diff --git a/src/widgets/layers.rs b/src/widgets/layers.rs index 583d388..eac04c4 100644 --- a/src/widgets/layers.rs +++ b/src/widgets/layers.rs @@ -168,8 +168,7 @@ impl Widget for Layers { /// A widget that displays other widgets relative to widgets in another layer. /// -/// This widget is for use inside of a [`Layers`](crate::widgets::Layers) -/// widget. +/// This widget is for use inside of a [`Layers`] widget. #[derive(Debug, Clone, Default)] pub struct OverlayLayer { state: Dynamic, diff --git a/src/widgets/progress.rs b/src/widgets/progress.rs index 67678ca..33d314e 100644 --- a/src/widgets/progress.rs +++ b/src/widgets/progress.rs @@ -3,7 +3,7 @@ use std::ops::RangeInclusive; use std::time::Duration; -use kludgine::figures::Ranged; +use kludgine::figures::{Ranged, Zero}; use crate::animation::easings::{EaseInOutQuadradic, EaseOutQuadradic}; use crate::animation::{ diff --git a/src/widgets/scroll.rs b/src/widgets/scroll.rs index cc9ae95..4088c1e 100644 --- a/src/widgets/scroll.rs +++ b/src/widgets/scroll.rs @@ -6,7 +6,7 @@ use kludgine::app::winit::event::{DeviceId, MouseScrollDelta, TouchPhase}; use kludgine::app::winit::window::CursorIcon; use kludgine::figures::units::{Lp, Px, UPx}; use kludgine::figures::{ - FloatConversion, IntoSigned, IntoUnsigned, Point, Rect, ScreenScale, Size, + FloatConversion, IntoSigned, IntoUnsigned, Point, Rect, ScreenScale, Size, Zero, }; use kludgine::shapes::Shape; use kludgine::Color; diff --git a/src/window.rs b/src/window.rs index 81d427a..4163e14 100644 --- a/src/window.rs +++ b/src/window.rs @@ -21,7 +21,7 @@ use kludgine::app::winit::window; use kludgine::app::WindowBehavior as _; use kludgine::cosmic_text::{Family, FamilyOwned}; use kludgine::figures::units::{Px, UPx}; -use kludgine::figures::{IntoSigned, IntoUnsigned, Point, Ranged, Rect, ScreenScale, Size}; +use kludgine::figures::{IntoSigned, IntoUnsigned, Point, Ranged, Rect, ScreenScale, Size, Zero}; use kludgine::render::Drawing; use kludgine::wgpu::CompositeAlphaMode; use kludgine::Kludgine;