mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge pull request #8705 from the-unknown/feat/lens-flare-look
feat(filters): Lens Flare looks like Photoshop's (SSIM 0.97–0.995 per lens)
This commit is contained in:
6 files changed
+14900
-109
No files matched your search
@@ -0,0 +1,275 @@
|
||||
//! Filter › Render › Lens Flare.
|
||||
//!
|
||||
//! A flare is built from elements placed along its axis: the line from the flare centre (t = 0)
|
||||
//! through the centre of the image (t = 1), as in a real lens, where the internal reflections line
|
||||
//! up with the optical centre. Each lens has its own set, measured from Photoshop's output
|
||||
//! (`lens_flare_data.rs`):
|
||||
//!
|
||||
//! - radial elements: a colour profile by distance around a point on the axis (the core, glows,
|
||||
//! rings and the reflection discs, with their coloured rims);
|
||||
//! - streaks: straight lines centred on the axis (Movie Prime's horizontal and diagonal streaks, the
|
||||
//! 105 mm Prime's spike);
|
||||
//! - rays: thin one-pixel rays out of the centre, drawn without antialiasing as Photoshop does.
|
||||
//!
|
||||
//! Sizes are in units of 1/800 of the image width: Photoshop sizes a flare by the width alone, the
|
||||
//! same in landscape, square and portrait images. Brightness changes the shape of the elements, not
|
||||
//! just their light (the core grows, the glows widen, at 300 % most lenses wash out to white), so
|
||||
//! each lens is measured at several brightnesses; between two the flare blends them. The light is
|
||||
//! screened onto the pixels.
|
||||
|
||||
use photocraft_geom::Rect;
|
||||
|
||||
use crate::LensType;
|
||||
use crate::fxutil::{rgba, set_rgba, smoothstep};
|
||||
use crate::image::Image;
|
||||
use crate::{Ctx, lens_flare_data as data};
|
||||
|
||||
/// A colour profile by distance (in flare units) around a point on the axis; zero outside the
|
||||
/// first and last knot, linear between knots.
|
||||
pub(crate) struct Radial {
|
||||
pub t: f32,
|
||||
/// Offset across the axis, in flare units.
|
||||
pub perp: f32,
|
||||
pub knots: &'static [(f32, [f32; 3])],
|
||||
}
|
||||
|
||||
/// A straight streak centred on the axis: full strength along `half · (1 − taper)`, fading to
|
||||
/// nothing at `half`; a Gaussian `width` across.
|
||||
pub(crate) struct Streak {
|
||||
pub t: f32,
|
||||
pub perp: f32,
|
||||
/// Degrees, clockwise from the +x axis (image y points down).
|
||||
pub angle: f32,
|
||||
pub half: f32,
|
||||
pub taper: f32,
|
||||
pub width: f32,
|
||||
pub rgb: [f32; 3],
|
||||
}
|
||||
|
||||
/// A one-pixel ray out of the flare centre from radius `r0` to `r1`, fading in and out over
|
||||
/// `fade` of its length.
|
||||
pub(crate) struct Ray {
|
||||
pub angle: f32,
|
||||
pub r0: f32,
|
||||
pub r1: f32,
|
||||
pub fade: f32,
|
||||
pub rgb: [f32; 3],
|
||||
}
|
||||
|
||||
/// A lens's flare at one measured brightness (percent).
|
||||
pub(crate) struct Level {
|
||||
pub brightness: f32,
|
||||
pub radial: &'static [Radial],
|
||||
pub streaks: &'static [Streak],
|
||||
pub rays: &'static [Ray],
|
||||
}
|
||||
|
||||
fn levels(lens: LensType) -> &'static [Level] {
|
||||
match lens {
|
||||
LensType::Zoom => data::ZOOM,
|
||||
LensType::Prime35 => data::PRIME35,
|
||||
LensType::Prime105 => data::PRIME105,
|
||||
LensType::MoviePrime => data::MOVIE_PRIME,
|
||||
}
|
||||
}
|
||||
|
||||
/// The two measured levels around `brightness` and the weight of the second (levels are sorted).
|
||||
fn bracket(levels: &[Level], brightness: f32) -> Option<(&Level, &Level, f32)> {
|
||||
let first = levels.first()?;
|
||||
let last = levels.last()?;
|
||||
if brightness <= first.brightness {
|
||||
return Some((first, first, 0.0));
|
||||
}
|
||||
let i = levels.partition_point(|l| l.brightness < brightness);
|
||||
let Some(hi) = levels.get(i) else { return Some((last, last, 0.0)) };
|
||||
let Some(lo) = i.checked_sub(1).and_then(|j| levels.get(j)) else { return Some((hi, hi, 0.0)) };
|
||||
let span = hi.brightness - lo.brightness;
|
||||
Some((lo, hi, if span > 0.0 { (brightness - lo.brightness) / span } else { 0.0 }))
|
||||
}
|
||||
|
||||
/// The profile at distance `d`; `None` outside it.
|
||||
fn profile(knots: &[(f32, [f32; 3])], d: f32) -> Option<[f32; 3]> {
|
||||
let (first, last) = (knots.first()?, knots.last()?);
|
||||
if d < first.0 || d > last.0 {
|
||||
return None;
|
||||
}
|
||||
// The first knot at or beyond `d` (binary search: profiles have up to a few hundred knots).
|
||||
let i = knots.partition_point(|k| k.0 < d);
|
||||
let Some(hi) = knots.get(i) else { return Some(last.1) };
|
||||
let Some(lo) = i.checked_sub(1).and_then(|j| knots.get(j)) else { return Some(hi.1) };
|
||||
let span = hi.0 - lo.0;
|
||||
let f = if span > 0.0 { (d - lo.0) / span } else { 0.0 };
|
||||
Some(std::array::from_fn(|k| lo.1[k] + (hi.1[k] - lo.1[k]) * f))
|
||||
}
|
||||
|
||||
/// Flare geometry in document pixels, and the output tile it is drawn into.
|
||||
struct Geometry {
|
||||
centre: (f32, f32),
|
||||
/// Axis: image centre minus flare centre.
|
||||
axis: (f32, f32),
|
||||
/// Unit normal to the axis.
|
||||
normal: (f32, f32),
|
||||
/// Pixels per flare unit.
|
||||
unit: f32,
|
||||
/// Output tile: origin and size.
|
||||
origin: (f32, f32),
|
||||
size: (usize, usize),
|
||||
}
|
||||
|
||||
impl Geometry {
|
||||
fn point(&self, t: f32, perp: f32) -> (f32, f32) {
|
||||
(self.centre.0 + t * self.axis.0 + perp * self.unit * self.normal.0, self.centre.1 + t * self.axis.1 + perp * self.unit * self.normal.1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `weight` times the light of one level into `light` (the output tile, row-major).
|
||||
fn add_level(level: &Level, weight: f32, g: &Geometry, light: &mut [[f32; 3]]) {
|
||||
if weight <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let (w, h) = g.size;
|
||||
let (ox, oy) = g.origin;
|
||||
// Radial elements, each only over the pixels it can reach.
|
||||
for e in level.radial {
|
||||
let Some(reach) = e.knots.last().map(|k| k.0 * g.unit) else { continue };
|
||||
let p = g.point(e.t, e.perp);
|
||||
let x0 = ((p.0 - reach - ox).floor().max(0.0) as usize).min(w);
|
||||
let x1 = ((p.0 + reach - ox).ceil().max(0.0) as usize).min(w);
|
||||
let y0 = ((p.1 - reach - oy).floor().max(0.0) as usize).min(h);
|
||||
let y1 = ((p.1 + reach - oy).ceil().max(0.0) as usize).min(h);
|
||||
for y in y0..y1 {
|
||||
let fy = oy + y as f32 + 0.5 - p.1;
|
||||
for x in x0..x1 {
|
||||
let fx = ox + x as f32 + 0.5 - p.0;
|
||||
if let Some(v) = profile(e.knots, fx.hypot(fy) / g.unit)
|
||||
&& let Some(px) = light.get_mut(y * w + x)
|
||||
{
|
||||
for (p, v) in px.iter_mut().zip(v) {
|
||||
*p += weight * v;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for s in level.streaks {
|
||||
let p = g.point(s.t, s.perp);
|
||||
let (sin, cos) = s.angle.to_radians().sin_cos();
|
||||
let half = s.half.max(1e-3);
|
||||
let taper = s.taper.clamp(0.01, 1.0);
|
||||
let width = s.width.max(1e-3);
|
||||
for (i, px) in light.iter_mut().enumerate() {
|
||||
let fx = ox + (i % w) as f32 + 0.5 - p.0;
|
||||
let fy = oy + (i / w) as f32 + 0.5 - p.1;
|
||||
let across = (-fx * sin + fy * cos) / g.unit / width;
|
||||
// NaN comes from overflowing geometry and must not reach the pixels.
|
||||
if across.is_nan() || across.abs() > 4.0 {
|
||||
continue;
|
||||
}
|
||||
let along = ((fx * cos + fy * sin) / g.unit).abs();
|
||||
let k = weight * (1.0 - smoothstep(half * (1.0 - taper), half, along)) * (-across * across).exp();
|
||||
for (p, c) in px.iter_mut().zip(s.rgb) {
|
||||
*p += k * c;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Rays: walk each ray in short steps and light every pixel it crosses once.
|
||||
for r in level.rays {
|
||||
let (sin, cos) = r.angle.to_radians().sin_cos();
|
||||
let (r0, r1) = (r.r0 * g.unit, r.r1 * g.unit);
|
||||
let length = (r1 - r0).max(1e-6);
|
||||
let fade = r.fade.max(1e-3);
|
||||
// Skip a ray whose segment misses this tile: none of its samples can land inside it.
|
||||
let (sx, sy) = (g.centre.0 + r0 * cos, g.centre.1 + r0 * sin);
|
||||
let (ex, ey) = (g.centre.0 + r1 * cos, g.centre.1 + r1 * sin);
|
||||
if sx.max(ex) < ox - 1.0 || sx.min(ex) > ox + w as f32 + 1.0 || sy.max(ey) < oy - 1.0 || sy.min(ey) > oy + h as f32 + 1.0 {
|
||||
continue;
|
||||
}
|
||||
let steps = ((r1 - r0) / 0.35).ceil().clamp(0.0, 1e6) as usize;
|
||||
let mut last = None;
|
||||
for i in 0..steps {
|
||||
let rad = r0 + i as f32 * 0.35;
|
||||
let (px, py) = ((g.centre.0 + rad * cos).floor(), (g.centre.1 + rad * sin).floor());
|
||||
if last == Some((px, py)) {
|
||||
continue;
|
||||
}
|
||||
last = Some((px, py));
|
||||
let (lx, ly) = (px - ox, py - oy);
|
||||
if lx < 0.0 || ly < 0.0 || lx >= w as f32 || ly >= h as f32 {
|
||||
continue;
|
||||
}
|
||||
let pos = (rad - r0) / length;
|
||||
let env = weight * ((pos.min(1.0 - pos)) / fade).clamp(0.0, 1.0);
|
||||
if let Some(v) = light.get_mut(ly as usize * w + lx as usize) {
|
||||
for (p, c) in v.iter_mut().zip(r.rgb) {
|
||||
*p += env * c;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn lens_flare(src: &Image, out: Rect, ctx: &Ctx, brightness: f32, centre: (f32, f32), lens: LensType) -> Vec<f32> {
|
||||
let n = src.ch;
|
||||
let b = ctx.bounds;
|
||||
let (bw, bh) = (b.width() as f32, b.height() as f32);
|
||||
let c = (b.x0 as f32 + centre.0 * bw, b.y0 as f32 + centre.1 * bh);
|
||||
let mid = (b.x0 as f32 + bw / 2.0, b.y0 as f32 + bh / 2.0);
|
||||
let axis = (mid.0 - c.0, mid.1 - c.1);
|
||||
let len = axis.0.hypot(axis.1);
|
||||
// A centre so far off the canvas that the geometry overflows f32 (e.g. 1e300 from a command)
|
||||
// lights nothing here; without this, NaN would reach every pixel through the streaks.
|
||||
if ![c.0, c.1, len].iter().all(|v| v.is_finite()) {
|
||||
return src.crop(out);
|
||||
}
|
||||
// At the image centre the axis has no direction; the offsets across it are tiny anyway.
|
||||
let normal = if len > 1e-6 { (-axis.1 / len, axis.0 / len) } else { (0.0, 1.0) };
|
||||
let (w, h) = (out.width() as usize, out.height() as usize);
|
||||
let g = Geometry { centre: c, axis, normal, unit: (bw / 800.0).max(1e-6), origin: (out.x0 as f32, out.y0 as f32), size: (w, h) };
|
||||
|
||||
let mut light = vec![[0.0f32; 3]; w * h];
|
||||
if let Some((lo, hi, f)) = bracket(levels(lens), brightness.clamp(10.0, 300.0)) {
|
||||
add_level(lo, 1.0 - f, &g, &mut light);
|
||||
if !std::ptr::eq(lo, hi) {
|
||||
add_level(hi, f, &g, &mut light);
|
||||
}
|
||||
}
|
||||
|
||||
let mut res = src.crop(out);
|
||||
for (i, px) in res.chunks_exact_mut(n).enumerate() {
|
||||
let Some(f) = light.get(i) else { break };
|
||||
let mut c = rgba(ctx, px);
|
||||
for k in 0..3 {
|
||||
// `clamp` keeps NaN; a non-finite amount adds no light.
|
||||
let a = if f[k].is_finite() { f[k].clamp(0.0, 1.0) } else { 0.0 };
|
||||
// Screen (c + a·(1 − c)) keeps display-referred values below white; a 32-bit value
|
||||
// already above white is left as is rather than pulled down towards it.
|
||||
c[k] += a * (1.0 - c[k]).max(0.0);
|
||||
}
|
||||
set_rgba(ctx, px, c);
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn brightness_between_levels_blends_the_two_around_it() {
|
||||
let lv = levels(LensType::Zoom);
|
||||
let (a, b) = (&lv[0], &lv[1]);
|
||||
let mid = (a.brightness + b.brightness) / 2.0;
|
||||
let (lo, hi, f) = bracket(lv, mid).unwrap();
|
||||
assert!(std::ptr::eq(lo, a) && std::ptr::eq(hi, b) && (f - 0.5).abs() < 1e-6);
|
||||
// Exactly on a level, and outside the measured range, one level is used as is.
|
||||
let (_, hi, f) = bracket(lv, b.brightness).unwrap();
|
||||
assert!(std::ptr::eq(hi, b) && f == 1.0);
|
||||
let (lo, hi, f) = bracket(lv, 1.0).unwrap();
|
||||
assert!(std::ptr::eq(lo, a) && std::ptr::eq(hi, a) && f == 0.0);
|
||||
let last = lv.last().unwrap();
|
||||
let (lo, _, f) = bracket(lv, 1000.0).unwrap();
|
||||
assert!(std::ptr::eq(lo, last) && f == 0.0);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -43,6 +43,8 @@ pub mod histogram;
|
||||
mod image;
|
||||
pub mod inpaint;
|
||||
pub mod lens;
|
||||
mod lens_flare;
|
||||
mod lens_flare_data;
|
||||
pub mod liquify;
|
||||
pub mod magnetic;
|
||||
pub mod matting;
|
||||
@@ -846,7 +848,7 @@ pub fn kernel(params: &FilterParams, src: &Image, out: Rect, ctx: &Ctx) -> Vec<f
|
||||
FilterParams::Fibers { variance, strength, seed, foreground, background } => {
|
||||
render::fibers(src, out, ctx, *variance, *strength, *seed, (*foreground, *background))
|
||||
}
|
||||
FilterParams::LensFlare { brightness, center_x, center_y, lens } => render::lens_flare(src, out, ctx, *brightness, (*center_x, *center_y), *lens),
|
||||
FilterParams::LensFlare { brightness, center_x, center_y, lens } => lens_flare::lens_flare(src, out, ctx, *brightness, (*center_x, *center_y), *lens),
|
||||
FilterParams::LightingEffects { lights, gloss, metallic, exposure, ambience, texture, height, white_is_high } => render::lighting(
|
||||
src,
|
||||
out,
|
||||
|
||||
+2
-103
@@ -1,11 +1,11 @@
|
||||
//! Render: Clouds, Difference Clouds, Fibers, Lens Flare, Lighting Effects.
|
||||
//! Render: Clouds, Difference Clouds, Fibers, Lighting Effects (Lens Flare: `lens_flare.rs`).
|
||||
|
||||
use photocraft_geom::Rect;
|
||||
|
||||
use crate::fxutil::{MAXC, luma, rgba, set_rgba, smoothstep, xy};
|
||||
use crate::image::Image;
|
||||
use crate::noise::hash01;
|
||||
use crate::{Ctx, LensType, Light, LightKind, TextureChannel};
|
||||
use crate::{Ctx, Light, LightKind, TextureChannel};
|
||||
|
||||
/// Smooth value noise in [0, 1).
|
||||
fn value_noise(x: f32, y: f32, seed: u32) -> f32 {
|
||||
@@ -106,107 +106,6 @@ pub(crate) fn fibers(src: &Image, out: Rect, ctx: &Ctx, variance: f32, strength:
|
||||
res
|
||||
}
|
||||
|
||||
/// One lens-flare ghost: position along the flare→centre axis, radius and tint.
|
||||
struct Ghost {
|
||||
t: f32,
|
||||
r: f32,
|
||||
tint: [f32; 3],
|
||||
k: f32,
|
||||
}
|
||||
|
||||
/// Lens Flare: an additive (screen) glow, rays, halo ring and ghost discs
|
||||
/// along the line through the image centre. Lens types vary the elements.
|
||||
pub(crate) fn lens_flare(src: &Image, out: Rect, ctx: &Ctx, brightness: f32, centre: (f32, f32), lens: LensType) -> Vec<f32> {
|
||||
let n = src.ch;
|
||||
let b = ctx.bounds;
|
||||
let (bw, bh) = (b.width() as f32, b.height() as f32);
|
||||
let diag = bw.hypot(bh).max(1.0);
|
||||
let (cx, cy) = (b.x0 as f32 + centre.0 * bw, b.y0 as f32 + centre.1 * bh);
|
||||
let (mx, my) = (b.x0 as f32 + bw / 2.0, b.y0 as f32 + bh / 2.0);
|
||||
let bright = brightness.clamp(10.0, 300.0) / 100.0;
|
||||
let s = diag / 1000.0;
|
||||
let (core, glow, ring_r, ring_w, rays, streak) = match lens {
|
||||
LensType::Zoom => (14.0, 90.0, 0.0, 0.0, 0.5, 0.0),
|
||||
LensType::Prime35 => (12.0, 70.0, 90.0, 6.0, 0.3, 0.0),
|
||||
LensType::Prime105 => (22.0, 130.0, 0.0, 0.0, 0.8, 0.0),
|
||||
LensType::MoviePrime => (10.0, 60.0, 0.0, 0.0, 0.2, 1.0),
|
||||
};
|
||||
let ghosts: Vec<Ghost> = match lens {
|
||||
LensType::Zoom => vec![
|
||||
Ghost { t: 0.35, r: 10.0, tint: [0.6, 0.8, 1.0], k: 0.18 },
|
||||
Ghost { t: 0.6, r: 26.0, tint: [0.5, 1.0, 0.6], k: 0.10 },
|
||||
Ghost { t: 0.85, r: 6.0, tint: [1.0, 0.7, 0.4], k: 0.25 },
|
||||
Ghost { t: 1.25, r: 40.0, tint: [0.7, 0.5, 1.0], k: 0.08 },
|
||||
Ghost { t: 1.5, r: 16.0, tint: [1.0, 0.6, 0.5], k: 0.15 },
|
||||
Ghost { t: 1.9, r: 70.0, tint: [0.5, 0.7, 1.0], k: 0.06 },
|
||||
],
|
||||
LensType::Prime35 => vec![Ghost { t: 0.7, r: 18.0, tint: [0.6, 1.0, 0.7], k: 0.12 }, Ghost { t: 1.4, r: 30.0, tint: [1.0, 0.7, 0.5], k: 0.09 }],
|
||||
LensType::Prime105 => vec![Ghost { t: 0.5, r: 14.0, tint: [1.0, 0.8, 0.5], k: 0.12 }, Ghost { t: 1.6, r: 50.0, tint: [0.6, 0.7, 1.0], k: 0.07 }],
|
||||
LensType::MoviePrime => vec![
|
||||
Ghost { t: 0.4, r: 8.0, tint: [0.5, 0.7, 1.0], k: 0.2 },
|
||||
Ghost { t: 1.0, r: 20.0, tint: [0.4, 0.6, 1.0], k: 0.12 },
|
||||
Ghost { t: 1.6, r: 12.0, tint: [0.5, 0.8, 1.0], k: 0.16 },
|
||||
],
|
||||
};
|
||||
let mut res = src.crop(out);
|
||||
for (i, px) in res.chunks_exact_mut(n).enumerate() {
|
||||
let (x, y) = xy(out, i);
|
||||
let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
|
||||
let (dx, dy) = (fx - cx, fy - cy);
|
||||
let d = (dx * dx + dy * dy).sqrt();
|
||||
let mut f = [0.0f32; 3];
|
||||
// Hot core and wide glow (warm white).
|
||||
let g = (-(d / (core * s)).powi(2)).exp() + 0.35 * (-d / (glow * s)).exp();
|
||||
for (k, w) in [1.0, 0.95, 0.85].iter().enumerate() {
|
||||
f[k] += g * w;
|
||||
}
|
||||
// Rays: angular modulation decaying with distance.
|
||||
if rays > 0.0 {
|
||||
let th = dy.atan2(dx);
|
||||
let m = ((th * 12.0).sin() * 0.5 + 0.5).powi(8) + ((th * 7.0 + 1.3).sin() * 0.5 + 0.5).powi(12) * 0.6;
|
||||
let rr = rays * m * (-d / (glow * 1.6 * s)).exp();
|
||||
for v in f.iter_mut() {
|
||||
*v += rr * 0.6;
|
||||
}
|
||||
}
|
||||
// Anamorphic horizontal streak (movie prime).
|
||||
if streak > 0.0 {
|
||||
let st = (-(dy.abs() / (2.5 * s))).exp() * (-(dx.abs() / (450.0 * s))).exp();
|
||||
f[0] += st * 0.5;
|
||||
f[1] += st * 0.7;
|
||||
f[2] += st;
|
||||
}
|
||||
// Halo ring with a slight chromatic spread.
|
||||
if ring_r > 0.0 {
|
||||
for (k, off) in [1.04f32, 1.0, 0.96].iter().enumerate() {
|
||||
let rd = (d - ring_r * s * off) / (ring_w * s);
|
||||
f[k] += 0.18 * (-rd * rd).exp();
|
||||
}
|
||||
}
|
||||
// Ghosts along the axis through the centre.
|
||||
for gh in &ghosts {
|
||||
let (gx, gy) = (cx + (mx - cx) * gh.t * 2.0, cy + (my - cy) * gh.t * 2.0);
|
||||
let gd = ((fx - gx).powi(2) + (fy - gy).powi(2)).sqrt() / (gh.r * s);
|
||||
if gd < 1.2 {
|
||||
// Soft-edged disc, slightly brighter at the rim.
|
||||
let e = smoothstep(1.0, 0.85, gd) * (0.6 + 0.4 * gd);
|
||||
for (fk, t) in f.iter_mut().zip(gh.tint) {
|
||||
*fk += e * gh.k * t;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut c = rgba(ctx, px);
|
||||
for k in 0..3 {
|
||||
let a = (f[k] * bright).max(0.0);
|
||||
// Screen (c + a·(1 − c)) keeps display-referred values below white; a 32-bit
|
||||
// value already above white is left as is rather than pulled down towards it.
|
||||
c[k] += a.min(1.0) * (1.0 - c[k]).max(0.0);
|
||||
}
|
||||
set_rgba(ctx, px, c);
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
pub(crate) struct LightingSpec<'a> {
|
||||
pub lights: &'a [Light],
|
||||
pub gloss: f32,
|
||||
|
||||
@@ -435,6 +435,82 @@ fn lens_flare_is_brightest_at_its_centre() {
|
||||
assert!(out.pixel(38, 2)[0] >= 0.2 - 1e-6, "screen never darkens");
|
||||
}
|
||||
|
||||
/// A Lens Flare on black over `r` (its reference bounds), as straight RGB.
|
||||
fn flare_on_black(r: Rect, lens: LensType) -> Vec<f32> {
|
||||
let s = flat(SampleType::F32, r, BLACK);
|
||||
let p = FilterParams::LensFlare { brightness: 100.0, center_x: 0.3, center_y: 0.3, lens };
|
||||
apply(&s, &p, output_area(&p, s.content_bounds(), r, None), r, None).read_region(r)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lens_flare_scales_with_the_image() {
|
||||
// Sizes are fractions of the image diagonal: the same flare on a twice-as-large image, halved,
|
||||
// is the small one (up to the one-pixel rays, which stay one pixel wide).
|
||||
for lens in [LensType::Zoom, LensType::Prime35, LensType::Prime105, LensType::MoviePrime] {
|
||||
let (small, big) = (Rect::new(0, 0, 200, 150), Rect::new(0, 0, 400, 300));
|
||||
let a = flare_on_black(small, lens);
|
||||
let b = flare_on_black(big, lens);
|
||||
let mut diff = 0.0f64;
|
||||
for y in 0..150usize {
|
||||
for x in 0..200usize {
|
||||
for k in 0..3 {
|
||||
let at = |xx: usize, yy: usize| f64::from(b[(yy * 400 + xx) * 4 + k]);
|
||||
let halved = (at(2 * x, 2 * y) + at(2 * x + 1, 2 * y) + at(2 * x, 2 * y + 1) + at(2 * x + 1, 2 * y + 1)) / 4.0;
|
||||
diff += (halved - f64::from(a[(y * 200 + x) * 4 + k])).abs();
|
||||
}
|
||||
}
|
||||
}
|
||||
let mean = diff / (200.0 * 150.0 * 3.0);
|
||||
assert!(mean < 0.01, "{lens:?}: mean difference {mean}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_lens_flare_lens_looks_different() {
|
||||
let r = Rect::new(0, 0, 160, 120);
|
||||
let lenses = [LensType::Zoom, LensType::Prime35, LensType::Prime105, LensType::MoviePrime];
|
||||
let flares: Vec<Vec<f32>> = lenses.iter().map(|l| flare_on_black(r, *l)).collect();
|
||||
for i in 0..flares.len() {
|
||||
for j in i + 1..flares.len() {
|
||||
let d: f32 = flares[i].iter().zip(&flares[j]).map(|(a, b)| (a - b).abs()).sum::<f32>() / flares[i].len() as f32;
|
||||
assert!(d > 0.01, "{:?} and {:?} are nearly the same ({d})", lenses[i], lenses[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lens_flare_with_an_overflowing_centre_leaves_finite_pixels() {
|
||||
// A centre of 1e300 from a command becomes infinite in f32; NaN must not reach the pixels.
|
||||
let src = flat(SampleType::F32, R, [0.2, 0.3, 0.4, 1.0]);
|
||||
for lens in [LensType::Zoom, LensType::Prime35, LensType::Prime105, LensType::MoviePrime] {
|
||||
for (cx, cy) in [(f32::INFINITY, f32::NEG_INFINITY), (1e38, -1e38), (f32::NAN, 0.5), (5.0, -5.0)] {
|
||||
let out = run(&src, &FilterParams::LensFlare { brightness: 100.0, center_x: cx, center_y: cy, lens });
|
||||
let px = out.read_region(R);
|
||||
assert!(px.iter().all(|v| v.is_finite()), "{lens:?} at ({cx}, {cy})");
|
||||
assert!(px.iter().zip(src.read_region(R)).all(|(a, b)| *a >= b - 1e-6), "{lens:?}: screen never darkens");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lens_flare_between_two_measured_brightnesses_blends_their_light() {
|
||||
// 75 % and 100 % are measured levels; 87.5 % is halfway, so its light is their mean. On black
|
||||
// 32-bit the result is the light itself; at 0 and 1 the clamp makes the blend nonlinear.
|
||||
let black = flat(SampleType::F32, R, [0.0, 0.0, 0.0, 1.0]);
|
||||
for lens in [LensType::Zoom, LensType::Prime35, LensType::Prime105, LensType::MoviePrime] {
|
||||
let at = |brightness: f32| run(&black, &FilterParams::LensFlare { brightness, center_x: 0.25, center_y: 0.5, lens }).read_region(R);
|
||||
let (lo, mid, hi) = (at(75.0), at(87.5), at(100.0));
|
||||
let mut checked = 0;
|
||||
for ((l, m), h) in lo.iter().zip(&mid).zip(&hi) {
|
||||
if [*l, *m, *h].iter().all(|v| *v > 0.0 && *v < 1.0) {
|
||||
assert!((m - 0.5 * (l + h)).abs() < 1e-4, "{lens:?}: {m} is not the mean of {l} and {h}");
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
assert!(checked >= 100, "{lens:?}: too few unclipped values ({checked})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lens_flare_never_darkens_32_bit_values_above_one() {
|
||||
// #5785: the screen formula turned 2.0 into 1.5 (and 1.0 at the core).
|
||||
|
||||
@@ -33,11 +33,18 @@ fn lens_flare_keeps_off_canvas_centers_and_native_defaults() {
|
||||
/// Extreme centers and malformed inputs remain bounded command executions with finite pixels.
|
||||
#[test]
|
||||
fn lens_flare_extreme_centers_do_not_panic_or_corrupt_pixels() {
|
||||
for p in [json!({"centerX": 1e300, "centerY": -1e300}), json!({"centerX": null, "centerY": []}), json!({"centerX": 5, "centerY": -5, "brightness": -100})] {
|
||||
let mut s = session();
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| s.execute("filter.render.lensFlare", p)));
|
||||
assert!(result.is_ok());
|
||||
assert!(pixels(&s).iter().all(|v| v.is_finite()));
|
||||
for lens in ["zoom", "prime35", "prime105", "moviePrime"] {
|
||||
for p in [
|
||||
json!({"centerX": 1e300, "centerY": -1e300, "lens": lens}),
|
||||
json!({"centerX": 1e38, "centerY": -1e38, "lens": lens}),
|
||||
json!({"centerX": null, "centerY": [], "lens": lens}),
|
||||
json!({"centerX": 5, "centerY": -5, "brightness": -100, "lens": lens}),
|
||||
] {
|
||||
let mut s = session();
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| s.execute("filter.render.lensFlare", p.clone())));
|
||||
assert!(result.is_ok(), "{p}");
|
||||
assert!(pixels(&s).iter().all(|v| v.is_finite()), "non-finite pixels for {p}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user