crtimg 0.1.0

A CLI tool that processes a pixel art image to make it CRT-ish.
Documentation
//! # CRT Effect Module
//!
//! This module contains the core logic for applying the CRT (Cathode Ray Tube)
//! effect to images. The main function, `crt`, orchestrates a pipeline of
//! image processing effects to simulate the appearance of an old CRT screen.

use image::{DynamicImage, GenericImage, GenericImageView, ImageBuffer, Rgba};
use std::path::PathBuf;

/// Applies a barrel distortion to an image to simulate the curvature of a CRT screen.
///
/// This function uses a backward mapping algorithm. For each pixel in the destination
/// (distorted) image, it calculates the corresponding coordinate in the source
/// (original) image. Since the source coordinate is unlikely to be an integer,
/// it uses bilinear interpolation to calculate the correct pixel color from the
/// four surrounding pixels.
///
/// # Arguments
///
/// * `image` - A reference to the `DynamicImage` to be distorted.
/// * `strength` - A `f64` value that controls the intensity of the distortion.
///   Higher values produce a more pronounced "fisheye" or barrel effect.
///
/// # Returns
///
/// A new `DynamicImage` with the barrel distortion applied.
fn apply_distortion(image: &DynamicImage, strength: f64) -> DynamicImage {
    let (width, height) = GenericImageView::dimensions(image);
    let mut distorted_image = ImageBuffer::new(width, height);

    let center_x = width as f64 / 2.0;
    let center_y = height as f64 / 2.0;

    for (x_dest, y_dest, pixel) in distorted_image.enumerate_pixels_mut() {
        let x_dest_f = x_dest as f64;
        let y_dest_f = y_dest as f64;

        // Calculate the vector from the center of the image to the current pixel
        let dx = x_dest_f - center_x;
        let dy = y_dest_f - center_y;
        let r_sq = dx * dx + dy * dy;

        // Apply the barrel distortion formula (backward mapping).
        // This calculates where to "pull" the source pixel from.
        let dist_factor = 1.0 + strength * r_sq;
        let x_src_f = center_x + dx / dist_factor;
        let y_src_f = center_y + dy / dist_factor;

        // If the calculated source coordinate is within the image bounds,
        // perform bilinear interpolation. Otherwise, the pixel is black.
        if x_src_f >= 0.0
            && x_src_f < (width - 1) as f64
            && y_src_f >= 0.0
            && y_src_f < (height - 1) as f64
        {
            // Get the four surrounding pixels (the "interpolation square").
            let x0 = x_src_f.floor() as u32;
            let y0 = y_src_f.floor() as u32;
            let x1 = x0 + 1;
            let y1 = y0 + 1;

            let p00 = GenericImageView::get_pixel(image, x0, y0);
            let p10 = GenericImageView::get_pixel(image, x1, y0);
            let p01 = GenericImageView::get_pixel(image, x0, y1);
            let p11 = GenericImageView::get_pixel(image, x1, y1);

            // Get the fractional parts of the source coordinates to use as weights.
            let dx_fract = x_src_f - x0 as f64;
            let dy_fract = y_src_f - y0 as f64;

            let mut final_pixel = [0u8; 4];
            // Interpolate each color channel (R, G, B, A) separately.
            for i in 0..4 {
                // Interpolate horizontally between the top two pixels.
                let top = p00[i] as f64 * (1.0 - dx_fract) + p10[i] as f64 * dx_fract;
                // Interpolate horizontally between the bottom two pixels.
                let bottom = p01[i] as f64 * (1.0 - dx_fract) + p11[i] as f64 * dx_fract;
                // Interpolate vertically between the two results.
                let interpolated = top * (1.0 - dy_fract) + bottom * dy_fract;
                final_pixel[i] = interpolated.round().clamp(0.0, 255.0) as u8;
            }
            *pixel = Rgba(final_pixel);
        } else {
            // For pixels mapped outside the source image, use black.
            *pixel = Rgba([0, 0, 0, 255]);
        }
    }
    DynamicImage::ImageRgba8(distorted_image)
}

/// Applies a pipeline of effects to an image to simulate a CRT screen.
///
/// The processing pipeline is as follows:
/// 1.  **Upscale**: The image is enlarged using Nearest Neighbor filtering to keep pixels sharp.
/// 2.  **Scanlines**: Dark horizontal lines are drawn over the image.
/// 3.  **Glow**: A bloom/glow effect is created by blurring the image at multiple intensities
///     and then additively blending these blurred layers back onto the upscaled image.
/// 4.  **Post-Blur (Optional)**: A light final blur can be applied.
/// 5.  **Distortion (Optional)**: A barrel distortion is applied to simulate screen curvature.
///
/// # Arguments
///
/// * `image` - The input `DynamicImage`.
/// * `upscale_factor` - The integer factor by which to scale the image.
/// * `scanline_height` - The height of the dark scanlines in pixels.
/// * `scanline_disable` - If `true`, the scanline effect is skipped.
/// * `distortion` - If `true`, barrel distortion is applied.
/// * `distortion_strength` - The strength of the barrel distortion.
/// * `blur` - If `true`, a final blur is applied.
/// * `cache` - If `true`, intermediate images from the pipeline are saved to `./cache/`.
///
/// # Returns
///
/// A `Result` containing the processed `DynamicImage`.
pub async fn crt(
    image: &DynamicImage,
    upscale_factor: u32,
    scanline_height: u32,
    scanline_disable: bool,
    distortion: bool,
    distortion_strength: f64,
    blur: bool,
    cache: bool,
) -> anyhow::Result<DynamicImage> {
    let cache_path = PathBuf::from("./cache/");
    if cache && !cache_path.exists() {
        std::fs::create_dir_all(&cache_path)?;
    }

    // --- 1. Upscale image ---
    // Use Nearest Neighbor filtering to preserve the sharp edges of pixel art.
    let (original_width, original_height) = GenericImageView::dimensions(image);
    let upscaled_width = upscale_factor * original_width;
    let upscaled_height = upscale_factor * original_height;
    log::info!(
        "Upscale image by {}x to ({}, {}).",
        upscale_factor,
        upscaled_width,
        upscaled_height
    );
    let mut upscaled = image.resize_exact(
        upscaled_width,
        upscaled_height,
        image::imageops::FilterType::Nearest,
    );
    assert_eq!(
        GenericImageView::dimensions(&upscaled),
        (upscaled_width, upscaled_height)
    );

    if cache {
        upscaled.save(cache_path.join("upscaled.png"))?;
    }

    // --- 2. Add Scanlines ---
    if !scanline_disable {
        log::info!("Adding scanline to image.");
        // The "shutter" is the part of the original pixel that is blacked out.
        let unshuttered_height = upscale_factor - scanline_height;
        // Iterate over each row of the *original* image.
        for oy in 0..original_height {
            // For each original row, draw the dark scanline on the corresponding upscaled rows.
            for i in 0..scanline_height {
                for x in 0..upscaled_width {
                    upscaled.put_pixel(
                        x,
                        oy * upscale_factor + unshuttered_height + i,
                        image::Rgba([0, 0, 0, 255]),
                    );
                }
            }
        }

        if cache {
            upscaled.save(cache_path.join("scanline.png"))?;
        }
    }

    // --- 3. Add Glow Effect ---
    // The glow is achieved by creating several blurred versions of the image
    // and additively blending them with the base image. This mimics the light
    // from CRT phosphors "bleeding" into adjacent areas.
    log::info!("Adding glow to image.");
    let glow_1x = upscaled.blur((upscale_factor as f32) / 2.0);
    let glow_2x = upscaled.blur(((upscale_factor * 2) as f32) / 2.0);
    let glow_3x = upscaled.blur(((upscale_factor * 3) as f32) / 2.0);

    if cache {
        glow_1x.save(cache_path.join("glow_1x.png"))?;
        glow_2x.save(cache_path.join("glow_2x.png"))?;
        glow_3x.save(cache_path.join("glow_3x.png"))?;
    }

    // Coefficients control how much of each blurred layer is added.
    const COEFFICIENT_1X: f32 = 0.5;
    const COEFFICIENT_2X: f32 = 0.5;
    const COEFFICIENT_3X: f32 = 0.5;

    for x in 0..upscaled_width {
        for y in 0..upscaled_height {
            let mut pixel = GenericImageView::get_pixel(&upscaled, x, y);
            let pixel_1x = GenericImageView::get_pixel(&glow_1x, x, y);
            let pixel_2x = GenericImageView::get_pixel(&glow_2x, x, y);
            let pixel_3x = GenericImageView::get_pixel(&glow_3x, x, y);

            // Additively blend the R, G, and B channels.
            pixel.0[0] = (pixel.0[0] as f32
                + COEFFICIENT_1X * pixel_1x.0[0] as f32
                + COEFFICIENT_2X * pixel_2x.0[0] as f32
                + COEFFICIENT_3X * pixel_3x.0[0] as f32)
                .clamp(0.0, 255.0) as u8;
            pixel.0[1] = (pixel.0[1] as f32
                + COEFFICIENT_1X * pixel_1x.0[1] as f32
                + COEFFICIENT_2X * pixel_2x.0[1] as f32
                + COEFFICIENT_3X * pixel_3x.0[1] as f32)
                .clamp(0.0, 255.0) as u8;
            pixel.0[2] = (pixel.0[2] as f32
                + COEFFICIENT_1X * pixel_1x.0[2] as f32
                + COEFFICIENT_2X * pixel_2x.0[2] as f32
                + COEFFICIENT_3X * pixel_3x.0[2] as f32)
                .clamp(0.0, 255.0) as u8;
            upscaled.put_pixel(x, y, pixel);
        }
    }
    if cache {
        upscaled.save(cache_path.join("glow.png"))?;
    }

    // --- 4. Optional Post-Blur ---
    if blur {
        log::info!("Post blur effect.");
        upscaled = upscaled.blur(0.25);
        if cache {
            upscaled.save(cache_path.join("blur.png"))?;
        }
    }

    // --- 5. Optional Barrel Distortion ---
    if distortion {
        log::info!("Add barrel distortion effect.");
        upscaled = apply_distortion(&upscaled, distortion_strength);
        if cache {
            upscaled.save(cache_path.join("distortion.png"))?;
        }
    }

    Ok(upscaled)
}