FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Blend graphic gradients in linear light and keep per-character fills solid.
Vikram Bhaskaranac83bae223cf
diff --git a/crates/project/src/graphic.rs b/crates/project/src/graphic.rsindex f92ebbb9a..978917e32 100644--- a/crates/project/src/graphic.rs+++ b/crates/project/src/graphic.rs@@ -162,7 +162,8 @@ pub struct LinearGradient {#[derive(Clone, Debug, PartialEq)]pub struct Appearance {pub fill: Option<[f32; 4]>,- /// Set when Fill Type is Linear Gradient. Replaces the solid fill for the whole layer.+ /// Set when Fill Type is Linear Gradient. Replaces the solid fill. A text run with its own+ /// fill colour stays solid; the other characters keep the ramp.pub gradient: Option<LinearGradient>,/// (colour, width px, type: 0 outer, 1 centre, 2 inner), outermost last.pub strokes: Vec<([f32; 4], f32, u32)>,diff --git a/crates/render/src/graphic_clip.rs b/crates/render/src/graphic_clip.rsindex 6f81c010b..eaf1f6b9b 100644--- a/crates/render/src/graphic_clip.rs+++ b/crates/render/src/graphic_clip.rs@@ -20,7 +20,7 @@ use filmcraft_text::{Align, Caps, Layout, Mask, ParagraphStyle, StrokeKind, Styluse filmcraft_time::Tick;use rayon::prelude::*;-use crate::graphics::premul_linear;+use crate::graphics::{premul_linear, premul_linear_lerp};use crate::image::Image;/// f64 affine → the text crate's f32 transform.@@ -226,12 +226,7 @@ fn over_linear_gradient(px: &mut [f32], msk: &Mask, grad: &LinearGradient, lb: [}let (lx, ly) = apply(inv, origin.0 as f32 + col as f32 + 0.5, py);let t = (((((lx - cx) * ax + (ly - cy) * ay) / half) + 1.0) * 0.5).clamp(0.0, 1.0);- let c = premul_linear([- start[0] * (1.0 - t) + end[0] * t,- start[1] * (1.0 - t) + end[1] * t,- start[2] * (1.0 - t) + end[2] * t,- start[3] * (1.0 - t) + end[3] * t,- ]);+ let c = premul_linear_lerp(start, end, t);let k = 1.0 - c[3] * cov;for i in 0..4 {p[i] = c[i] * cov + p[i] * k;@@ -240,6 +235,65 @@ fn over_linear_gradient(px: &mut [f32], msk: &Mask, grad: &LinearGradient, lb: [});}+/// Solid fill, one mask per distinct colour when text runs carry their own.+fn paint_solid(px: &mut [f32], cover: &Mask, color: [f32; 4], text: Option<&Layout>, m: &Xform, run_fills: &[Option<[f32; 4]>], origin: (i32, i32)) {+ let Some(layout) = text.filter(|_| run_fills.iter().any(Option::is_some)) else {+ over_mask(px, cover, premul_linear(color));+ return;+ };+ let mut groups: Vec<([f32; 4], Vec<u16>)> = Vec::new();+ for r in 0..=run_fills.len() {+ let col = if r == 0 { color } else { run_fills[r - 1].unwrap_or(color) };+ match groups.iter_mut().find(|g| g.0 == col) {+ Some(g) => g.1.push(r as u16),+ None => groups.push((col, vec![r as u16])),+ }+ }+ for (col, runs) in groups {+ let mut m_run = Mask::new(cover.w, cover.h);+ for r in runs {+ render::draw_run(layout, m, &mut m_run, origin, Some(r));+ }+ over_mask(px, &m_run, premul_linear(col));+ }+}++/// Gradient for runs that have no fill of their own; runs with a fill stay that solid colour.+fn paint_mixed_gradient(+ px: &mut [f32],+ cover: &Mask,+ grad: &LinearGradient,+ lb: [f32; 4],+ inv: &Xform,+ origin: (i32, i32),+ layout: &Layout,+ m: &Xform,+ run_fills: &[Option<[f32; 4]>],+) {+ let mut grad_mask = Mask::new(cover.w, cover.h);+ render::draw_run(layout, m, &mut grad_mask, origin, Some(0));+ let mut solids: Vec<([f32; 4], Vec<u16>)> = Vec::new();+ for (i, fill) in run_fills.iter().enumerate() {+ let run = (i + 1) as u16;+ if let Some(col) = fill {+ match solids.iter_mut().find(|g| g.0 == *col) {+ Some(g) => g.1.push(run),+ None => solids.push((*col, vec![run])),+ }+ } else {+ render::draw_run(layout, m, &mut grad_mask, origin, Some(run));+ }+ }+ over_linear_gradient(px, &grad_mask, grad, lb, inv, origin);+ for (col, runs) in solids {+ let mut m_run = Mask::new(cover.w, cover.h);+ for r in runs {+ render::draw_run(layout, m, &mut m_run, origin, Some(r));+ }+ over_mask(px, &m_run, premul_linear(col));+ }+}+/// Rasterise one layer with layer→device transform `m`, clipped to a `cw`×`ch` canvas.pub fn raster_layer(spec: &LayerSpec, m: &Xform, cw: usize, ch: usize) -> Option<LayerRaster> {if !spec.enabled || spec.transform.opacity <= 0.0 {@@ -343,40 +397,22 @@ pub fn raster_layer(spec: &LayerSpec, m: &Xform, cw: usize, ch: usize) -> Optionover_mask(&mut px, sm, premul_linear(*c));}}+ let run_fills: Vec<Option<[f32; 4]>> = match &spec.content {+ LayerContent::Text(t) => t.runs.iter().map(|(_, s)| s.fill).collect(),+ _ => Vec::new(),+ };if let Some(grad) = &ap.gradient- && !matches!(&spec.content, LayerContent::Text(t) if t.runs.iter().any(|(_, s)| s.fill.is_some()))+ && let Some(inv) = invert_xform(m){- if let Some(inv) = invert_xform(m) {+ if run_fills.iter().any(Option::is_some)+ && let Some(layout) = &text+ {+ paint_mixed_gradient(&mut px, &cover, grad, lb, &inv, (x0, y0), layout, m, &run_fills);+ } else {over_linear_gradient(&mut px, &cover, grad, lb, &inv, (x0, y0));- } else if let Some(c) = ap.fill {- over_mask(&mut px, &cover, premul_linear(c));}} else if let Some(c) = ap.fill {- // per-character fills: each style run with its own colour is drawn on its own- let run_fills: Vec<Option<[f32; 4]>> = match &spec.content {- LayerContent::Text(t) => t.runs.iter().map(|(_, s)| s.fill).collect(),- _ => Vec::new(),- };- match &text {- Some(l) if run_fills.iter().any(Option::is_some) => {- let mut groups: Vec<([f32; 4], Vec<u16>)> = Vec::new();- for r in 0..=run_fills.len() {- let col = if r == 0 { c } else { run_fills[r - 1].unwrap_or(c) };- match groups.iter_mut().find(|g| g.0 == col) {- Some(g) => g.1.push(r as u16),- None => groups.push((col, vec![r as u16])),- }- }- for (col, runs) in groups {- let mut m_run = Mask::new(w, h);- for r in runs {- render::draw_run(l, m, &mut m_run, (x0, y0), Some(r));- }- over_mask(&mut px, &m_run, premul_linear(col));- }- }- _ => over_mask(&mut px, &cover, premul_linear(c)),- }+ paint_solid(&mut px, &cover, c, text.as_deref(), m, &run_fills, (x0, y0));}for ((sm, c), (_, _, k)) in strokes.iter().zip(&ap.strokes).rev() {if !outer(*k) {@@ -798,6 +834,64 @@ mod tests {assert!(ls / ln > rs / rn + 0.15, "text ramps from red to blue: {} {}", ls / ln, rs / rn);}+ #[test]+ fn linear_gradient_blends_in_linear_light_and_turns_with_the_layer() {+ let mut shape = new_shape_layer(0, Vec2::new(100.0, 100.0), Vec2::new(80.0, 40.0), vec![]);+ set(&mut shape, "fill_kind", ParamValue::Choice(1));+ set(&mut shape, "gradient_start", ParamValue::Color([0.0, 0.0, 0.0, 1.0]));+ set(&mut shape, "gradient_end", ParamValue::Color([1.0, 1.0, 1.0, 1.0]));+ let mut img = Image::new(200, 200);+ render_graphic_layers(&[shape.clone()], Tick::ZERO, (200, 200), &Affine::IDENTITY, &mut img);+ let mid = img.get(100, 100)[0];+ // Linear-light midpoint is ~0.5. An sRGB midpoint converted to linear is ~0.21.+ assert!(mid > 0.4 && mid < 0.6, "centre of black→white is linear 0.5, got {mid}");+ assert!(img.get(70, 100)[0] < mid && mid < img.get(130, 100)[0]);++ set(&mut shape, "gradient_start", ParamValue::Color([1.0, 0.0, 0.0, 1.0]));+ set(&mut shape, "gradient_end", ParamValue::Color([0.0, 0.0, 1.0, 1.0]));+ set(&mut shape, "rotation", ParamValue::Float(90.0));+ let mut turned = Image::new(200, 200);+ render_graphic_layers(&[shape], Tick::ZERO, (200, 200), &Affine::IDENTITY, &mut turned);+ let top = turned.get(100, 70);+ let bot = turned.get(100, 130);+ assert!(top[3] > 0.9 && bot[3] > 0.9, "the rotated ramp is inside the shape: {top:?} {bot:?}");+ assert!(top[0] > top[2], "clockwise 90° carries the start colour to the top {top:?}");+ assert!(bot[2] > bot[0], "and the end colour to the bottom {bot:?}");+ }++ #[test]+ fn linear_gradient_keeps_a_per_character_fill_solid() {+ use filmcraft_project::graphic_design::{CharStyle, LayerExtra, StyleRun};+ let mut e = new_text_layer("AAAA", Vec2::new(20.0, 100.0), 60.0);+ set(&mut e, "fill_kind", ParamValue::Choice(1));+ set(&mut e, "gradient_start", ParamValue::Color([0.0, 1.0, 0.0, 1.0]));+ set(&mut e, "gradient_end", ParamValue::Color([0.0, 0.0, 1.0, 1.0]));+ let red = CharStyle { fill: Some([1.0, 0.0, 0.0, 1.0]), ..Default::default() };+ e.layer = Some(Box::new(LayerExtra { runs: vec![StyleRun { start: 2, end: 4, style: red }], ..Default::default() }));+ let mut img = Image::new(400, 200);+ render_graphic_layers(&[e.clone()], Tick::ZERO, (400, 200), &Affine::IDENTITY, &mut img);+ let l = text_layout(match &eval_layer(&e, Tick::ZERO, (400, 200)).unwrap().content {+ LayerContent::Text(t) => t,+ _ => unreachable!(),+ });+ let split = 20.0 + l.caret(2).0;+ let (mut green, mut red_px) = (0, 0);+ for y in 0..200 {+ for x in 0..400 {+ let p = img.get(x, y);+ if p[3] < 0.8 {+ continue;+ }+ if (x as f32) < split - 1.0 && p[1] > p[0] && p[1] > p[2] {+ green += 1;+ } else if (x as f32) > split + 1.0 && p[0] > 0.9 && p[1] < 0.05 {+ red_px += 1;+ }+ }+ }+ assert!(green > 80 && red_px > 80, "gradient on the plain letters, solid red on the styled ones: {green} {red_px}");+ }+#[test]fn inner_and_centre_strokes() {for (kind, inside, outside) in [(2u32, true, false), (1, true, true)] {diff --git a/crates/render/src/graphics.rs b/crates/render/src/graphics.rsindex 3664aa01f..dd98fe744 100644--- a/crates/render/src/graphics.rs+++ b/crates/render/src/graphics.rs@@ -14,6 +14,15 @@ pub fn premul_linear(c: [f32; 4]) -> [f32; 4] {[srgb_to_linear(c[0]) * a, srgb_to_linear(c[1]) * a, srgb_to_linear(c[2]) * a, a]}+/// Blend two sRGB straight colours in linear light, then premultiply. `t` is 0 at `start`.+pub fn premul_linear_lerp(start: [f32; 4], end: [f32; 4], t: f32) -> [f32; 4] {+ let t = t.clamp(0.0, 1.0);+ let s = [srgb_to_linear(start[0]), srgb_to_linear(start[1]), srgb_to_linear(start[2]), start[3].clamp(0.0, 1.0)];+ let e = [srgb_to_linear(end[0]), srgb_to_linear(end[1]), srgb_to_linear(end[2]), end[3].clamp(0.0, 1.0)];+ let a = s[3] * (1.0 - t) + e[3] * t;+ [(s[0] * (1.0 - t) + e[0] * t) * a, (s[1] * (1.0 - t) + e[1] * t) * a, (s[2] * (1.0 - t) + e[2] * t) * a, a]+}+/// Composite `color` (premultiplied linear) through coverage `m` placed at (`x0`, `y0`), scaled by/// `opacity`, over `img`.pub fn paint_mask(img: &mut Image, m: &Mask, x0: i32, y0: i32, color: [f32; 4], opacity: f32) {diff --git a/docs/graphics.md b/docs/graphics.mdindex 8f888b38b..0f14cdea3 100644--- a/docs/graphics.md+++ b/docs/graphics.md@@ -251,10 +251,12 @@ panel state and the Type-tool selection.## Gradient fillsAppearance › Fill Type › Linear Gradient paints the shape or the text with a ramp from Gradient-Start to Gradient End. The angle is degrees clockwise on screen; 0° runs left to right across the-layer's own bounds, and the ramp turns with the layer. `graphics.set` accepts `fill_kind`-(`solid` or `linear gradient`), `gradient_start`, `gradient_end` and `gradient_angle`. A-per-character fill colour still paints those characters as a solid.+Start to Gradient End. Stops are blended in linear light. The angle is degrees clockwise on+screen; 0° runs left to right across the layer's own bounds, and the ramp turns with the layer.+`graphics.set` accepts `fill_kind` (`solid` or `linear gradient`), `gradient_start`,+`gradient_end` and `gradient_angle`. A per-character fill colour still paints those characters+as a solid; the rest of the text keeps the ramp. A singular layer transform falls back to the+solid fill colour.## Not yet