use std::{error::Error, fmt};
use bevy_ecs::prelude::Component;
use sim_engine::{Color, Layer, LogicalScreenPosition, LogicalScreenVector};
use crate::assets::ImageAssetId;
use super::{ScreenRectangleVisual, ScreenVisualError};
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ImageFilter {
#[default]
Nearest,
Linear,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ImageRegion {
x: u32,
y: u32,
width: u32,
height: u32,
}
impl ImageRegion {
pub fn new(x: u32, y: u32, width: u32, height: u32) -> Result<Self, ImageVisualError> {
let region = Self {
x,
y,
width,
height,
};
region.validate()?;
Ok(region)
}
pub const fn x(self) -> u32 {
self.x
}
pub const fn y(self) -> u32 {
self.y
}
pub const fn width(self) -> u32 {
self.width
}
pub const fn height(self) -> u32 {
self.height
}
fn validate(self) -> Result<(), ImageVisualError> {
if self.width == 0
|| self.height == 0
|| self.x.checked_add(self.width).is_none()
|| self.y.checked_add(self.height).is_none()
{
return Err(ImageVisualError::InvalidRegion {
x: self.x,
y: self.y,
width: self.width,
height: self.height,
});
}
Ok(())
}
fn validate_image(self, image: ImageAssetId) -> Result<(), ImageVisualError> {
self.validate()?;
if self.x + self.width > image.width() || self.y + self.height > image.height() {
return Err(ImageVisualError::RegionOutOfBounds {
region: self,
image,
});
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Component)]
pub struct ScreenImageVisual {
rotation: f32,
image: ImageAssetId,
source_region: Option<ImageRegion>,
filter: ImageFilter,
rectangle: ScreenRectangleVisual,
}
impl ScreenImageVisual {
pub const fn rotation(&self) -> f32 {
self.rotation
}
pub fn set_rotation(&mut self, radians: f32) -> Result<(), ImageVisualError> {
if !radians.is_finite() {
return Err(ScreenVisualError::InvalidRotation { value: radians }.into());
}
self.rotation = radians.rem_euclid(std::f32::consts::TAU);
Ok(())
}
pub fn contains_pointer(&self, sample: crate::input::PointerSample) -> bool {
if !self.clip().contains_pointer(sample) {
return false;
}
let size = self.size().to_vec2();
let min = self.position().to_vec2();
let p = sample.position().to_vec2();
let x = f64::from(p.x()) - (f64::from(min.x()) + f64::from(size.x()) * 0.5);
let y = f64::from(p.y()) - (f64::from(min.y()) + f64::from(size.y()) * 0.5);
let (sin, cos) = f64::from(self.rotation).sin_cos();
let local_x = x * cos + y * sin + f64::from(size.x()) * 0.5;
let local_y = -x * sin + y * cos + f64::from(size.y()) * 0.5;
local_x >= 0.0
&& local_y >= 0.0
&& local_x < f64::from(size.x())
&& local_y < f64::from(size.y())
}
pub const fn clip(&self) -> super::ScreenClip {
self.rectangle.clip()
}
pub fn set_clip(&mut self, clip: super::ScreenClip) {
self.rectangle.set_clip(clip);
}
pub fn new(
image: ImageAssetId,
position: LogicalScreenPosition,
size: LogicalScreenVector,
) -> Result<Self, ImageVisualError> {
Ok(Self {
rotation: 0.0,
image,
source_region: None,
filter: ImageFilter::Nearest,
rectangle: ScreenRectangleVisual::new(position, size, Color::WHITE)?,
})
}
pub const fn image(&self) -> ImageAssetId {
self.image
}
pub const fn source_region(&self) -> Option<ImageRegion> {
self.source_region
}
pub const fn filter(&self) -> ImageFilter {
self.filter
}
pub const fn position(&self) -> LogicalScreenPosition {
self.rectangle.position()
}
pub const fn size(&self) -> LogicalScreenVector {
self.rectangle.size()
}
pub const fn tint(&self) -> Color {
self.rectangle.color()
}
pub const fn layer(&self) -> Layer {
self.rectangle.layer()
}
pub const fn draw_order_depth(&self) -> f32 {
self.rectangle.draw_order_depth()
}
pub fn set_image(&mut self, image: ImageAssetId) -> Result<(), ImageVisualError> {
if let Some(region) = self.source_region {
region.validate_image(image)?;
}
self.image = image;
Ok(())
}
pub fn set_source_region(
&mut self,
region: Option<ImageRegion>,
) -> Result<(), ImageVisualError> {
if let Some(region) = region {
region.validate_image(self.image)?;
}
self.source_region = region;
Ok(())
}
pub fn set_filter(&mut self, filter: ImageFilter) {
self.filter = filter;
}
pub fn set_geometry(
&mut self,
position: LogicalScreenPosition,
size: LogicalScreenVector,
) -> Result<(), ImageVisualError> {
self.rectangle.set_geometry(position, size)?;
Ok(())
}
pub fn set_position(
&mut self,
position: LogicalScreenPosition,
) -> Result<(), ImageVisualError> {
self.rectangle.set_position(position)?;
Ok(())
}
pub fn set_size(&mut self, size: LogicalScreenVector) -> Result<(), ImageVisualError> {
self.rectangle.set_size(size)?;
Ok(())
}
pub fn set_tint(&mut self, tint: Color) -> Result<(), ImageVisualError> {
self.rectangle.set_color(tint)?;
Ok(())
}
pub fn set_layer(&mut self, layer: Layer) {
self.rectangle.set_layer(layer);
}
pub fn set_draw_order_depth(&mut self, depth: f32) -> Result<(), ImageVisualError> {
self.rectangle.set_draw_order_depth(depth)?;
Ok(())
}
pub(crate) fn validate(&self) -> Result<(), ImageVisualError> {
self.rectangle.validate()?;
if let Some(region) = self.source_region {
region.validate_image(self.image)?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum ImageVisualError {
Screen(ScreenVisualError),
InvalidRegion {
x: u32,
y: u32,
width: u32,
height: u32,
},
RegionOutOfBounds {
region: ImageRegion,
image: ImageAssetId,
},
}
impl From<ScreenVisualError> for ImageVisualError {
fn from(source: ScreenVisualError) -> Self {
Self::Screen(source)
}
}
impl fmt::Display for ImageVisualError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Screen(source) => {
write!(formatter, "invalid screen image presentation: {source}")
}
Self::InvalidRegion {
x,
y,
width,
height,
} => write!(
formatter,
"image source region ({x}, {y}, {width}, {height}) needs positive extents and non-overflowing texel bounds"
),
Self::RegionOutOfBounds { region, image } => write!(
formatter,
"image source region {region:?} exceeds image dimensions {} by {}",
image.width(),
image.height()
),
}
}
}
impl Error for ImageVisualError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Screen(source) => Some(source),
_ => None,
}
}
}
#[cfg(test)]
#[path = "image_tests.rs"]
mod tests;