takumi 1.0.15

Render UI component trees to images.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
use crate::rendering::BufferPool;
use crate::{Error, Result};

const BLUR_DOWNSAMPLE_TARGET_SIGMA: f32 = 6.0;
const BLUR_DOWNSAMPLE_MIN_DIMENSION: u32 = 128;
const BLUR_DOWNSAMPLE_MAX_SCALE: u32 = 8;

/// Specifies the type of blur operation, which affects how the CSS radius is interpreted.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BlurType {
  /// CSS `filter: blur()` - radius equals σ (standard deviation).
  Filter,
  /// CSS `box-shadow` / `text-shadow` blur - radius equals 2σ.
  Shadow,
}

impl BlurType {
  #[inline]
  pub fn to_sigma(self, css_radius: f32) -> f32 {
    match self {
      BlurType::Filter => css_radius,
      BlurType::Shadow => css_radius * 0.5,
    }
  }

  #[inline]
  pub fn extent_multiplier(self) -> f32 {
    match self {
      BlurType::Filter => 3.0,
      BlurType::Shadow => 1.5,
    }
  }
}

#[derive(Clone, Copy)]
struct BlurPassParams {
  width: u32,
  height: u32,
  radius: u32,
  stride: usize,
  mul_val: u32,
  shg: i32,
}

pub(crate) enum BlurFormat<'a> {
  Alpha {
    data: &'a mut [u8],
    width: u32,
    height: u32,
  },
}

impl<'a> BlurFormat<'a> {
  pub fn width(&self) -> u32 {
    match self {
      Self::Alpha { width, .. } => *width,
    }
  }

  pub fn height(&self) -> u32 {
    match self {
      Self::Alpha { height, .. } => *height,
    }
  }
}

fn blur_pass_params(
  width: u32,
  height: u32,
  radius: f32,
  blur_type: BlurType,
  stride: usize,
) -> Option<BlurPassParams> {
  let sigma = blur_type.to_sigma(radius);
  if sigma <= 0.5 || width == 0 || height == 0 {
    return None;
  }

  let box_radius = (((4.0 * sigma * sigma + 1.0).sqrt() - 1.0) * 0.5)
    .round()
    .max(1.0) as u32;
  let div = 2 * box_radius + 1;
  let (mul_val, shg) = compute_mul_shg(div);

  Some(BlurPassParams {
    width,
    height,
    radius: box_radius,
    stride,
    mul_val,
    shg,
  })
}

/// Applies a Gaussian approximation using 3-pass Box Blur.
pub(crate) fn apply_blur(
  format: BlurFormat<'_>,
  radius: f32,
  blur_type: BlurType,
  pool: &mut BufferPool,
) -> Result<()> {
  let width = format.width();
  let height = format.height();
  let Some(pass_params) = blur_pass_params(width, height, radius, blur_type, width as usize) else {
    return Ok(());
  };

  let mut col_sums = pool.acquire_u32(pass_params.stride);

  match format {
    BlurFormat::Alpha { data, .. } => {
      let mut temp_image = pool.acquire_dirty((width * height) as usize);
      let temp_data = &mut *temp_image;

      for _ in 0..3 {
        box_blur_h::<1>(data, temp_data, pass_params);
        box_blur_v(temp_data, data, pass_params, &mut col_sums);
      }

      pool.release(temp_image);
    }
  }

  pool.release_u32(col_sums);

  Ok(())
}

pub(crate) fn apply_blur_rgba_bytes(
  data: &mut [u8],
  width: u32,
  height: u32,
  radius: f32,
  blur_type: BlurType,
  pool: &mut BufferPool,
) -> Result<()> {
  apply_blur_rgba_bytes_internal(data, width, height, radius, blur_type, pool, true)
}

fn apply_blur_rgba_bytes_internal(
  data: &mut [u8],
  width: u32,
  height: u32,
  radius: f32,
  blur_type: BlurType,
  pool: &mut BufferPool,
  allow_downsample: bool,
) -> Result<()> {
  if width == 0 || height == 0 {
    return Ok(());
  }

  let expected = (width as usize)
    .saturating_mul(height as usize)
    .saturating_mul(4);
  if data.len() != expected {
    return Err(Error::InvalidRgbaBufferLength {
      actual: data.len(),
      expected,
    });
  }

  if allow_downsample {
    let scale = blur_downsample_scale(width, height, radius, blur_type);
    if scale > 1 {
      return apply_blur_rgba_downsampled(data, width, height, radius, blur_type, pool, scale);
    }
  }

  let Some(pass_params) = blur_pass_params(width, height, radius, blur_type, width as usize * 4)
  else {
    return Ok(());
  };
  let mut col_sums = pool.acquire_u32(pass_params.stride);

  let mut temp = pool.acquire_dirty(expected);
  for _ in 0..3 {
    box_blur_h::<4>(data, &mut temp, pass_params);
    box_blur_v(&temp, data, pass_params, &mut col_sums);
  }
  pool.release(temp);
  pool.release_u32(col_sums);

  Ok(())
}

fn blur_downsample_scale(width: u32, height: u32, radius: f32, blur_type: BlurType) -> u32 {
  let sigma = blur_type.to_sigma(radius);
  if sigma <= BLUR_DOWNSAMPLE_TARGET_SIGMA {
    return 1;
  }

  let min_dim = width.min(height);
  if min_dim < BLUR_DOWNSAMPLE_MIN_DIMENSION {
    return 1;
  }

  let mut scale = 1u32;
  while scale < BLUR_DOWNSAMPLE_MAX_SCALE {
    let next_scale = scale * 2;
    if sigma / (next_scale as f32) < BLUR_DOWNSAMPLE_TARGET_SIGMA {
      break;
    }
    if min_dim / next_scale < BLUR_DOWNSAMPLE_MIN_DIMENSION {
      break;
    }
    scale = next_scale;
  }

  scale
}

fn apply_blur_rgba_downsampled(
  data: &mut [u8],
  width: u32,
  height: u32,
  radius: f32,
  blur_type: BlurType,
  pool: &mut BufferPool,
  scale: u32,
) -> Result<()> {
  let ds_width = width.div_ceil(scale);
  let ds_height = height.div_ceil(scale);
  let ds_len = (ds_width as usize)
    .saturating_mul(ds_height as usize)
    .saturating_mul(4);

  let mut downsampled = pool.acquire_dirty(ds_len);
  downsample_rgba_box(
    data,
    width,
    height,
    &mut downsampled,
    ds_width,
    ds_height,
    scale,
  );

  let scaled_radius = radius / scale as f32;
  apply_blur_rgba_bytes_internal(
    &mut downsampled,
    ds_width,
    ds_height,
    scaled_radius,
    blur_type,
    pool,
    false,
  )?;

  upsample_rgba_bilinear(
    &downsampled,
    ds_width,
    ds_height,
    data,
    width,
    height,
    scale,
  );
  pool.release(downsampled);
  Ok(())
}

fn downsample_rgba_box(
  src: &[u8],
  src_width: u32,
  src_height: u32,
  dst: &mut [u8],
  dst_width: u32,
  dst_height: u32,
  scale: u32,
) {
  for dy in 0..dst_height {
    let src_y0 = dy * scale;
    let src_y1 = (src_y0 + scale).min(src_height);
    for dx in 0..dst_width {
      let src_x0 = dx * scale;
      let src_x1 = (src_x0 + scale).min(src_width);
      let mut sum = [0u32; 4];
      let mut count = 0u32;

      for sy in src_y0..src_y1 {
        let row_offset = sy as usize * src_width as usize * 4;
        for sx in src_x0..src_x1 {
          let index = row_offset + sx as usize * 4;
          sum[0] += src[index] as u32;
          sum[1] += src[index + 1] as u32;
          sum[2] += src[index + 2] as u32;
          sum[3] += src[index + 3] as u32;
          count += 1;
        }
      }

      let dst_index = (dy as usize * dst_width as usize + dx as usize) * 4;
      if count == 0 {
        dst[dst_index] = 0;
        dst[dst_index + 1] = 0;
        dst[dst_index + 2] = 0;
        dst[dst_index + 3] = 0;
        continue;
      }

      dst[dst_index] = (sum[0] / count) as u8;
      dst[dst_index + 1] = (sum[1] / count) as u8;
      dst[dst_index + 2] = (sum[2] / count) as u8;
      dst[dst_index + 3] = (sum[3] / count) as u8;
    }
  }
}

fn upsample_rgba_bilinear(
  src: &[u8],
  src_width: u32,
  src_height: u32,
  dst: &mut [u8],
  dst_width: u32,
  dst_height: u32,
  scale: u32,
) {
  if src_width == 0 || src_height == 0 {
    dst.fill(0);
    return;
  }

  let max_x = src_width.saturating_sub(1) as f32;
  let max_y = src_height.saturating_sub(1) as f32;
  let scale_f = scale as f32;

  for y in 0..dst_height {
    let src_y = ((y as f32 + 0.5) / scale_f - 0.5).clamp(0.0, max_y);
    let y0 = src_y.floor() as u32;
    let y1 = (y0 + 1).min(src_height - 1);
    let wy = src_y - y0 as f32;
    for x in 0..dst_width {
      let src_x = ((x as f32 + 0.5) / scale_f - 0.5).clamp(0.0, max_x);
      let x0 = src_x.floor() as u32;
      let x1 = (x0 + 1).min(src_width - 1);
      let wx = src_x - x0 as f32;

      let top_left = ((y0 as usize * src_width as usize) + x0 as usize) * 4;
      let top_right = ((y0 as usize * src_width as usize) + x1 as usize) * 4;
      let bottom_left = ((y1 as usize * src_width as usize) + x0 as usize) * 4;
      let bottom_right = ((y1 as usize * src_width as usize) + x1 as usize) * 4;
      let dst_index = ((y as usize * dst_width as usize) + x as usize) * 4;

      for channel in 0..4 {
        let top =
          src[top_left + channel] as f32 * (1.0 - wx) + src[top_right + channel] as f32 * wx;
        let bottom =
          src[bottom_left + channel] as f32 * (1.0 - wx) + src[bottom_right + channel] as f32 * wx;
        dst[dst_index + channel] = (top * (1.0 - wy) + bottom * wy).round().clamp(0.0, 255.0) as u8;
      }
    }
  }
}

macro_rules! update_h_pixel {
  ($src:expr, $dst:expr, $sum:expr, $out:expr, $entering:expr, $leaving:expr, $mul:expr, $shift:expr) => {
    if $sum[STRIDE - 1] == 0 && $src[$entering + STRIDE - 1] == 0 {
      for c in 0..STRIDE {
        $dst[$out + c] = 0;
        let entering = $src[$entering + c] as u32;
        let leaving = $src[$leaving + c] as u32;
        $sum[c] = $sum[c].saturating_add(entering).saturating_sub(leaving);
      }
    } else {
      for c in 0..STRIDE {
        $dst[$out + c] = (($sum[c] * $mul) >> $shift) as u8;
        let entering = $src[$entering + c] as u32;
        let leaving = $src[$leaving + c] as u32;
        $sum[c] = $sum[c].saturating_add(entering).saturating_sub(leaving);
      }
    }
  };
}

/// Horizontal Box Blur Pass
// Kept as a range loop for forced unrolling and to avoid iterator overhead
#[allow(clippy::needless_range_loop)]
fn box_blur_h<const STRIDE: usize>(src: &[u8], dst: &mut [u8], params: BlurPassParams) {
  let radius = params.radius as usize;
  let width = params.width as usize;
  let multiplier = params.mul_val;
  let shift = params.shg;
  let stride = params.stride;

  assert!(src.len() >= params.height as usize * stride);
  assert!(dst.len() >= params.height as usize * stride);

  for y in 0..params.height as usize {
    let line_offset = y * stride;
    let mut sum = [0u32; STRIDE];

    let first_px = line_offset;
    for c in 0..STRIDE {
      sum[c] = src[first_px + c] as u32 * (radius as u32 + 1);
    }

    for dx in 1..=radius {
      let px = dx.min(width - 1);
      let src_offset = line_offset + px * STRIDE;
      for c in 0..STRIDE {
        sum[c] += src[src_offset + c] as u32;
      }
    }

    let left_end = (radius + 1).min(width);
    for x in 0..left_end {
      let out_offset = line_offset + x * STRIDE;
      let entering_x = (x + radius + 1).min(width - 1);
      let entering_offset = line_offset + entering_x * STRIDE;
      update_h_pixel!(
        src,
        dst,
        sum,
        out_offset,
        entering_offset,
        first_px,
        multiplier,
        shift
      );
    }

    let middle_end = width.saturating_sub(radius + 1).max(left_end);
    for x in left_end..middle_end {
      let out_offset = line_offset + x * STRIDE;
      let leaving_offset = line_offset + (x - radius) * STRIDE;
      let entering_offset = line_offset + (x + radius + 1) * STRIDE;
      update_h_pixel!(
        src,
        dst,
        sum,
        out_offset,
        entering_offset,
        leaving_offset,
        multiplier,
        shift
      );
    }

    let last_px = line_offset + (width - 1) * STRIDE;
    for x in middle_end..width {
      let out_offset = line_offset + x * STRIDE;
      let leaving_offset = line_offset + (x - radius) * STRIDE;
      update_h_pixel!(
        src,
        dst,
        sum,
        out_offset,
        last_px,
        leaving_offset,
        multiplier,
        shift
      );
    }
  }
}

macro_rules! update_v_pixel {
  ($src:expr, $dst:expr, $sums:expr, $x:expr, $out:expr, $entering:expr, $leaving:expr, $mul:expr, $shift:expr) => {
    let sum = $sums[$x];
    let entering = $src[$entering + $x] as u32;
    let leaving = $src[$leaving + $x] as u32;
    if sum == 0 && entering == 0 {
      $dst[$out + $x] = 0;
      $sums[$x] = sum.saturating_add(entering).saturating_sub(leaving);
    } else {
      $dst[$out + $x] = ((sum * $mul) >> $shift) as u8;
      $sums[$x] = sum.saturating_add(entering).saturating_sub(leaving);
    }
  };
}

/// Vertical Box Blur Pass
// Kept as a range loop for forced unrolling and to avoid iterator overhead in WASM
#[allow(clippy::needless_range_loop)]
fn box_blur_v(src: &[u8], dst: &mut [u8], params: BlurPassParams, sums: &mut [u32]) {
  let radius = params.radius as usize;
  let height = params.height as usize;
  let multiplier = params.mul_val;
  let shift = params.shg;
  let stride = params.stride;

  assert!(src.len() >= params.height as usize * stride);
  assert!(dst.len() >= params.height as usize * stride);

  // Initialize sums with the first row repeated
  for x in 0..stride {
    sums[x] = src[x] as u32 * (radius as u32 + 1);
  }

  // Add trailing edge
  for dy in 1..=radius {
    let py = dy.min(height - 1);
    let row_offset = py * stride;
    for x in 0..stride {
      sums[x] += src[row_offset + x] as u32;
    }
  }

  let left_end = (radius + 1).min(height);
  for y in 0..left_end {
    let out_offset = y * stride;
    let entering_y = (y + radius + 1).min(height - 1);
    let entering_row = entering_y * stride;

    for x in 0..stride {
      update_v_pixel!(
        src,
        dst,
        sums,
        x,
        out_offset,
        entering_row,
        0,
        multiplier,
        shift
      );
    }
  }

  let middle_end = height.saturating_sub(radius + 1).max(left_end);
  for y in left_end..middle_end {
    let out_offset = y * stride;
    let leaving_row = (y - radius) * stride;
    let entering_row = (y + radius + 1) * stride;

    for x in 0..stride {
      update_v_pixel!(
        src,
        dst,
        sums,
        x,
        out_offset,
        entering_row,
        leaving_row,
        multiplier,
        shift
      );
    }
  }

  let last_row = (height - 1) * stride;
  for y in middle_end..height {
    let out_offset = y * stride;
    let leaving_row = (y - radius) * stride;

    for x in 0..stride {
      update_v_pixel!(
        src,
        dst,
        sums,
        x,
        out_offset,
        last_row,
        leaving_row,
        multiplier,
        shift
      );
    }
  }
}

#[inline(always)]
fn compute_mul_shg(d: u32) -> (u32, i32) {
  let shg = 23;
  let mul = ((1u64 << shg) as f64 / d as f64).round() as u32;
  (mul, shg)
}

#[cfg(test)]
mod tests {
  use super::{BlurType, apply_blur_rgba_bytes, blur_downsample_scale};
  use crate::{Error, rendering::BufferPool};

  #[test]
  fn apply_blur_rgba_bytes_returns_error_for_invalid_buffer_length() {
    let mut data = vec![0u8; 3];
    let mut pool = BufferPool::default();

    assert!(matches!(
      apply_blur_rgba_bytes(&mut data, 1, 1, 4.0, BlurType::Filter, &mut pool),
      Err(Error::InvalidRgbaBufferLength {
        actual: 3,
        expected: 4
      })
    ));
  }

  #[test]
  fn blur_downsample_scale_uses_sigma_and_dimensions() {
    assert_eq!(blur_downsample_scale(80, 80, 24.0, BlurType::Filter), 1);
    assert_eq!(blur_downsample_scale(256, 256, 6.0, BlurType::Filter), 1);
    assert_eq!(blur_downsample_scale(256, 256, 16.0, BlurType::Filter), 2);
    assert_eq!(blur_downsample_scale(1024, 1024, 64.0, BlurType::Filter), 8);
  }
}