Merge branch 'rust-ui' of https://git.skyler.io/skyler/Lightningbeam into rust-ui
This commit is contained in:
@@ -32,7 +32,9 @@ pub mod region_split;
|
||||
pub mod toggle_group_expansion;
|
||||
pub mod group_layers;
|
||||
pub mod raster_stroke;
|
||||
pub mod raster_fill;
|
||||
pub mod move_layer;
|
||||
pub mod set_fill_paint;
|
||||
|
||||
pub use add_clip_instance::AddClipInstanceAction;
|
||||
pub use add_effect::AddEffectAction;
|
||||
@@ -63,4 +65,6 @@ pub use region_split::RegionSplitAction;
|
||||
pub use toggle_group_expansion::ToggleGroupExpansionAction;
|
||||
pub use group_layers::GroupLayersAction;
|
||||
pub use raster_stroke::RasterStrokeAction;
|
||||
pub use raster_fill::RasterFillAction;
|
||||
pub use move_layer::MoveLayerAction;
|
||||
pub use set_fill_paint::SetFillPaintAction;
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
//! Raster flood-fill action — records and undoes a paint bucket fill on a RasterLayer.
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct RasterFillAction {
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
buffer_before: Vec<u8>,
|
||||
buffer_after: Vec<u8>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
name: String,
|
||||
}
|
||||
|
||||
impl RasterFillAction {
|
||||
pub fn new(
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
buffer_before: Vec<u8>,
|
||||
buffer_after: Vec<u8>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
) -> Self {
|
||||
Self { layer_id, time, buffer_before, buffer_after, width, height, name: "Flood fill".to_string() }
|
||||
}
|
||||
|
||||
pub fn with_description(mut self, name: &str) -> Self {
|
||||
self.name = name.to_string();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for RasterFillAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let layer = document.get_layer_mut(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
|
||||
let raster = match layer {
|
||||
AnyLayer::Raster(rl) => rl,
|
||||
_ => return Err("Not a raster layer".to_string()),
|
||||
};
|
||||
let kf = raster.ensure_keyframe_at(self.time, self.width, self.height);
|
||||
kf.raw_pixels = self.buffer_after.clone();
|
||||
kf.texture_dirty = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let layer = document.get_layer_mut(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
|
||||
let raster = match layer {
|
||||
AnyLayer::Raster(rl) => rl,
|
||||
_ => return Err("Not a raster layer".to_string()),
|
||||
};
|
||||
let kf = raster.ensure_keyframe_at(self.time, self.width, self.height);
|
||||
kf.raw_pixels = self.buffer_before.clone();
|
||||
kf.texture_dirty = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
self.name.clone()
|
||||
}
|
||||
}
|
||||
@@ -49,12 +49,14 @@ impl Action for RasterStrokeAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let kf = get_keyframe_mut(document, &self.layer_id, self.time, self.width, self.height)?;
|
||||
kf.raw_pixels = self.buffer_after.clone();
|
||||
kf.texture_dirty = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let kf = get_keyframe_mut(document, &self.layer_id, self.time, self.width, self.height)?;
|
||||
kf.raw_pixels = self.buffer_before.clone();
|
||||
kf.texture_dirty = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Action that changes the fill of one or more DCEL faces.
|
||||
//!
|
||||
//! Handles both solid-colour and gradient fills, clearing the other type so they
|
||||
//! don't coexist on a face.
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::dcel::FaceId;
|
||||
use crate::document::Document;
|
||||
use crate::gradient::ShapeGradient;
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::shape::ShapeColor;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Snapshot of one face's fill state (both types) for undo.
|
||||
#[derive(Clone)]
|
||||
struct OldFill {
|
||||
face_id: FaceId,
|
||||
color: Option<ShapeColor>,
|
||||
gradient: Option<ShapeGradient>,
|
||||
}
|
||||
|
||||
/// Action that sets a solid-colour *or* gradient fill on a set of faces,
|
||||
/// clearing the other fill type.
|
||||
pub struct SetFillPaintAction {
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
face_ids: Vec<FaceId>,
|
||||
new_color: Option<ShapeColor>,
|
||||
new_gradient: Option<ShapeGradient>,
|
||||
old_fills: Vec<OldFill>,
|
||||
description: &'static str,
|
||||
}
|
||||
|
||||
impl SetFillPaintAction {
|
||||
/// Set a solid fill (clears any gradient on the same faces).
|
||||
pub fn solid(
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
face_ids: Vec<FaceId>,
|
||||
color: Option<ShapeColor>,
|
||||
) -> Self {
|
||||
Self {
|
||||
layer_id,
|
||||
time,
|
||||
face_ids,
|
||||
new_color: color,
|
||||
new_gradient: None,
|
||||
old_fills: Vec::new(),
|
||||
description: "Set fill colour",
|
||||
}
|
||||
}
|
||||
|
||||
/// Set a gradient fill (clears any solid colour on the same faces).
|
||||
pub fn gradient(
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
face_ids: Vec<FaceId>,
|
||||
gradient: Option<ShapeGradient>,
|
||||
) -> Self {
|
||||
Self {
|
||||
layer_id,
|
||||
time,
|
||||
face_ids,
|
||||
new_color: None,
|
||||
new_gradient: gradient,
|
||||
old_fills: Vec::new(),
|
||||
description: "Set gradient fill",
|
||||
}
|
||||
}
|
||||
|
||||
fn get_dcel_mut<'a>(
|
||||
document: &'a mut Document,
|
||||
layer_id: &Uuid,
|
||||
time: f64,
|
||||
) -> Result<&'a mut crate::dcel::Dcel, String> {
|
||||
let layer = document
|
||||
.get_layer_mut(layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", layer_id))?;
|
||||
match layer {
|
||||
AnyLayer::Vector(vl) => vl
|
||||
.dcel_at_time_mut(time)
|
||||
.ok_or_else(|| format!("No keyframe at time {}", time)),
|
||||
_ => Err("Not a vector layer".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for SetFillPaintAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let dcel = Self::get_dcel_mut(document, &self.layer_id, self.time)?;
|
||||
self.old_fills.clear();
|
||||
|
||||
for &fid in &self.face_ids {
|
||||
let face = dcel.face(fid);
|
||||
self.old_fills.push(OldFill {
|
||||
face_id: fid,
|
||||
color: face.fill_color,
|
||||
gradient: face.gradient_fill.clone(),
|
||||
});
|
||||
|
||||
let face_mut = dcel.face_mut(fid);
|
||||
// Setting a gradient clears solid colour and vice-versa.
|
||||
if self.new_gradient.is_some() || self.new_color.is_none() {
|
||||
face_mut.fill_color = self.new_color;
|
||||
face_mut.gradient_fill = self.new_gradient.clone();
|
||||
} else {
|
||||
face_mut.fill_color = self.new_color;
|
||||
face_mut.gradient_fill = None;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let dcel = Self::get_dcel_mut(document, &self.layer_id, self.time)?;
|
||||
for old in &self.old_fills {
|
||||
let face = dcel.face_mut(old.face_id);
|
||||
face.fill_color = old.color;
|
||||
face.gradient_fill = old.gradient.clone();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
self.description.to_string()
|
||||
}
|
||||
}
|
||||
@@ -15,17 +15,26 @@
|
||||
//! The GPU compute shader (`brush_dab.wgsl`) is the authoritative implementation.
|
||||
//!
|
||||
//! ### Dab placement
|
||||
//! Dabs are placed along the stroke polyline at intervals of
|
||||
//! `spacing = radius * dabs_per_radius`. Fractional remainder is tracked across
|
||||
//! consecutive calls via `StrokeState`.
|
||||
//! Follows the libmypaint model: distance-based and time-based contributions are
|
||||
//! **summed** into a single `partial_dabs` accumulator. A dab fires whenever the
|
||||
//! accumulator reaches 1.0.
|
||||
//!
|
||||
//! Rate (dabs per pixel) = dabs_per_actual_radius / actual_radius
|
||||
//! + dabs_per_basic_radius / base_radius
|
||||
//! Time contribution added per call = dt × dabs_per_second
|
||||
//!
|
||||
//! ### Opacity
|
||||
//! Matches libmypaint's `opaque_linearize` formula. `dabs_per_pixel` is a fixed
|
||||
//! brush-level estimate of how many dabs overlap at any pixel:
|
||||
//!
|
||||
//! `dabs_per_pixel = 1 + opaque_linearize × ((dabs_per_actual + dabs_per_basic) × 2 - 1)`
|
||||
//! `per_dab_alpha = 1 - (1 - raw_opacity) ^ (1 / dabs_per_pixel)`
|
||||
//!
|
||||
//! With `opaque_linearize = 0` the raw opacity is used directly per dab.
|
||||
//!
|
||||
//! ### Blending
|
||||
//! Normal mode uses the standard "over" operator on premultiplied RGBA:
|
||||
//! ```text
|
||||
//! result_a = opa_a + (1 - opa_a) * bottom_a
|
||||
//! result_rgb = opa_a * top_rgb + (1 - opa_a) * bottom_rgb
|
||||
//! ```
|
||||
//! Erase mode: subtract `opa_a` from the destination alpha and premultiply.
|
||||
//! Normal mode uses the standard "over" operator on premultiplied RGBA.
|
||||
//! Erase mode subtracts from destination alpha.
|
||||
|
||||
use image::RgbaImage;
|
||||
use crate::raster_layer::{RasterBlendMode, StrokeRecord};
|
||||
@@ -65,20 +74,48 @@ pub struct GpuDab {
|
||||
|
||||
/// Blend mode: 0 = Normal, 1 = Erase, 2 = Smudge
|
||||
pub blend_mode: u32,
|
||||
pub _pad0: u32,
|
||||
pub _pad1: u32,
|
||||
pub _pad2: u32,
|
||||
/// Elliptical dab aspect ratio (1.0 = circle)
|
||||
pub elliptical_dab_ratio: f32,
|
||||
/// Elliptical dab rotation angle in radians
|
||||
pub elliptical_dab_angle: f32,
|
||||
/// Lock alpha: 0.0 = modify alpha normally, 1.0 = don't modify destination alpha
|
||||
pub lock_alpha: f32,
|
||||
}
|
||||
|
||||
/// Transient brush stroke state (tracks partial dab position between segments)
|
||||
/// Transient brush stroke state (tracks position and randomness between segments)
|
||||
pub struct StrokeState {
|
||||
/// Distance along the path already "consumed" toward the next dab (in pixels)
|
||||
pub distance_since_last_dab: f32,
|
||||
/// Fractional dab accumulator — reaches 1.0 when the next dab should fire.
|
||||
/// Initialised to 1.0 so the very first call always emits at least one dab.
|
||||
pub partial_dabs: f32,
|
||||
/// Exponentially-smoothed cursor X for slow_tracking
|
||||
pub smooth_x: f32,
|
||||
/// Exponentially-smoothed cursor Y for slow_tracking
|
||||
pub smooth_y: f32,
|
||||
/// Whether smooth_x/y have been initialised yet
|
||||
pub smooth_initialized: bool,
|
||||
/// xorshift32 seed for jitter and radius variation
|
||||
pub rng_seed: u32,
|
||||
/// Accumulated per-dab hue shift
|
||||
pub color_h_phase: f32,
|
||||
/// Accumulated per-dab value shift
|
||||
pub color_v_phase: f32,
|
||||
/// Accumulated per-dab saturation shift
|
||||
pub color_s_phase: f32,
|
||||
}
|
||||
|
||||
impl StrokeState {
|
||||
pub fn new() -> Self {
|
||||
Self { distance_since_last_dab: 0.0 }
|
||||
Self {
|
||||
// Start at 1.0 so the first call always emits the stroke-start dab.
|
||||
partial_dabs: 1.0,
|
||||
smooth_x: 0.0,
|
||||
smooth_y: 0.0,
|
||||
smooth_initialized: false,
|
||||
rng_seed: 0xDEAD_BEEF,
|
||||
color_h_phase: 0.0,
|
||||
color_v_phase: 0.0,
|
||||
color_s_phase: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,37 +123,199 @@ impl Default for StrokeState {
|
||||
fn default() -> Self { Self::new() }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// xorshift32 — fast, no-alloc PRNG. Returns a value in [0, 1).
|
||||
#[inline]
|
||||
fn xorshift(seed: &mut u32) -> f32 {
|
||||
let mut s = *seed;
|
||||
s ^= s << 13;
|
||||
s ^= s >> 17;
|
||||
s ^= s << 5;
|
||||
*seed = s;
|
||||
(s as f32) / (u32::MAX as f32)
|
||||
}
|
||||
|
||||
/// Box-Muller Gaussian sample with mean 0 and std-dev 1.
|
||||
/// Consumes two xorshift samples; the second half of the pair is discarded
|
||||
/// (acceptable for brush jitter which doesn't need correlated pairs).
|
||||
#[inline]
|
||||
fn gaussian(seed: &mut u32) -> f32 {
|
||||
let u1 = xorshift(seed).max(1e-7); // avoid ln(0)
|
||||
let u2 = xorshift(seed);
|
||||
(-2.0 * u1.ln()).sqrt() * (2.0 * std::f32::consts::PI * u2).cos()
|
||||
}
|
||||
|
||||
/// Convert linear RGB (not premultiplied) to HSV.
|
||||
fn rgb_to_hsv(r: f32, g: f32, b: f32) -> (f32, f32, f32) {
|
||||
let max = r.max(g).max(b);
|
||||
let min = r.min(g).min(b);
|
||||
let delta = max - min;
|
||||
let v = max;
|
||||
let s = if max > 1e-6 { delta / max } else { 0.0 };
|
||||
let h = if delta < 1e-6 {
|
||||
0.0
|
||||
} else if max == r {
|
||||
((g - b) / delta).rem_euclid(6.0) / 6.0
|
||||
} else if max == g {
|
||||
((b - r) / delta + 2.0) / 6.0
|
||||
} else {
|
||||
((r - g) / delta + 4.0) / 6.0
|
||||
};
|
||||
(h, s, v)
|
||||
}
|
||||
|
||||
/// Convert HSV to linear RGB.
|
||||
fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) {
|
||||
let h6 = h.rem_euclid(1.0) * 6.0;
|
||||
let i = h6.floor() as i32;
|
||||
let f = h6 - i as f32;
|
||||
let p = v * (1.0 - s);
|
||||
let q = v * (1.0 - s * f);
|
||||
let t = v * (1.0 - s * (1.0 - f));
|
||||
match i % 6 {
|
||||
0 => (v, t, p),
|
||||
1 => (q, v, p),
|
||||
2 => (p, v, t),
|
||||
3 => (p, q, v),
|
||||
4 => (t, p, v),
|
||||
_ => (v, p, q),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Per-dab effects helper
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Apply per-dab randomness and color-shift effects, matching libmypaint.
|
||||
///
|
||||
/// Returns `(ex, ey, radius, opacity, cr, cg, cb)` ready for the dab emitter.
|
||||
///
|
||||
/// Opacity uses the `opaque_linearize` formula (same fixed brush-level estimate
|
||||
/// whether called from the single-point path or the drag path).
|
||||
///
|
||||
/// Jitter uses Gaussian noise (matching libmypaint), not uniform.
|
||||
///
|
||||
/// Radius jitter applies an opacity correction `× (base_r / jittered_r)²` to
|
||||
/// keep perceived ink-amount constant as radius varies (matches libmypaint).
|
||||
fn apply_dab_effects(
|
||||
state: &mut StrokeState,
|
||||
bs: &crate::brush_settings::BrushSettings,
|
||||
x: f32, y: f32,
|
||||
base_radius: f32, // radius_at_pressure(pressure), before jitter
|
||||
pressure: f32,
|
||||
color: [f32; 4],
|
||||
) -> (f32, f32, f32, f32, f32, f32, f32) {
|
||||
// ---- Opacity (libmypaint opaque_linearize formula) --------------------
|
||||
// Estimate average dab overlap per pixel from brush settings (fixed, not
|
||||
// speed-dependent), then convert stroke-level opacity to per-dab alpha.
|
||||
let raw_dpp = ((bs.dabs_per_actual_radius + bs.dabs_per_radius) * 2.0).max(1.0);
|
||||
let dabs_per_pixel = (1.0 + bs.opaque_linearize * (raw_dpp - 1.0)).max(1.0);
|
||||
let raw_o = bs.opacity_at_pressure(pressure);
|
||||
let mut opacity = 1.0 - (1.0 - raw_o).powf(1.0 / dabs_per_pixel);
|
||||
|
||||
// ---- Radius jitter (Gaussian in log-space, matching libmypaint) -------
|
||||
let mut radius = base_radius;
|
||||
if bs.radius_by_random != 0.0 {
|
||||
let noise = gaussian(&mut state.rng_seed) * bs.radius_by_random;
|
||||
let jittered_log = bs.radius_log + noise;
|
||||
radius = jittered_log.exp().clamp(0.5, 500.0);
|
||||
// Opacity correction: keep ink-amount constant as radius varies.
|
||||
let alpha_correction = (base_radius / radius).powi(2);
|
||||
opacity = (opacity * alpha_correction).clamp(0.0, 1.0);
|
||||
}
|
||||
|
||||
// ---- Position jitter + fixed offset (Gaussian, matching libmypaint) ---
|
||||
let mut ex = x;
|
||||
let mut ey = y;
|
||||
if bs.offset_by_random != 0.0 || bs.offset_x != 0.0 || bs.offset_y != 0.0 {
|
||||
// libmypaint uses base_radius (no-pressure) for the jitter scale.
|
||||
let base_r_fixed = bs.radius_log.exp();
|
||||
ex += gaussian(&mut state.rng_seed) * bs.offset_by_random * base_r_fixed
|
||||
+ bs.offset_x * base_r_fixed;
|
||||
ey += gaussian(&mut state.rng_seed) * bs.offset_by_random * base_r_fixed
|
||||
+ bs.offset_y * base_r_fixed;
|
||||
}
|
||||
|
||||
// ---- Per-dab color phase shifts ---------------------------------------
|
||||
state.color_h_phase += bs.change_color_h;
|
||||
state.color_v_phase += bs.change_color_v;
|
||||
state.color_s_phase += bs.change_color_hsv_s;
|
||||
|
||||
let (mut cr, mut cg, mut cb) = (color[0], color[1], color[2]);
|
||||
let ca = color[3];
|
||||
if ca > 1e-6
|
||||
&& (bs.change_color_h != 0.0
|
||||
|| bs.change_color_v != 0.0
|
||||
|| bs.change_color_hsv_s != 0.0)
|
||||
{
|
||||
let (ur, ug, ub) = (cr / ca, cg / ca, cb / ca);
|
||||
let (mut h, mut s, mut v) = rgb_to_hsv(ur, ug, ub);
|
||||
h = (h + state.color_h_phase).rem_euclid(1.0);
|
||||
v = (v + state.color_v_phase).clamp(0.0, 1.0);
|
||||
s = (s + state.color_s_phase).clamp(0.0, 1.0);
|
||||
let (r2, g2, b2) = hsv_to_rgb(h, s, v);
|
||||
cr = r2 * ca;
|
||||
cg = g2 * ca;
|
||||
cb = b2 * ca;
|
||||
}
|
||||
|
||||
(ex, ey, radius, opacity.clamp(0.0, 1.0), cr, cg, cb)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Brush engine
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Pure-Rust MyPaint-style Gaussian dab brush engine
|
||||
pub struct BrushEngine;
|
||||
|
||||
impl BrushEngine {
|
||||
/// Compute the list of GPU dabs for a stroke segment.
|
||||
///
|
||||
/// Uses the same dab-spacing logic as [`apply_stroke_with_state`] but produces
|
||||
/// [`GpuDab`] structs for upload to the GPU compute pipeline instead of painting
|
||||
/// into a pixel buffer.
|
||||
/// `dt` is the elapsed time in seconds since the previous call for this
|
||||
/// stroke. Pass `0.0` on the very first call (stroke start).
|
||||
///
|
||||
/// Also returns the union bounding box of all dabs as `(x0, y0, x1, y1)` in
|
||||
/// integer canvas pixel coordinates (clamped to non-negative values; `x0==i32::MAX`
|
||||
/// when the returned Vec is empty).
|
||||
/// Follows the libmypaint spacing model: distance-based and time-based
|
||||
/// contributions are **summed** in a single `partial_dabs` accumulator.
|
||||
/// A dab is emitted whenever `partial_dabs` reaches 1.0.
|
||||
///
|
||||
/// Also returns the union bounding box of all dabs as `(x0, y0, x1, y1)`.
|
||||
pub fn compute_dabs(
|
||||
stroke: &StrokeRecord,
|
||||
state: &mut StrokeState,
|
||||
dt: f32,
|
||||
) -> (Vec<GpuDab>, (i32, i32, i32, i32)) {
|
||||
let mut dabs: Vec<GpuDab> = Vec::new();
|
||||
let mut bbox = (i32::MAX, i32::MAX, i32::MIN, i32::MIN);
|
||||
let bs = &stroke.brush_settings;
|
||||
|
||||
let blend_mode_u = match stroke.blend_mode {
|
||||
RasterBlendMode::Normal => 0u32,
|
||||
RasterBlendMode::Erase => 1u32,
|
||||
RasterBlendMode::Smudge => 2u32,
|
||||
// Determine blend mode, allowing brush settings to override Normal
|
||||
let base_blend = match stroke.blend_mode {
|
||||
RasterBlendMode::Normal if bs.eraser > 0.5 => RasterBlendMode::Erase,
|
||||
RasterBlendMode::Normal if bs.smudge > 0.5 => RasterBlendMode::Smudge,
|
||||
other => other,
|
||||
};
|
||||
let blend_mode_u = match base_blend {
|
||||
RasterBlendMode::Normal => 0u32,
|
||||
RasterBlendMode::Erase => 1u32,
|
||||
RasterBlendMode::Smudge => 2u32,
|
||||
RasterBlendMode::CloneStamp => 3u32,
|
||||
RasterBlendMode::Healing => 4u32,
|
||||
RasterBlendMode::PatternStamp => 5u32,
|
||||
RasterBlendMode::DodgeBurn => 6u32,
|
||||
RasterBlendMode::Sponge => 7u32,
|
||||
RasterBlendMode::BlurSharpen => 8u32,
|
||||
};
|
||||
|
||||
let push_dab = |dabs: &mut Vec<GpuDab>,
|
||||
bbox: &mut (i32, i32, i32, i32),
|
||||
x: f32, y: f32,
|
||||
radius: f32, opacity: f32,
|
||||
ndx: f32, ndy: f32, smudge_dist: f32| {
|
||||
bbox: &mut (i32, i32, i32, i32),
|
||||
x: f32, y: f32,
|
||||
radius: f32, opacity: f32,
|
||||
cr: f32, cg: f32, cb: f32,
|
||||
ndx: f32, ndy: f32, smudge_dist: f32| {
|
||||
let r_fringe = radius + 1.0;
|
||||
bbox.0 = bbox.0.min((x - r_fringe).floor() as i32);
|
||||
bbox.1 = bbox.1.min((y - r_fringe).floor() as i32);
|
||||
@@ -124,32 +323,83 @@ impl BrushEngine {
|
||||
bbox.3 = bbox.3.max((y + r_fringe).ceil() as i32);
|
||||
dabs.push(GpuDab {
|
||||
x, y, radius,
|
||||
hardness: stroke.brush_settings.hardness,
|
||||
hardness: bs.hardness,
|
||||
opacity,
|
||||
color_r: stroke.color[0],
|
||||
color_g: stroke.color[1],
|
||||
color_b: stroke.color[2],
|
||||
color_a: stroke.color[3],
|
||||
color_r: cr,
|
||||
color_g: cg,
|
||||
color_b: cb,
|
||||
// Clone stamp: color_r/color_g hold source canvas X/Y, so color_a = 1.0
|
||||
// (blend strength is opa_weight × opacity × 1.0 in the shader).
|
||||
color_a: if base_blend.uses_brush_color() { stroke.color[3] } else { 1.0 },
|
||||
ndx, ndy, smudge_dist,
|
||||
blend_mode: blend_mode_u,
|
||||
_pad0: 0, _pad1: 0, _pad2: 0,
|
||||
elliptical_dab_ratio: bs.elliptical_dab_ratio.max(1.0),
|
||||
elliptical_dab_angle: bs.elliptical_dab_angle.to_radians(),
|
||||
lock_alpha: bs.lock_alpha,
|
||||
});
|
||||
};
|
||||
|
||||
// Time-based accumulation: dt × dabs_per_second contributes to partial_dabs
|
||||
// regardless of whether the cursor moved.
|
||||
// Cap dt to 0.1 s to avoid a burst of dabs after a long pause.
|
||||
let dt_capped = dt.min(0.1);
|
||||
state.partial_dabs += dt_capped * bs.dabs_per_second;
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Single-point path: emit time-based (and stroke-start) dabs.
|
||||
// The caller is responsible for timing; we just fire whenever
|
||||
// partial_dabs ≥ 1.0.
|
||||
// ----------------------------------------------------------------
|
||||
if stroke.points.len() < 2 {
|
||||
if let Some(pt) = stroke.points.first() {
|
||||
let r = stroke.brush_settings.radius_at_pressure(pt.pressure);
|
||||
let raw_o = stroke.brush_settings.opacity_at_pressure(pt.pressure);
|
||||
let o = 1.0 - (1.0 - raw_o).powf(stroke.brush_settings.dabs_per_radius * 0.5);
|
||||
// Single-tap smudge has no direction — skip (same as CPU engine)
|
||||
if !matches!(stroke.blend_mode, RasterBlendMode::Smudge) {
|
||||
push_dab(&mut dabs, &mut bbox, pt.x, pt.y, r, o, 0.0, 0.0, 0.0);
|
||||
if !state.smooth_initialized {
|
||||
state.smooth_x = pt.x;
|
||||
state.smooth_y = pt.y;
|
||||
state.smooth_initialized = true;
|
||||
}
|
||||
while state.partial_dabs >= 1.0 {
|
||||
state.partial_dabs -= 1.0;
|
||||
let base_r = bs.radius_at_pressure(pt.pressure);
|
||||
let (ex, ey, r, o, cr, cg, cb) = apply_dab_effects(
|
||||
state, bs, pt.x, pt.y, base_r, pt.pressure, stroke.color,
|
||||
);
|
||||
if !matches!(base_blend, RasterBlendMode::Smudge) {
|
||||
let tp = &stroke.tool_params;
|
||||
let (cr2, cg2, cb2, ndx2, ndy2) = match base_blend {
|
||||
RasterBlendMode::CloneStamp | RasterBlendMode::Healing =>
|
||||
(tp[0], tp[1], 0.0, 0.0, 0.0),
|
||||
RasterBlendMode::PatternStamp =>
|
||||
(cr, cg, cb, tp[0], tp[1]),
|
||||
RasterBlendMode::DodgeBurn | RasterBlendMode::Sponge =>
|
||||
(tp[0], 0.0, 0.0, 0.0, 0.0),
|
||||
RasterBlendMode::BlurSharpen =>
|
||||
(tp[0], 0.0, 0.0, tp[1], 0.0),
|
||||
_ => (cr, cg, cb, 0.0, 0.0),
|
||||
};
|
||||
push_dab(&mut dabs, &mut bbox, ex, ey, r, o, cr2, cg2, cb2,
|
||||
ndx2, ndy2, 0.0);
|
||||
}
|
||||
}
|
||||
state.distance_since_last_dab = 0.0;
|
||||
}
|
||||
return (dabs, bbox);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// Drag path: walk the polyline, accumulating partial_dabs from
|
||||
// both distance-based and time-based contributions.
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
// Track the last smoothed position so that any residual time-based
|
||||
// dabs can be emitted at the end of the segment walk.
|
||||
let mut last_smooth_x = state.smooth_x;
|
||||
let mut last_smooth_y = state.smooth_y;
|
||||
let mut last_pressure = stroke.points.last()
|
||||
.map(|p| p.pressure)
|
||||
.unwrap_or(1.0);
|
||||
|
||||
// Fixed base radius (no pressure) used for the basic-radius spacing rate.
|
||||
let base_radius_fixed = bs.radius_log.exp();
|
||||
|
||||
for window in stroke.points.windows(2) {
|
||||
let p0 = &window[0];
|
||||
let p1 = &window[1];
|
||||
@@ -159,45 +409,143 @@ impl BrushEngine {
|
||||
let seg_len = (dx * dx + dy * dy).sqrt();
|
||||
if seg_len < 1e-4 { continue; }
|
||||
|
||||
last_pressure = p1.pressure;
|
||||
|
||||
let mut t = 0.0f32;
|
||||
while t < 1.0 {
|
||||
let pressure = p0.pressure + t * (p1.pressure - p0.pressure);
|
||||
let radius = stroke.brush_settings.radius_at_pressure(pressure);
|
||||
let spacing = (radius * stroke.brush_settings.dabs_per_radius).max(0.5);
|
||||
let radius_for_rate = bs.radius_at_pressure(pressure);
|
||||
|
||||
let dist_to_next = spacing - state.distance_since_last_dab;
|
||||
let seg_t_to_next = (dist_to_next / seg_len).max(0.0);
|
||||
// Dab rate = sum of distance-based contributions (dabs per pixel).
|
||||
// Matches libmypaint: dabs_per_actual/actual_r + dabs_per_basic/base_r.
|
||||
// For elliptical brushes use the minor-axis radius so dabs connect
|
||||
// when moving perpendicular to the major axis.
|
||||
let eff_radius = if bs.elliptical_dab_ratio > 1.001 {
|
||||
radius_for_rate / bs.elliptical_dab_ratio
|
||||
} else {
|
||||
radius_for_rate
|
||||
};
|
||||
let rate_actual = if bs.dabs_per_actual_radius > 0.0 {
|
||||
bs.dabs_per_actual_radius / eff_radius
|
||||
} else { 0.0 };
|
||||
let rate_basic = if bs.dabs_per_radius > 0.0 {
|
||||
bs.dabs_per_radius / base_radius_fixed
|
||||
} else { 0.0 };
|
||||
let rate = rate_actual + rate_basic; // dabs per pixel
|
||||
|
||||
let remaining = 1.0 - state.partial_dabs;
|
||||
let pixels_to_next = if rate > 1e-8 { remaining / rate } else { f32::MAX };
|
||||
let seg_t_to_next = (pixels_to_next / seg_len).max(0.0);
|
||||
|
||||
if seg_t_to_next > 1.0 - t {
|
||||
state.distance_since_last_dab += seg_len * (1.0 - t);
|
||||
// Won't reach the next dab within this segment.
|
||||
if rate > 1e-8 {
|
||||
state.partial_dabs += (1.0 - t) * seg_len * rate;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
t += seg_t_to_next;
|
||||
let x2 = p0.x + t * dx;
|
||||
let y2 = p0.y + t * dy;
|
||||
let pressure2 = p0.pressure + t * (p1.pressure - p0.pressure);
|
||||
let radius2 = stroke.brush_settings.radius_at_pressure(pressure2);
|
||||
let raw_opacity = stroke.brush_settings.opacity_at_pressure(pressure2);
|
||||
// Normalize per-dab opacity so dense dabs don't saturate faster than sparse ones.
|
||||
// Formula: per_dab = 1 − (1 − raw)^(dabs_per_radius / 2)
|
||||
// Derivation: N = 2/dabs_per_radius dabs cover one full diameter at the centre;
|
||||
// accumulated = 1 − (1 − per_dab)^N = raw → per_dab = 1 − (1−raw)^(dabs_per_radius/2)
|
||||
let opacity2 = 1.0 - (1.0 - raw_opacity).powf(stroke.brush_settings.dabs_per_radius * 0.5);
|
||||
|
||||
if matches!(stroke.blend_mode, RasterBlendMode::Smudge) {
|
||||
let ndx = dx / seg_len;
|
||||
let ndy = dy / seg_len;
|
||||
let smudge_dist =
|
||||
(radius2 * stroke.brush_settings.dabs_per_radius).max(1.0);
|
||||
push_dab(&mut dabs, &mut bbox,
|
||||
x2, y2, radius2, opacity2, ndx, ndy, smudge_dist);
|
||||
} else {
|
||||
push_dab(&mut dabs, &mut bbox,
|
||||
x2, y2, radius2, opacity2, 0.0, 0.0, 0.0);
|
||||
// Stroke threshold gating
|
||||
if pressure2 < bs.stroke_threshold {
|
||||
state.partial_dabs = 0.0;
|
||||
continue;
|
||||
}
|
||||
|
||||
state.distance_since_last_dab = 0.0;
|
||||
let base_r2 = bs.radius_at_pressure(pressure2);
|
||||
|
||||
// Slow tracking: exponential position smoothing
|
||||
let x2 = p0.x + t * dx;
|
||||
let y2 = p0.y + t * dy;
|
||||
if !state.smooth_initialized {
|
||||
state.smooth_x = x2; state.smooth_y = y2;
|
||||
state.smooth_initialized = true;
|
||||
}
|
||||
// spacing_px ≈ 1 / rate (pixels per dab), used as time-constant scale
|
||||
let spacing_px = if rate > 1e-8 { 1.0 / rate } else { 1.0 };
|
||||
let k = if bs.slow_tracking > 0.0 {
|
||||
(-spacing_px / bs.slow_tracking.max(0.1)).exp()
|
||||
} else { 0.0 };
|
||||
state.smooth_x = state.smooth_x * k + x2 * (1.0 - k);
|
||||
state.smooth_y = state.smooth_y * k + y2 * (1.0 - k);
|
||||
last_smooth_x = state.smooth_x;
|
||||
last_smooth_y = state.smooth_y;
|
||||
|
||||
let (sx, sy) = (state.smooth_x, state.smooth_y);
|
||||
let (ex, ey, radius2, opacity2, cr, cg, cb) = apply_dab_effects(
|
||||
state, bs, sx, sy, base_r2, pressure2, stroke.color,
|
||||
);
|
||||
|
||||
if matches!(base_blend, RasterBlendMode::Smudge) {
|
||||
let ndx = dx / seg_len;
|
||||
let ndy = dy / seg_len;
|
||||
// strength=1.0 → sample from 1 dab back (drag pixels with us).
|
||||
// strength=0.0 → sample from current position (no change).
|
||||
// smudge_radius_log is repurposed as a linear [0,1] strength value here.
|
||||
let smudge_dist = spacing_px * bs.smudge_radius_log.clamp(0.0, 1.0);
|
||||
push_dab(&mut dabs, &mut bbox,
|
||||
ex, ey, radius2, opacity2, cr, cg, cb,
|
||||
ndx, ndy, smudge_dist);
|
||||
} else {
|
||||
let tp = &stroke.tool_params;
|
||||
let (cr2, cg2, cb2, ndx2, ndy2) = match base_blend {
|
||||
RasterBlendMode::CloneStamp | RasterBlendMode::Healing =>
|
||||
(tp[0], tp[1], 0.0, 0.0, 0.0),
|
||||
RasterBlendMode::PatternStamp =>
|
||||
(cr, cg, cb, tp[0], tp[1]),
|
||||
RasterBlendMode::DodgeBurn | RasterBlendMode::Sponge =>
|
||||
(tp[0], 0.0, 0.0, 0.0, 0.0),
|
||||
RasterBlendMode::BlurSharpen =>
|
||||
(tp[0], 0.0, 0.0, tp[1], 0.0),
|
||||
_ => (cr, cg, cb, 0.0, 0.0),
|
||||
};
|
||||
push_dab(&mut dabs, &mut bbox,
|
||||
ex, ey, radius2, opacity2, cr2, cg2, cb2,
|
||||
ndx2, ndy2, 0.0);
|
||||
}
|
||||
|
||||
state.partial_dabs = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
// Emit any residual time-based dabs (partial_dabs ≥ 1.0 from the dt
|
||||
// contribution not consumed by distance-based movement) at the last
|
||||
// known cursor position.
|
||||
if state.partial_dabs >= 1.0 && !matches!(base_blend, RasterBlendMode::Smudge) {
|
||||
// Initialise smooth position if we never entered the segment loop.
|
||||
if !state.smooth_initialized {
|
||||
if let Some(pt) = stroke.points.last() {
|
||||
state.smooth_x = pt.x;
|
||||
state.smooth_y = pt.y;
|
||||
state.smooth_initialized = true;
|
||||
last_smooth_x = state.smooth_x;
|
||||
last_smooth_y = state.smooth_y;
|
||||
}
|
||||
}
|
||||
while state.partial_dabs >= 1.0 {
|
||||
state.partial_dabs -= 1.0;
|
||||
let base_r = bs.radius_at_pressure(last_pressure);
|
||||
let (ex, ey, r, o, cr, cg, cb) = apply_dab_effects(
|
||||
state, bs,
|
||||
last_smooth_x, last_smooth_y,
|
||||
base_r, last_pressure, stroke.color,
|
||||
);
|
||||
let tp = &stroke.tool_params;
|
||||
let (cr2, cg2, cb2, ndx2, ndy2) = match base_blend {
|
||||
RasterBlendMode::CloneStamp | RasterBlendMode::Healing =>
|
||||
(tp[0], tp[1], 0.0, 0.0, 0.0),
|
||||
RasterBlendMode::PatternStamp =>
|
||||
(cr, cg, cb, tp[0], tp[1]),
|
||||
RasterBlendMode::DodgeBurn | RasterBlendMode::Sponge =>
|
||||
(tp[0], 0.0, 0.0, 0.0, 0.0),
|
||||
RasterBlendMode::BlurSharpen =>
|
||||
(tp[0], 0.0, 0.0, tp[1], 0.0),
|
||||
_ => (cr, cg, cb, 0.0, 0.0),
|
||||
};
|
||||
push_dab(&mut dabs, &mut bbox, ex, ey, r, o, cr2, cg2, cb2,
|
||||
ndx2, ndy2, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,63 +1,215 @@
|
||||
//! Brush settings for the raster paint engine
|
||||
//!
|
||||
//! Settings that describe the appearance and behavior of a paint brush.
|
||||
//! Compatible with MyPaint .myb brush file format (subset).
|
||||
//! Compatible with MyPaint .myb brush file format.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
/// Settings for a paint brush
|
||||
/// Settings for a paint brush — mirrors the MyPaint .myb settings schema.
|
||||
///
|
||||
/// All fields correspond directly to MyPaint JSON keys. Fields marked
|
||||
/// "parse-only" are stored so that .myb files round-trip cleanly; they will
|
||||
/// be used when the dynamic-input system is wired up in a future task.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct BrushSettings {
|
||||
// ── Core shape ──────────────────────────────────────────────────────────
|
||||
/// log(radius) base value; actual radius = exp(radius_log)
|
||||
pub radius_log: f32,
|
||||
/// Edge hardness 0.0 (fully soft/gaussian) to 1.0 (hard edge)
|
||||
pub hardness: f32,
|
||||
/// Base opacity 0.0–1.0
|
||||
pub opaque: f32,
|
||||
/// Dab spacing as fraction of radius (smaller = denser strokes)
|
||||
/// Additional opacity multiplier (opaque_multiply)
|
||||
pub opaque_multiply: f32,
|
||||
/// Dabs per basic_radius distance (MyPaint: dabs_per_basic_radius)
|
||||
pub dabs_per_radius: f32,
|
||||
/// Dabs per actual (pressure-modified) radius distance
|
||||
pub dabs_per_actual_radius: f32,
|
||||
|
||||
// ── Elliptical dab ──────────────────────────────────────────────────────
|
||||
/// Dab aspect ratio ≥ 1.0 (1.0 = circle, 3.0 = 3:1 ellipse)
|
||||
pub elliptical_dab_ratio: f32,
|
||||
/// Elliptical dab rotation angle in degrees (0–180)
|
||||
pub elliptical_dab_angle: f32,
|
||||
|
||||
// ── Jitter / offset ─────────────────────────────────────────────────────
|
||||
/// Random radius variation (log-scale, 0 = none)
|
||||
pub radius_by_random: f32,
|
||||
/// Random positional jitter in units of radius
|
||||
pub offset_by_random: f32,
|
||||
/// Fixed X offset in units of radius
|
||||
pub offset_x: f32,
|
||||
/// Fixed Y offset in units of radius
|
||||
pub offset_y: f32,
|
||||
|
||||
// ── Position tracking ───────────────────────────────────────────────────
|
||||
/// Slow position tracking — higher = brush lags behind cursor more
|
||||
pub slow_tracking: f32,
|
||||
/// Per-dab position tracking smoothing
|
||||
pub slow_tracking_per_dab: f32,
|
||||
|
||||
// ── Color ───────────────────────────────────────────────────────────────
|
||||
/// HSV hue (0.0–1.0); usually overridden by stroke color
|
||||
pub color_h: f32,
|
||||
/// HSV saturation (0.0–1.0)
|
||||
pub color_s: f32,
|
||||
/// HSV value (0.0–1.0)
|
||||
pub color_v: f32,
|
||||
/// Per-dab hue shift (accumulates over the stroke)
|
||||
pub change_color_h: f32,
|
||||
/// Per-dab HSV value shift
|
||||
pub change_color_v: f32,
|
||||
/// Per-dab HSV saturation shift
|
||||
pub change_color_hsv_s: f32,
|
||||
/// Per-dab HSL lightness shift
|
||||
pub change_color_l: f32,
|
||||
/// Per-dab HSL saturation shift
|
||||
pub change_color_hsl_s: f32,
|
||||
|
||||
// ── Blend ───────────────────────────────────────────────────────────────
|
||||
/// Lock alpha channel (0 = off, 1 = on — don't modify destination alpha)
|
||||
pub lock_alpha: f32,
|
||||
/// Eraser strength (>0.5 activates erase blend when tool mode is Normal)
|
||||
pub eraser: f32,
|
||||
|
||||
// ── Smudge ──────────────────────────────────────────────────────────────
|
||||
/// Smudge amount (>0.5 activates smudge blend when tool mode is Normal)
|
||||
pub smudge: f32,
|
||||
/// How quickly the smudge color updates (0 = instant, 1 = slow)
|
||||
pub smudge_length: f32,
|
||||
/// Smudge pickup radius offset (log-scale added to radius_log)
|
||||
pub smudge_radius_log: f32,
|
||||
|
||||
// ── Stroke gating ───────────────────────────────────────────────────────
|
||||
/// Minimum pressure required to emit dabs (0 = always emit)
|
||||
pub stroke_threshold: f32,
|
||||
|
||||
// ── Pressure dynamics ───────────────────────────────────────────────────
|
||||
/// How much pressure increases/decreases radius
|
||||
/// Final radius = exp(radius_log + pressure_radius_gain * pressure)
|
||||
pub pressure_radius_gain: f32,
|
||||
/// How much pressure increases/decreases opacity
|
||||
/// Final opacity = opaque * (1 + pressure_opacity_gain * (pressure - 0.5))
|
||||
pub pressure_opacity_gain: f32,
|
||||
|
||||
// ── Parse-only: future input curve system ───────────────────────────────
|
||||
pub opaque_linearize: f32,
|
||||
pub anti_aliasing: f32,
|
||||
pub dabs_per_second: f32,
|
||||
pub offset_by_speed: f32,
|
||||
pub offset_by_speed_slowness: f32,
|
||||
pub speed1_slowness: f32,
|
||||
pub speed2_slowness: f32,
|
||||
pub speed1_gamma: f32,
|
||||
pub speed2_gamma: f32,
|
||||
pub direction_filter: f32,
|
||||
pub stroke_duration_log: f32,
|
||||
pub stroke_holdtime: f32,
|
||||
pub pressure_gain_log: f32,
|
||||
pub smudge_transparency: f32,
|
||||
pub smudge_length_log: f32,
|
||||
pub smudge_bucket: f32,
|
||||
pub paint_mode: f32,
|
||||
pub colorize: f32,
|
||||
pub posterize: f32,
|
||||
pub posterize_num: f32,
|
||||
pub snap_to_pixel: f32,
|
||||
pub custom_input: f32,
|
||||
pub custom_input_slowness: f32,
|
||||
pub gridmap_scale: f32,
|
||||
pub gridmap_scale_x: f32,
|
||||
pub gridmap_scale_y: f32,
|
||||
pub restore_color: f32,
|
||||
pub offset_angle: f32,
|
||||
pub offset_angle_asc: f32,
|
||||
pub offset_angle_view: f32,
|
||||
pub offset_angle_2: f32,
|
||||
pub offset_angle_2_asc: f32,
|
||||
pub offset_angle_2_view: f32,
|
||||
pub offset_angle_adj: f32,
|
||||
pub offset_multiplier: f32,
|
||||
}
|
||||
|
||||
impl BrushSettings {
|
||||
/// Default soft round brush (smooth Gaussian falloff)
|
||||
pub fn default_round_soft() -> Self {
|
||||
Self {
|
||||
radius_log: 2.0, // radius ≈ 7.4 px
|
||||
radius_log: 2.0,
|
||||
hardness: 0.1,
|
||||
opaque: 0.8,
|
||||
dabs_per_radius: 0.25,
|
||||
opaque_multiply: 0.0,
|
||||
dabs_per_radius: 2.0,
|
||||
dabs_per_actual_radius: 2.0,
|
||||
elliptical_dab_ratio: 1.0,
|
||||
elliptical_dab_angle: 90.0,
|
||||
radius_by_random: 0.0,
|
||||
offset_by_random: 0.0,
|
||||
offset_x: 0.0,
|
||||
offset_y: 0.0,
|
||||
slow_tracking: 0.0,
|
||||
slow_tracking_per_dab: 0.0,
|
||||
color_h: 0.0,
|
||||
color_s: 0.0,
|
||||
color_v: 0.0,
|
||||
change_color_h: 0.0,
|
||||
change_color_v: 0.0,
|
||||
change_color_hsv_s: 0.0,
|
||||
change_color_l: 0.0,
|
||||
change_color_hsl_s: 0.0,
|
||||
lock_alpha: 0.0,
|
||||
eraser: 0.0,
|
||||
smudge: 0.0,
|
||||
smudge_length: 0.5,
|
||||
smudge_radius_log: 0.0,
|
||||
stroke_threshold: 0.0,
|
||||
pressure_radius_gain: 0.5,
|
||||
pressure_opacity_gain: 1.0,
|
||||
opaque_linearize: 0.9,
|
||||
anti_aliasing: 1.0,
|
||||
dabs_per_second: 0.0,
|
||||
offset_by_speed: 0.0,
|
||||
offset_by_speed_slowness: 1.0,
|
||||
speed1_slowness: 0.04,
|
||||
speed2_slowness: 0.8,
|
||||
speed1_gamma: 4.0,
|
||||
speed2_gamma: 4.0,
|
||||
direction_filter: 2.0,
|
||||
stroke_duration_log: 4.0,
|
||||
stroke_holdtime: 0.0,
|
||||
pressure_gain_log: 0.0,
|
||||
smudge_transparency: 0.0,
|
||||
smudge_length_log: 0.0,
|
||||
smudge_bucket: 0.0,
|
||||
paint_mode: 1.0,
|
||||
colorize: 0.0,
|
||||
posterize: 0.0,
|
||||
posterize_num: 0.05,
|
||||
snap_to_pixel: 0.0,
|
||||
custom_input: 0.0,
|
||||
custom_input_slowness: 0.0,
|
||||
gridmap_scale: 0.0,
|
||||
gridmap_scale_x: 1.0,
|
||||
gridmap_scale_y: 1.0,
|
||||
restore_color: 0.0,
|
||||
offset_angle: 0.0,
|
||||
offset_angle_asc: 0.0,
|
||||
offset_angle_view: 0.0,
|
||||
offset_angle_2: 0.0,
|
||||
offset_angle_2_asc: 0.0,
|
||||
offset_angle_2_view: 0.0,
|
||||
offset_angle_adj: 0.0,
|
||||
offset_multiplier: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Default hard round brush (sharp edge)
|
||||
pub fn default_round_hard() -> Self {
|
||||
Self {
|
||||
radius_log: 2.0,
|
||||
hardness: 0.9,
|
||||
opaque: 1.0,
|
||||
dabs_per_radius: 0.2,
|
||||
color_h: 0.0,
|
||||
color_s: 0.0,
|
||||
color_v: 0.0,
|
||||
dabs_per_radius: 2.0,
|
||||
pressure_radius_gain: 0.3,
|
||||
pressure_opacity_gain: 0.8,
|
||||
..Self::default_round_soft()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,10 +225,10 @@ impl BrushSettings {
|
||||
o.clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// Parse a MyPaint .myb JSON brush file (subset).
|
||||
/// Parse a MyPaint .myb JSON brush file.
|
||||
///
|
||||
/// Reads `radius_logarithmic`, `hardness`, `opaque`, `dabs_per_basic_radius`,
|
||||
/// `color_h`, `color_s`, `color_v` from the `settings` key's `base_value` fields.
|
||||
/// Reads all known settings from `settings[key].base_value`.
|
||||
/// Unknown keys are silently ignored for forward compatibility.
|
||||
pub fn from_myb(json: &str) -> Result<Self, String> {
|
||||
let v: serde_json::Value =
|
||||
serde_json::from_str(json).map_err(|e| format!("JSON parse error: {e}"))?;
|
||||
@@ -92,15 +244,13 @@ impl BrushSettings {
|
||||
.unwrap_or(default)
|
||||
};
|
||||
|
||||
// Pressure dynamics: read from the "inputs" mapping of radius/opacity
|
||||
// For simplicity, look for the pressure input point in radius_logarithmic
|
||||
// Pressure dynamics: approximate from the pressure input curve endpoints
|
||||
let pressure_radius_gain = settings
|
||||
.get("radius_logarithmic")
|
||||
.and_then(|s| s.get("inputs"))
|
||||
.and_then(|inp| inp.get("pressure"))
|
||||
.and_then(|pts| pts.as_array())
|
||||
.and_then(|arr| {
|
||||
// arr = [[x0,y0],[x1,y1],...] – approximate as linear gain at x=1.0
|
||||
if arr.len() >= 2 {
|
||||
let y0 = arr[0].get(1)?.as_f64()? as f32;
|
||||
let y1 = arr[arr.len() - 1].get(1)?.as_f64()? as f32;
|
||||
@@ -128,15 +278,81 @@ impl BrushSettings {
|
||||
.unwrap_or(1.0);
|
||||
|
||||
Ok(Self {
|
||||
radius_log: read_base("radius_logarithmic", 2.0),
|
||||
hardness: read_base("hardness", 0.5).clamp(0.0, 1.0),
|
||||
opaque: read_base("opaque", 1.0).clamp(0.0, 1.0),
|
||||
dabs_per_radius: read_base("dabs_per_basic_radius", 0.25).clamp(0.01, 10.0),
|
||||
color_h: read_base("color_h", 0.0),
|
||||
color_s: read_base("color_s", 0.0),
|
||||
color_v: read_base("color_v", 0.0),
|
||||
// Core shape
|
||||
radius_log: read_base("radius_logarithmic", 2.0),
|
||||
hardness: read_base("hardness", 0.8).clamp(0.0, 1.0),
|
||||
opaque: read_base("opaque", 1.0).clamp(0.0, 2.0),
|
||||
opaque_multiply: read_base("opaque_multiply", 0.0),
|
||||
dabs_per_radius: read_base("dabs_per_basic_radius", 0.0).max(0.0),
|
||||
dabs_per_actual_radius: read_base("dabs_per_actual_radius", 2.0).max(0.0),
|
||||
// Elliptical dab
|
||||
elliptical_dab_ratio: read_base("elliptical_dab_ratio", 1.0).max(1.0),
|
||||
elliptical_dab_angle: read_base("elliptical_dab_angle", 90.0),
|
||||
// Jitter / offset
|
||||
radius_by_random: read_base("radius_by_random", 0.0),
|
||||
offset_by_random: read_base("offset_by_random", 0.0),
|
||||
offset_x: read_base("offset_x", 0.0),
|
||||
offset_y: read_base("offset_y", 0.0),
|
||||
// Tracking
|
||||
slow_tracking: read_base("slow_tracking", 0.0),
|
||||
slow_tracking_per_dab: read_base("slow_tracking_per_dab", 0.0),
|
||||
// Color
|
||||
color_h: read_base("color_h", 0.0),
|
||||
color_s: read_base("color_s", 0.0),
|
||||
color_v: read_base("color_v", 0.0),
|
||||
change_color_h: read_base("change_color_h", 0.0),
|
||||
change_color_v: read_base("change_color_v", 0.0),
|
||||
change_color_hsv_s: read_base("change_color_hsv_s", 0.0),
|
||||
change_color_l: read_base("change_color_l", 0.0),
|
||||
change_color_hsl_s: read_base("change_color_hsl_s", 0.0),
|
||||
// Blend
|
||||
lock_alpha: read_base("lock_alpha", 0.0).clamp(0.0, 1.0),
|
||||
eraser: read_base("eraser", 0.0).clamp(0.0, 1.0),
|
||||
// Smudge
|
||||
smudge: read_base("smudge", 0.0).clamp(0.0, 1.0),
|
||||
smudge_length: read_base("smudge_length", 0.5).clamp(0.0, 1.0),
|
||||
smudge_radius_log: read_base("smudge_radius_log", 0.0),
|
||||
// Stroke gating
|
||||
stroke_threshold: read_base("stroke_threshold", 0.0).clamp(0.0, 0.5),
|
||||
// Pressure dynamics
|
||||
pressure_radius_gain,
|
||||
pressure_opacity_gain,
|
||||
// Parse-only
|
||||
opaque_linearize: read_base("opaque_linearize", 0.9),
|
||||
anti_aliasing: read_base("anti_aliasing", 1.0),
|
||||
dabs_per_second: read_base("dabs_per_second", 0.0),
|
||||
offset_by_speed: read_base("offset_by_speed", 0.0),
|
||||
offset_by_speed_slowness: read_base("offset_by_speed_slowness", 1.0),
|
||||
speed1_slowness: read_base("speed1_slowness", 0.04),
|
||||
speed2_slowness: read_base("speed2_slowness", 0.8),
|
||||
speed1_gamma: read_base("speed1_gamma", 4.0),
|
||||
speed2_gamma: read_base("speed2_gamma", 4.0),
|
||||
direction_filter: read_base("direction_filter", 2.0),
|
||||
stroke_duration_log: read_base("stroke_duration_logarithmic", 4.0),
|
||||
stroke_holdtime: read_base("stroke_holdtime", 0.0),
|
||||
pressure_gain_log: read_base("pressure_gain_log", 0.0),
|
||||
smudge_transparency: read_base("smudge_transparency", 0.0),
|
||||
smudge_length_log: read_base("smudge_length_log", 0.0),
|
||||
smudge_bucket: read_base("smudge_bucket", 0.0),
|
||||
paint_mode: read_base("paint_mode", 1.0),
|
||||
colorize: read_base("colorize", 0.0),
|
||||
posterize: read_base("posterize", 0.0),
|
||||
posterize_num: read_base("posterize_num", 0.05),
|
||||
snap_to_pixel: read_base("snap_to_pixel", 0.0),
|
||||
custom_input: read_base("custom_input", 0.0),
|
||||
custom_input_slowness: read_base("custom_input_slowness", 0.0),
|
||||
gridmap_scale: read_base("gridmap_scale", 0.0),
|
||||
gridmap_scale_x: read_base("gridmap_scale_x", 1.0),
|
||||
gridmap_scale_y: read_base("gridmap_scale_y", 1.0),
|
||||
restore_color: read_base("restore_color", 0.0),
|
||||
offset_angle: read_base("offset_angle", 0.0),
|
||||
offset_angle_asc: read_base("offset_angle_asc", 0.0),
|
||||
offset_angle_view: read_base("offset_angle_view", 0.0),
|
||||
offset_angle_2: read_base("offset_angle_2", 0.0),
|
||||
offset_angle_2_asc: read_base("offset_angle_2_asc", 0.0),
|
||||
offset_angle_2_view: read_base("offset_angle_2_view", 0.0),
|
||||
offset_angle_adj: read_base("offset_angle_adj", 0.0),
|
||||
offset_multiplier: read_base("offset_multiplier", 0.0),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -146,3 +362,41 @@ impl Default for BrushSettings {
|
||||
Self::default_round_soft()
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Bundled brush presets
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// A named brush preset backed by a bundled .myb file.
|
||||
pub struct BrushPreset {
|
||||
pub name: &'static str,
|
||||
pub settings: BrushSettings,
|
||||
}
|
||||
|
||||
/// Returns the list of bundled brush presets (parsed once from embedded .myb files).
|
||||
///
|
||||
/// Sources: mypaint/mypaint-brushes — CC0 1.0 Universal (Public Domain)
|
||||
pub fn bundled_brushes() -> &'static [BrushPreset] {
|
||||
static CACHE: OnceLock<Vec<BrushPreset>> = OnceLock::new();
|
||||
CACHE.get_or_init(|| {
|
||||
let mut v = Vec::new();
|
||||
macro_rules! brush {
|
||||
($name:literal, $path:literal) => {
|
||||
if let Ok(s) = BrushSettings::from_myb(include_str!($path)) {
|
||||
v.push(BrushPreset { name: $name, settings: s });
|
||||
}
|
||||
};
|
||||
}
|
||||
brush!("Pencil", "../../../src/assets/brushes/pencil.myb");
|
||||
brush!("Pen", "../../../src/assets/brushes/pen.myb");
|
||||
brush!("Charcoal", "../../../src/assets/brushes/charcoal.myb");
|
||||
brush!("Brush", "../../../src/assets/brushes/brush.myb");
|
||||
brush!("Dry Brush", "../../../src/assets/brushes/dry_brush.myb");
|
||||
brush!("Ink", "../../../src/assets/brushes/ink_blot.myb");
|
||||
brush!("Calligraphy", "../../../src/assets/brushes/calligraphy.myb");
|
||||
brush!("Airbrush", "../../../src/assets/brushes/airbrush.myb");
|
||||
brush!("Chalk", "../../../src/assets/brushes/chalk.myb");
|
||||
brush!("Liner", "../../../src/assets/brushes/liner.myb");
|
||||
v
|
||||
})
|
||||
}
|
||||
|
||||
@@ -117,6 +117,8 @@ pub struct Face {
|
||||
pub image_fill: Option<uuid::Uuid>,
|
||||
pub fill_rule: FillRule,
|
||||
#[serde(default)]
|
||||
pub gradient_fill: Option<crate::gradient::ShapeGradient>,
|
||||
#[serde(default)]
|
||||
pub deleted: bool,
|
||||
}
|
||||
|
||||
@@ -244,6 +246,7 @@ impl Dcel {
|
||||
fill_color: None,
|
||||
image_fill: None,
|
||||
fill_rule: FillRule::NonZero,
|
||||
gradient_fill: None,
|
||||
deleted: false,
|
||||
};
|
||||
let debug_recorder = if std::env::var("DAW_DCEL_RECORD").is_ok() {
|
||||
@@ -375,6 +378,7 @@ impl Dcel {
|
||||
fill_color: None,
|
||||
image_fill: None,
|
||||
fill_rule: FillRule::NonZero,
|
||||
gradient_fill: None,
|
||||
deleted: false,
|
||||
};
|
||||
if let Some(idx) = self.free_faces.pop() {
|
||||
|
||||
@@ -390,6 +390,59 @@ impl VideoExportSettings {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Image export ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// Image export formats (single-frame still image)
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ImageFormat {
|
||||
Png,
|
||||
Jpeg,
|
||||
WebP,
|
||||
}
|
||||
|
||||
impl ImageFormat {
|
||||
pub fn name(self) -> &'static str {
|
||||
match self { Self::Png => "PNG", Self::Jpeg => "JPEG", Self::WebP => "WebP" }
|
||||
}
|
||||
pub fn extension(self) -> &'static str {
|
||||
match self { Self::Png => "png", Self::Jpeg => "jpg", Self::WebP => "webp" }
|
||||
}
|
||||
/// Whether quality (1–100) applies to this format.
|
||||
pub fn has_quality(self) -> bool { matches!(self, Self::Jpeg | Self::WebP) }
|
||||
}
|
||||
|
||||
/// Settings for exporting a single frame as a still image.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ImageExportSettings {
|
||||
pub format: ImageFormat,
|
||||
/// Document time (seconds) of the frame to render.
|
||||
pub time: f64,
|
||||
/// Override width; None = use document canvas width.
|
||||
pub width: Option<u32>,
|
||||
/// Override height; None = use document canvas height.
|
||||
pub height: Option<u32>,
|
||||
/// Encode quality 1–100 (JPEG / WebP only).
|
||||
pub quality: u8,
|
||||
/// Preserve the alpha channel in the output (respect document background alpha).
|
||||
/// When false, the image is composited onto an opaque background before encoding.
|
||||
/// Only meaningful for formats that support alpha (PNG, WebP).
|
||||
pub allow_transparency: bool,
|
||||
}
|
||||
|
||||
impl Default for ImageExportSettings {
|
||||
fn default() -> Self {
|
||||
Self { format: ImageFormat::Png, time: 0.0, width: None, height: None, quality: 90, allow_transparency: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl ImageExportSettings {
|
||||
pub fn validate(&self) -> Result<(), String> {
|
||||
if let Some(w) = self.width { if w == 0 { return Err("Width must be > 0".into()); } }
|
||||
if let Some(h) = self.height { if h == 0 { return Err("Height must be > 0".into()); } }
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Progress updates during export
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ExportProgress {
|
||||
|
||||
@@ -1,8 +1,198 @@
|
||||
//! Flood fill algorithm for paint bucket tool
|
||||
//! Flood fill algorithms for paint bucket tool
|
||||
//!
|
||||
//! This module implements a flood fill that tracks which curves each point
|
||||
//! touches. Instead of filling with pixels, it returns boundary points that
|
||||
//! can be used to construct a filled shape from exact curve geometry.
|
||||
//! This module contains two fill implementations:
|
||||
//! - `flood_fill` — vector curve-boundary fill (used by vector paint bucket)
|
||||
//! - `raster_flood_fill` — pixel BFS fill with configurable threshold, soft
|
||||
//! edge, and optional selection clipping (used by raster paint bucket)
|
||||
|
||||
// ── Raster flood fill ─────────────────────────────────────────────────────────
|
||||
|
||||
/// Which pixel to compare against when deciding if a neighbor should be filled.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum FillThresholdMode {
|
||||
/// Compare each candidate pixel to the original seed pixel (Photoshop default).
|
||||
Absolute,
|
||||
/// Compare each candidate pixel to the pixel it was reached from (spreads
|
||||
/// through gradients without a global seed-color reference).
|
||||
Relative,
|
||||
}
|
||||
|
||||
/// BFS / global scan flood fill mask.
|
||||
///
|
||||
/// Returns a `Vec<Option<f32>>` of length `width × height`:
|
||||
/// - `Some(d)` — pixel is within the fill region; `d` is the color distance
|
||||
/// from its comparison color (0.0 at seed, up to `threshold` at the edge).
|
||||
/// - `None` — pixel is outside the fill region.
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `pixels` – raw RGBA buffer (read-only)
|
||||
/// - `width/height` – canvas dimensions
|
||||
/// - `seed_x/y` – click coordinates (canvas pixel indices, 0-based)
|
||||
/// - `threshold` – max color distance to include
|
||||
/// - `mode` – Absolute = compare to seed; Relative = compare to BFS parent
|
||||
/// - `contiguous` – true = BFS from seed (connected region only);
|
||||
/// false = scan every pixel against seed color globally
|
||||
/// - `selection` – optional clip mask; pixels outside are never included
|
||||
pub fn raster_fill_mask(
|
||||
pixels: &[u8],
|
||||
width: u32,
|
||||
height: u32,
|
||||
seed_x: i32,
|
||||
seed_y: i32,
|
||||
threshold: f32,
|
||||
mode: FillThresholdMode,
|
||||
contiguous: bool,
|
||||
selection: Option<&crate::selection::RasterSelection>,
|
||||
) -> Vec<Option<f32>> {
|
||||
use std::collections::VecDeque;
|
||||
|
||||
let w = width as i32;
|
||||
let h = height as i32;
|
||||
let n = (width * height) as usize;
|
||||
|
||||
let mut dist_map: Vec<Option<f32>> = vec![None; n];
|
||||
|
||||
if seed_x < 0 || seed_y < 0 || seed_x >= w || seed_y >= h {
|
||||
return dist_map;
|
||||
}
|
||||
|
||||
let seed_idx = (seed_y * w + seed_x) as usize;
|
||||
let seed_color = [
|
||||
pixels[seed_idx * 4],
|
||||
pixels[seed_idx * 4 + 1],
|
||||
pixels[seed_idx * 4 + 2],
|
||||
pixels[seed_idx * 4 + 3],
|
||||
];
|
||||
|
||||
if contiguous {
|
||||
// BFS: only connected pixels within threshold.
|
||||
let mut parent_color: Vec<[u8; 4]> = vec![[0; 4]; n];
|
||||
let mut queue: VecDeque<(i32, i32)> = VecDeque::new();
|
||||
|
||||
dist_map[seed_idx] = Some(0.0);
|
||||
parent_color[seed_idx] = seed_color;
|
||||
queue.push_back((seed_x, seed_y));
|
||||
|
||||
let dirs: [(i32, i32); 4] = [(0, -1), (0, 1), (-1, 0), (1, 0)];
|
||||
|
||||
while let Some((cx, cy)) = queue.pop_front() {
|
||||
let ci = (cy * w + cx) as usize;
|
||||
let compare_color = match mode {
|
||||
FillThresholdMode::Absolute => seed_color,
|
||||
FillThresholdMode::Relative => parent_color[ci],
|
||||
};
|
||||
for (dx, dy) in dirs {
|
||||
let nx = cx + dx;
|
||||
let ny = cy + dy;
|
||||
if nx < 0 || ny < 0 || nx >= w || ny >= h { continue; }
|
||||
let ni = (ny * w + nx) as usize;
|
||||
if dist_map[ni].is_some() { continue; }
|
||||
if let Some(sel) = selection {
|
||||
if !sel.contains_pixel(nx, ny) { continue; }
|
||||
}
|
||||
let npx = [pixels[ni*4], pixels[ni*4+1], pixels[ni*4+2], pixels[ni*4+3]];
|
||||
let d = color_distance(npx, compare_color);
|
||||
if d <= threshold {
|
||||
dist_map[ni] = Some(d);
|
||||
parent_color[ni] = npx;
|
||||
queue.push_back((nx, ny));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Global scan: every pixel compared against seed color (Absolute mode).
|
||||
for row in 0..h {
|
||||
for col in 0..w {
|
||||
if let Some(sel) = selection {
|
||||
if !sel.contains_pixel(col, row) { continue; }
|
||||
}
|
||||
let ni = (row * w + col) as usize;
|
||||
let npx = [pixels[ni*4], pixels[ni*4+1], pixels[ni*4+2], pixels[ni*4+3]];
|
||||
let d = color_distance(npx, seed_color);
|
||||
if d <= threshold {
|
||||
dist_map[ni] = Some(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dist_map
|
||||
}
|
||||
|
||||
/// Pixel flood fill for the raster paint bucket tool.
|
||||
///
|
||||
/// Calls [`raster_fill_mask`] then alpha-composites `fill_color` over each
|
||||
/// matched pixel. `softness` controls a fade zone near the fill boundary.
|
||||
pub fn raster_flood_fill(
|
||||
pixels: &mut Vec<u8>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
seed_x: i32,
|
||||
seed_y: i32,
|
||||
fill_color: [u8; 4],
|
||||
threshold: f32,
|
||||
softness: f32,
|
||||
mode: FillThresholdMode,
|
||||
contiguous: bool,
|
||||
selection: Option<&crate::selection::RasterSelection>,
|
||||
) {
|
||||
let dist_map = raster_fill_mask(pixels, width, height, seed_x, seed_y,
|
||||
threshold, mode, contiguous, selection);
|
||||
let n = (width * height) as usize;
|
||||
|
||||
let fr = fill_color[0] as f32 / 255.0;
|
||||
let fg = fill_color[1] as f32 / 255.0;
|
||||
let fb = fill_color[2] as f32 / 255.0;
|
||||
let fa_base = fill_color[3] as f32 / 255.0;
|
||||
|
||||
let falloff_start = if softness <= 0.0 || threshold <= 0.0 {
|
||||
1.0_f32
|
||||
} else {
|
||||
1.0 - softness / 100.0
|
||||
};
|
||||
|
||||
for i in 0..n {
|
||||
if let Some(d) = dist_map[i] {
|
||||
let alpha = if threshold <= 0.0 {
|
||||
fa_base
|
||||
} else {
|
||||
let t = d / threshold;
|
||||
if t <= falloff_start {
|
||||
fa_base
|
||||
} else {
|
||||
let frac = (t - falloff_start) / (1.0 - falloff_start).max(1e-6);
|
||||
fa_base * (1.0 - frac)
|
||||
}
|
||||
};
|
||||
if alpha <= 0.0 { continue; }
|
||||
|
||||
let dst_r = pixels[i * 4 ] as f32 / 255.0;
|
||||
let dst_g = pixels[i * 4 + 1] as f32 / 255.0;
|
||||
let dst_b = pixels[i * 4 + 2] as f32 / 255.0;
|
||||
let dst_a = pixels[i * 4 + 3] as f32 / 255.0;
|
||||
let inv_a = 1.0 - alpha;
|
||||
let out_a = alpha + dst_a * inv_a;
|
||||
if out_a > 0.0 {
|
||||
pixels[i*4 ] = ((fr * alpha + dst_r * dst_a * inv_a) / out_a * 255.0).round() as u8;
|
||||
pixels[i*4+1] = ((fg * alpha + dst_g * dst_a * inv_a) / out_a * 255.0).round() as u8;
|
||||
pixels[i*4+2] = ((fb * alpha + dst_b * dst_a * inv_a) / out_a * 255.0).round() as u8;
|
||||
pixels[i*4+3] = (out_a * 255.0).round() as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn color_distance(a: [u8; 4], b: [u8; 4]) -> f32 {
|
||||
let dr = a[0] as f32 - b[0] as f32;
|
||||
let dg = a[1] as f32 - b[1] as f32;
|
||||
let db = a[2] as f32 - b[2] as f32;
|
||||
let da = a[3] as f32 - b[3] as f32;
|
||||
(dr * dr + dg * dg + db * db + da * da).sqrt()
|
||||
}
|
||||
|
||||
// ── Vector (curve-boundary) flood fill ───────────────────────────────────────
|
||||
// The following is the original vector-layer flood fill, kept for the vector
|
||||
// paint bucket tool.
|
||||
|
||||
use crate::curve_segment::CurveSegment;
|
||||
use crate::quadtree::{BoundingBox, Quadtree};
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
//! Gradient types for vector and raster fills.
|
||||
|
||||
use crate::shape::ShapeColor;
|
||||
use kurbo::Point;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use vello::peniko::{self, Brush, Extend, Gradient};
|
||||
|
||||
// ── Stop ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// One colour stop in a gradient.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct GradientStop {
|
||||
/// Normalised position in [0.0, 1.0].
|
||||
pub position: f32,
|
||||
pub color: ShapeColor,
|
||||
}
|
||||
|
||||
// ── Kind / Extend ────────────────────────────────────────────────────────────
|
||||
|
||||
/// Whether the gradient transitions along a line or radiates from a point.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum GradientType {
|
||||
#[default]
|
||||
Linear,
|
||||
Radial,
|
||||
}
|
||||
|
||||
/// Behaviour outside the gradient's natural [0, 1] range.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum GradientExtend {
|
||||
/// Clamp to edge colour (default).
|
||||
#[default]
|
||||
Pad,
|
||||
/// Mirror the gradient.
|
||||
Reflect,
|
||||
/// Repeat the gradient.
|
||||
Repeat,
|
||||
}
|
||||
|
||||
impl From<GradientExtend> for Extend {
|
||||
fn from(e: GradientExtend) -> Self {
|
||||
match e {
|
||||
GradientExtend::Pad => Extend::Pad,
|
||||
GradientExtend::Reflect => Extend::Reflect,
|
||||
GradientExtend::Repeat => Extend::Repeat,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── ShapeGradient ────────────────────────────────────────────────────────────
|
||||
|
||||
/// A serialisable gradient description.
|
||||
///
|
||||
/// Stops are kept sorted by position (ascending). There are always ≥ 2 stops.
|
||||
///
|
||||
/// *Rendering*: call [`to_peniko_brush`](ShapeGradient::to_peniko_brush) with
|
||||
/// explicit start/end canvas-space points. For vector faces the caller derives
|
||||
/// the points from the bounding box + `angle`; for the raster tool the caller
|
||||
/// uses the drag start/end directly.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ShapeGradient {
|
||||
pub kind: GradientType,
|
||||
/// Colour stops, sorted by position.
|
||||
pub stops: Vec<GradientStop>,
|
||||
/// Angle in degrees for Linear (0 = left→right, 90 = top→bottom).
|
||||
/// Ignored for Radial.
|
||||
pub angle: f32,
|
||||
pub extend: GradientExtend,
|
||||
}
|
||||
|
||||
impl Default for ShapeGradient {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
kind: GradientType::Linear,
|
||||
stops: vec![
|
||||
GradientStop { position: 0.0, color: ShapeColor::rgba(0, 0, 0, 255) },
|
||||
GradientStop { position: 1.0, color: ShapeColor::rgba(0, 0, 0, 0) },
|
||||
],
|
||||
angle: 0.0,
|
||||
extend: GradientExtend::Pad,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ShapeGradient {
|
||||
// ── CPU evaluation ───────────────────────────────────────────────────────
|
||||
|
||||
/// Sample RGBA at `t ∈ [0,1]` by linear interpolation between adjacent stops.
|
||||
/// Stops must be sorted ascending by position.
|
||||
pub fn eval(&self, t: f32) -> [u8; 4] {
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
if self.stops.is_empty() {
|
||||
return [0, 0, 0, 0];
|
||||
}
|
||||
if self.stops.len() == 1 {
|
||||
let c = self.stops[0].color;
|
||||
return [c.r, c.g, c.b, c.a];
|
||||
}
|
||||
// Find first stop with position > t
|
||||
let i = self.stops.partition_point(|s| s.position <= t);
|
||||
if i == 0 {
|
||||
let c = self.stops[0].color;
|
||||
return [c.r, c.g, c.b, c.a];
|
||||
}
|
||||
if i >= self.stops.len() {
|
||||
let c = self.stops.last().unwrap().color;
|
||||
return [c.r, c.g, c.b, c.a];
|
||||
}
|
||||
let s0 = self.stops[i - 1];
|
||||
let s1 = self.stops[i];
|
||||
let span = s1.position - s0.position;
|
||||
let f = if span <= 0.0 { 0.0 } else { (t - s0.position) / span };
|
||||
fn lerp(a: u8, b: u8, f: f32) -> u8 {
|
||||
(a as f32 + (b as f32 - a as f32) * f).round().clamp(0.0, 255.0) as u8
|
||||
}
|
||||
[
|
||||
lerp(s0.color.r, s1.color.r, f),
|
||||
lerp(s0.color.g, s1.color.g, f),
|
||||
lerp(s0.color.b, s1.color.b, f),
|
||||
lerp(s0.color.a, s1.color.a, f),
|
||||
]
|
||||
}
|
||||
|
||||
/// Apply `extend` mode to a raw t value, returning t ∈ [0,1].
|
||||
pub fn apply_extend(&self, t_raw: f32) -> f32 {
|
||||
match self.extend {
|
||||
GradientExtend::Pad => t_raw.clamp(0.0, 1.0),
|
||||
GradientExtend::Repeat => {
|
||||
let t = t_raw.rem_euclid(1.0);
|
||||
if t < 0.0 { t + 1.0 } else { t }
|
||||
}
|
||||
GradientExtend::Reflect => {
|
||||
let t = t_raw.rem_euclid(2.0).abs();
|
||||
if t > 1.0 { 2.0 - t } else { t }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── GPU / peniko rendering ───────────────────────────────────────────────
|
||||
|
||||
/// Build a `peniko::Brush` from explicit start/end canvas-coordinate points.
|
||||
///
|
||||
/// `opacity` in [0,1] is multiplied into all stop alphas.
|
||||
pub fn to_peniko_brush(&self, start: Point, end: Point, opacity: f32) -> Brush {
|
||||
// Convert stops to peniko tuples.
|
||||
let peniko_stops: Vec<(f32, peniko::Color)> = self.stops.iter().map(|s| {
|
||||
let a_scaled = (s.color.a as f32 * opacity).round().clamp(0.0, 255.0) as u8;
|
||||
let col = peniko::Color::from_rgba8(s.color.r, s.color.g, s.color.b, a_scaled);
|
||||
(s.position, col)
|
||||
}).collect();
|
||||
|
||||
let extend: Extend = self.extend.into();
|
||||
|
||||
match self.kind {
|
||||
GradientType::Linear => {
|
||||
Brush::Gradient(
|
||||
Gradient::new_linear(start, end)
|
||||
.with_extend(extend)
|
||||
.with_stops(peniko_stops.as_slice()),
|
||||
)
|
||||
}
|
||||
GradientType::Radial => {
|
||||
let mid = Point::new(
|
||||
(start.x + end.x) * 0.5,
|
||||
(start.y + end.y) * 0.5,
|
||||
);
|
||||
let dx = end.x - start.x;
|
||||
let dy = end.y - start.y;
|
||||
let radius = ((dx * dx + dy * dy).sqrt() * 0.5) as f32;
|
||||
Brush::Gradient(
|
||||
Gradient::new_radial(mid, radius)
|
||||
.with_extend(extend)
|
||||
.with_stops(peniko_stops.as_slice()),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,8 @@ pub mod webcam;
|
||||
pub mod raster_layer;
|
||||
pub mod brush_settings;
|
||||
pub mod brush_engine;
|
||||
pub mod raster_draw;
|
||||
pub mod gradient;
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
pub mod test_mode;
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
//! CPU-side raster drawing primitives for geometric shapes on raster layers.
|
||||
//!
|
||||
//! All coordinates are in canvas pixels (f32). The pixel buffer is RGBA u8,
|
||||
//! 4 bytes per pixel, row-major, top-left origin.
|
||||
|
||||
/// RGBA color as `[R, G, B, A]` bytes.
|
||||
pub type Rgba = [u8; 4];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Alpha-composite `color` (RGBA) onto `pixels[idx..idx+4]` with an extra
|
||||
/// `coverage` factor (0.0 = transparent, 1.0 = full color alpha).
|
||||
#[inline]
|
||||
fn blend_at(pixels: &mut [u8], idx: usize, color: Rgba, coverage: f32) {
|
||||
let a = (color[3] as f32 / 255.0) * coverage;
|
||||
if a <= 0.0 { return; }
|
||||
let inv = 1.0 - a;
|
||||
pixels[idx] = (color[0] as f32 * a + pixels[idx] as f32 * inv) as u8;
|
||||
pixels[idx + 1] = (color[1] as f32 * a + pixels[idx + 1] as f32 * inv) as u8;
|
||||
pixels[idx + 2] = (color[2] as f32 * a + pixels[idx + 2] as f32 * inv) as u8;
|
||||
pixels[idx + 3] = ((a + pixels[idx + 3] as f32 / 255.0 * inv) * 255.0).min(255.0) as u8;
|
||||
}
|
||||
|
||||
/// Write a pixel at integer canvas coordinates, clipped to canvas bounds.
|
||||
#[inline]
|
||||
fn put(pixels: &mut [u8], w: u32, h: u32, x: i32, y: i32, color: Rgba, coverage: f32) {
|
||||
if x < 0 || y < 0 || x >= w as i32 || y >= h as i32 { return; }
|
||||
let idx = (y as u32 * w + x as u32) as usize * 4;
|
||||
blend_at(pixels, idx, color, coverage);
|
||||
}
|
||||
|
||||
/// Draw an anti-aliased filled disk at (`cx`, `cy`) with the given `radius`.
|
||||
fn draw_disk(pixels: &mut [u8], w: u32, h: u32, cx: f32, cy: f32, radius: f32, color: Rgba) {
|
||||
let r = (radius + 1.0) as i32;
|
||||
let ix = cx as i32;
|
||||
let iy = cy as i32;
|
||||
for dy in -r..=r {
|
||||
for dx in -r..=r {
|
||||
let px = ix + dx;
|
||||
let py = iy + dy;
|
||||
let dist = ((px as f32 - cx).powi(2) + (py as f32 - cy).powi(2)).sqrt();
|
||||
let cov = (radius + 0.5 - dist).clamp(0.0, 1.0);
|
||||
if cov > 0.0 {
|
||||
put(pixels, w, h, px, py, color, cov);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Public API
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Draw a thick line from (`x0`, `y0`) to (`x1`, `y1`) by stamping
|
||||
/// anti-aliased disks of radius `thickness / 2` at every half-pixel step.
|
||||
pub fn draw_line(
|
||||
pixels: &mut [u8], w: u32, h: u32,
|
||||
x0: f32, y0: f32, x1: f32, y1: f32,
|
||||
color: Rgba, thickness: f32,
|
||||
) {
|
||||
let radius = (thickness / 2.0).max(0.5);
|
||||
let dx = x1 - x0;
|
||||
let dy = y1 - y0;
|
||||
let len = (dx * dx + dy * dy).sqrt();
|
||||
if len < 0.5 {
|
||||
draw_disk(pixels, w, h, x0, y0, radius, color);
|
||||
return;
|
||||
}
|
||||
let steps = ((len * 2.0).ceil() as i32).max(1);
|
||||
for i in 0..=steps {
|
||||
let t = i as f32 / steps as f32;
|
||||
draw_disk(pixels, w, h, x0 + dx * t, y0 + dy * t, radius, color);
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw a rectangle with corners (`x0`, `y0`) and (`x1`, `y1`).
|
||||
///
|
||||
/// `stroke` draws the four edges; `fill` fills the interior. Either may be
|
||||
/// `None` to skip that part.
|
||||
pub fn draw_rect(
|
||||
pixels: &mut [u8], w: u32, h: u32,
|
||||
x0: f32, y0: f32, x1: f32, y1: f32,
|
||||
stroke: Option<Rgba>, fill: Option<Rgba>, thickness: f32,
|
||||
) {
|
||||
let (lx, rx) = if x0 <= x1 { (x0, x1) } else { (x1, x0) };
|
||||
let (ty, by) = if y0 <= y1 { (y0, y1) } else { (y1, y0) };
|
||||
|
||||
if let Some(fc) = fill {
|
||||
let px0 = lx.ceil() as i32;
|
||||
let py0 = ty.ceil() as i32;
|
||||
let px1 = rx.floor() as i32;
|
||||
let py1 = by.floor() as i32;
|
||||
for py in py0..=py1 {
|
||||
for px in px0..=px1 {
|
||||
put(pixels, w, h, px, py, fc, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(sc) = stroke {
|
||||
draw_line(pixels, w, h, lx, ty, rx, ty, sc, thickness); // top
|
||||
draw_line(pixels, w, h, rx, ty, rx, by, sc, thickness); // right
|
||||
draw_line(pixels, w, h, rx, by, lx, by, sc, thickness); // bottom
|
||||
draw_line(pixels, w, h, lx, by, lx, ty, sc, thickness); // left
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw an ellipse centred at (`cx`, `cy`) with semi-axes `rx` and `ry`.
|
||||
///
|
||||
/// `stroke` draws the outline; `fill` fills the interior via scanline.
|
||||
pub fn draw_ellipse(
|
||||
pixels: &mut [u8], w: u32, h: u32,
|
||||
cx: f32, cy: f32, rx: f32, ry: f32,
|
||||
stroke: Option<Rgba>, fill: Option<Rgba>, thickness: f32,
|
||||
) {
|
||||
if rx <= 0.0 || ry <= 0.0 { return; }
|
||||
|
||||
if let Some(fc) = fill {
|
||||
let py0 = (cy - ry).ceil() as i32;
|
||||
let py1 = (cy + ry).floor() as i32;
|
||||
for py in py0..=py1 {
|
||||
let dy = py as f32 - cy;
|
||||
let t = 1.0 - (dy / ry).powi(2);
|
||||
if t <= 0.0 { continue; }
|
||||
let x_ext = rx * t.sqrt();
|
||||
let px0 = (cx - x_ext).ceil() as i32;
|
||||
let px1 = (cx + x_ext).floor() as i32;
|
||||
for px in px0..=px1 {
|
||||
put(pixels, w, h, px, py, fc, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(sc) = stroke {
|
||||
let radius = (thickness / 2.0).max(0.5);
|
||||
// Ramanujan's perimeter approximation for step count.
|
||||
let perim = std::f32::consts::PI
|
||||
* (3.0 * (rx + ry) - ((3.0 * rx + ry) * (rx + 3.0 * ry)).sqrt());
|
||||
let steps = ((perim * 2.0).ceil() as i32).max(16);
|
||||
for i in 0..steps {
|
||||
let t = i as f32 / steps as f32 * std::f32::consts::TAU;
|
||||
draw_disk(pixels, w, h, cx + rx * t.cos(), cy + ry * t.sin(), radius, sc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw a closed polygon given world-space `vertices` (at least 2).
|
||||
///
|
||||
/// `stroke` draws the outline; `fill` fills the interior via scanline.
|
||||
pub fn draw_polygon(
|
||||
pixels: &mut [u8], w: u32, h: u32,
|
||||
vertices: &[(f32, f32)],
|
||||
stroke: Option<Rgba>, fill: Option<Rgba>, thickness: f32,
|
||||
) {
|
||||
let n = vertices.len();
|
||||
if n < 2 { return; }
|
||||
|
||||
if let Some(fc) = fill {
|
||||
let min_y = vertices.iter().map(|v| v.1).fold(f32::MAX, f32::min).ceil() as i32;
|
||||
let max_y = vertices.iter().map(|v| v.1).fold(f32::MIN, f32::max).floor() as i32;
|
||||
let mut xs: Vec<f32> = Vec::with_capacity(n);
|
||||
for py in min_y..=max_y {
|
||||
xs.clear();
|
||||
let scan_y = py as f32 + 0.5;
|
||||
for i in 0..n {
|
||||
let (x0, y0) = vertices[i];
|
||||
let (x1, y1) = vertices[(i + 1) % n];
|
||||
if (y0 <= scan_y && scan_y < y1) || (y1 <= scan_y && scan_y < y0) {
|
||||
xs.push(x0 + (scan_y - y0) / (y1 - y0) * (x1 - x0));
|
||||
}
|
||||
}
|
||||
xs.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
|
||||
let mut j = 0;
|
||||
while j + 1 < xs.len() {
|
||||
let px0 = xs[j].ceil() as i32;
|
||||
let px1 = xs[j + 1].floor() as i32;
|
||||
for px in px0..=px1 {
|
||||
put(pixels, w, h, px, py, fc, 1.0);
|
||||
}
|
||||
j += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(sc) = stroke {
|
||||
for i in 0..n {
|
||||
let (x0, y0) = vertices[i];
|
||||
let (x1, y1) = vertices[(i + 1) % n];
|
||||
draw_line(pixels, w, h, x0, y0, x1, y1, sc, thickness);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,18 @@ pub enum RasterBlendMode {
|
||||
Erase,
|
||||
/// Smudge / blend surrounding pixels
|
||||
Smudge,
|
||||
/// Clone stamp: copy pixels from a source region
|
||||
CloneStamp,
|
||||
/// Healing brush: color-corrected clone stamp (preserves source texture, shifts color to match destination)
|
||||
Healing,
|
||||
/// Pattern stamp: paint with a repeating procedural tile pattern
|
||||
PatternStamp,
|
||||
/// Dodge / Burn: lighten (dodge) or darken (burn) existing pixels
|
||||
DodgeBurn,
|
||||
/// Sponge: saturate or desaturate existing pixels
|
||||
Sponge,
|
||||
/// Blur / Sharpen: soften or crisp up existing pixels
|
||||
BlurSharpen,
|
||||
}
|
||||
|
||||
impl Default for RasterBlendMode {
|
||||
@@ -26,6 +38,15 @@ impl Default for RasterBlendMode {
|
||||
}
|
||||
}
|
||||
|
||||
impl RasterBlendMode {
|
||||
/// Returns false for blend modes that operate on existing pixels and don't
|
||||
/// use the brush color at all (clone, heal, dodge/burn, sponge).
|
||||
/// Used by brush_engine.rs to decide whether color_a should be 1.0 or stroke.color[3].
|
||||
pub fn uses_brush_color(self) -> bool {
|
||||
!matches!(self, Self::CloneStamp | Self::Healing | Self::DodgeBurn | Self::Sponge | Self::BlurSharpen)
|
||||
}
|
||||
}
|
||||
|
||||
/// A single point along a stroke
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct StrokePoint {
|
||||
@@ -48,6 +69,13 @@ pub struct StrokeRecord {
|
||||
/// RGBA linear color [r, g, b, a]
|
||||
pub color: [f32; 4],
|
||||
pub blend_mode: RasterBlendMode,
|
||||
/// Generic tool parameters — encoding depends on blend_mode:
|
||||
/// - CloneStamp / Healing: [offset_x, offset_y, 0, 0]
|
||||
/// - PatternStamp: [pattern_type, pattern_scale, 0, 0]
|
||||
/// - DodgeBurn / Sponge: [mode, 0, 0, 0]
|
||||
/// - all others: [0, 0, 0, 0]
|
||||
#[serde(default)]
|
||||
pub tool_params: [f32; 4],
|
||||
pub points: Vec<StrokePoint>,
|
||||
}
|
||||
|
||||
@@ -85,8 +113,14 @@ pub struct RasterKeyframe {
|
||||
/// and encoded back to PNG on save. An empty Vec means the canvas is blank (transparent).
|
||||
#[serde(skip)]
|
||||
pub raw_pixels: Vec<u8>,
|
||||
/// Set to `true` whenever `raw_pixels` changes so the GPU texture cache can re-upload.
|
||||
/// Always `true` after load; cleared by the renderer after uploading.
|
||||
#[serde(skip, default = "default_true")]
|
||||
pub texture_dirty: bool,
|
||||
}
|
||||
|
||||
fn default_true() -> bool { true }
|
||||
|
||||
impl RasterKeyframe {
|
||||
/// Returns true when the pixel buffer has been initialised (non-blank).
|
||||
pub fn has_pixels(&self) -> bool {
|
||||
@@ -105,6 +139,7 @@ impl RasterKeyframe {
|
||||
stroke_log: Vec::new(),
|
||||
tween_after: TweenType::Hold,
|
||||
raw_pixels: Vec::new(),
|
||||
texture_dirty: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
use vello::kurbo::Rect;
|
||||
use vello::peniko::{Blob, Fill, ImageAlphaType, ImageBrush, ImageData, ImageFormat};
|
||||
use vello::peniko::{Blob, Fill, ImageAlphaType, ImageBrush, ImageData, ImageFormat, ImageQuality};
|
||||
use vello::Scene;
|
||||
|
||||
/// Cache for decoded image data to avoid re-decoding every frame
|
||||
@@ -88,14 +88,53 @@ fn decode_image_asset(asset: &ImageAsset) -> Option<ImageBrush> {
|
||||
// Per-Layer Rendering for HDR Compositing Pipeline
|
||||
// ============================================================================
|
||||
|
||||
/// A single decoded video frame ready for GPU upload, with its document-space transform.
|
||||
pub struct VideoRenderInstance {
|
||||
/// sRGB RGBA8 pixel data (straight alpha — as decoded by ffmpeg).
|
||||
pub rgba_data: Arc<Vec<u8>>,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Affine transform that maps from video-pixel space to document space.
|
||||
/// Composed from the clip's animated position/rotation/scale properties.
|
||||
pub transform: Affine,
|
||||
/// Final opacity [0,1] after cascading layer and instance opacity.
|
||||
pub opacity: f32,
|
||||
}
|
||||
|
||||
/// Type of rendered layer for compositor handling
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum RenderedLayerType {
|
||||
/// Regular content layer (vector, video) - composite its scene
|
||||
Content,
|
||||
/// Effect layer - apply effects to current composite state
|
||||
/// Vector / group layer — Vello scene in `RenderedLayer::scene` is used.
|
||||
Vector,
|
||||
/// Raster keyframe — bypass Vello; compositor uploads pixels via GPU texture cache.
|
||||
Raster {
|
||||
kf_id: Uuid,
|
||||
width: u32,
|
||||
height: u32,
|
||||
/// True when `raw_pixels` changed since the last upload; forces a cache re-upload.
|
||||
dirty: bool,
|
||||
/// Accumulated parent-clip affine (IDENTITY for top-level layers).
|
||||
/// Compositor composes this with the camera into the blit matrix.
|
||||
transform: Affine,
|
||||
},
|
||||
/// Video layer — bypass Vello; each active clip instance carries decoded frame data.
|
||||
Video {
|
||||
instances: Vec<VideoRenderInstance>,
|
||||
},
|
||||
/// Floating raster selection — blitted immediately above its parent layer.
|
||||
Float {
|
||||
canvas_id: Uuid,
|
||||
x: i32,
|
||||
y: i32,
|
||||
width: u32,
|
||||
height: u32,
|
||||
/// Accumulated parent-clip affine (IDENTITY for top-level layers).
|
||||
transform: Affine,
|
||||
/// CPU pixel data (sRGB-premultiplied RGBA8). Arc so the per-frame clone is O(1).
|
||||
/// Used by the export compositor; the live compositor reads the GPU canvas directly.
|
||||
pixels: std::sync::Arc<Vec<u8>>,
|
||||
},
|
||||
/// Effect layer — applied as a post-process pass on the HDR accumulator.
|
||||
Effect {
|
||||
/// Active effect instances at the current time
|
||||
effect_instances: Vec<ClipInstance>,
|
||||
},
|
||||
}
|
||||
@@ -104,7 +143,7 @@ pub enum RenderedLayerType {
|
||||
pub struct RenderedLayer {
|
||||
/// The layer's unique identifier
|
||||
pub layer_id: Uuid,
|
||||
/// The Vello scene containing the layer's rendered content
|
||||
/// Vello scene — only populated for `RenderedLayerType::Vector`.
|
||||
pub scene: Scene,
|
||||
/// Layer opacity (0.0 to 1.0)
|
||||
pub opacity: f32,
|
||||
@@ -112,12 +151,12 @@ pub struct RenderedLayer {
|
||||
pub blend_mode: BlendMode,
|
||||
/// Whether this layer has any visible content
|
||||
pub has_content: bool,
|
||||
/// Type of layer for compositor (content vs effect)
|
||||
/// Layer variant — determines how the compositor renders this entry.
|
||||
pub layer_type: RenderedLayerType,
|
||||
}
|
||||
|
||||
impl RenderedLayer {
|
||||
/// Create a new rendered layer with default settings
|
||||
/// Create a new vector layer with default settings.
|
||||
pub fn new(layer_id: Uuid) -> Self {
|
||||
Self {
|
||||
layer_id,
|
||||
@@ -125,11 +164,11 @@ impl RenderedLayer {
|
||||
opacity: 1.0,
|
||||
blend_mode: BlendMode::Normal,
|
||||
has_content: false,
|
||||
layer_type: RenderedLayerType::Content,
|
||||
layer_type: RenderedLayerType::Vector,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create with specific opacity and blend mode
|
||||
/// Create a vector layer with specific opacity and blend mode.
|
||||
pub fn with_settings(layer_id: Uuid, opacity: f32, blend_mode: BlendMode) -> Self {
|
||||
Self {
|
||||
layer_id,
|
||||
@@ -137,11 +176,11 @@ impl RenderedLayer {
|
||||
opacity,
|
||||
blend_mode,
|
||||
has_content: false,
|
||||
layer_type: RenderedLayerType::Content,
|
||||
layer_type: RenderedLayerType::Vector,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create an effect layer with active effect instances
|
||||
/// Create an effect layer with active effect instances.
|
||||
pub fn effect_layer(layer_id: Uuid, opacity: f32, effect_instances: Vec<ClipInstance>) -> Self {
|
||||
let has_content = !effect_instances.is_empty();
|
||||
Self {
|
||||
@@ -179,12 +218,14 @@ pub fn render_document_for_compositing(
|
||||
image_cache: &mut ImageCache,
|
||||
video_manager: &std::sync::Arc<std::sync::Mutex<crate::video::VideoManager>>,
|
||||
camera_frame: Option<&crate::webcam::CaptureFrame>,
|
||||
floating_selection: Option<&crate::selection::RasterFloatingSelection>,
|
||||
draw_checkerboard: bool,
|
||||
) -> CompositeRenderResult {
|
||||
let time = document.current_time;
|
||||
|
||||
// Render background to its own scene
|
||||
let mut background = Scene::new();
|
||||
render_background(document, &mut background, base_transform);
|
||||
render_background(document, &mut background, base_transform, draw_checkerboard);
|
||||
|
||||
// Check if any layers are soloed
|
||||
let any_soloed = document.visible_layers().any(|layer| layer.soloed());
|
||||
@@ -217,6 +258,36 @@ pub fn render_document_for_compositing(
|
||||
rendered_layers.push(rendered);
|
||||
}
|
||||
|
||||
// Insert the floating raster selection immediately above its parent layer.
|
||||
// This ensures it composites at the correct z-position in both edit and export.
|
||||
if let Some(float_sel) = floating_selection {
|
||||
if let Some(pos) = rendered_layers.iter().position(|l| l.layer_id == float_sel.layer_id) {
|
||||
// Inherit the parent layer's transform so the float follows it into
|
||||
// any transformed clip context.
|
||||
let parent_transform = match &rendered_layers[pos].layer_type {
|
||||
RenderedLayerType::Raster { transform, .. } => *transform,
|
||||
_ => Affine::IDENTITY,
|
||||
};
|
||||
let float_entry = RenderedLayer {
|
||||
layer_id: Uuid::nil(), // sentinel — not a real document layer
|
||||
scene: Scene::new(),
|
||||
opacity: 1.0,
|
||||
blend_mode: crate::gpu::BlendMode::Normal,
|
||||
has_content: !float_sel.pixels.is_empty(),
|
||||
layer_type: RenderedLayerType::Float {
|
||||
canvas_id: float_sel.canvas_id,
|
||||
x: float_sel.x,
|
||||
y: float_sel.y,
|
||||
width: float_sel.width,
|
||||
height: float_sel.height,
|
||||
transform: parent_transform,
|
||||
pixels: std::sync::Arc::clone(&float_sel.pixels),
|
||||
},
|
||||
};
|
||||
rendered_layers.insert(pos + 1, float_entry);
|
||||
}
|
||||
}
|
||||
|
||||
CompositeRenderResult {
|
||||
background,
|
||||
layers: rendered_layers,
|
||||
@@ -269,21 +340,74 @@ pub fn render_layer_isolated(
|
||||
rendered.has_content = false;
|
||||
}
|
||||
AnyLayer::Video(video_layer) => {
|
||||
use crate::animation::TransformProperty;
|
||||
let layer_opacity = layer.opacity();
|
||||
let mut video_mgr = video_manager.lock().unwrap();
|
||||
// Only pass camera_frame for the layer that has camera enabled
|
||||
let layer_camera_frame = if video_layer.camera_enabled { camera_frame } else { None };
|
||||
render_video_layer_to_scene(
|
||||
document,
|
||||
time,
|
||||
video_layer,
|
||||
&mut rendered.scene,
|
||||
base_transform,
|
||||
1.0, // Full opacity - layer opacity handled in compositing
|
||||
&mut video_mgr,
|
||||
layer_camera_frame,
|
||||
);
|
||||
rendered.has_content = !video_layer.clip_instances.is_empty()
|
||||
|| (video_layer.camera_enabled && camera_frame.is_some());
|
||||
let mut instances = Vec::new();
|
||||
|
||||
for clip_instance in &video_layer.clip_instances {
|
||||
let Some(video_clip) = document.video_clips.get(&clip_instance.clip_id) else { continue };
|
||||
let Some(clip_time) = clip_instance.remap_time(time, video_clip.duration) else { continue };
|
||||
let Some(frame) = video_mgr.get_frame(&clip_instance.clip_id, clip_time) else { continue };
|
||||
|
||||
// Evaluate animated transform properties.
|
||||
let anim = &video_layer.layer.animation_data;
|
||||
let id = clip_instance.id;
|
||||
let t = &clip_instance.transform;
|
||||
let x = anim.eval(&crate::animation::AnimationTarget::Object { id, property: TransformProperty::X }, time, t.x);
|
||||
let y = anim.eval(&crate::animation::AnimationTarget::Object { id, property: TransformProperty::Y }, time, t.y);
|
||||
let rotation = anim.eval(&crate::animation::AnimationTarget::Object { id, property: TransformProperty::Rotation }, time, t.rotation);
|
||||
let scale_x = anim.eval(&crate::animation::AnimationTarget::Object { id, property: TransformProperty::ScaleX }, time, t.scale_x);
|
||||
let scale_y = anim.eval(&crate::animation::AnimationTarget::Object { id, property: TransformProperty::ScaleY }, time, t.scale_y);
|
||||
let skew_x = anim.eval(&crate::animation::AnimationTarget::Object { id, property: TransformProperty::SkewX }, time, t.skew_x);
|
||||
let skew_y = anim.eval(&crate::animation::AnimationTarget::Object { id, property: TransformProperty::SkewY }, time, t.skew_y);
|
||||
let inst_opacity = anim.eval(&crate::animation::AnimationTarget::Object { id, property: TransformProperty::Opacity }, time, clip_instance.opacity);
|
||||
|
||||
let cx = video_clip.width / 2.0;
|
||||
let cy = video_clip.height / 2.0;
|
||||
let skew_transform = if skew_x != 0.0 || skew_y != 0.0 {
|
||||
let sx = if skew_x != 0.0 { Affine::new([1.0, 0.0, skew_x.to_radians().tan(), 1.0, 0.0, 0.0]) } else { Affine::IDENTITY };
|
||||
let sy = if skew_y != 0.0 { Affine::new([1.0, skew_y.to_radians().tan(), 0.0, 1.0, 0.0, 0.0]) } else { Affine::IDENTITY };
|
||||
Affine::translate((cx, cy)) * sx * sy * Affine::translate((-cx, -cy))
|
||||
} else { Affine::IDENTITY };
|
||||
|
||||
let clip_transform = Affine::translate((x, y))
|
||||
* Affine::rotate(rotation.to_radians())
|
||||
* Affine::scale_non_uniform(scale_x, scale_y)
|
||||
* skew_transform;
|
||||
|
||||
instances.push(VideoRenderInstance {
|
||||
rgba_data: frame.rgba_data.clone(),
|
||||
width: frame.width,
|
||||
height: frame.height,
|
||||
transform: base_transform * clip_transform,
|
||||
opacity: (layer_opacity * inst_opacity) as f32,
|
||||
});
|
||||
}
|
||||
|
||||
// Camera / webcam frame.
|
||||
if instances.is_empty() && video_layer.camera_enabled {
|
||||
if let Some(frame) = camera_frame {
|
||||
let vw = frame.width as f64;
|
||||
let vh = frame.height as f64;
|
||||
let scale = (document.width / vw).min(document.height / vh);
|
||||
let ox = (document.width - vw * scale) / 2.0;
|
||||
let oy = (document.height - vh * scale) / 2.0;
|
||||
let cam_transform = base_transform
|
||||
* Affine::translate((ox, oy))
|
||||
* Affine::scale(scale);
|
||||
instances.push(VideoRenderInstance {
|
||||
rgba_data: frame.rgba_data.clone(),
|
||||
width: frame.width,
|
||||
height: frame.height,
|
||||
transform: cam_transform,
|
||||
opacity: layer_opacity as f32,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
rendered.has_content = !instances.is_empty();
|
||||
rendered.layer_type = RenderedLayerType::Video { instances };
|
||||
}
|
||||
AnyLayer::Effect(effect_layer) => {
|
||||
// Effect layers are processed during compositing, not rendered to scene
|
||||
@@ -307,9 +431,16 @@ pub fn render_layer_isolated(
|
||||
rendered.has_content = !group_layer.children.is_empty();
|
||||
}
|
||||
AnyLayer::Raster(raster_layer) => {
|
||||
render_raster_layer_to_scene(raster_layer, time, &mut rendered.scene, base_transform);
|
||||
rendered.has_content = raster_layer.keyframe_at(time)
|
||||
.map_or(false, |kf| kf.has_pixels());
|
||||
if let Some(kf) = raster_layer.keyframe_at(time) {
|
||||
rendered.has_content = kf.has_pixels();
|
||||
rendered.layer_type = RenderedLayerType::Raster {
|
||||
kf_id: kf.id,
|
||||
width: kf.width,
|
||||
height: kf.height,
|
||||
dirty: kf.texture_dirty,
|
||||
transform: base_transform,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,35 +494,11 @@ fn render_raster_layer_to_scene(
|
||||
// decode the sRGB channels without premultiplying again.
|
||||
alpha_type: ImageAlphaType::AlphaPremultiplied,
|
||||
};
|
||||
let brush = ImageBrush::new(image_data);
|
||||
let brush = ImageBrush::new(image_data).with_quality(ImageQuality::Low);
|
||||
let canvas_rect = Rect::new(0.0, 0.0, kf.width as f64, kf.height as f64);
|
||||
scene.fill(Fill::NonZero, base_transform, &brush, None, &canvas_rect);
|
||||
}
|
||||
|
||||
/// Render a video layer to an isolated scene (for compositing pipeline)
|
||||
fn render_video_layer_to_scene(
|
||||
document: &Document,
|
||||
time: f64,
|
||||
layer: &crate::layer::VideoLayer,
|
||||
scene: &mut Scene,
|
||||
base_transform: Affine,
|
||||
parent_opacity: f64,
|
||||
video_manager: &mut crate::video::VideoManager,
|
||||
camera_frame: Option<&crate::webcam::CaptureFrame>,
|
||||
) {
|
||||
// Render using the existing function but to this isolated scene
|
||||
render_video_layer(
|
||||
document,
|
||||
time,
|
||||
layer,
|
||||
scene,
|
||||
base_transform,
|
||||
parent_opacity,
|
||||
video_manager,
|
||||
camera_frame,
|
||||
);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Legacy Single-Scene Rendering (kept for backwards compatibility)
|
||||
// ============================================================================
|
||||
@@ -415,8 +522,8 @@ pub fn render_document_with_transform(
|
||||
image_cache: &mut ImageCache,
|
||||
video_manager: &std::sync::Arc<std::sync::Mutex<crate::video::VideoManager>>,
|
||||
) {
|
||||
// 1. Draw background
|
||||
render_background(document, scene, base_transform);
|
||||
// 1. Draw background (with checkerboard for transparent backgrounds — UI path)
|
||||
render_background(document, scene, base_transform, true);
|
||||
|
||||
// 2. Recursively render the root graphics object at current time
|
||||
let time = document.current_time;
|
||||
@@ -436,12 +543,12 @@ pub fn render_document_with_transform(
|
||||
}
|
||||
|
||||
/// Draw the document background
|
||||
fn render_background(document: &Document, scene: &mut Scene, base_transform: Affine) {
|
||||
fn render_background(document: &Document, scene: &mut Scene, base_transform: Affine, draw_checkerboard: bool) {
|
||||
let background_rect = Rect::new(0.0, 0.0, document.width, document.height);
|
||||
let bg = &document.background_color;
|
||||
|
||||
// Draw checkerboard behind transparent backgrounds
|
||||
if bg.a < 255 {
|
||||
// Draw checkerboard behind transparent backgrounds (UI-only; skip in export)
|
||||
if draw_checkerboard && bg.a < 255 {
|
||||
use vello::peniko::{Blob, Color, Extend, ImageAlphaType, ImageData, ImageQuality};
|
||||
// 2x2 pixel checkerboard pattern: light/dark alternating
|
||||
let light: [u8; 4] = [204, 204, 204, 255];
|
||||
@@ -923,7 +1030,25 @@ fn render_video_layer(
|
||||
}
|
||||
}
|
||||
|
||||
/// Render a vector layer with all its clip instances and shape instances
|
||||
/// Compute start/end canvas points for a linear gradient across a bounding box.
|
||||
///
|
||||
/// The axis is centred on the bbox midpoint and oriented at `angle_deg` degrees
|
||||
/// (0 = left→right, 90 = top→bottom). The axis extends ± half the bbox diagonal
|
||||
/// so the gradient covers the entire shape regardless of angle.
|
||||
fn gradient_bbox_endpoints(angle_deg: f32, bbox: kurbo::Rect) -> (kurbo::Point, kurbo::Point) {
|
||||
let cx = bbox.center().x;
|
||||
let cy = bbox.center().y;
|
||||
let dx = bbox.width();
|
||||
let dy = bbox.height();
|
||||
// Use half the diagonal so the full gradient fits at any angle.
|
||||
let half_len = (dx * dx + dy * dy).sqrt() * 0.5;
|
||||
let rad = (angle_deg as f64).to_radians();
|
||||
let (sin, cos) = (rad.sin(), rad.cos());
|
||||
let start = kurbo::Point::new(cx - cos * half_len, cy - sin * half_len);
|
||||
let end = kurbo::Point::new(cx + cos * half_len, cy + sin * half_len);
|
||||
(start, end)
|
||||
}
|
||||
|
||||
/// Render a DCEL to a Vello scene.
|
||||
///
|
||||
/// Walks faces for fills and edges for strokes.
|
||||
@@ -942,7 +1067,7 @@ pub fn render_dcel(
|
||||
if face.deleted || i == 0 {
|
||||
continue; // Skip unbounded face and deleted faces
|
||||
}
|
||||
if face.fill_color.is_none() && face.image_fill.is_none() {
|
||||
if face.fill_color.is_none() && face.image_fill.is_none() && face.gradient_fill.is_none() {
|
||||
continue; // No fill to render
|
||||
}
|
||||
|
||||
@@ -963,7 +1088,19 @@ pub fn render_dcel(
|
||||
}
|
||||
}
|
||||
|
||||
// Color fill
|
||||
// Gradient fill (takes priority over solid colour fill)
|
||||
if !filled {
|
||||
if let Some(ref grad) = face.gradient_fill {
|
||||
use kurbo::{Point, Rect};
|
||||
let bbox: Rect = vello::kurbo::Shape::bounding_box(&path);
|
||||
let (start, end) = gradient_bbox_endpoints(grad.angle, bbox);
|
||||
let brush = grad.to_peniko_brush(start, end, opacity_f32);
|
||||
scene.fill(fill_rule, base_transform, &brush, None, &path);
|
||||
filled = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Solid colour fill
|
||||
if !filled {
|
||||
if let Some(fill_color) = &face.fill_color {
|
||||
let alpha = ((fill_color.a as f32 / 255.0) * opacity_f32 * 255.0) as u8;
|
||||
|
||||
@@ -15,6 +15,16 @@ pub enum RasterSelection {
|
||||
Rect(i32, i32, i32, i32),
|
||||
/// Closed freehand lasso polygon.
|
||||
Lasso(Vec<(i32, i32)>),
|
||||
/// Per-pixel boolean mask (e.g. from magic wand flood fill).
|
||||
/// `data` is row-major, length = width × height.
|
||||
Mask {
|
||||
data: Vec<bool>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
/// Top-left canvas pixel of the mask's bounding canvas region.
|
||||
origin_x: i32,
|
||||
origin_y: i32,
|
||||
},
|
||||
}
|
||||
|
||||
impl RasterSelection {
|
||||
@@ -29,6 +39,23 @@ impl RasterSelection {
|
||||
let y1 = pts.iter().map(|p| p.1).max().unwrap_or(0);
|
||||
(x0, y0, x1, y1)
|
||||
}
|
||||
Self::Mask { data, width, height, origin_x, origin_y } => {
|
||||
let w = *width as i32;
|
||||
let mut bx0 = i32::MAX; let mut by0 = i32::MAX;
|
||||
let mut bx1 = i32::MIN; let mut by1 = i32::MIN;
|
||||
for row in 0..*height as i32 {
|
||||
for col in 0..w {
|
||||
if data[(row * w + col) as usize] {
|
||||
bx0 = bx0.min(origin_x + col);
|
||||
by0 = by0.min(origin_y + row);
|
||||
bx1 = bx1.max(origin_x + col + 1);
|
||||
by1 = by1.max(origin_y + row + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if bx0 == i32::MAX { (*origin_x, *origin_y, *origin_x, *origin_y) }
|
||||
else { (bx0, by0, bx1, by1) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +64,14 @@ impl RasterSelection {
|
||||
match self {
|
||||
Self::Rect(x0, y0, x1, y1) => px >= *x0 && px < *x1 && py >= *y0 && py < *y1,
|
||||
Self::Lasso(pts) => point_in_polygon(px, py, pts),
|
||||
Self::Mask { data, width, height, origin_x, origin_y } => {
|
||||
let lx = px - origin_x;
|
||||
let ly = py - origin_y;
|
||||
if lx < 0 || ly < 0 || lx >= *width as i32 || ly >= *height as i32 {
|
||||
return false;
|
||||
}
|
||||
data[(ly * *width as i32 + lx) as usize]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,7 +104,9 @@ fn point_in_polygon(px: i32, py: i32, polygon: &[(i32, i32)]) -> bool {
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RasterFloatingSelection {
|
||||
/// sRGB-encoded premultiplied RGBA, width × height × 4 bytes.
|
||||
pub pixels: Vec<u8>,
|
||||
/// Wrapped in Arc so the renderer can clone a reference each frame (O(1))
|
||||
/// instead of copying megabytes of pixel data.
|
||||
pub pixels: std::sync::Arc<Vec<u8>>,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Top-left position in canvas pixel coordinates.
|
||||
@@ -81,7 +118,7 @@ pub struct RasterFloatingSelection {
|
||||
/// Snapshot of `raw_pixels` before the cut/paste was initiated, used for
|
||||
/// undo (via `RasterStrokeAction`) when the float is committed, and for
|
||||
/// Cancel (Escape) to restore the canvas without creating an undo entry.
|
||||
pub canvas_before: Vec<u8>,
|
||||
pub canvas_before: std::sync::Arc<Vec<u8>>,
|
||||
/// Key for this float's GPU canvas in `GpuBrushEngine::canvases`.
|
||||
/// Allows painting strokes directly onto the float buffer (B) without
|
||||
/// touching the layer canvas (A).
|
||||
|
||||
@@ -11,9 +11,10 @@ use vello::kurbo::Point;
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Tool {
|
||||
// ── Vector / shared tools ──────────────────────────────────────────────
|
||||
/// Selection tool - select and move objects
|
||||
Select,
|
||||
/// Draw/Pen tool - freehand drawing
|
||||
/// Draw/Brush tool - freehand drawing (vector) / paintbrush (raster)
|
||||
Draw,
|
||||
/// Transform tool - scale, rotate, skew
|
||||
Transform,
|
||||
@@ -37,12 +38,48 @@ pub enum Tool {
|
||||
RegionSelect,
|
||||
/// Split tool - split audio/video clips at a point
|
||||
Split,
|
||||
// ── Raster brush tools ────────────────────────────────────────────────
|
||||
/// Pencil tool - hard-edged raster brush
|
||||
Pencil,
|
||||
/// Pen tool - pressure-sensitive raster pen
|
||||
Pen,
|
||||
/// Airbrush tool - soft spray raster brush
|
||||
Airbrush,
|
||||
/// Erase tool - erase raster pixels
|
||||
Erase,
|
||||
/// Smudge tool - smudge/blend raster pixels
|
||||
Smudge,
|
||||
/// Lasso select tool - freehand selection on raster layers
|
||||
/// Clone Stamp - copy pixels from a source point
|
||||
CloneStamp,
|
||||
/// Healing Brush - content-aware pixel repair
|
||||
HealingBrush,
|
||||
/// Pattern Stamp - paint with a repeating pattern
|
||||
PatternStamp,
|
||||
/// Dodge/Burn - lighten or darken pixels
|
||||
DodgeBurn,
|
||||
/// Sponge - saturate or desaturate pixels
|
||||
Sponge,
|
||||
/// Blur/Sharpen - blur or sharpen pixel regions
|
||||
BlurSharpen,
|
||||
// ── Raster fill / shape ───────────────────────────────────────────────
|
||||
/// Gradient tool - fill with a gradient
|
||||
Gradient,
|
||||
/// Custom Shape tool - draw from a shape library
|
||||
CustomShape,
|
||||
// ── Raster selection tools ────────────────────────────────────────────
|
||||
/// Elliptical marquee selection
|
||||
SelectEllipse,
|
||||
/// Lasso select tool - freehand / polygonal / magnetic selection
|
||||
SelectLasso,
|
||||
/// Magic Wand - select by colour similarity
|
||||
MagicWand,
|
||||
/// Quick Select - brush-based smart selection
|
||||
QuickSelect,
|
||||
// ── Raster transform tools ────────────────────────────────────────────
|
||||
/// Warp / perspective transform
|
||||
Warp,
|
||||
/// Liquify - freeform pixel warping
|
||||
Liquify,
|
||||
}
|
||||
|
||||
/// Region select mode
|
||||
@@ -60,6 +97,23 @@ impl Default for RegionSelectMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lasso selection sub-mode
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum LassoMode {
|
||||
/// Freehand lasso (existing, implemented)
|
||||
Freehand,
|
||||
/// Click-to-place polygonal lasso
|
||||
Polygonal,
|
||||
/// Magnetically snaps to edges
|
||||
Magnetic,
|
||||
}
|
||||
|
||||
impl Default for LassoMode {
|
||||
fn default() -> Self {
|
||||
Self::Freehand
|
||||
}
|
||||
}
|
||||
|
||||
/// Tool state tracking for interactive operations
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ToolState {
|
||||
@@ -229,44 +283,77 @@ impl Tool {
|
||||
/// Get display name for the tool
|
||||
pub fn display_name(self) -> &'static str {
|
||||
match self {
|
||||
Tool::Select => "Select",
|
||||
Tool::Draw => "Draw",
|
||||
Tool::Transform => "Transform",
|
||||
Tool::Rectangle => "Rectangle",
|
||||
Tool::Ellipse => "Ellipse",
|
||||
Tool::PaintBucket => "Paint Bucket",
|
||||
Tool::Eyedropper => "Eyedropper",
|
||||
Tool::Line => "Line",
|
||||
Tool::Polygon => "Polygon",
|
||||
Tool::BezierEdit => "Bezier Edit",
|
||||
Tool::Text => "Text",
|
||||
Tool::RegionSelect => "Region Select",
|
||||
Tool::Split => "Split",
|
||||
Tool::Erase => "Erase",
|
||||
Tool::Smudge => "Smudge",
|
||||
Tool::SelectLasso => "Lasso Select",
|
||||
Tool::Select => "Select",
|
||||
Tool::Draw => "Brush",
|
||||
Tool::Transform => "Transform",
|
||||
Tool::Rectangle => "Rectangle",
|
||||
Tool::Ellipse => "Ellipse",
|
||||
Tool::PaintBucket => "Paint Bucket",
|
||||
Tool::Eyedropper => "Eyedropper",
|
||||
Tool::Line => "Line",
|
||||
Tool::Polygon => "Polygon",
|
||||
Tool::BezierEdit => "Bezier Edit",
|
||||
Tool::Text => "Text",
|
||||
Tool::RegionSelect => "Region Select",
|
||||
Tool::Split => "Split",
|
||||
Tool::Pencil => "Pencil",
|
||||
Tool::Pen => "Pen",
|
||||
Tool::Airbrush => "Airbrush",
|
||||
Tool::Erase => "Eraser",
|
||||
Tool::Smudge => "Smudge",
|
||||
Tool::CloneStamp => "Clone Stamp",
|
||||
Tool::HealingBrush => "Healing Brush",
|
||||
Tool::PatternStamp => "Pattern Stamp",
|
||||
Tool::DodgeBurn => "Dodge / Burn",
|
||||
Tool::Sponge => "Sponge",
|
||||
Tool::BlurSharpen => "Blur / Sharpen",
|
||||
Tool::Gradient => "Gradient",
|
||||
Tool::CustomShape => "Custom Shape",
|
||||
Tool::SelectEllipse => "Elliptical Select",
|
||||
Tool::SelectLasso => "Lasso Select",
|
||||
Tool::MagicWand => "Magic Wand",
|
||||
Tool::QuickSelect => "Quick Select",
|
||||
Tool::Warp => "Warp",
|
||||
Tool::Liquify => "Liquify",
|
||||
}
|
||||
}
|
||||
|
||||
/// Get SVG icon file name for the tool
|
||||
pub fn icon_file(self) -> &'static str {
|
||||
match self {
|
||||
Tool::Select => "select.svg",
|
||||
Tool::Draw => "draw.svg",
|
||||
Tool::Transform => "transform.svg",
|
||||
Tool::Rectangle => "rectangle.svg",
|
||||
Tool::Ellipse => "ellipse.svg",
|
||||
Tool::PaintBucket => "paint_bucket.svg",
|
||||
Tool::Eyedropper => "eyedropper.svg",
|
||||
Tool::Line => "line.svg",
|
||||
Tool::Polygon => "polygon.svg",
|
||||
Tool::BezierEdit => "bezier_edit.svg",
|
||||
Tool::Text => "text.svg",
|
||||
Tool::RegionSelect => "region_select.svg",
|
||||
Tool::Split => "split.svg",
|
||||
Tool::Erase => "erase.svg",
|
||||
Tool::Smudge => "smudge.svg",
|
||||
Tool::SelectLasso => "lasso.svg",
|
||||
Tool::Select => "select.svg",
|
||||
Tool::Draw => "draw.svg",
|
||||
Tool::Transform => "transform.svg",
|
||||
Tool::Rectangle => "rectangle.svg",
|
||||
Tool::Ellipse => "ellipse.svg",
|
||||
Tool::PaintBucket => "paint_bucket.svg",
|
||||
Tool::Eyedropper => "eyedropper.svg",
|
||||
Tool::Line => "line.svg",
|
||||
Tool::Polygon => "polygon.svg",
|
||||
Tool::BezierEdit => "bezier_edit.svg",
|
||||
Tool::Text => "text.svg",
|
||||
Tool::RegionSelect => "region_select.svg",
|
||||
Tool::Split => "split.svg",
|
||||
Tool::Erase => "erase.svg",
|
||||
Tool::Smudge => "smudge.svg",
|
||||
Tool::SelectLasso => "lasso.svg",
|
||||
// Not yet implemented — use the placeholder icon
|
||||
Tool::Pencil
|
||||
| Tool::Pen
|
||||
| Tool::Airbrush
|
||||
| Tool::CloneStamp
|
||||
| Tool::HealingBrush
|
||||
| Tool::PatternStamp
|
||||
| Tool::DodgeBurn
|
||||
| Tool::Sponge
|
||||
| Tool::BlurSharpen
|
||||
| Tool::Gradient
|
||||
| Tool::CustomShape
|
||||
| Tool::SelectEllipse
|
||||
| Tool::MagicWand
|
||||
| Tool::QuickSelect
|
||||
| Tool::Warp
|
||||
| Tool::Liquify => "todo.svg",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,7 +381,23 @@ impl Tool {
|
||||
match layer_type {
|
||||
None | Some(LayerType::Vector) => Tool::all(),
|
||||
Some(LayerType::Audio) | Some(LayerType::Video) => &[Tool::Select, Tool::Split],
|
||||
Some(LayerType::Raster) => &[Tool::Select, Tool::SelectLasso, Tool::Draw, Tool::Erase, Tool::Smudge, Tool::Eyedropper],
|
||||
Some(LayerType::Raster) => &[
|
||||
// Brush tools
|
||||
Tool::Draw, Tool::Pencil, Tool::Pen, Tool::Airbrush,
|
||||
Tool::Erase, Tool::Smudge,
|
||||
Tool::CloneStamp, Tool::HealingBrush, Tool::PatternStamp,
|
||||
Tool::DodgeBurn, Tool::Sponge, Tool::BlurSharpen,
|
||||
// Fill / shape
|
||||
Tool::PaintBucket, Tool::Gradient,
|
||||
Tool::Rectangle, Tool::Ellipse, Tool::Polygon, Tool::Line, Tool::CustomShape,
|
||||
// Selection
|
||||
Tool::Select, Tool::SelectLasso,
|
||||
Tool::MagicWand, Tool::QuickSelect,
|
||||
// Transform
|
||||
Tool::Transform, Tool::Warp, Tool::Liquify,
|
||||
// Utility
|
||||
Tool::Eyedropper,
|
||||
],
|
||||
_ => &[Tool::Select],
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user