use crate::colour::Colour;
use crate::material::TextureFilter;
use crate::overlay::{NineSlice, OverlayTextureId, TextureTransform};
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum OverlayFill {
Solid(crate::colour::Colour),
LinearGradient {
stops: Vec<GradientStop>,
angle: f32,
},
RadialGradient {
stops: Vec<GradientStop>,
},
ConicalGradient {
stops: Vec<GradientStop>,
offset_angle: f32,
},
SweepGradient {
stops: Vec<GradientStop>,
centre: [f32; 2],
start_angle: f32,
end_angle: f32,
},
Texture {
id: OverlayTextureId,
transform: TextureTransform,
nine_slice: Option<NineSlice>,
tint: crate::colour::Colour,
filter: TextureFilter,
},
Custom {
kind: CustomFillId,
params: [f32; CUSTOM_FILL_PARAMS],
},
}
pub const CUSTOM_FILL_PARAMS: usize = 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CustomFillId(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OverlayFillKind {
Solid,
Gradient,
Texture,
Custom,
}
impl Default for OverlayFill {
fn default() -> Self {
OverlayFill::Solid(Colour::linear(0.0, 0.0, 0.0, 0.55))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub struct GradientStop {
pub position: f32,
pub colour: crate::colour::Colour,
}
impl GradientStop {
pub fn new(position: f32, colour: impl Into<crate::colour::Colour>) -> Self {
Self {
position,
colour: colour.into(),
}
}
pub fn pair(
start: impl Into<crate::colour::Colour>,
end: impl Into<crate::colour::Colour>,
) -> Vec<GradientStop> {
vec![GradientStop::new(0.0, start), GradientStop::new(1.0, end)]
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum OutlineMode {
#[default]
Inset,
Outer,
Centre,
}
impl OverlayFill {
pub fn linear_gradient(
start: impl Into<crate::colour::Colour>,
end: impl Into<crate::colour::Colour>,
angle: f32,
) -> Self {
OverlayFill::LinearGradient {
stops: GradientStop::pair(start, end),
angle,
}
}
pub fn radial_gradient(
centre: impl Into<crate::colour::Colour>,
edge: impl Into<crate::colour::Colour>,
) -> Self {
OverlayFill::RadialGradient {
stops: GradientStop::pair(centre, edge),
}
}
pub fn conical_gradient(
start: impl Into<crate::colour::Colour>,
end: impl Into<crate::colour::Colour>,
offset_angle: f32,
) -> Self {
OverlayFill::ConicalGradient {
stops: GradientStop::pair(start, end),
offset_angle,
}
}
pub fn sweep_gradient(
start: impl Into<crate::colour::Colour>,
end: impl Into<crate::colour::Colour>,
start_angle: f32,
end_angle: f32,
) -> Self {
OverlayFill::SweepGradient {
stops: GradientStop::pair(start, end),
centre: [0.5, 0.5],
start_angle,
end_angle,
}
}
pub fn custom(kind: CustomFillId, params: [f32; CUSTOM_FILL_PARAMS]) -> Self {
OverlayFill::Custom { kind, params }
}
pub fn texture(id: OverlayTextureId) -> Self {
OverlayFill::Texture {
id,
transform: TextureTransform::default(),
nine_slice: None,
tint: crate::colour::Colour::linear(1.0, 1.0, 1.0, 1.0),
filter: TextureFilter::Linear,
}
}
pub fn none() -> Self {
OverlayFill::Solid(crate::colour::Colour::linear(0.0, 0.0, 0.0, 0.0))
}
pub fn is_set(&self) -> bool {
*self != OverlayFill::none()
}
pub fn kind(&self) -> OverlayFillKind {
match self {
OverlayFill::Solid(_) => OverlayFillKind::Solid,
OverlayFill::Texture { .. } => OverlayFillKind::Texture,
OverlayFill::Custom { .. } => OverlayFillKind::Custom,
_ => OverlayFillKind::Gradient,
}
}
pub fn stops(&self) -> Option<&[GradientStop]> {
match self {
OverlayFill::LinearGradient { stops, .. }
| OverlayFill::RadialGradient { stops }
| OverlayFill::ConicalGradient { stops, .. }
| OverlayFill::SweepGradient { stops, .. } => Some(stops),
OverlayFill::Solid(_) | OverlayFill::Texture { .. } | OverlayFill::Custom { .. } => {
None
}
}
}
pub fn texture_id(&self) -> Option<OverlayTextureId> {
match self {
OverlayFill::Texture { id, .. } => Some(*id),
_ => None,
}
}
pub fn with_texture_transform(mut self, tt: TextureTransform) -> Self {
if let OverlayFill::Texture { transform, .. } = &mut self {
*transform = tt;
}
self
}
pub fn with_nine_slice(mut self, ns: NineSlice) -> Self {
if let OverlayFill::Texture { nine_slice, .. } = &mut self {
*nine_slice = Some(ns);
}
self
}
pub fn with_texture_filter(mut self, f: TextureFilter) -> Self {
if let OverlayFill::Texture { filter, .. } = &mut self {
*filter = f;
}
self
}
pub fn with_tint(mut self, colour: impl Into<crate::colour::Colour>) -> Self {
if let OverlayFill::Texture { tint, .. } = &mut self {
*tint = colour.into();
}
self
}
pub fn map_colours(&self, f: impl Fn(Colour) -> Colour) -> OverlayFill {
let stops = |stops: &[GradientStop]| -> Vec<GradientStop> {
stops
.iter()
.map(|s| GradientStop {
position: s.position,
colour: f(s.colour),
})
.collect()
};
match self {
OverlayFill::Solid(c) => OverlayFill::Solid(f(*c)),
OverlayFill::LinearGradient { stops: s, angle } => OverlayFill::LinearGradient {
stops: stops(s),
angle: *angle,
},
OverlayFill::RadialGradient { stops: s } => {
OverlayFill::RadialGradient { stops: stops(s) }
}
OverlayFill::ConicalGradient {
stops: s,
offset_angle,
} => OverlayFill::ConicalGradient {
stops: stops(s),
offset_angle: *offset_angle,
},
OverlayFill::SweepGradient {
stops: s,
centre,
start_angle,
end_angle,
} => OverlayFill::SweepGradient {
stops: stops(s),
centre: *centre,
start_angle: *start_angle,
end_angle: *end_angle,
},
OverlayFill::Texture {
id,
transform,
nine_slice,
tint,
filter,
} => OverlayFill::Texture {
id: *id,
transform: *transform,
nine_slice: *nine_slice,
tint: f(*tint),
filter: *filter,
},
OverlayFill::Custom { kind, params } => OverlayFill::Custom {
kind: *kind,
params: *params,
},
}
}
pub fn sample_in_box(&self, p: [f32; 2], half_size: [f32; 2]) -> [f32; 4] {
match self {
OverlayFill::Solid(c) => c.to_linear_rgba(),
OverlayFill::Texture { tint, .. } => tint.to_linear_rgba(),
OverlayFill::Custom { .. } => [1.0; 4],
OverlayFill::LinearGradient { stops, angle } => {
sample_sorted_stops(stops, linear_t(p, half_size, *angle))
}
OverlayFill::RadialGradient { stops } => {
sample_sorted_stops(stops, radial_t(p, half_size))
}
OverlayFill::ConicalGradient {
stops,
offset_angle,
} => sample_sorted_stops(
stops,
sweep_t(p, [0.0, 0.0], *offset_angle, std::f32::consts::TAU),
),
OverlayFill::SweepGradient {
stops,
centre,
start_angle,
end_angle,
} => {
let c = [
(centre[0] * 2.0 - 1.0) * half_size[0],
(centre[1] * 2.0 - 1.0) * half_size[1],
];
sample_sorted_stops(stops, sweep_t(p, c, *start_angle, end_angle - start_angle))
}
}
}
}
fn linear_t(p: [f32; 2], hs: [f32; 2], angle: f32) -> f32 {
let dir = [angle.cos(), angle.sin()];
let max_proj = (hs[0] * dir[0]).abs() + (hs[1] * dir[1]).abs();
((p[0] * dir[0] + p[1] * dir[1]) / max_proj.max(0.001) * 0.5 + 0.5).clamp(0.0, 1.0)
}
fn radial_t(p: [f32; 2], hs: [f32; 2]) -> f32 {
let max_half = hs[0].max(hs[1]);
((p[0] * p[0] + p[1] * p[1]).sqrt() / max_half.max(0.001)).clamp(0.0, 1.0)
}
fn sweep_t(p: [f32; 2], centre: [f32; 2], start: f32, span: f32) -> f32 {
let tau = std::f32::consts::TAU;
let span = if span > 0.0 { span } else { tau };
let a = (p[1] - centre[1]).atan2(p[0] - centre[0]) - start;
let turned = (a / tau + 1.0).fract() * tau;
(turned / span).clamp(0.0, 1.0)
}
fn sample_sorted_stops(stops: &[GradientStop], t: f32) -> [f32; 4] {
fn lerp(a: [f32; 4], b: [f32; 4], t: f32) -> [f32; 4] {
[
a[0] + (b[0] - a[0]) * t,
a[1] + (b[1] - a[1]) * t,
a[2] + (b[2] - a[2]) * t,
a[3] + (b[3] - a[3]) * t,
]
}
let mut sorted: Vec<&GradientStop> = stops.iter().collect();
sorted.sort_by(|a, b| {
a.position
.partial_cmp(&b.position)
.unwrap_or(std::cmp::Ordering::Equal)
});
let Some(first) = sorted.first() else {
return [0.0; 4];
};
if t <= first.position {
return first.colour.to_linear_rgba();
}
for pair in sorted.windows(2) {
let (a, b) = (pair[0], pair[1]);
if t <= b.position {
let span = (b.position - a.position).max(1e-6);
return lerp(
a.colour.to_linear_rgba(),
b.colour.to_linear_rgba(),
((t - a.position) / span).clamp(0.0, 1.0),
);
}
}
sorted[sorted.len() - 1].colour.to_linear_rgba()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn map_colours_reaches_every_colour() {
let a = Colour::linear(0.2, 0.4, 0.6, 1.0);
let b = Colour::linear(0.8, 0.6, 0.4, 0.5);
let double = |c: Colour| {
let [r, g, b, a] = c.to_linear_rgba();
Colour::linear(r * 2.0, g * 2.0, b * 2.0, a)
};
let stops = vec![
GradientStop::new(0.0, a),
GradientStop::new(0.3, b),
GradientStop::new(0.7, a),
];
let fills = [
OverlayFill::Solid(a),
OverlayFill::linear_gradient(a, b, 0.3),
OverlayFill::radial_gradient(a, b),
OverlayFill::conical_gradient(a, b, 0.3),
OverlayFill::sweep_gradient(a, b, 0.2, 2.0),
OverlayFill::LinearGradient {
stops: stops.clone(),
angle: 0.3,
},
OverlayFill::RadialGradient {
stops: stops.clone(),
},
OverlayFill::SweepGradient {
stops: stops.clone(),
centre: [0.2, 0.7],
start_angle: -1.0,
end_angle: 1.5,
},
OverlayFill::texture(OverlayTextureId(3)).with_tint(a),
];
let p = [3.0, -2.0];
let half = [10.0, 10.0];
for fill in fills {
let mapped = fill.map_colours(double);
assert_eq!(mapped.kind(), fill.kind());
assert_eq!(mapped.texture_id(), fill.texture_id());
if let OverlayFill::Texture { tint, .. } = &mapped {
assert_eq!(*tint, double(a));
continue;
}
let before = fill.sample_in_box(p, half);
let after = mapped.sample_in_box(p, half);
for i in 0..3 {
assert!((after[i] - before[i] * 2.0).abs() < 1e-5, "{fill:?}");
}
assert!((after[3] - before[3]).abs() < 1e-5, "{fill:?}");
}
}
#[test]
fn a_full_turn_sweep_is_a_conical_gradient() {
let a = Colour::linear(1.0, 0.0, 0.0, 1.0);
let b = Colour::linear(0.0, 0.0, 1.0, 1.0);
let conical = OverlayFill::conical_gradient(a, b, 0.4);
let sweep = OverlayFill::sweep_gradient(a, b, 0.4, 0.4 + std::f32::consts::TAU);
for p in [[3.0, -2.0], [-5.0, 1.0], [0.5, 4.0], [-2.0, -6.0]] {
let c = conical.sample_in_box(p, [10.0, 10.0]);
let s = sweep.sample_in_box(p, [10.0, 10.0]);
for i in 0..4 {
assert!((c[i] - s[i]).abs() < 1e-4, "{p:?}");
}
}
}
#[test]
fn a_partial_sweep_holds_its_end_stops_outside_the_arc() {
let a = Colour::linear(1.0, 0.0, 0.0, 1.0);
let b = Colour::linear(0.0, 0.0, 1.0, 1.0);
let sweep = OverlayFill::sweep_gradient(a, b, 0.0, std::f32::consts::FRAC_PI_2);
let half = [10.0, 10.0];
let mid = sweep.sample_in_box([1.0, 1.0], half);
assert!((mid[0] - 0.5).abs() < 1e-4 && (mid[2] - 0.5).abs() < 1e-4);
assert_eq!(sweep.sample_in_box([-1.0, 1.0], half), b.to_linear_rgba());
}
#[test]
fn stops_have_no_cap() {
let stops: Vec<GradientStop> = (0..12)
.map(|i| {
GradientStop::new(
i as f32 / 11.0,
Colour::linear(i as f32 / 11.0, 0.0, 0.0, 1.0),
)
})
.collect();
let fill = OverlayFill::LinearGradient { stops, angle: 0.0 };
let right = fill.sample_in_box([10.0, 0.0], [10.0, 10.0]);
assert!((right[0] - 1.0).abs() < 1e-5);
let near = fill.sample_in_box([9.0, 0.0], [10.0, 10.0]);
assert!((near[0] - 0.95).abs() < 1e-4);
}
}