diff --git a/crates/engine/src/filters_ext.rs b/crates/engine/src/filters_ext.rs index 7aa726f8e0..97aaba6374 100644 --- a/crates/engine/src/filters_ext.rs +++ b/crates/engine/src/filters_ext.rs @@ -66,343 +66,390 @@ fn list(p: &Value, k: &str) -> Option> { const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0]; const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0]; +fn choice(p: &Value, k: &str, d: &str, options: &[(&str, T)], other: T) -> T { + let name = s(p, k, d); + options.iter().find(|(n, _)| *n == name).map_or(other, |&(_, v)| v) +} + +const MEZZOTINT_TYPES: &[(&str, MezzotintType)] = &[ + ("fineDots", MezzotintType::FineDots), + ("mediumDots", MezzotintType::MediumDots), + ("grainyDots", MezzotintType::GrainyDots), + ("coarseDots", MezzotintType::CoarseDots), + ("shortLines", MezzotintType::ShortLines), + ("mediumLines", MezzotintType::MediumLines), + ("longLines", MezzotintType::LongLines), + ("shortStrokes", MezzotintType::ShortStrokes), + ("mediumStrokes", MezzotintType::MediumStrokes), + ("longStrokes", MezzotintType::LongStrokes), +]; +const DIFFUSE_MODES: &[(&str, DiffuseMode)] = &[ + ("normal", DiffuseMode::Normal), + ("darkenOnly", DiffuseMode::DarkenOnly), + ("lightenOnly", DiffuseMode::LightenOnly), + ("anisotropic", DiffuseMode::Anisotropic), +]; +const TILE_FILLS: &[(&str, TileFill)] = + &[("background", TileFill::Background), ("foreground", TileFill::Foreground), ("inverse", TileFill::Inverse), ("unaltered", TileFill::Unaltered)]; +const WIND_METHODS: &[(&str, WindMethod)] = &[("wind", WindMethod::Wind), ("blast", WindMethod::Blast), ("stagger", WindMethod::Stagger)]; +const ZIGZAG_STYLES: &[(&str, ZigZagStyle)] = + &[("pondRipples", ZigZagStyle::PondRipples), ("outFromCenter", ZigZagStyle::OutFromCenter), ("aroundCenter", ZigZagStyle::AroundCenter)]; +const LENS_TYPES: &[(&str, LensType)] = + &[("zoom", LensType::Zoom), ("prime35", LensType::Prime35), ("prime105", LensType::Prime105), ("moviePrime", LensType::MoviePrime)]; +const LIGHT_KINDS: &[(&str, LightKind)] = &[("spot", LightKind::Spot), ("point", LightKind::Point), ("infinite", LightKind::Infinite)]; +const TEXTURE_CHANNELS: &[(&str, TextureChannel)] = &[ + ("none", TextureChannel::None), + ("red", TextureChannel::Red), + ("green", TextureChannel::Green), + ("blue", TextureChannel::Blue), + ("alpha", TextureChannel::Alpha), + ("luminance", TextureChannel::Luminance), +]; +const BLUR_QUALITIES: &[(&str, BlurQuality)] = &[("high", BlurQuality::High), ("low", BlurQuality::Low), ("medium", BlurQuality::Medium)]; +const SMART_BLUR_MODES: &[(&str, SmartBlurMode)] = + &[("normal", SmartBlurMode::Normal), ("edgeOnly", SmartBlurMode::EdgeOnly), ("overlayEdge", SmartBlurMode::OverlayEdge)]; +const IRIS_BLADES: &[(&str, u32)] = &[("triangle", 3), ("square", 4), ("pentagon", 5), ("hexagon", 6), ("heptagon", 7), ("octagon", 8)]; +const DEPTH_SOURCES: &[(&str, DepthSource)] = + &[("none", DepthSource::None), ("transparency", DepthSource::Transparency), ("layerMask", DepthSource::LayerMask), ("channel", DepthSource::Channel)]; +const BLUR_SHAPES: &[(&str, BlurShape)] = &[ + ("circle", BlurShape::Circle), + ("ring", BlurShape::Ring), + ("square", BlurShape::Square), + ("diamond", BlurShape::Diamond), + ("triangle", BlurShape::Triangle), + ("hexagon", BlurShape::Hexagon), + ("star", BlurShape::Star), + ("heart", BlurShape::Heart), + ("cross", BlurShape::Cross), +]; +const HSB_MODELS: &[(&str, HsbModel)] = &[("rgb", HsbModel::Rgb), ("hsb", HsbModel::Hsb), ("hsl", HsbModel::Hsl)]; + +type Build = fn(&Value) -> FilterParams; + +const PARAMS: &[(&str, Build)] = &[ + // Pixelate + ("filter.pixelate.colorHalftone", |p| FilterParams::ColorHalftone { + max_radius: f(p, "maxRadius", 8.0).clamp(4.0, 127.0), + angles: [f(p, "channel1", 108.0), f(p, "channel2", 162.0), f(p, "channel3", 90.0), f(p, "channel4", 45.0)], + }), + ("filter.pixelate.crystallize", |p| FilterParams::Crystallize { cell_size: f(p, "cellSize", 10.0).clamp(3.0, 300.0), seed: seed(p) }), + ("filter.pixelate.facet", |_| FilterParams::Facet), + ("filter.pixelate.fragment", |_| FilterParams::Fragment), + ("filter.pixelate.mezzotint", |p| FilterParams::Mezzotint { kind: choice(p, "type", "fineDots", MEZZOTINT_TYPES, MezzotintType::FineDots), seed: seed(p) }), + ("filter.pixelate.pointillize", |p| FilterParams::Pointillize { + cell_size: f(p, "cellSize", 5.0).clamp(3.0, 300.0), + seed: seed(p), + background: colour(p, "background", WHITE), + }), + // Stylize + ("filter.stylize.diffuse", |p| FilterParams::Diffuse { mode: choice(p, "mode", "normal", DIFFUSE_MODES, DiffuseMode::Normal), seed: seed(p) }), + ("filter.stylize.extrude", extrude), + ("filter.stylize.oilPaint", oil_paint), + ("filter.stylize.tiles", tiles), + ("filter.stylize.traceContour", |p| FilterParams::TraceContour { level: f(p, "level", 128.0).clamp(0.0, 255.0), upper: s(p, "edge", "lower") == "upper" }), + ("filter.stylize.wind", |p| FilterParams::Wind { + method: choice(p, "method", "wind", WIND_METHODS, WindMethod::Wind), + from_right: s(p, "direction", "fromRight") != "fromLeft", + seed: seed(p), + }), + // Distort + ("filter.distort.displace", displace), + ("filter.distort.shear", shear), + ("filter.distort.zigZag", |p| FilterParams::ZigZag { + amount: f(p, "amount", 10.0).clamp(-100.0, 100.0), + ridges: f(p, "ridges", 5.0).clamp(0.0, 20.0), + style: choice(p, "style", "pondRipples", ZIGZAG_STYLES, ZigZagStyle::PondRipples), + }), + // Render + ("filter.render.clouds", |p| FilterParams::Clouds { + seed: seed(p), + difference: false, + foreground: colour(p, "foreground", BLACK), + background: colour(p, "background", WHITE), + }), + ("filter.render.differenceClouds", |p| FilterParams::Clouds { + seed: seed(p), + difference: true, + foreground: colour(p, "foreground", BLACK), + background: colour(p, "background", WHITE), + }), + ("filter.render.fibers", |p| FilterParams::Fibers { + variance: f(p, "variance", 16.0).clamp(1.0, 64.0), + strength: f(p, "strength", 4.0).clamp(1.0, 64.0), + seed: seed(p), + foreground: colour(p, "foreground", BLACK), + background: colour(p, "background", WHITE), + }), + ("filter.render.lensFlare", lens_flare), + ("filter.render.relight", |p| FilterParams::Relight { + angle: f(p, "angle", 45.0).clamp(-180.0, 180.0), + elevation: f(p, "elevation", 40.0).clamp(0.0, 90.0), + intensity: f(p, "intensity", 40.0).clamp(0.0, 100.0), + ambient: f(p, "ambient", 55.0).clamp(0.0, 100.0), + warmth: f(p, "warmth", 0.0).clamp(-100.0, 100.0), + softness: f(p, "softness", 25.0).clamp(1.0, 100.0), + }), + ("filter.render.lightingEffects", lighting_effects), + // Noise + ("filter.noise.reduceNoise", |p| FilterParams::ReduceNoise { + strength: f(p, "strength", 6.0).clamp(0.0, 10.0), + preserve_details: f(p, "preserveDetails", 60.0).clamp(0.0, 100.0), + reduce_color_noise: f(p, "reduceColorNoise", 45.0).clamp(0.0, 100.0), + sharpen_details: f(p, "sharpenDetails", 25.0).clamp(0.0, 100.0), + remove_jpeg_artifact: b(p, "removeJpegArtifact", false), + }), + // Blur + ("filter.blur.smartBlur", smart_blur), + ("filter.blur.lensBlur", lens_blur), + ("filter.blur.shapeBlur", |p| FilterParams::ShapeBlur { + radius: f(p, "radius", 10.0).clamp(5.0, 1000.0), + shape: choice(p, "shape", "circle", BLUR_SHAPES, BlurShape::Circle), + }), + // Blur Gallery + ("filter.blurGallery.tiltShift", tilt_shift), + ("filter.blurGallery.irisBlur", iris_blur), + ("filter.blurGallery.fieldBlur", |p| FilterParams::FieldBlur { + pins: list::(p, "pins").unwrap_or_else(|| vec![FieldPin { x: f(p, "centerX", 0.5), y: f(p, "centerY", 0.5), blur: gallery_blur(p) }]), + }), + ("filter.blurGallery.spinBlur", spin_blur), + ("filter.blurGallery.pathBlur", path_blur), + // Other + ("filter.other.custom", custom), + ("filter.other.hsbHsl", |p| FilterParams::HsbHsl { + input: choice(p, "inputMode", "rgb", HSB_MODELS, HsbModel::Rgb), + output: choice(p, "rowOrder", "hsb", HSB_MODELS, HsbModel::Rgb), + }), + (crate::color_to_alpha_cmds::ID, crate::color_to_alpha_cmds::params), + // Video + ("filter.video.deInterlace", |p| FilterParams::DeInterlace { + eliminate_even: s(p, "eliminate", "oddFields") == "evenFields", + interpolate: s(p, "createBy", "interpolation") != "duplication", + }), + ("filter.video.ntscColors", |_| FilterParams::NtscColors), +]; + /// Algorithm parameters for the ids this module owns (Photoshop dialog units). pub fn params_for(id: &str, p: &Value) -> Option { - let blur = |d: f32| f(p, "blur", d).clamp(0.0, 500.0); - Some(match id { - // ---- Pixelate ---- - "filter.pixelate.colorHalftone" => FilterParams::ColorHalftone { - max_radius: f(p, "maxRadius", 8.0).clamp(4.0, 127.0), - angles: [f(p, "channel1", 108.0), f(p, "channel2", 162.0), f(p, "channel3", 90.0), f(p, "channel4", 45.0)], - }, - "filter.pixelate.crystallize" => FilterParams::Crystallize { cell_size: f(p, "cellSize", 10.0).clamp(3.0, 300.0), seed: seed(p) }, - "filter.pixelate.facet" => FilterParams::Facet, - "filter.pixelate.fragment" => FilterParams::Fragment, - "filter.pixelate.mezzotint" => FilterParams::Mezzotint { - kind: match s(p, "type", "fineDots") { - "mediumDots" => MezzotintType::MediumDots, - "grainyDots" => MezzotintType::GrainyDots, - "coarseDots" => MezzotintType::CoarseDots, - "shortLines" => MezzotintType::ShortLines, - "mediumLines" => MezzotintType::MediumLines, - "longLines" => MezzotintType::LongLines, - "shortStrokes" => MezzotintType::ShortStrokes, - "mediumStrokes" => MezzotintType::MediumStrokes, - "longStrokes" => MezzotintType::LongStrokes, - _ => MezzotintType::FineDots, - }, - seed: seed(p), - }, - "filter.pixelate.pointillize" => { - FilterParams::Pointillize { cell_size: f(p, "cellSize", 5.0).clamp(3.0, 300.0), seed: seed(p), background: colour(p, "background", WHITE) } - } - // ---- Stylize ---- - "filter.stylize.diffuse" => FilterParams::Diffuse { - mode: match s(p, "mode", "normal") { - "darkenOnly" => DiffuseMode::DarkenOnly, - "lightenOnly" => DiffuseMode::LightenOnly, - "anisotropic" => DiffuseMode::Anisotropic, - _ => DiffuseMode::Normal, - }, - seed: seed(p), - }, - "filter.stylize.extrude" => FilterParams::Extrude { - kind: if s(p, "type", "blocks") == "pyramids" { ExtrudeType::Pyramids } else { ExtrudeType::Blocks }, - size: f(p, "size", 30.0).clamp(2.0, 255.0), - depth: f(p, "depth", 30.0).clamp(1.0, 255.0), - level_based: s(p, "depthMode", "random") == "levelBased", - solid_front: b(p, "solidFrontFaces", false), - mask_incomplete: b(p, "maskIncompleteBlocks", false), - seed: seed(p), - }, - "filter.stylize.oilPaint" => FilterParams::OilPaint { - stylization: f(p, "stylization", 4.0).clamp(0.1, 10.0), - cleanliness: f(p, "cleanliness", 5.0).clamp(0.0, 10.0), - scale: f(p, "scale", 1.0).clamp(0.1, 10.0), - bristle_detail: f(p, "bristleDetail", 5.0).clamp(0.0, 10.0), - lighting: b(p, "lighting", true), - angle: f(p, "angle", -60.0), - shine: f(p, "shine", 1.0).clamp(0.0, 10.0), - }, - "filter.stylize.tiles" => FilterParams::Tiles { - count: i(p, "count", 10).clamp(1, 99) as u32, - max_offset: f(p, "maxOffset", 10.0).clamp(1.0, 99.0), - fill: match s(p, "fill", "background") { - "foreground" => TileFill::Foreground, - "inverse" => TileFill::Inverse, - "unaltered" => TileFill::Unaltered, - _ => TileFill::Background, - }, - foreground: colour(p, "foreground", BLACK), - background: colour(p, "background", WHITE), - seed: seed(p), - }, - "filter.stylize.traceContour" => FilterParams::TraceContour { level: f(p, "level", 128.0).clamp(0.0, 255.0), upper: s(p, "edge", "lower") == "upper" }, - "filter.stylize.wind" => FilterParams::Wind { - method: match s(p, "method", "wind") { - "blast" => WindMethod::Blast, - "stagger" => WindMethod::Stagger, - _ => WindMethod::Wind, - }, - from_right: s(p, "direction", "fromRight") != "fromLeft", - seed: seed(p), - }, - // ---- Distort ---- - "filter.distort.displace" => FilterParams::Displace { - horizontal: f(p, "horizontal", 10.0).clamp(-999.0, 999.0), - vertical: f(p, "vertical", 10.0).clamp(-999.0, 999.0), - stretch: s(p, "fit", "stretch") != "tile", - undefined: undefined(p, "repeat"), - // A Displace imported from PSD carries its map; `mapPath` / `mapDocument` resolve later. - map: photocraft_io::smart_map::displace_embedded_map(p), - }, - "filter.distort.shear" => FilterParams::Shear { - points: list::<[f32; 2]>(p, "points").unwrap_or_else(|| { - let a = f(p, "amount", 0.0).clamp(-100.0, 100.0) / 100.0; - vec![[0.0, 0.0], [0.5, a], [1.0, 0.0]] - }), - undefined: undefined(p, "wrap"), - }, - "filter.distort.zigZag" => FilterParams::ZigZag { - amount: f(p, "amount", 10.0).clamp(-100.0, 100.0), - ridges: f(p, "ridges", 5.0).clamp(0.0, 20.0), - style: match s(p, "style", "pondRipples") { - "outFromCenter" => ZigZagStyle::OutFromCenter, - "aroundCenter" => ZigZagStyle::AroundCenter, - _ => ZigZagStyle::PondRipples, - }, - }, - // ---- Render ---- - "filter.render.clouds" | "filter.render.differenceClouds" => FilterParams::Clouds { - seed: seed(p), - difference: id == "filter.render.differenceClouds", - foreground: colour(p, "foreground", BLACK), - background: colour(p, "background", WHITE), - }, - "filter.render.fibers" => FilterParams::Fibers { - variance: f(p, "variance", 16.0).clamp(1.0, 64.0), - strength: f(p, "strength", 4.0).clamp(1.0, 64.0), - seed: seed(p), - foreground: colour(p, "foreground", BLACK), - background: colour(p, "background", WHITE), - }, - "filter.render.lensFlare" => FilterParams::LensFlare { - brightness: f(p, "brightness", 100.0).clamp(10.0, 300.0), - center_x: f(p, "centerX", 0.5).clamp(-0.5, 1.5), - center_y: f(p, "centerY", 0.5).clamp(-0.5, 1.5), - lens: match s(p, "lens", "zoom") { - "prime35" => LensType::Prime35, - "prime105" => LensType::Prime105, - "moviePrime" => LensType::MoviePrime, - _ => LensType::Zoom, - }, - }, - "filter.render.relight" => FilterParams::Relight { - angle: f(p, "angle", 45.0).clamp(-180.0, 180.0), - elevation: f(p, "elevation", 40.0).clamp(0.0, 90.0), - intensity: f(p, "intensity", 40.0).clamp(0.0, 100.0), - ambient: f(p, "ambient", 55.0).clamp(0.0, 100.0), - warmth: f(p, "warmth", 0.0).clamp(-100.0, 100.0), - softness: f(p, "softness", 25.0).clamp(1.0, 100.0), - }, - "filter.render.lightingEffects" => FilterParams::LightingEffects { - lights: list::(p, "lights").unwrap_or_else(|| { - vec![Light { - kind: match s(p, "lightType", "spot") { - "point" => LightKind::Point, - "infinite" => LightKind::Infinite, - _ => LightKind::Spot, - }, - x: f(p, "lightX", 0.25), - y: f(p, "lightY", 0.2), - z: f(p, "lightZ", 0.6).clamp(0.0, 10.0), - target_x: f(p, "targetX", 0.5), - target_y: f(p, "targetY", 0.55), - angle: f(p, "angle", 135.0), - elevation: f(p, "elevation", 45.0).clamp(0.0, 90.0), - color: { - let c = colour(p, "color", WHITE); - [c[0], c[1], c[2]] - }, - intensity: f(p, "intensity", 75.0).clamp(-100.0, 100.0), - cone: f(p, "cone", 45.0).clamp(1.0, 89.0), - hotspot: f(p, "hotspot", 50.0).clamp(0.0, 100.0), - radius: f(p, "radius", 0.8).clamp(0.01, 10.0), - }] - }), - gloss: f(p, "gloss", 0.0).clamp(-100.0, 100.0), - metallic: f(p, "metallic", 0.0).clamp(-100.0, 100.0), - exposure: f(p, "exposure", 0.0).clamp(-100.0, 100.0), - ambience: f(p, "ambience", 8.0).clamp(-100.0, 100.0), - texture: match s(p, "texture", "none") { - "red" => TextureChannel::Red, - "green" => TextureChannel::Green, - "blue" => TextureChannel::Blue, - "alpha" => TextureChannel::Alpha, - "luminance" => TextureChannel::Luminance, - _ => TextureChannel::None, - }, - height: f(p, "height", 50.0).clamp(0.0, 100.0), - white_is_high: b(p, "whiteIsHigh", true), - }, - // ---- Noise ---- - "filter.noise.reduceNoise" => FilterParams::ReduceNoise { - strength: f(p, "strength", 6.0).clamp(0.0, 10.0), - preserve_details: f(p, "preserveDetails", 60.0).clamp(0.0, 100.0), - reduce_color_noise: f(p, "reduceColorNoise", 45.0).clamp(0.0, 100.0), - sharpen_details: f(p, "sharpenDetails", 25.0).clamp(0.0, 100.0), - remove_jpeg_artifact: b(p, "removeJpegArtifact", false), - }, - // ---- Blur ---- - "filter.blur.smartBlur" => FilterParams::SmartBlur { - radius: f(p, "radius", 3.0).clamp(0.1, 100.0), - threshold: f(p, "threshold", 25.0).clamp(0.1, 100.0), - quality: match s(p, "quality", "high") { - "low" => BlurQuality::Low, - "medium" => BlurQuality::Medium, - _ => BlurQuality::High, - }, - mode: match s(p, "mode", "normal") { - "edgeOnly" => SmartBlurMode::EdgeOnly, - "overlayEdge" => SmartBlurMode::OverlayEdge, - _ => SmartBlurMode::Normal, - }, - }, - "filter.blur.lensBlur" => FilterParams::LensBlur { - radius: f(p, "radius", 15.0).clamp(0.0, 100.0), - blades: match s(p, "shape", "hexagon") { - "triangle" => 3, - "square" => 4, - "pentagon" => 5, - "heptagon" => 7, - "octagon" => 8, - _ => 6, - }, - curvature: f(p, "bladeCurvature", 0.0).clamp(0.0, 100.0), - rotation: f(p, "rotation", 0.0), - depth: match s(p, "depthMap", "none") { - "transparency" => DepthSource::Transparency, - "layerMask" => DepthSource::LayerMask, - "channel" => DepthSource::Channel, - _ => DepthSource::None, - }, - focal_distance: f(p, "focalDistance", 0.0).clamp(0.0, 255.0), - invert_depth: b(p, "invert", false), - brightness: f(p, "brightness", 0.0).clamp(0.0, 100.0), - threshold: f(p, "threshold", 255.0).clamp(0.0, 255.0), - noise: f(p, "noise", 0.0).clamp(0.0, 100.0), - distribution: if s(p, "distribution", "uniform") == "gaussian" { Distribution::Gaussian } else { Distribution::Uniform }, - monochromatic: b(p, "monochromatic", false), - seed: seed(p), - depth_map: None, - }, - "filter.blur.shapeBlur" => FilterParams::ShapeBlur { - radius: f(p, "radius", 10.0).clamp(5.0, 1000.0), - shape: match s(p, "shape", "circle") { - "ring" => BlurShape::Ring, - "square" => BlurShape::Square, - "diamond" => BlurShape::Diamond, - "triangle" => BlurShape::Triangle, - "hexagon" => BlurShape::Hexagon, - "star" => BlurShape::Star, - "heart" => BlurShape::Heart, - "cross" => BlurShape::Cross, - _ => BlurShape::Circle, - }, - }, - // ---- Blur Gallery ---- - "filter.blurGallery.tiltShift" => FilterParams::TiltShift { - blur: blur(15.0), - center_x: f(p, "centerX", 0.5), - center_y: f(p, "centerY", 0.5), - angle: f(p, "angle", 0.0), - focus: f(p, "focus", 0.1).clamp(0.0, 2.0), - transition: f(p, "transition", 0.15).clamp(0.001, 2.0), - }, - "filter.blurGallery.irisBlur" => FilterParams::IrisBlur { - pins: list::(p, "pins").unwrap_or_else(|| { - vec![IrisPin { + match PARAMS.iter().find(|(k, _)| *k == id) { + Some((_, build)) => Some(build(p)), + None => crate::gallery_cmds::params_for(id, p), + } +} + +fn gallery_blur(p: &Value) -> f32 { + f(p, "blur", 15.0).clamp(0.0, 500.0) +} + +fn extrude(p: &Value) -> FilterParams { + FilterParams::Extrude { + kind: if s(p, "type", "blocks") == "pyramids" { ExtrudeType::Pyramids } else { ExtrudeType::Blocks }, + size: f(p, "size", 30.0).clamp(2.0, 255.0), + depth: f(p, "depth", 30.0).clamp(1.0, 255.0), + level_based: s(p, "depthMode", "random") == "levelBased", + solid_front: b(p, "solidFrontFaces", false), + mask_incomplete: b(p, "maskIncompleteBlocks", false), + seed: seed(p), + } +} + +fn oil_paint(p: &Value) -> FilterParams { + FilterParams::OilPaint { + stylization: f(p, "stylization", 4.0).clamp(0.1, 10.0), + cleanliness: f(p, "cleanliness", 5.0).clamp(0.0, 10.0), + scale: f(p, "scale", 1.0).clamp(0.1, 10.0), + bristle_detail: f(p, "bristleDetail", 5.0).clamp(0.0, 10.0), + lighting: b(p, "lighting", true), + angle: f(p, "angle", -60.0), + shine: f(p, "shine", 1.0).clamp(0.0, 10.0), + } +} + +fn tiles(p: &Value) -> FilterParams { + FilterParams::Tiles { + count: i(p, "count", 10).clamp(1, 99) as u32, + max_offset: f(p, "maxOffset", 10.0).clamp(1.0, 99.0), + fill: choice(p, "fill", "background", TILE_FILLS, TileFill::Background), + foreground: colour(p, "foreground", BLACK), + background: colour(p, "background", WHITE), + seed: seed(p), + } +} + +fn displace(p: &Value) -> FilterParams { + FilterParams::Displace { + horizontal: f(p, "horizontal", 10.0).clamp(-999.0, 999.0), + vertical: f(p, "vertical", 10.0).clamp(-999.0, 999.0), + stretch: s(p, "fit", "stretch") != "tile", + undefined: undefined(p, "repeat"), + // PSD imports carry the map, and `mapPath` or `mapDocument` resolve later. + map: photocraft_io::smart_map::displace_embedded_map(p), + } +} + +fn shear(p: &Value) -> FilterParams { + FilterParams::Shear { + points: list::<[f32; 2]>(p, "points").unwrap_or_else(|| { + let a = f(p, "amount", 0.0).clamp(-100.0, 100.0) / 100.0; + vec![[0.0, 0.0], [0.5, a], [1.0, 0.0]] + }), + undefined: undefined(p, "wrap"), + } +} + +fn lens_flare(p: &Value) -> FilterParams { + FilterParams::LensFlare { + brightness: f(p, "brightness", 100.0).clamp(10.0, 300.0), + center_x: f(p, "centerX", 0.5).clamp(-0.5, 1.5), + center_y: f(p, "centerY", 0.5).clamp(-0.5, 1.5), + lens: choice(p, "lens", "zoom", LENS_TYPES, LensType::Zoom), + } +} + +fn single_light(p: &Value) -> Light { + let c = colour(p, "color", WHITE); + Light { + kind: choice(p, "lightType", "spot", LIGHT_KINDS, LightKind::Spot), + x: f(p, "lightX", 0.25), + y: f(p, "lightY", 0.2), + z: f(p, "lightZ", 0.6).clamp(0.0, 10.0), + target_x: f(p, "targetX", 0.5), + target_y: f(p, "targetY", 0.55), + angle: f(p, "angle", 135.0), + elevation: f(p, "elevation", 45.0).clamp(0.0, 90.0), + color: [c[0], c[1], c[2]], + intensity: f(p, "intensity", 75.0).clamp(-100.0, 100.0), + cone: f(p, "cone", 45.0).clamp(1.0, 89.0), + hotspot: f(p, "hotspot", 50.0).clamp(0.0, 100.0), + radius: f(p, "radius", 0.8).clamp(0.01, 10.0), + } +} + +fn lighting_effects(p: &Value) -> FilterParams { + FilterParams::LightingEffects { + lights: list::(p, "lights").unwrap_or_else(|| vec![single_light(p)]), + gloss: f(p, "gloss", 0.0).clamp(-100.0, 100.0), + metallic: f(p, "metallic", 0.0).clamp(-100.0, 100.0), + exposure: f(p, "exposure", 0.0).clamp(-100.0, 100.0), + ambience: f(p, "ambience", 8.0).clamp(-100.0, 100.0), + texture: choice(p, "texture", "none", TEXTURE_CHANNELS, TextureChannel::None), + height: f(p, "height", 50.0).clamp(0.0, 100.0), + white_is_high: b(p, "whiteIsHigh", true), + } +} + +fn smart_blur(p: &Value) -> FilterParams { + FilterParams::SmartBlur { + radius: f(p, "radius", 3.0).clamp(0.1, 100.0), + threshold: f(p, "threshold", 25.0).clamp(0.1, 100.0), + quality: choice(p, "quality", "high", BLUR_QUALITIES, BlurQuality::High), + mode: choice(p, "mode", "normal", SMART_BLUR_MODES, SmartBlurMode::Normal), + } +} + +fn lens_blur(p: &Value) -> FilterParams { + FilterParams::LensBlur { + radius: f(p, "radius", 15.0).clamp(0.0, 100.0), + blades: choice(p, "shape", "hexagon", IRIS_BLADES, 6), + curvature: f(p, "bladeCurvature", 0.0).clamp(0.0, 100.0), + rotation: f(p, "rotation", 0.0), + depth: choice(p, "depthMap", "none", DEPTH_SOURCES, DepthSource::None), + focal_distance: f(p, "focalDistance", 0.0).clamp(0.0, 255.0), + invert_depth: b(p, "invert", false), + brightness: f(p, "brightness", 0.0).clamp(0.0, 100.0), + threshold: f(p, "threshold", 255.0).clamp(0.0, 255.0), + noise: f(p, "noise", 0.0).clamp(0.0, 100.0), + distribution: if s(p, "distribution", "uniform") == "gaussian" { Distribution::Gaussian } else { Distribution::Uniform }, + monochromatic: b(p, "monochromatic", false), + seed: seed(p), + depth_map: None, + } +} + +fn tilt_shift(p: &Value) -> FilterParams { + FilterParams::TiltShift { + blur: gallery_blur(p), + center_x: f(p, "centerX", 0.5), + center_y: f(p, "centerY", 0.5), + angle: f(p, "angle", 0.0), + focus: f(p, "focus", 0.1).clamp(0.0, 2.0), + transition: f(p, "transition", 0.15).clamp(0.001, 2.0), + } +} + +fn iris_blur(p: &Value) -> FilterParams { + FilterParams::IrisBlur { + pins: list::(p, "pins").unwrap_or_else(|| { + vec![IrisPin { + x: f(p, "centerX", 0.5), + y: f(p, "centerY", 0.5), + radius_x: f(p, "radiusX", 0.35).max(0.001), + radius_y: f(p, "radiusY", 0.25).max(0.001), + angle: f(p, "angle", 0.0), + roundness: f(p, "roundness", 0.0).clamp(0.0, 100.0), + feather: f(p, "feather", 0.5).clamp(0.0, 0.99), + blur: gallery_blur(p), + }] + }), + } +} + +fn spin_angle(a: f32, lo: f32) -> f32 { + if a.is_finite() { a.clamp(lo, 360.0) } else { 0.0 } +} + +fn spin_blur(p: &Value) -> FilterParams { + FilterParams::SpinBlur { + pins: list::(p, "pins") + .map(|mut v| { + for pin in &mut v { + pin.angle = spin_angle(pin.angle, -360.0); + pin.blur_angle = spin_angle(pin.blur_angle, 0.0); + } + v + }) + .unwrap_or_else(|| { + vec![SpinPin { x: f(p, "centerX", 0.5), y: f(p, "centerY", 0.5), - radius_x: f(p, "radiusX", 0.35).max(0.001), - radius_y: f(p, "radiusY", 0.25).max(0.001), - angle: f(p, "angle", 0.0), - roundness: f(p, "roundness", 0.0).clamp(0.0, 100.0), - feather: f(p, "feather", 0.5).clamp(0.0, 0.99), - blur: blur(15.0), + radius_x: f(p, "radiusX", 0.3).max(0.001), + radius_y: f(p, "radiusY", 0.3).max(0.001), + angle: spin_angle(f(p, "angle", 0.0), -360.0), + blur_angle: f(p, "blurAngle", 15.0).clamp(0.0, 360.0), }] }), - }, - "filter.blurGallery.fieldBlur" => FilterParams::FieldBlur { - pins: list::(p, "pins").unwrap_or_else(|| vec![FieldPin { x: f(p, "centerX", 0.5), y: f(p, "centerY", 0.5), blur: blur(15.0) }]), - }, - "filter.blurGallery.spinBlur" => FilterParams::SpinBlur { - pins: list::(p, "pins") - .map(|mut v| { - for pin in &mut v { - pin.angle = if pin.angle.is_finite() { pin.angle.clamp(-360.0, 360.0) } else { 0.0 }; - pin.blur_angle = if pin.blur_angle.is_finite() { pin.blur_angle.clamp(0.0, 360.0) } else { 0.0 }; - } - v - }) - .unwrap_or_else(|| { - let a = f(p, "angle", 0.0); - vec![SpinPin { - x: f(p, "centerX", 0.5), - y: f(p, "centerY", 0.5), - radius_x: f(p, "radiusX", 0.3).max(0.001), - radius_y: f(p, "radiusY", 0.3).max(0.001), - angle: if a.is_finite() { a.clamp(-360.0, 360.0) } else { 0.0 }, - blur_angle: f(p, "blurAngle", 15.0).clamp(0.0, 360.0), - }] - }), - }, - "filter.blurGallery.pathBlur" => FilterParams::PathBlur { - paths: list::(p, "paths") - .map(|mut v| { - // Entry speeds bypass the scalar clamp above; the halo - // casts one to i32 and adds, so an unclamped value - // overflows (#708). - for b in &mut v { - b.speed = b.speed.clamp(0.0, 500.0); - } - v - }) - .unwrap_or_else(|| { - vec![BlurPath { - points: vec![[f(p, "startX", 0.2), f(p, "startY", 0.5)], [f(p, "endX", 0.8), f(p, "endY", 0.5)]], - speed: f(p, "speed", 50.0).clamp(0.0, 500.0), - taper: f(p, "taper", 0.0).clamp(0.0, 100.0), - }] - }), - }, - // ---- Other ---- - "filter.other.custom" => FilterParams::Custom { - kernel: p - .get("kernel") - .and_then(Value::as_array) - .map(|a| a.iter().take(25).map(|v| v.as_f64().unwrap_or(0.0).clamp(-999.0, 999.0) as f32).collect()) - .unwrap_or_else(|| (0..25).map(|k| if k == 12 { 1.0 } else { 0.0 }).collect()), - scale: f(p, "scale", 1.0).clamp(1.0, 9999.0), - offset: f(p, "offset", 0.0).clamp(-9999.0, 9999.0), - }, - "filter.other.hsbHsl" => { - let m = |k: &str, d: &str| match s(p, k, d) { - "hsb" => HsbModel::Hsb, - "hsl" => HsbModel::Hsl, - _ => HsbModel::Rgb, - }; - FilterParams::HsbHsl { input: m("inputMode", "rgb"), output: m("rowOrder", "hsb") } - } - crate::color_to_alpha_cmds::ID => crate::color_to_alpha_cmds::params(p), - // ---- Video ---- - "filter.video.deInterlace" => FilterParams::DeInterlace { - eliminate_even: s(p, "eliminate", "oddFields") == "evenFields", - interpolate: s(p, "createBy", "interpolation") != "duplication", - }, - "filter.video.ntscColors" => FilterParams::NtscColors, - _ => return crate::gallery_cmds::params_for(id, p), - }) + } +} + +fn path_blur(p: &Value) -> FilterParams { + FilterParams::PathBlur { + paths: list::(p, "paths") + .map(|mut v| { + // The halo casts speeds to i32, so unclamped entries overflow (#708). + for b in &mut v { + b.speed = b.speed.clamp(0.0, 500.0); + } + v + }) + .unwrap_or_else(|| { + vec![BlurPath { + points: vec![[f(p, "startX", 0.2), f(p, "startY", 0.5)], [f(p, "endX", 0.8), f(p, "endY", 0.5)]], + speed: f(p, "speed", 50.0).clamp(0.0, 500.0), + taper: f(p, "taper", 0.0).clamp(0.0, 100.0), + }] + }), + } +} + +fn custom(p: &Value) -> FilterParams { + FilterParams::Custom { + kernel: p + .get("kernel") + .and_then(Value::as_array) + .map(|a| a.iter().take(25).map(|v| v.as_f64().unwrap_or(0.0).clamp(-999.0, 999.0) as f32).collect()) + .unwrap_or_else(|| (0..25).map(|k| if k == 12 { 1.0 } else { 0.0 }).collect()), + scale: f(p, "scale", 1.0).clamp(1.0, 9999.0), + offset: f(p, "offset", 0.0).clamp(-9999.0, 9999.0), + } } /// Ids whose rendering uses the foreground/background colours. diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index db204a3bf4..dc87d3f4e7 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -25,13 +25,14 @@ use std::collections::HashMap; use std::hash::{Hash, Hasher}; use std::sync::Arc; -use photocraft_compose::effects::BevelPaint; use photocraft_compose::effects::FieldKind; -use photocraft_doc::{BevelTechnique, Contour, Effect, GlobalLight, GlowSource, GlowTechnique, Layer, LayerContent, Pattern}; +use photocraft_doc::{Contour, Effect, GlobalLight, Layer, LayerContent, Pattern}; use photocraft_geom::{Rect, TileCoord}; use photocraft_raster::{Surface, Tile}; -use crate::plan::{Kernel, stroke_widths}; +use crate::plan::Kernel; + +mod builders; /// Input of a map stage. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -306,181 +307,14 @@ pub(crate) fn program(e: &Effect, light: &GlobalLight, vector_shape: bool) -> Ma pub(crate) fn program_with(e: &Effect, light: &GlobalLight, vector_shape: bool, patterns: &[Pattern], anchor: (f64, f64)) -> MapProgram { let mut b = B { stages: Vec::new(), fields: Vec::new() }; let maps = match e { - Effect::DropShadow(s) | Effect::InnerShadow(s) => { - // shadow_map - let inner = matches!(e, Effect::InnerShadow(_)); - let angle = if s.use_global_light { light.angle } else { s.angle }; - let (dx, dy) = offset(angle, s.distance); - let src = b.shift(In::Shape, dx, dy, if inner { 1.0 } else { 0.0 }, inner); - let (r, bw) = photocraft_compose::effects::spread_split(s.size, s.spread); - let mut m = src; - if r > 0.0 { - // dist_outside of the shifted map is the shifted field (integer offsets; shifted-in - // pixels are far away for a drop shadow, inside for an inner shadow). - let f = b.field(if inner { FieldKind::ChokeInside } else { FieldKind::StrokeOutside }, r); - let d = if dx == 0.0 && dy == 0.0 { - f - } else { - b.push(stage(Kernel::MShift, Some(f), None, [dx, dy, if inner { -0.5 } else { 1e10 }, 0.0], dx.abs().max(dy.abs()) as i32)) - }; - m = b.dilate(src, d, r); - } - let m = b.blur(m, bw); - b.finish(m, None, false, &s.contour, inner, 0); - 1 - } - Effect::OuterGlow(g) | Effect::InnerGlow(g) => { - // glow_map - let inner = matches!(e, Effect::InnerGlow(_)); - let center = inner && g.source == GlowSource::Center; - match g.technique { - GlowTechnique::Precise => { - let d = b.field(if inner { FieldKind::Inside } else { FieldKind::Outside }, g.size); - let solid = g.size * g.spread; - let soft = (g.size + 1.0 - solid).max(1e-3); - let m = b.push(stage(Kernel::MGlow, Some(d), None, [solid, soft, 0.0, 0.0], 0)); - b.finish_glow(m, photocraft_compose::effects::glow_lut(g), inner, center); - } - GlowTechnique::Softer => { - // Inner glows (edge, and centre as 1 - the edge result) spread 1 - alpha. - let src = if inner { b.shift(In::Shape, 0.0, 0.0, 0.0, true) } else { In::Shape }; - let (r, bw) = photocraft_compose::effects::spread_split(g.size, g.spread); - let mut m = src; - if r > 0.0 { - let d = b.field(if inner { FieldKind::ChokeInside } else { FieldKind::StrokeOutside }, r); - m = b.dilate(src, d, r); - } - let m = b.blur(m, bw); - b.finish_glow(m, photocraft_compose::effects::glow_lut(g), inner, center); - } - } - 1 - } - Effect::Satin(s) => { - // satin_map - let (dx, dy) = offset(s.angle, photocraft_compose::effects::satin_distance(s)); - let a = b.shift(In::Shape, dx, dy, 0.0, false); - let a = b.conv(a, photocraft_compose::effects::tent_kernel(s.size)); - let c = b.shift(In::Shape, -dx, -dy, 0.0, false); - let c = b.conv(c, photocraft_compose::effects::tent_kernel(s.size)); - b.finish_lut(a, Some(c), s.invert, photocraft_compose::effects::satin_lut(&s.contour), true, 0); - 1 - } - Effect::BevelEmboss(bv) => { - // bevel_maps: height map (tent blur of the shape, or chiselled distance ramps), then - // highlight / shadow shading inside and / or outside the shape. - let g = photocraft_compose::effects::bevel_geom(bv); - let size = bv.size.max(1.0); - let paint = |p: BevelPaint| match p { - BevelPaint::Outer => 0.0, - BevelPaint::Both => 1.0, - BevelPaint::Inner => 2.0, - }; - let mut h = if bv.technique == BevelTechnique::Smooth { - b.conv(In::Shape, photocraft_compose::effects::tent_kernel(g.width)) - } else { - let [din, dout] = b.bevel_fields(size); - let soft = g.chisel_soft > 0.0; - let h = b.push(stage(Kernel::MBevelH, Some(din), Some(dout), [paint(g.paint), size, f32::from(u8::from(soft)), 0.0], 0)); - // As `effects::bevel_height`: only emboss styles blur a Chisel Soft ramp. - if soft && g.paint == BevelPaint::Both { b.conv(h, photocraft_compose::effects::tent_kernel(g.chisel_soft)) } else { h } - }; - if let Some(c) = &bv.contour { - // Contour element: the height through the contour (`bevel_contour_lut`). - let lut = photocraft_compose::effects::bevel_contour_lut(c); - let mut st = stage(Kernel::MFinish, Some(h), None, [0.0, 0.0, 1.0, 0.0], 0); - st.lut = Some(Arc::new(lut)); - h = b.push(st); - } - if let Some(t) = &bv.texture - && let Some(pat) = photocraft_doc::pattern::find(patterns, &t.id, &t.name).filter(|p| p.is_paintable()) - { - // Texture element (`effects::bevel_height`): luminance × depth / unit added. - let unit = if bv.depth.abs() > 1e-6 { (g.depth / bv.depth).abs().max(1e-3) } else { g.width.max(1.0) }; - let pl = photocraft_compose::pattern::Placement::anchored(anchor, t.link, t.phase, t.scale, 0.0); - let (origin, cs, inv) = pl.parts(); - let mut st = stage(Kernel::MBevelTex, Some(h), None, [t.depth / unit, f32::from(u8::from(t.invert)), 0.0, 0.0], 0); - st.p3 = [origin.0 as f32, origin.1 as f32, cs.0 as f32, cs.1 as f32]; - st.p4 = [inv as f32, pat.width as f32, pat.height as f32, 0.0]; - st.pattern = Some(pat.clone()); - h = b.push(st); - } - if bv.soften >= 1.0 { - h = b.conv(h, photocraft_compose::effects::tent_kernel(bv.soften)); - } - let (angle, altitude) = if bv.use_global_light { (light.angle, light.altitude) } else { (bv.angle, bv.altitude) }; - let (sa, ca) = angle.to_radians().sin_cos(); - let (se, ce) = altitude.to_radians().sin_cos(); - let lut = contour_lut(&bv.gloss_contour).map(Arc::new); - // Region (`fs_mbevelshade`): 0 inside, 1 under the edge and outside, 2 / 3 emboss / - // pillow emboss (both halves in one map). - let passes: Vec<(f32, f32)> = match g.paint { - BevelPaint::Inner => vec![(g.depth, 0.0)], - BevelPaint::Outer => vec![(g.depth, 1.0)], - BevelPaint::Both => vec![(g.depth, if g.pillow { 3.0 } else { 2.0 })], - }; - let mut out = 0; - for (depth, region) in &passes { - for which in [0.0, 1.0] { - let mut s = stage(Kernel::MBevelShade, Some(h), None, [ca * ce, -sa * ce, se, se], 1); - s.p1 = [*depth, *region, which, f32::from(u8::from(lut.is_some()))]; - s.p3 = [f32::from(u8::from(g.paint == BevelPaint::Outer && bv.technique != BevelTechnique::Smooth)), 0.0, 0.0, 0.0]; - s.lut = lut.clone(); - s.s = Some(In::Shape); - s.out = Some(out); - out += 1; - b.stages.push(s); - } - } - out - } - Effect::Stroke(st) => { - // composite_with_effects' stroke bands (maps 0 outside, 1 inside) - let (in_w, out_w) = stroke_widths(st); - if out_w > 0.0 { - // Narrow strokes keep the fitted chamfer, wide ones the exact transform (#3646); - // the CPU picks the same field by the same width (`stroke_outside_exact`). - let kind = match (vector_shape, photocraft_compose::effects::stroke_outside_exact(out_w)) { - (true, true) => FieldKind::StrokeOutsideVector, - (true, false) => FieldKind::StrokeOutsideVectorChamfer, - (false, true) => FieldKind::StrokeOutsideExact, - (false, false) => FieldKind::StrokeOutside, - }; - let d = b.field(kind, out_w); - let mut s = stage(Kernel::MStroke, Some(d), None, [out_w, 0.0, 0.0, 0.0], 0); - s.out = Some(0); - b.stages.push(s); - } - if in_w > 0.0 { - let d = b.field(FieldKind::StrokeInside, in_w); - let mut s = stage(Kernel::MStroke, Some(d), None, [in_w, 0.0, 0.0, 0.0], 0); - s.out = Some(1); - b.stages.push(s); - } - 2 - } + Effect::DropShadow(s) | Effect::InnerShadow(s) => b.shadow(s, light, matches!(e, Effect::InnerShadow(_))), + Effect::OuterGlow(g) | Effect::InnerGlow(g) => b.glow(g, matches!(e, Effect::InnerGlow(_))), + Effect::Satin(s) => b.satin(s), + Effect::BevelEmboss(bv) => b.bevel(bv, light, patterns, anchor), + Effect::Stroke(st) => b.stroke(st, vector_shape), Effect::ColorOverlay { .. } | Effect::GradientOverlay { .. } | Effect::PatternOverlay { .. } => return MapProgram::empty(), }; - let mut h = std::collections::hash_map::DefaultHasher::new(); - for s in &b.stages { - (format!("{:?}", s.kernel), s.a, s.b, s.s, s.radius, s.out).hash(&mut h); - for v in s.p0.iter().chain(&s.p1).chain(&s.p3).chain(&s.p4) { - v.to_bits().hash(&mut h); - } - if let Some(p) = &s.pattern { - (&p.id, &p.name, p.width, p.height).hash(&mut h); - for (c, t) in p.surface.tiles() { - (c.tx, c.ty, Arc::as_ptr(t) as usize).hash(&mut h); - } - } - if let Some(l) = &s.lut { - for v in l.iter() { - v.to_bits().hash(&mut h); - } - } - } - (maps, &b.fields).hash(&mut h); - MapProgram { key: h.finish() | 1, maps, stages: b.stages, fields: b.fields } + MapProgram { key: b.key(maps), maps, stages: b.stages, fields: b.fields } } // --------------------------------------------------------------------------------------------- diff --git a/crates/gpu/src/fx/builders.rs b/crates/gpu/src/fx/builders.rs new file mode 100644 index 0000000000..3c92de99f6 --- /dev/null +++ b/crates/gpu/src/fx/builders.rs @@ -0,0 +1,195 @@ +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use photocraft_compose::effects::{self as fx, BevelGeom, BevelPaint, FieldKind}; +use photocraft_doc::{Bevel, BevelTechnique, BevelTexture, GlobalLight, Glow, GlowSource, GlowTechnique, Pattern, Satin, Shadow, StrokeFx}; + +use super::{B, In, contour_lut, offset, stage}; +use crate::plan::{Kernel, stroke_widths}; + +fn flag(v: bool) -> f32 { + f32::from(u8::from(v)) +} + +impl B { + pub(super) fn shadow(&mut self, s: &Shadow, light: &GlobalLight, inner: bool) -> usize { + // shadow_map + let angle = if s.use_global_light { light.angle } else { s.angle }; + let (dx, dy) = offset(angle, s.distance); + let src = self.shift(In::Shape, dx, dy, if inner { 1.0 } else { 0.0 }, inner); + let m = self.spread_blur(src, (s.size, s.spread), inner, dx, dy); + self.finish(m, None, false, &s.contour, inner, 0); + 1 + } + + fn spread_blur(&mut self, src: In, (size, spread): (f32, f32), inner: bool, dx: f32, dy: f32) -> In { + let (r, bw) = fx::spread_split(size, spread); + if r <= 0.0 { + return self.blur(src, bw); + } + // The shifted map's distance field is the field shifted by the same whole pixels. + let f = self.field(if inner { FieldKind::ChokeInside } else { FieldKind::StrokeOutside }, r); + let d = if dx == 0.0 && dy == 0.0 { + f + } else { + self.push(stage(Kernel::MShift, Some(f), None, [dx, dy, if inner { -0.5 } else { 1e10 }, 0.0], dx.abs().max(dy.abs()) as i32)) + }; + let m = self.dilate(src, d, r); + self.blur(m, bw) + } + + pub(super) fn glow(&mut self, g: &Glow, inner: bool) -> usize { + // glow_map + let center = inner && g.source == GlowSource::Center; + let m = match g.technique { + GlowTechnique::Precise => { + let d = self.field(if inner { FieldKind::Inside } else { FieldKind::Outside }, g.size); + let solid = g.size * g.spread; + let soft = (g.size + 1.0 - solid).max(1e-3); + self.push(stage(Kernel::MGlow, Some(d), None, [solid, soft, 0.0, 0.0], 0)) + } + GlowTechnique::Softer => { + // Inner glows spread 1 - alpha. + let src = if inner { self.shift(In::Shape, 0.0, 0.0, 0.0, true) } else { In::Shape }; + self.spread_blur(src, (g.size, g.spread), inner, 0.0, 0.0) + } + }; + self.finish_glow(m, fx::glow_lut(g), inner, center); + 1 + } + + pub(super) fn satin(&mut self, s: &Satin) -> usize { + // satin_map + let (dx, dy) = offset(s.angle, fx::satin_distance(s)); + let a = self.shift(In::Shape, dx, dy, 0.0, false); + let a = self.conv(a, fx::tent_kernel(s.size)); + let c = self.shift(In::Shape, -dx, -dy, 0.0, false); + let c = self.conv(c, fx::tent_kernel(s.size)); + self.finish_lut(a, Some(c), s.invert, fx::satin_lut(&s.contour), true, 0); + 1 + } + + pub(super) fn bevel(&mut self, bv: &Bevel, light: &GlobalLight, patterns: &[Pattern], anchor: (f64, f64)) -> usize { + // bevel_maps: a height map, then highlight and shadow shading. + let g = fx::bevel_geom(bv); + let mut h = self.bevel_height(bv, &g); + if let Some(c) = &bv.contour { + // Contour element: the height through `bevel_contour_lut`. + let mut st = stage(Kernel::MFinish, Some(h), None, [0.0, 0.0, 1.0, 0.0], 0); + st.lut = Some(Arc::new(fx::bevel_contour_lut(c))); + h = self.push(st); + } + if let Some(t) = &bv.texture + && let Some(pat) = photocraft_doc::pattern::find(patterns, &t.id, &t.name).filter(|p| p.is_paintable()) + { + let unit = if bv.depth.abs() > 1e-6 { (g.depth / bv.depth).abs().max(1e-3) } else { g.width.max(1.0) }; + h = self.bevel_texture(h, t, pat, unit, anchor); + } + if bv.soften >= 1.0 { + h = self.conv(h, fx::tent_kernel(bv.soften)); + } + self.bevel_shading(h, bv, &g, light) + } + + fn bevel_height(&mut self, bv: &Bevel, g: &BevelGeom) -> In { + if bv.technique == BevelTechnique::Smooth { + return self.conv(In::Shape, fx::tent_kernel(g.width)); + } + let paint = match g.paint { + BevelPaint::Outer => 0.0, + BevelPaint::Both => 1.0, + BevelPaint::Inner => 2.0, + }; + let size = bv.size.max(1.0); + let [din, dout] = self.bevel_fields(size); + let soft = g.chisel_soft > 0.0; + let h = self.push(stage(Kernel::MBevelH, Some(din), Some(dout), [paint, size, flag(soft), 0.0], 0)); + // Only emboss styles blur a Chisel Soft ramp, as in `effects::bevel_height`. + if soft && g.paint == BevelPaint::Both { self.conv(h, fx::tent_kernel(g.chisel_soft)) } else { h } + } + + fn bevel_texture(&mut self, h: In, t: &BevelTexture, pat: &Pattern, unit: f32, anchor: (f64, f64)) -> In { + // Texture element: adds luminance × depth / unit to the height. + let pl = photocraft_compose::pattern::Placement::anchored(anchor, t.link, t.phase, t.scale, 0.0); + let (origin, cs, inv) = pl.parts(); + let mut st = stage(Kernel::MBevelTex, Some(h), None, [t.depth / unit, flag(t.invert), 0.0, 0.0], 0); + st.p3 = [origin.0 as f32, origin.1 as f32, cs.0 as f32, cs.1 as f32]; + st.p4 = [inv as f32, pat.width as f32, pat.height as f32, 0.0]; + st.pattern = Some(pat.clone()); + self.push(st) + } + + fn bevel_shading(&mut self, h: In, bv: &Bevel, g: &BevelGeom, light: &GlobalLight) -> usize { + let (angle, altitude) = if bv.use_global_light { (light.angle, light.altitude) } else { (bv.angle, bv.altitude) }; + let (sa, ca) = angle.to_radians().sin_cos(); + let (se, ce) = altitude.to_radians().sin_cos(); + let lut = contour_lut(&bv.gloss_contour).map(Arc::new); + // Region for `fs_mbevelshade`: 0 inside, 1 outside, 2 emboss, 3 pillow emboss. + let region = match g.paint { + BevelPaint::Inner => 0.0, + BevelPaint::Outer => 1.0, + BevelPaint::Both if g.pillow => 3.0, + BevelPaint::Both => 2.0, + }; + let outer_chisel = g.paint == BevelPaint::Outer && bv.technique != BevelTechnique::Smooth; + for (out, which) in [0.0, 1.0].into_iter().enumerate() { + let mut s = stage(Kernel::MBevelShade, Some(h), None, [ca * ce, -sa * ce, se, se], 1); + s.p1 = [g.depth, region, which, flag(lut.is_some())]; + s.p3 = [flag(outer_chisel), 0.0, 0.0, 0.0]; + s.lut = lut.clone(); + s.s = Some(In::Shape); + s.out = Some(out); + self.stages.push(s); + } + 2 + } + + pub(super) fn stroke(&mut self, st: &StrokeFx, vector_shape: bool) -> usize { + // Stroke bands: map 0 outside, map 1 inside. + let (in_w, out_w) = stroke_widths(st); + if out_w > 0.0 { + // Narrow strokes use the chamfer field and wide ones the exact field, as on the CPU (#3646). + let kind = match (vector_shape, fx::stroke_outside_exact(out_w)) { + (true, true) => FieldKind::StrokeOutsideVector, + (true, false) => FieldKind::StrokeOutsideVectorChamfer, + (false, true) => FieldKind::StrokeOutsideExact, + (false, false) => FieldKind::StrokeOutside, + }; + self.stroke_band(kind, out_w, 0); + } + if in_w > 0.0 { + self.stroke_band(FieldKind::StrokeInside, in_w, 1); + } + 2 + } + + fn stroke_band(&mut self, kind: FieldKind, width: f32, out: usize) { + let d = self.field(kind, width); + let mut s = stage(Kernel::MStroke, Some(d), None, [width, 0.0, 0.0, 0.0], 0); + s.out = Some(out); + self.stages.push(s); + } + + pub(super) fn key(&self, maps: usize) -> u64 { + let mut h = std::collections::hash_map::DefaultHasher::new(); + for s in &self.stages { + (format!("{:?}", s.kernel), s.a, s.b, s.s, s.radius, s.out).hash(&mut h); + for v in s.p0.iter().chain(&s.p1).chain(&s.p3).chain(&s.p4) { + v.to_bits().hash(&mut h); + } + if let Some(p) = &s.pattern { + (&p.id, &p.name, p.width, p.height).hash(&mut h); + for (c, t) in p.surface.tiles() { + (c.tx, c.ty, Arc::as_ptr(t) as usize).hash(&mut h); + } + } + if let Some(l) = &s.lut { + for v in l.iter() { + v.to_bits().hash(&mut h); + } + } + } + (maps, &self.fields).hash(&mut h); + h.finish() | 1 + } +} diff --git a/crates/io/src/adjust_map.rs b/crates/io/src/adjust_map.rs index 9cd7479b81..f2ec34309d 100644 --- a/crates/io/src/adjust_map.rs +++ b/crates/io/src/adjust_map.rs @@ -11,9 +11,11 @@ //! stay [`Adjustment::Unsupported`] and are written back verbatim. use photocraft_doc::Adjustment; -use photocraft_doc::adjust::{CURVE_MAP_LEN, CurvePoint, HueRange, LevelsChannel, ToneSpace, curve_map, curve_map_outputs}; +use photocraft_doc::adjust::{CURVE_MAP_LEN, CurvePoint, HueRange, LevelsChannel, ToneSpace, curve_map}; use photocraft_psd::descriptor::{Descriptor, Value, VersionedDescriptor}; +mod encode; + /// All PSD adjustment keys recognized as adjustment layers. pub const ADJUSTMENT_KEYS: [&[u8; 4]; 16] = [b"levl", b"curv", b"hue2", b"brit", b"nvrt", b"thrs", b"post", b"expA", b"vibA", b"blnc", b"mixr", b"grdm", b"phfl", b"selc", b"blwh", b"clrL"]; @@ -609,206 +611,37 @@ fn levels_write(v: &mut Vec, c: &LevelsChannel) { /// (Brightness/Contrast also writes a `CgEd` descriptor). Every evaluated kind has an /// encoding; the result is empty only for an [`Adjustment::Unsupported`] with a malformed key. pub fn write(adj: &Adjustment) -> Vec<([u8; 4], Vec)> { - let mut v = Vec::new(); + let block = |key: &[u8; 4], data: Vec| vec![(*key, data)]; match adj { - Adjustment::Invert => return vec![(*b"nvrt", Vec::new())], - Adjustment::Threshold { level } => { - put16(&mut v, q255(*level).max(1)); - put16(&mut v, 0); - return vec![(*b"thrs", v)]; - } - Adjustment::Posterize { levels } => { - put16(&mut v, (*levels).clamp(2, 255) as u16); - put16(&mut v, 0); - return vec![(*b"post", v)]; - } - Adjustment::BrightnessContrast { brightness, contrast, legacy } => { - v.extend_from_slice(&clamp_i16(*brightness).to_be_bytes()); - v.extend_from_slice(&clamp_i16(*contrast).to_be_bytes()); - put16(&mut v, 127); - v.push(0); - let d = Descriptor::new("null") - .with("Vrsn", Value::Integer(1)) - .with("Brgh", Value::Integer(brightness.round() as i32)) - .with("Cntr", Value::Integer(contrast.round() as i32)) - .with("means", Value::Integer(127)) - .with("Lab ", Value::Boolean(false)) - .with("useLegacy", Value::Boolean(*legacy)) - .with("Auto", Value::Boolean(false)); - return vec![(*b"brit", v), (*b"CgEd", VersionedDescriptor::new(d).to_bytes())]; - } + Adjustment::Invert => return block(b"nvrt", Vec::new()), + Adjustment::Threshold { level } => return block(b"thrs", encode::words(&[q255(*level).max(1), 0])), + Adjustment::Posterize { levels } => return block(b"post", encode::words(&[(*levels).clamp(2, 255) as u16, 0])), + Adjustment::BrightnessContrast { brightness, contrast, legacy } => return encode::brightness_contrast(*brightness, *contrast, *legacy), Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges } => { - put16(&mut v, 2); - v.push(u8::from(*colorize)); - v.push(0); - // The colorize triplet, then the master triplet. The inactive one gets Photoshop's - // defaults; the colorize hue (0..360 in the model) is stored signed, -180..180. - let (colorize_hsl, master) = if *colorize { - let h = hue.rem_euclid(360.0); - ([if h > 180.0 { h - 360.0 } else { h }, *saturation, *lightness], [0.0; 3]) - } else { - ([30.0, 25.0, 0.0], [*hue, *saturation, *lightness]) - }; - for x in colorize_hsl.into_iter().chain(master) { - v.extend_from_slice(&clamp_i16(x).to_be_bytes()); - } - // Six hue ranges (reds, yellows, greens, cyans, blues, magentas): range values in - // 0..360, then the range's hue, saturation and lightness. - for r in ranges { - for x in r.bounds { - put16(&mut v, x.rem_euclid(360.0).round() as u16 % 360); - } - for x in [r.hue, r.saturation, r.lightness] { - v.extend_from_slice(&clamp_i16(x).to_be_bytes()); - } - } - return vec![(*b"hue2", v)]; - } - Adjustment::Exposure { exposure, offset, gamma } => { - put16(&mut v, 1); - for x in [exposure, offset, gamma] { - v.extend_from_slice(&x.to_be_bytes()); - } - v.push(1); // color space flag (spec: "1 byte") - return vec![(*b"expA", v)]; - } - Adjustment::Levels { master, per_channel, space, black } => { - put16(&mut v, 2); - levels_write(&mut v, master); - for c in per_channel { - levels_write(&mut v, c); - } - let ident = LevelsChannel::default(); - levels_write(&mut v, if *space == ToneSpace::Cmyk { black } else { &ident }); - for _ in 5..29 { - levels_write(&mut v, &LevelsChannel::default()); - } - return vec![(*b"levl", v)]; + return block(b"hue2", encode::hue_saturation([*hue, *saturation, *lightness], *colorize, ranges)); } + Adjustment::Exposure { exposure, offset, gamma } => return block(b"expA", encode::exposure(*exposure, *offset, *gamma)), + Adjustment::Levels { master, per_channel, space, black } => return block(b"levl", encode::levels(master, per_channel, *space, black)), Adjustment::Curves { master, per_channel, space, black, pencil } => { - v.push(u8::from(*pencil)); - put16(&mut v, 1); - let ink = *space == ToneSpace::Cmyk && black.len() >= 2; - v.extend_from_slice(&(if ink { 0b11111u32 } else { 0b1111 }).to_be_bytes()); - for c in std::iter::once(master).chain(per_channel.iter()).chain(ink.then_some(black)) { - if *pencil { - v.extend(curve_map_outputs(c).iter().map(|&o| u8::try_from(q255(o)).unwrap_or(u8::MAX))); - continue; - } - put16(&mut v, c.len().min(19) as u16); - for p in c.iter().take(19) { - put16(&mut v, q255(p.output)); - put16(&mut v, q255(p.input)); - } - } - return vec![(*b"curv", v)]; - } - Adjustment::SelectiveColor { relative, adjustments } => { - put16(&mut v, 1); - put16(&mut v, u16::from(!*relative)); - v.extend_from_slice(&[0; 8]); - for rec in adjustments { - for x in rec { - v.extend_from_slice(&clamp_i16(x.clamp(-100.0, 100.0)).to_be_bytes()); - } - } - return vec![(*b"selc", v)]; + return block(b"curv", encode::curves(master, per_channel, *space, black, *pencil)); } + Adjustment::SelectiveColor { relative, adjustments } => return block(b"selc", encode::selective_color(*relative, adjustments)), Adjustment::ColorLookup { name, lut, size, dither, .. } => { - // A lookup without a usable table (none chosen yet, or a bad size) renders as the - // identity, so it is written as a 2³ identity cube rather than dropped. - let n = *size as usize; - let cube = lut.as_deref().zip(photocraft_doc::adjust::lut3d_len(*size)).and_then(|(table, len)| table.get(..len)).filter(|_| n <= 256); - let (file, dither) = match cube { - Some(cube) => ( - photocraft_cms::lutfile::LutFile { title: String::new(), size: n, data: cube.to_vec(), domain_min: [0.0; 3], domain_max: [1.0; 3] }, - *dither, - ), - _ => (photocraft_cms::lutfile::LutFile { title: String::new(), ..photocraft_cms::lutfile::LutFile::identity(2) }, false), - }; - let en = - |t: &str, val: &str| Value::Enumerated { type_id: photocraft_psd::descriptor::Id::new(t), value: photocraft_psd::descriptor::Id::new(val) }; - let text = |t: &str| Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul(t)); - let d = Descriptor::new("null") - .with("lookupType", en("colorLookupType", "3DLUT")) - .with("NM ", text(name)) - .with("Dthr", Value::Boolean(dither)) - .with("profile", Value::RawData(Vec::new())) - .with("LUTFormat", en("LUTFormatType", "LUTFormatCUBE")) - .with("dataOrder", en("colorLookupOrder", "rgbOrder")) - .with("tableOrder", en("colorLookupOrder", "bgrOrder")) - .with("LUT3DFileData", Value::RawData(photocraft_cms::lutfile::write_cube(&file).into_bytes())) - .with("LUT3DFileName", text(name)); - put16(&mut v, 1); - v.extend_from_slice(&VersionedDescriptor::new(d).to_bytes()); - return vec![(*b"clrL", v)]; + return block(b"clrL", encode::color_lookup(name, lut.as_deref().map(Vec::as_slice), *size, *dither)); } Adjustment::GradientMap { stops, reverse, dither } => { - // Photoshop needs two stops; fewer are written as the gradient they render as - // (none: black to white, i.e. the gray value itself; one: that colour throughout). - let stops = match stops.as_slice() { - [] => vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])], - [(_, c)] => vec![(0.0, *c), (1.0, *c)], - s => s.to_vec(), - }; - return vec![(*b"grdm", write_gradient_map(&stops, *reverse, *dither))]; - } - Adjustment::Vibrance { vibrance, saturation } => { - let d = Descriptor::new("null") - .with("vibrance", Value::Integer(i32::from(clamp_i16(vibrance.clamp(-100.0, 100.0))))) - .with("Strt", Value::Integer(i32::from(clamp_i16(saturation.clamp(-100.0, 100.0))))); - return vec![(*b"vibA", VersionedDescriptor::new(d).to_bytes())]; + return block(b"grdm", write_gradient_map(&encode::gradient_stops(stops), *reverse, *dither)); } + Adjustment::Vibrance { vibrance, saturation } => return block(b"vibA", encode::vibrance(*vibrance, *saturation)), Adjustment::ColorBalance { shadows, midtones, highlights, preserve_luminosity } => { - for x in shadows.iter().chain(midtones).chain(highlights) { - v.extend_from_slice(&clamp_i16(x.clamp(-100.0, 100.0)).to_be_bytes()); - } - v.push(u8::from(*preserve_luminosity)); - v.push(0); - return vec![(*b"blnc", v)]; - } - Adjustment::BlackWhite { weights, tint } => { - let mut d = Descriptor::new("null"); - for (w, k) in weights.iter().zip(BW_KEYS) { - d = d.with(k, Value::Integer(i32::from(clamp_i16(w.clamp(-200.0, 300.0))))); - } - let d = d - .with("useTint", Value::Boolean(tint.is_some())) - .with("tintColor", Value::Descriptor(rgb_desc(tint.unwrap_or(BW_TINT)))) - .with("bwPresetKind", Value::Integer(1)) - .with("blackAndWhitePresetFileName", Value::Text(photocraft_psd::descriptor::UnicodeString::new_nul(""))); - return vec![(*b"blwh", VersionedDescriptor::new(d).to_bytes())]; + return block(b"blnc", encode::color_balance([shadows, midtones, highlights], *preserve_luminosity)); } + Adjustment::BlackWhite { weights, tint } => return block(b"blwh", encode::black_white(weights, *tint)), Adjustment::PhotoFilter { color, density, preserve_luminosity } => { - // Version 2: an RGB colour structure keeps the colour at 16 bits. - put16(&mut v, 2); - put16(&mut v, 0); - for x in color { - put16(&mut v, (x.clamp(0.0, 1.0) * 65535.0).round() as u16); - } - put16(&mut v, 0); - v.extend_from_slice(&((density.clamp(0.0, 1.0) * 100.0).round() as u32).to_be_bytes()); - v.push(u8::from(*preserve_luminosity)); - // Photoshop requires the 17-byte Photo Filter payload after the version to be - // padded to a 4-byte boundary INSIDE the tagged block's declared length. - // A single pad byte made an 18-byte `phfl` block that Photoshop could not open - // even though PhotoCraft and other tolerant readers accepted it (#1455). - v.extend_from_slice(&[0, 0, 0]); - return vec![(*b"phfl", v)]; + return block(b"phfl", encode::photo_filter(*color, *density, *preserve_luminosity)); } Adjustment::ChannelMixer { matrix, monochrome } => { - put16(&mut v, 1); - put16(&mut v, u16::from(*monochrome)); - // Red, green, blue, then the gray record (the first row, which monochrome uses). - for row in matrix.iter().chain(std::iter::once(&matrix[0])) { - let pct = |x: f32| clamp_i16((x * 100.0).clamp(-200.0, 200.0)).to_be_bytes(); - for x in &row[..3] { - v.extend_from_slice(&pct(*x)); - } - v.extend_from_slice(&[0, 0]); - v.extend_from_slice(&pct(row[3])); - } - return vec![(*b"mixr", v)]; + return block(b"mixr", encode::channel_mixer(matrix, *monochrome)); } Adjustment::Unsupported { psd_key, raw } => { let k = psd_key.as_bytes(); diff --git a/crates/io/src/adjust_map/encode.rs b/crates/io/src/adjust_map/encode.rs new file mode 100644 index 0000000000..3318160924 --- /dev/null +++ b/crates/io/src/adjust_map/encode.rs @@ -0,0 +1,210 @@ +use photocraft_doc::adjust::{CurvePoint, HueRange, LevelsChannel, ToneSpace, curve_map_outputs}; +use photocraft_psd::descriptor::{Descriptor, Id, UnicodeString, Value, VersionedDescriptor}; + +use super::{BW_KEYS, BW_TINT, clamp_i16, levels_write, put16, q255, rgb_desc}; + +pub(super) fn words(xs: &[u16]) -> Vec { + let mut v = Vec::new(); + for &x in xs { + put16(&mut v, x); + } + v +} + +fn push_i16(v: &mut Vec, x: f32) { + v.extend_from_slice(&clamp_i16(x).to_be_bytes()); +} + +pub(super) fn brightness_contrast(brightness: f32, contrast: f32, legacy: bool) -> Vec<([u8; 4], Vec)> { + let mut v = Vec::new(); + push_i16(&mut v, brightness); + push_i16(&mut v, contrast); + put16(&mut v, 127); + v.push(0); + let d = Descriptor::new("null") + .with("Vrsn", Value::Integer(1)) + .with("Brgh", Value::Integer(brightness.round() as i32)) + .with("Cntr", Value::Integer(contrast.round() as i32)) + .with("means", Value::Integer(127)) + .with("Lab ", Value::Boolean(false)) + .with("useLegacy", Value::Boolean(legacy)) + .with("Auto", Value::Boolean(false)); + vec![(*b"brit", v), (*b"CgEd", VersionedDescriptor::new(d).to_bytes())] +} + +pub(super) fn hue_saturation(hsl: [f32; 3], colorize: bool, ranges: &[HueRange; 6]) -> Vec { + let mut v = words(&[2]); + v.push(u8::from(colorize)); + v.push(0); + // The colorize triplet, then the master triplet. The inactive one gets Photoshop's + // defaults; the colorize hue (0..360 in the model) is stored signed, -180..180. + let [hue, saturation, lightness] = hsl; + let (colorize_hsl, master) = if colorize { + let h = hue.rem_euclid(360.0); + ([if h > 180.0 { h - 360.0 } else { h }, saturation, lightness], [0.0; 3]) + } else { + ([30.0, 25.0, 0.0], hsl) + }; + for x in colorize_hsl.into_iter().chain(master) { + push_i16(&mut v, x); + } + // Six hue ranges: four bounds in 0..360, then hue, saturation and lightness. + for r in ranges { + for x in r.bounds { + put16(&mut v, x.rem_euclid(360.0).round() as u16 % 360); + } + for x in [r.hue, r.saturation, r.lightness] { + push_i16(&mut v, x); + } + } + v +} + +pub(super) fn exposure(exposure: f32, offset: f32, gamma: f32) -> Vec { + let mut v = words(&[1]); + for x in [exposure, offset, gamma] { + v.extend_from_slice(&x.to_be_bytes()); + } + v.push(1); // color space flag (spec: "1 byte") + v +} + +pub(super) fn levels(master: &LevelsChannel, per_channel: &[LevelsChannel; 3], space: ToneSpace, black: &LevelsChannel) -> Vec { + let mut v = words(&[2]); + levels_write(&mut v, master); + for c in per_channel { + levels_write(&mut v, c); + } + let ident = LevelsChannel::default(); + levels_write(&mut v, if space == ToneSpace::Cmyk { black } else { &ident }); + for _ in 5..29 { + levels_write(&mut v, &LevelsChannel::default()); + } + v +} + +pub(super) fn curves(master: &[CurvePoint], per_channel: &[Vec; 3], space: ToneSpace, black: &[CurvePoint], pencil: bool) -> Vec { + let mut v = vec![u8::from(pencil)]; + put16(&mut v, 1); + let ink = space == ToneSpace::Cmyk && black.len() >= 2; + v.extend_from_slice(&(if ink { 0b11111u32 } else { 0b1111 }).to_be_bytes()); + for c in std::iter::once(master).chain(per_channel.iter().map(Vec::as_slice)).chain(ink.then_some(black)) { + if pencil { + v.extend(curve_map_outputs(c).iter().map(|&o| u8::try_from(q255(o)).unwrap_or(u8::MAX))); + continue; + } + put16(&mut v, c.len().min(19) as u16); + for p in c.iter().take(19) { + put16(&mut v, q255(p.output)); + put16(&mut v, q255(p.input)); + } + } + v +} + +pub(super) fn selective_color(relative: bool, adjustments: &[[f32; 4]; 9]) -> Vec { + let mut v = words(&[1, u16::from(!relative)]); + v.extend_from_slice(&[0; 8]); + for rec in adjustments { + for x in rec { + push_i16(&mut v, x.clamp(-100.0, 100.0)); + } + } + v +} + +pub(super) fn color_lookup(name: &str, lut: Option<&[f32]>, size: u32, dither: bool) -> Vec { + // A lookup without a usable table renders as identity, so it is written as a 2³ identity cube. + let n = size as usize; + let cube = lut.zip(photocraft_doc::adjust::lut3d_len(size)).and_then(|(table, len)| table.get(..len)).filter(|_| n <= 256); + let (file, dither) = match cube { + Some(cube) => { + (photocraft_cms::lutfile::LutFile { title: String::new(), size: n, data: cube.to_vec(), domain_min: [0.0; 3], domain_max: [1.0; 3] }, dither) + } + _ => (photocraft_cms::lutfile::LutFile { title: String::new(), ..photocraft_cms::lutfile::LutFile::identity(2) }, false), + }; + let en = |t: &str, val: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(val) }; + let text = |t: &str| Value::Text(UnicodeString::new_nul(t)); + let d = Descriptor::new("null") + .with("lookupType", en("colorLookupType", "3DLUT")) + .with("NM ", text(name)) + .with("Dthr", Value::Boolean(dither)) + .with("profile", Value::RawData(Vec::new())) + .with("LUTFormat", en("LUTFormatType", "LUTFormatCUBE")) + .with("dataOrder", en("colorLookupOrder", "rgbOrder")) + .with("tableOrder", en("colorLookupOrder", "bgrOrder")) + .with("LUT3DFileData", Value::RawData(photocraft_cms::lutfile::write_cube(&file).into_bytes())) + .with("LUT3DFileName", text(name)); + let mut v = words(&[1]); + v.extend_from_slice(&VersionedDescriptor::new(d).to_bytes()); + v +} + +pub(super) fn gradient_stops(stops: &[(f32, [f32; 3])]) -> Vec<(f32, [f32; 3])> { + // Photoshop needs two stops: none becomes black to white, one becomes a flat colour. + match stops { + [] => vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])], + [(_, c)] => vec![(0.0, *c), (1.0, *c)], + s => s.to_vec(), + } +} + +fn percent(x: f32, lo: f32, hi: f32) -> Value { + Value::Integer(i32::from(clamp_i16(x.clamp(lo, hi)))) +} + +pub(super) fn vibrance(vibrance: f32, saturation: f32) -> Vec { + let d = Descriptor::new("null").with("vibrance", percent(vibrance, -100.0, 100.0)).with("Strt", percent(saturation, -100.0, 100.0)); + VersionedDescriptor::new(d).to_bytes() +} + +pub(super) fn color_balance(tones: [&[f32; 3]; 3], preserve_luminosity: bool) -> Vec { + let mut v = Vec::new(); + for x in tones.into_iter().flatten() { + push_i16(&mut v, x.clamp(-100.0, 100.0)); + } + v.push(u8::from(preserve_luminosity)); + v.push(0); + v +} + +pub(super) fn black_white(weights: &[f32; 6], tint: Option<[f32; 3]>) -> Vec { + let mut d = Descriptor::new("null"); + for (w, k) in weights.iter().zip(BW_KEYS) { + d = d.with(k, percent(*w, -200.0, 300.0)); + } + let d = d + .with("useTint", Value::Boolean(tint.is_some())) + .with("tintColor", Value::Descriptor(rgb_desc(tint.unwrap_or(BW_TINT)))) + .with("bwPresetKind", Value::Integer(1)) + .with("blackAndWhitePresetFileName", Value::Text(UnicodeString::new_nul(""))); + VersionedDescriptor::new(d).to_bytes() +} + +pub(super) fn photo_filter(color: [f32; 3], density: f32, preserve_luminosity: bool) -> Vec { + // Version 2 keeps the colour at 16 bits. + let mut v = words(&[2, 0]); + for x in color { + put16(&mut v, (x.clamp(0.0, 1.0) * 65535.0).round() as u16); + } + put16(&mut v, 0); + v.extend_from_slice(&((density.clamp(0.0, 1.0) * 100.0).round() as u32).to_be_bytes()); + v.push(u8::from(preserve_luminosity)); + // Photoshop only opens the payload padded to 4 bytes inside the block (#1455). + v.extend_from_slice(&[0, 0, 0]); + v +} + +pub(super) fn channel_mixer(matrix: &[[f32; 4]; 3], monochrome: bool) -> Vec { + let mut v = words(&[1, u16::from(monochrome)]); + // Red, green and blue rows, then the gray record that monochrome uses. + for row in matrix.iter().chain(std::iter::once(&matrix[0])) { + let pct = |x: f32| clamp_i16((x * 100.0).clamp(-200.0, 200.0)).to_be_bytes(); + for x in &row[..3] { + v.extend_from_slice(&pct(*x)); + } + v.extend_from_slice(&[0, 0]); + v.extend_from_slice(&pct(row[3])); + } + v +} diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index 73e9ce5642..d6b11e8fee 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -766,96 +766,108 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool let p = match ev { ToolEvent::Down { x, y, .. } | ToolEvent::Move { x, y, .. } | ToolEvent::Up { x, y } => [x, y], }; - if app.session.active().is_none() || !p[0].is_finite() || !p[1].is_finite() { + if app.session.active().is_none() || !p.iter().all(|v| v.is_finite()) || straighten(app, ev, mods, p) { return true; } - // The Straighten button, or ⌘ held: the drag draws a line to level the frame on. - if crate::crop_straighten::pointer(app, ev, mods) { - claim(app); - // Default mode: the image turns so the line ends up level (the press keeps its point). - // The turn is one box Undo step, like any other frame gesture. - match ev { - ToolEvent::Down { .. } => { - app.crop.press_step = Some(step_of(app)); - crate::crop_mode::sync(app, Some(p)); - } - ToolEvent::Move { .. } => crate::crop_mode::sync_frame(app), - ToolEvent::Up { .. } => { - crate::crop_mode::sync_frame(app); - push_press_step(app); - } - } - return true; + if track(app, ev, p, mods) { + crate::crop_mode::sync_frame(app); } + true +} + +fn track(app: &mut PhotocraftApp, ev: ToolEvent, p: [f64; 2], mods: Modifiers) -> bool { match ev { - ToolEvent::Down { .. } => { - claim(app); - app.crop.editing = true; - app.crop.press_step = Some(step_of(app)); - // Default mode: the view is upright for the frame (picking the tool already made it so; - // this catches a frame set over the control channel), about the pressed point. - crate::crop_mode::sync(app, Some(p)); - let frame = app.ui.crop_rect.filter(|r| r.iter().all(|v| v.is_finite())); - let deg = angle(app); - let image = crate::crop_mode::moves_image(app); - app.crop.drag = Some(match frame.map(|r| (r, hit_turned(r, deg, p, tolerance(app)))) { - Some((rect, Hit::Handle(hx, hy))) => { - let view = if crate::crop_mode::live_center(app) { crate::crop_mode::press_view(app) } else { None }; - CropDrag::Resize { hx, hy, start: p, rect, view } - } - // Default mode: inside the box the image moves, the box staying where it is on - // screen (Photoshop doesn't re-centre it). Inside the untouched frame a drag still - // draws a new box. - Some((rect, Hit::Inside)) if !app.crop.default_frame && image => { - CropDrag::MoveImage { start: p, rect, view: crate::crop_mode::press_view(app) } - } - Some((rect, Hit::Inside)) if !app.crop.default_frame => CropDrag::Move { start: p, rect }, - Some((rect, Hit::Outside)) if image => { - let c = center(rect); - CropDrag::TurnImage { center: c, grab: (p[1] - c[1]).atan2(p[0] - c[0]), from: deg, view: crate::crop_mode::press_view(app) } - } - // Outside the frame a drag turns it, as in Photoshop (#1792). - Some((rect, Hit::Outside)) => { - let c = center(rect); - CropDrag::Rotate { center: c, grab: (p[1] - c[1]).atan2(p[0] - c[0]), from: deg } - } - _ => { - app.ui.crop_angle = 0.0; - CropDrag::Draw { anchor: p, cur: p, last: p, prev: app.ui.crop_rect } - } - }); - } + ToolEvent::Down { .. } => begin_drag(app, p), ToolEvent::Move { .. } => update(app, p, mods), ToolEvent::Up { .. } => { update(app, p, mods); - let Some(drag) = app.crop.drag.take() else { return true }; - let ok = app.ui.crop_rect.is_some_and(size_ok); - // A click outside the untouched default frame (no turn) leaves it the default. - let changed = !matches!(drag, CropDrag::Rotate { from, .. } | CropDrag::TurnImage { from, .. } if from == angle(app)) - && !matches!(drag, CropDrag::MoveImage { rect, .. } if app.ui.crop_rect == Some(rect)); - if ok && changed { - app.crop.default_frame = false; - } - match drag { - CropDrag::Draw { prev, .. } if !ok => app.ui.crop_rect = prev, - CropDrag::Move { rect, .. } | CropDrag::Resize { rect, view: None, .. } if !ok => app.ui.crop_rect = Some(rect), - // A live-centred resize collapsed: the frame and the view it moved go back. - CropDrag::Resize { rect, view: Some(view), .. } if !ok => crate::crop_mode::offset_image(app, rect, Some(view), [0.0, 0.0]), - // Auto Center Preview: a box drawn in default mode moves to the middle. (A resized - // one stays where its centre was: `crop_mode::live_resize`.) - CropDrag::Draw { .. } if ok => { - crate::crop_mode::sync_frame(app); - crate::crop_mode::auto_center(app); - } - _ => {} - } + let Some(drag) = app.crop.drag.take() else { return false }; + release(app, drag); + } + } + true +} + +fn straighten(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers, p: [f64; 2]) -> bool { + // Straighten button or ⌘: the drag draws a line to level the frame on. + if !crate::crop_straighten::pointer(app, ev, mods) { + return false; + } + claim(app); + // Default mode: the image turns so the line ends up level. + // The turn is one box Undo step, like any other frame gesture. + match ev { + ToolEvent::Down { .. } => { + app.crop.press_step = Some(step_of(app)); + crate::crop_mode::sync(app, Some(p)); + } + ToolEvent::Move { .. } => crate::crop_mode::sync_frame(app), + ToolEvent::Up { .. } => { + crate::crop_mode::sync_frame(app); push_press_step(app); } } - crate::crop_mode::sync_frame(app); true } +fn begin_drag(app: &mut PhotocraftApp, p: [f64; 2]) { + claim(app); + app.crop.editing = true; + app.crop.press_step = Some(step_of(app)); + // Default mode: the view stays upright for the frame, about the pressed point. + crate::crop_mode::sync(app, Some(p)); + let frame = app.ui.crop_rect.filter(|r| r.iter().all(|v| v.is_finite())); + let deg = angle(app); + app.crop.drag = Some(match frame.map(|r| (r, hit_turned(r, deg, p, tolerance(app)))) { + Some((rect, Hit::Handle(hx, hy))) => { + let view = if crate::crop_mode::live_center(app) { crate::crop_mode::press_view(app) } else { None }; + CropDrag::Resize { hx, hy, start: p, rect, view } + } + Some((rect, Hit::Inside)) if !app.crop.default_frame => inside_drag(app, p, rect), + Some((rect, Hit::Outside)) => outside_drag(app, p, rect, deg), + _ => { + app.ui.crop_angle = 0.0; + CropDrag::Draw { anchor: p, cur: p, last: p, prev: app.ui.crop_rect } + } + }); +} + +fn inside_drag(app: &PhotocraftApp, p: [f64; 2], rect: [f64; 4]) -> CropDrag { + // Default mode moves the image and keeps the box in place on screen, as in Photoshop. + if crate::crop_mode::moves_image(app) { + CropDrag::MoveImage { start: p, rect, view: crate::crop_mode::press_view(app) } + } else { + CropDrag::Move { start: p, rect } + } +} + +fn outside_drag(app: &PhotocraftApp, p: [f64; 2], rect: [f64; 4], deg: f64) -> CropDrag { + let c = center(rect); + let grab = (p[1] - c[1]).atan2(p[0] - c[0]); + if crate::crop_mode::moves_image(app) { + CropDrag::TurnImage { center: c, grab, from: deg, view: crate::crop_mode::press_view(app) } + } else { + // Outside the frame a drag turns it, as in Photoshop (#1792). + CropDrag::Rotate { center: c, grab, from: deg } + } +} + +fn release(app: &mut PhotocraftApp, drag: CropDrag) { + let ok = app.ui.crop_rect.is_some_and(size_ok); + // A click outside the untouched default frame (no turn) leaves it the default. + let changed = !matches!(drag, CropDrag::Rotate { from, .. } | CropDrag::TurnImage { from, .. } if from == angle(app)) + && !matches!(drag, CropDrag::MoveImage { rect, .. } if app.ui.crop_rect == Some(rect)); + if ok && changed { + app.crop.default_frame = false; + } + if ok { + finish_frame(app, drag); + } else { + restore_frame(app, drag); + } + push_press_step(app); +} + /// On release: the frame state at the press becomes a box Undo step when the gesture changed it. fn push_press_step(app: &mut PhotocraftApp) { if let Some(before) = app.crop.press_step.take() @@ -866,45 +878,68 @@ fn push_press_step(app: &mut PhotocraftApp) { } } +fn restore_frame(app: &mut PhotocraftApp, drag: CropDrag) { + match drag { + CropDrag::Draw { prev, .. } => app.ui.crop_rect = prev, + CropDrag::Move { rect, .. } | CropDrag::Resize { rect, view: None, .. } => app.ui.crop_rect = Some(rect), + // A collapsed live-centred resize restores the frame and the view. + CropDrag::Resize { rect, view: Some(view), .. } => crate::crop_mode::offset_image(app, rect, Some(view), [0.0, 0.0]), + _ => {} + } +} + +fn finish_frame(app: &mut PhotocraftApp, drag: CropDrag) { + // Auto Center Preview moves a box drawn in default mode to the middle. + if let CropDrag::Draw { .. } = drag { + crate::crop_mode::sync_frame(app); + crate::crop_mode::auto_center(app); + } +} + /// The frame follows the pointer at `p`. fn update(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) { + if follow_view_drag(app, p, mods) { + return; + } + if let Some(rect) = dragged_frame(app, p, mods) { + app.ui.crop_rect = Some(rect); + } +} + +fn follow_view_drag(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) -> bool { + match app.crop.drag { + Some(CropDrag::Rotate { center, grab, from }) => app.ui.crop_angle = turned_angle(center, grab, from, p, mods.shift), + Some(CropDrag::TurnImage { center, grab, from, view }) => { + // The image turns with the pointer's sweep on screen, so the frame turns against it. + let at = crate::crop_mode::to_press(app, view, p); + let turned = from - ((at[1] - center[1]).atan2(at[0] - center[0]) - grab).to_degrees(); + if turned.is_finite() { + app.ui.crop_angle = normalized_angle(if mods.shift { (turned / 15.0).round() * 15.0 } else { turned }); + crate::crop_mode::sync_frame(app); + } + } + Some(CropDrag::MoveImage { start, rect, view }) => { + // The image follows the pointer, so the frame and view move the other way. + let at = crate::crop_mode::to_press(app, view, p); + crate::crop_mode::offset_image(app, rect, view, [at[0] - start[0], at[1] - start[1]]); + } + Some(CropDrag::Resize { hx, hy, start, rect, view: Some(view) }) => { + // Auto Center Preview keeps the box centred while the handle follows the pointer. + let at = crate::crop_mode::to_press(app, Some(view), p); + let ratio = resize_ratio(app, rect, mods); + let deg = angle(app); + crate::crop_mode::live_resize(app, crate::crop_mode::LiveResize { rect, deg, hx, hy, start, q: at, ratio, alt: mods.alt }, view); + } + _ => return false, + } + true +} + +fn dragged_frame(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) -> Option<[f64; 4]> { let ratio = preset_ratio(app); let space = app.crop.space; let deg = angle(app); - match app.crop.drag { - Some(CropDrag::Rotate { center, grab, from }) => { - app.ui.crop_angle = turned_angle(center, grab, from, p, mods.shift); - return; - } - Some(CropDrag::TurnImage { center, grab, from, view }) => { - // The image turns with the pointer's sweep on screen, so the frame turns against it. - let q = crate::crop_mode::to_press(app, view, p); - let a = from - ((q[1] - center[1]).atan2(q[0] - center[0]) - grab).to_degrees(); - if a.is_finite() { - app.ui.crop_angle = normalized_angle(if mods.shift { (a / 15.0).round() * 15.0 } else { a }); - crate::crop_mode::sync_frame(app); - } - return; - } - Some(CropDrag::MoveImage { start, rect, view }) => { - // The image follows the pointer: the frame moves the other way on it, and the view - // with the frame, so the box stays put. - let q = crate::crop_mode::to_press(app, view, p); - crate::crop_mode::offset_image(app, rect, view, [q[0] - start[0], q[1] - start[1]]); - return; - } - Some(CropDrag::Resize { hx, hy, start, rect, view: Some(view) }) => { - // Auto Center Preview: the box stays centred where it was while the handle follows - // the pointer. - let q = crate::crop_mode::to_press(app, Some(view), p); - let ratio = resize_ratio(app, rect, mods); - crate::crop_mode::live_resize(app, crate::crop_mode::LiveResize { rect, deg, hx, hy, start, q, ratio, alt: mods.alt }, view); - return; - } - _ => {} - } - let Some(drag) = app.crop.drag.as_mut() else { return }; - let rect = match drag { + match app.crop.drag.as_mut()? { CropDrag::Draw { anchor, cur, last, .. } => { if space { // Space: the frame being drawn follows the pointer, keeping its size. @@ -915,14 +950,11 @@ fn update(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) { *cur = p; } *last = p; - if *anchor == *cur { - return; - } - drawn(*anchor, *cur, ratio, mods) + (*anchor != *cur).then(|| drawn(*anchor, *cur, ratio, mods)) } CropDrag::Move { start, rect } => { let (dx, dy) = (p[0] - start[0], p[1] - start[1]); - [rect[0] + dx, rect[1] + dy, rect[2] + dx, rect[3] + dy] + Some([rect[0] + dx, rect[1] + dy, rect[2] + dx, rect[3] + dy]) } CropDrag::Resize { hx, hy, start, rect, .. } => { let keep = || { @@ -930,11 +962,10 @@ fn update(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) { (w > 0.0 && h > 0.0).then(|| w / h) }; let ratio = ratio.or_else(|| if mods.shift { keep() } else { None }); - resized_turned(*rect, deg, *hx, *hy, [p[0] - start[0], p[1] - start[1]], ratio, mods.alt) + Some(resized_turned(*rect, deg, *hx, *hy, [p[0] - start[0], p[1] - start[1]], ratio, mods.alt)) } - CropDrag::Rotate { .. } | CropDrag::TurnImage { .. } | CropDrag::MoveImage { .. } => return, - }; - app.ui.crop_rect = Some(rect); + CropDrag::Rotate { .. } | CropDrag::TurnImage { .. } | CropDrag::MoveImage { .. } => None, + } } /// Geometry and snapping must use the same ratio so constrained handles stay aligned.