use std::ops::RangeInclusive;
use image::RgbaImage;
use image::imageops;
use rand::Rng;
use rand::seq::IndexedRandom;
use crate::{CaptchaError, Challenge, Format, Image, Point, Rect, Size, render};
const EDGE_MARGIN: u32 = 5;
const TEMPLATE_SIDE: u32 = 96;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum Mode {
#[default]
Slide,
DragDrop,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Edge {
Left,
Right,
Top,
Bottom,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum VerticalPlacement {
#[default]
Aligned,
Independent,
}
#[derive(Clone, Debug)]
pub struct Graph {
mask: RgbaImage,
shadow: RgbaImage,
overlay: RgbaImage,
}
impl Graph {
#[must_use]
pub fn new(mask: RgbaImage, shadow: RgbaImage, overlay: RgbaImage) -> Self {
Self {
mask,
shadow,
overlay,
}
}
#[must_use]
pub fn puzzle() -> Self {
let distance = |x: u32, y: u32| {
let x = f64::from(x) + 0.5;
let y = f64::from(y) + 0.5;
let body = (x - 15.0).min(81.0 - x).min(y - 23.0).min(83.0 - y);
let tab = 14.0 - (x - 48.0).hypot(y - 23.0);
let notch = (x - 81.0).hypot(y - 53.0) - 13.0;
body.max(tab).min(notch)
};
let coverage = |distance: f64| (distance + 0.5).clamp(0.0, 1.0);
let mask = RgbaImage::from_fn(TEMPLATE_SIDE, TEMPLATE_SIDE, |x, y| {
image::Rgba([
255,
255,
255,
(255.0 * coverage(distance(x, y))).round() as u8,
])
});
let shadow = RgbaImage::from_fn(TEMPLATE_SIDE, TEMPLATE_SIDE, |x, y| {
image::Rgba([0, 0, 0, render::multiply_alpha(mask[(x, y)][3], 155)])
});
let overlay = RgbaImage::from_fn(TEMPLATE_SIDE, TEMPLATE_SIDE, |x, y| {
let distance = distance(x, y);
let outline = coverage(distance) - coverage(distance - 1.6);
image::Rgba([255, 255, 255, (135.0 * outline).round() as u8])
});
Self::new(mask, shadow, overlay)
}
}
#[derive(Clone, Debug)]
pub struct Resources {
backgrounds: Vec<RgbaImage>,
graphs: Vec<Graph>,
}
impl Resources {
#[must_use]
pub fn new(backgrounds: Vec<RgbaImage>, graphs: Vec<Graph>) -> Self {
Self {
backgrounds,
graphs,
}
}
#[must_use]
pub fn from_backgrounds(backgrounds: Vec<RgbaImage>) -> Self {
Self::new(backgrounds, vec![Graph::puzzle()])
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Options {
pub image_size: Size,
pub image_opacity: u8,
pub tile_size: RangeInclusive<u32>,
pub angles: Vec<RangeInclusive<i16>>,
pub holes: u32,
pub start_edges: Vec<Edge>,
pub vertical_placement: VerticalPlacement,
}
impl Default for Options {
fn default() -> Self {
Self {
image_size: Size::new(300, 220),
image_opacity: 255,
tile_size: 60..=70,
angles: Vec::new(),
holes: 1,
start_edges: vec![Edge::Left, Edge::Right, Edge::Top, Edge::Bottom],
vertical_placement: VerticalPlacement::Aligned,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Answer {
target: Rect,
start: Point,
angle: i16,
}
impl Answer {
#[must_use]
pub fn target(&self) -> Rect {
self.target
}
#[must_use]
pub fn start(&self) -> Point {
self.start
}
#[must_use]
pub fn angle(&self) -> i16 {
self.angle
}
#[must_use]
pub fn verify(&self, point: Point, padding: u32) -> bool {
validate(point, self.target.origin, padding)
}
}
#[must_use]
pub fn validate(point: Point, target: Point, padding: u32) -> bool {
point.x.abs_diff(target.x) <= padding && point.y.abs_diff(target.y) <= padding
}
#[derive(Debug)]
pub struct Captcha {
options: Options,
mode: Mode,
resources: Resources,
}
impl Captcha {
pub fn new(options: Options, mode: Mode, resources: Resources) -> Result<Self, CaptchaError> {
validate_options(&options, mode)?;
if resources.backgrounds.is_empty() || resources.graphs.is_empty() {
return Err(CaptchaError::invalid(
"slide resources",
"need at least one background and one template",
));
}
for image in &resources.backgrounds {
render::check_image(image, "slide background")?;
}
for graph in &resources.graphs {
for (image, field) in [
(&graph.mask, "tile mask"),
(&graph.shadow, "tile shadow"),
(&graph.overlay, "tile overlay"),
] {
render::check_size(Size::new(image.width(), image.height()), field)?;
}
if !graph.mask.pixels().any(|pixel| pixel[3] != 0) {
return Err(CaptchaError::invalid(
"tile mask",
"must contain visible pixels",
));
}
}
Ok(Self {
options,
mode,
resources,
})
}
#[must_use]
pub fn options(&self) -> &Options {
&self.options
}
pub fn generate(&self) -> Result<Challenge<Answer>, CaptchaError> {
let mut rng = crate::rng()?;
let options = &self.options;
let size = options.image_size;
let side = rng.random_range(options.tile_size.clone());
let turn = render::angle(&options.angles, &mut rng);
let edge = match self.mode {
Mode::Slide => Edge::Left,
Mode::DragDrop => *choose_resource(&options.start_edges, &mut rng),
};
let layout = Layout::new(size, side, edge);
let positions = layout.positions(options, self.mode, &mut rng);
let target = *choose_resource(&positions, &mut rng);
let start = layout.start(self.mode, target, &mut rng);
let graph = choose_resource(&self.resources.graphs, &mut rng);
let source = choose_resource(&self.resources.backgrounds, &mut rng);
let mut master = render::crop_background(source, size, &mut rng);
let mut tile =
imageops::crop_imm(&master, target.x as u32, target.y as u32, side, side).to_image();
let prepare = |image: &RgbaImage| {
let layer = render::scale(image.clone(), side, side);
render::rotate(layer, turn, Size::square(side))
};
let mask = prepare(&graph.mask);
for (pixel, mask_pixel) in tile.pixels_mut().zip(mask.pixels()) {
pixel[3] = render::multiply_alpha(pixel[3], mask_pixel[3]);
}
imageops::overlay(&mut tile, &prepare(&graph.overlay), 0, 0);
let shadow = prepare(&graph.shadow);
for point in positions {
imageops::overlay(&mut master, &shadow, i64::from(point.x), i64::from(point.y));
}
render::opacity(&mut master, options.image_opacity);
render::opacity(&mut tile, options.image_opacity);
Ok(Challenge::new(
Image::new(master, Format::Jpeg),
Image::new(tile, Format::Png),
Answer {
target: Rect::new(target, Size::square(side)),
start,
angle: turn,
},
))
}
}
fn choose_resource<'a, T>(resources: &'a [T], rng: &mut impl Rng) -> &'a T {
resources
.choose(rng)
.expect("generator configuration guarantees nonempty candidates")
}
fn validate_options(options: &Options, mode: Mode) -> Result<(), CaptchaError> {
let size = options.image_size;
render::check_size(size, "image_size")?;
render::check_range(
&options.tile_size,
1..=size.width.min(size.height),
"tile_size",
)?;
render::check_angles(&options.angles, -360..=360)?;
if options.holes == 0 {
return Err(CaptchaError::invalid(
"holes",
"at least one hole is required",
));
}
let edges = match mode {
Mode::Slide => &[Edge::Left][..],
Mode::DragDrop if options.start_edges.is_empty() => {
return Err(CaptchaError::invalid(
"start_edges",
"at least one edge is required",
));
}
Mode::DragDrop => &options.start_edges,
};
let side = *options.tile_size.end();
if edges
.iter()
.any(|&edge| !Layout::new(size, side, edge).fits(options.holes))
{
return Err(CaptchaError::invalid(
"slide layout",
"largest tile, starting edge and holes must fit without overlap",
));
}
Ok(())
}
struct Layout {
size: Size,
side: u32,
edge: Edge,
x: RangeInclusive<u32>,
y: RangeInclusive<u32>,
}
impl Layout {
fn new(size: Size, side: u32, edge: Edge) -> Self {
let strip = |at_edge| if at_edge { side } else { 0 };
let left = EDGE_MARGIN + strip(edge == Edge::Left);
let top = EDGE_MARGIN + strip(edge == Edge::Top);
let right = size
.width
.saturating_sub(EDGE_MARGIN + strip(edge == Edge::Right));
let bottom = size
.height
.saturating_sub(EDGE_MARGIN + strip(edge == Edge::Bottom));
Self {
size,
side,
edge,
x: left..=right,
y: top..=bottom,
}
}
fn fits(&self, holes: u32) -> bool {
self.x.end().saturating_sub(*self.x.start()) / holes >= self.side
&& self.y.end().saturating_sub(*self.y.start()) >= self.side
}
fn positions(&self, options: &Options, mode: Mode, rng: &mut impl Rng) -> Vec<Point> {
let slot_width = (self.x.end() - self.x.start()) / options.holes;
let y = *self.y.start()..=self.y.end() - self.side;
let shared_y = rng.random_range(y.clone());
(0..options.holes)
.map(|index| {
let left = self.x.start() + index * slot_width;
let x = rng.random_range(left..=left + slot_width - self.side);
let y = if mode == Mode::DragDrop
&& options.vertical_placement == VerticalPlacement::Independent
{
rng.random_range(y.clone())
} else {
shared_y
};
Point::new(x as i32, y as i32)
})
.collect()
}
fn start(&self, mode: Mode, target: Point, rng: &mut impl Rng) -> Point {
if mode == Mode::Slide {
return Point::new(EDGE_MARGIN as i32, target.y);
}
let right = self.size.width - self.side - EDGE_MARGIN;
let bottom = self.size.height - self.side - EDGE_MARGIN;
let (x, y) = match self.edge {
Edge::Left => (EDGE_MARGIN, rng.random_range(EDGE_MARGIN..=bottom)),
Edge::Right => (right, rng.random_range(EDGE_MARGIN..=bottom)),
Edge::Top => (rng.random_range(EDGE_MARGIN..=right), EDGE_MARGIN),
Edge::Bottom => (rng.random_range(EDGE_MARGIN..=right), bottom),
};
Point::new(x as i32, y as i32)
}
}