1#[derive(Debug, Clone, Copy, PartialEq)]
5pub struct Color {
6 pub r: f64,
8 pub g: f64,
10 pub b: f64,
12}
13
14impl Color {
15 pub const BLACK: Self = Self::rgb(0.0, 0.0, 0.0);
17 pub const WHITE: Self = Self::rgb(1.0, 1.0, 1.0);
19
20 pub const fn rgb(r: f64, g: f64, b: f64) -> Self {
22 Self { r, g, b }
23 }
24
25 pub fn from_bytes(r: u8, g: u8, b: u8) -> Self {
27 Self::rgb(
28 f64::from(r) / 255.0,
29 f64::from(g) / 255.0,
30 f64::from(b) / 255.0,
31 )
32 }
33
34 pub fn to_bytes(self) -> [u8; 3] {
36 [
37 component_to_byte(self.r),
38 component_to_byte(self.g),
39 component_to_byte(self.b),
40 ]
41 }
42
43 pub fn from_cmyk(c: f64, m: f64, y: f64, k: f64) -> Self {
46 let c = c.clamp(0.0, 1.0);
47 let m = m.clamp(0.0, 1.0);
48 let y = y.clamp(0.0, 1.0);
49 let k = k.clamp(0.0, 1.0);
50 Self::rgb(
51 (1.0 - c) * (1.0 - k),
52 (1.0 - m) * (1.0 - k),
53 (1.0 - y) * (1.0 - k),
54 )
55 }
56}
57
58fn component_to_byte(value: f64) -> u8 {
59 let scaled = (value.clamp(0.0, 1.0) * 255.0).round();
60 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
61 let byte = scaled as u8;
62 byte
63}
64
65#[derive(Debug, Clone, PartialEq)]
67pub struct Canvas {
68 width: u32,
69 height: u32,
70 pixels: Vec<u8>,
71 background: [u8; 4],
73}
74
75impl Canvas {
76 pub fn new(width: u32, height: u32, background: Color) -> Self {
78 let [r, g, b] = background.to_bytes();
79 let background = [r, g, b, 255];
80 let mut pixels = Vec::with_capacity((width as usize) * (height as usize) * 4);
81 for _ in 0..(width as usize) * (height as usize) {
82 pixels.extend_from_slice(&[r, g, b, 255]);
83 }
84 Self {
85 width,
86 height,
87 pixels,
88 background,
89 }
90 }
91
92 pub fn width(&self) -> u32 {
94 self.width
95 }
96
97 pub fn height(&self) -> u32 {
99 self.height
100 }
101
102 pub fn pixels(&self) -> &[u8] {
104 &self.pixels
105 }
106
107 pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
109 if x >= self.width || y >= self.height {
110 return None;
111 }
112 let index = ((y as usize) * (self.width as usize) + (x as usize)) * 4;
113 let slice = &self.pixels[index..index + 4];
114 Some([slice[0], slice[1], slice[2], slice[3]])
115 }
116
117 pub fn is_blank(&self) -> bool {
123 let background = self.background;
124 self.pixels.chunks_exact(4).all(|pixel| pixel == background)
125 }
126
127 pub fn blend(&mut self, x: u32, y: u32, color: Color, alpha: f64) {
129 self.blend_with(x, y, color, alpha, BlendMode::Normal);
130 }
131
132 pub fn blend_with(&mut self, x: u32, y: u32, color: Color, alpha: f64, mode: BlendMode) {
138 if x >= self.width || y >= self.height || alpha <= 0.0 {
139 return;
140 }
141 let alpha = alpha.clamp(0.0, 1.0);
142 let [r, g, b] = color.to_bytes();
143 let index = ((y as usize) * (self.width as usize) + (x as usize)) * 4;
144 let target = &mut self.pixels[index..index + 4];
145 let backdrop = [
146 f64::from(target[0]) / 255.0,
147 f64::from(target[1]) / 255.0,
148 f64::from(target[2]) / 255.0,
149 ];
150 let source = [
151 f64::from(r) / 255.0,
152 f64::from(g) / 255.0,
153 f64::from(b) / 255.0,
154 ];
155 let blended = if mode == BlendMode::Normal {
156 source
157 } else if mode.is_non_separable() {
158 non_separable(mode, backdrop, source)
159 } else {
160 [
161 separable(mode, backdrop[0], source[0]),
162 separable(mode, backdrop[1], source[1]),
163 separable(mode, backdrop[2], source[2]),
164 ]
165 };
166 for (slot, (backdrop, blended)) in target.iter_mut().zip(backdrop.iter().zip(blended)) {
167 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
168 let value = ((blended * alpha + backdrop * (1.0 - alpha)).clamp(0.0, 1.0) * 255.0)
169 .round() as u8;
170 *slot = value;
171 }
172 target[3] = 255;
173 }
174}
175
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
180pub enum BlendMode {
181 #[default]
183 Normal,
184 Multiply,
186 Screen,
188 Overlay,
190 Darken,
192 Lighten,
194 ColorDodge,
196 ColorBurn,
198 HardLight,
200 SoftLight,
202 Difference,
204 Exclusion,
206 Hue,
208 Saturation,
210 Color,
212 Luminosity,
214}
215
216impl BlendMode {
217 pub fn from_name(name: &[u8]) -> Option<Self> {
219 Some(match name {
220 b"Normal" | b"Compatible" => Self::Normal,
221 b"Multiply" => Self::Multiply,
222 b"Screen" => Self::Screen,
223 b"Overlay" => Self::Overlay,
224 b"Darken" => Self::Darken,
225 b"Lighten" => Self::Lighten,
226 b"ColorDodge" => Self::ColorDodge,
227 b"ColorBurn" => Self::ColorBurn,
228 b"HardLight" => Self::HardLight,
229 b"SoftLight" => Self::SoftLight,
230 b"Difference" => Self::Difference,
231 b"Exclusion" => Self::Exclusion,
232 b"Hue" => Self::Hue,
233 b"Saturation" => Self::Saturation,
234 b"Color" => Self::Color,
235 b"Luminosity" => Self::Luminosity,
236 _ => return None,
237 })
238 }
239
240 fn is_non_separable(self) -> bool {
242 matches!(
243 self,
244 Self::Hue | Self::Saturation | Self::Color | Self::Luminosity
245 )
246 }
247}
248
249fn separable(mode: BlendMode, backdrop: f64, source: f64) -> f64 {
251 match mode {
252 BlendMode::Multiply => backdrop * source,
253 BlendMode::Screen => backdrop + source - backdrop * source,
254 BlendMode::Overlay => separable(BlendMode::HardLight, source, backdrop),
255 BlendMode::Darken => backdrop.min(source),
256 BlendMode::Lighten => backdrop.max(source),
257 BlendMode::ColorDodge => {
258 if backdrop <= 0.0 {
259 0.0
260 } else if source >= 1.0 {
261 1.0
262 } else {
263 (backdrop / (1.0 - source)).min(1.0)
264 }
265 }
266 BlendMode::ColorBurn => {
267 if backdrop >= 1.0 {
268 1.0
269 } else if source <= 0.0 {
270 0.0
271 } else {
272 1.0 - ((1.0 - backdrop) / source).min(1.0)
273 }
274 }
275 BlendMode::HardLight => {
276 if source <= 0.5 {
277 separable(BlendMode::Multiply, backdrop, 2.0 * source)
278 } else {
279 separable(BlendMode::Screen, backdrop, 2.0 * source - 1.0)
280 }
281 }
282 BlendMode::SoftLight => {
283 if source <= 0.5 {
284 backdrop - (1.0 - 2.0 * source) * backdrop * (1.0 - backdrop)
285 } else {
286 let d = if backdrop <= 0.25 {
287 ((16.0 * backdrop - 12.0) * backdrop + 4.0) * backdrop
288 } else {
289 backdrop.sqrt()
290 };
291 backdrop + (2.0 * source - 1.0) * (d - backdrop)
292 }
293 }
294 BlendMode::Difference => (backdrop - source).abs(),
295 BlendMode::Exclusion => backdrop + source - 2.0 * backdrop * source,
296 _ => source,
298 }
299}
300
301fn luminance(colour: [f64; 3]) -> f64 {
303 0.3 * colour[0] + 0.59 * colour[1] + 0.11 * colour[2]
304}
305
306fn clip_colour(colour: [f64; 3]) -> [f64; 3] {
307 let l = luminance(colour);
308 let low = colour.iter().copied().fold(f64::MAX, f64::min);
309 let high = colour.iter().copied().fold(f64::MIN, f64::max);
310 if low < 0.0 {
311 let scale = l / (l - low);
312 colour.map(|value| l + (value - l) * scale)
313 } else if high > 1.0 {
314 let scale = (1.0 - l) / (high - l);
315 colour.map(|value| l + (value - l) * scale)
316 } else {
317 colour
318 }
319}
320
321fn set_luminance(colour: [f64; 3], l: f64) -> [f64; 3] {
322 let delta = l - luminance(colour);
323 clip_colour(colour.map(|value| value + delta))
324}
325
326fn saturation(colour: [f64; 3]) -> f64 {
327 let low = colour.iter().copied().fold(f64::MAX, f64::min);
328 let high = colour.iter().copied().fold(f64::MIN, f64::max);
329 high - low
330}
331
332fn set_saturation(colour: [f64; 3], s: f64) -> [f64; 3] {
333 let mut order = [0_usize, 1, 2];
334 order.sort_by(|left, right| {
335 colour[*left]
336 .partial_cmp(&colour[*right])
337 .unwrap_or(core::cmp::Ordering::Equal)
338 });
339 let (min, mid, max) = (order[0], order[1], order[2]);
340 let mut result = [0.0; 3];
341 if colour[max] > colour[min] {
342 result[mid] = (colour[mid] - colour[min]) * s / (colour[max] - colour[min]);
343 result[max] = s;
344 }
345 result[min] = 0.0;
346 result
347}
348
349fn non_separable(mode: BlendMode, backdrop: [f64; 3], source: [f64; 3]) -> [f64; 3] {
351 match mode {
352 BlendMode::Hue => set_luminance(
353 set_saturation(source, saturation(backdrop)),
354 luminance(backdrop),
355 ),
356 BlendMode::Saturation => set_luminance(
357 set_saturation(backdrop, saturation(source)),
358 luminance(backdrop),
359 ),
360 BlendMode::Color => set_luminance(source, luminance(backdrop)),
361 _ => set_luminance(backdrop, luminance(source)),
362 }
363}
364
365#[derive(Debug, Clone, PartialEq)]
370pub struct ClipMask {
371 width: u32,
372 height: u32,
373 coverage: Vec<u8>,
377}
378
379impl ClipMask {
380 pub fn all(width: u32, height: u32) -> Self {
382 Self {
383 width,
384 height,
385 coverage: vec![255; (width as usize) * (height as usize)],
386 }
387 }
388
389 pub fn none(width: u32, height: u32) -> Self {
391 Self {
392 width,
393 height,
394 coverage: vec![0; (width as usize) * (height as usize)],
395 }
396 }
397
398 pub fn contains(&self, x: u32, y: u32) -> bool {
400 if x >= self.width || y >= self.height {
401 return false;
402 }
403 self.coverage[(y as usize) * (self.width as usize) + (x as usize)] > 0
404 }
405
406 pub fn alpha(&self, x: u32, y: u32) -> f64 {
408 if x >= self.width || y >= self.height {
409 return 0.0;
410 }
411 f64::from(self.coverage[(y as usize) * (self.width as usize) + (x as usize)]) / 255.0
412 }
413
414 pub fn multiply_luminosity(&mut self, group: &Canvas) {
419 if group.width != self.width || group.height != self.height {
420 return;
421 }
422 for y in 0..self.height {
423 for x in 0..self.width {
424 let pixel = group.pixel(x, y).unwrap_or([0, 0, 0, 255]);
425 let luminance = 0.3 * f64::from(pixel[0])
426 + 0.59 * f64::from(pixel[1])
427 + 0.11 * f64::from(pixel[2]);
428 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
429 let coverage = (luminance * 255.0 / 255.0).round() as u8;
430 let index = (y as usize) * (self.width as usize) + (x as usize);
431 let scaled = u16::from(self.coverage[index]) * u16::from(coverage) / 255;
432 #[allow(clippy::cast_possible_truncation)]
433 let scaled = scaled as u8;
434 self.coverage[index] = scaled;
435 }
436 }
437 }
438
439 pub fn intersect(&mut self, other: &Self) {
441 if other.width != self.width || other.height != self.height {
442 return;
443 }
444 for (coverage, other) in self.coverage.iter_mut().zip(&other.coverage) {
445 let product = u16::from(*coverage) * u16::from(*other) / 255;
446 *coverage = u8::try_from(product).unwrap_or(u8::MAX);
447 }
448 }
449
450 pub fn set(&mut self, x: u32, y: u32, inside: bool) {
452 if x < self.width && y < self.height {
453 let value = if inside { 255 } else { 0 };
454 self.coverage[(y as usize) * (self.width as usize) + (x as usize)] = value;
455 }
456 }
457
458 pub fn count(&self) -> usize {
460 self.coverage
461 .iter()
462 .filter(|coverage| **coverage > 0)
463 .count()
464 }
465}
466
467#[cfg(test)]
468mod tests {
469 use super::{Canvas, ClipMask, Color};
470
471 #[test]
472 fn a_new_canvas_is_uniformly_filled() {
473 let canvas = Canvas::new(3, 2, Color::WHITE);
474 assert_eq!(canvas.width(), 3);
475 assert_eq!(canvas.height(), 2);
476 assert_eq!(canvas.pixels().len(), 3 * 2 * 4);
477 for y in 0..2 {
478 for x in 0..3 {
479 assert_eq!(canvas.pixel(x, y), Some([255, 255, 255, 255]));
480 }
481 }
482 assert_eq!(canvas.pixel(3, 0), None);
483 }
484
485 #[test]
486 fn blending_mixes_towards_the_source() {
487 let mut canvas = Canvas::new(1, 1, Color::WHITE);
488 canvas.blend(0, 0, Color::BLACK, 1.0);
489 assert_eq!(canvas.pixel(0, 0), Some([0, 0, 0, 255]));
490 let mut canvas = Canvas::new(1, 1, Color::BLACK);
491 canvas.blend(0, 0, Color::WHITE, 0.5);
492 assert_eq!(canvas.pixel(0, 0), Some([128, 128, 128, 255]));
493 canvas.blend(0, 0, Color::WHITE, 0.0);
494 assert_eq!(canvas.pixel(0, 0), Some([128, 128, 128, 255]));
495 }
496
497 #[test]
498 fn cmyk_conversion_is_the_naive_one() {
499 let red = Color::from_cmyk(0.0, 1.0, 1.0, 0.0);
500 assert_eq!(red.to_bytes(), [255, 0, 0]);
501 assert_eq!(Color::from_cmyk(0.0, 0.0, 0.0, 1.0).to_bytes(), [0, 0, 0]);
502 }
503
504 #[test]
505 fn clip_masks_intersect() {
506 let mut mask = ClipMask::all(4, 2);
507 assert_eq!(mask.count(), 8);
508 mask.set(1, 1, false);
509 assert!(!mask.contains(1, 1));
510 let mut other = ClipMask::all(4, 2);
511 other.set(0, 0, false);
512 mask.intersect(&other);
513 assert!(!mask.contains(0, 0));
514 assert!(mask.contains(2, 0));
515 assert_eq!(mask.count(), 6);
516 assert!(!mask.contains(4, 0));
517 }
518}