rayimage coverage - 53.38%

R/render_vibrance.R 183 105 0 105 0.0 0.00%
R/add_padding.R 187 105 0 105 0.0 0.00%
R/render_convolution_fft.R 184 77 0 77 0.0 0.00%
R/rotate_image_array.R 105 77 0 77 0.0 0.00%
R/render_convolution.R 163 65 0 65 0.0 0.00%
R/render_bokeh.R 150 60 0 60 0.0 0.00%
R/plot_image_grid.R 124 58 0 58 0.0 0.00%
R/make_vignette_overlay.R 67 38 0 38 0.0 0.00%
R/preview_focus.R 51 27 0 27 0.0 0.00%
R/render_bw.R 61 26 0 26 0.0 0.00%
R/render_color_correction.R 93 25 0 25 0.0 0.00%
R/render_vignette.R 75 23 0 23 0.0 0.00%
R/generate_2d_gaussian.R 54 22 0 22 0.0 0.00%
R/render_reorient.R 65 20 0 20 0.0 0.00%
R/render_to_display.R 43 19 0 19 0.0 0.00%
R/generate_2d_disk.R 56 19 0 19 0.0 0.00%
R/generate_2d_exponential.R 43 16 0 16 0.0 0.00%
R/flipfunctions.R 34 6 0 6 0.0 0.00%
R/calc_bokeh_size.R 17 4 0 4 0.0 0.00%
src/pointspread.cpp 778 564 25 539 630.9 4.43%
R/cli_helpers.R 149 69 10 59 10.7 14.49%
src/covert_to_nr.cpp 57 21 7 14 20086.4 33.33%
R/plot_image.R 89 37 14 23 13.6 37.84%
R/linear_png_device.R 34 12 5 7 28.1 41.67%
R/render_tonemap.R 135 64 29 35 0.9 45.31%
R/convert_to_native_raster.R 48 33 15 18 28.2 45.45%
R/render_distance.R 29 8 4 4 3.5 50.00%
R/render_crop.R 172 78 42 36 0.7 53.85%
R/render_title.R 423 251 136 115 13.5 54.18%
R/render_resized.R 142 72 42 30 1.7 58.33%
src/dng_io.cpp 1170 745 443 302 21.4 59.46%
R/plot_asp_native_raster.R 112 73 45 28 22.2 61.64%
R/ray_read_image.R 371 219 142 77 128.8 64.84%
R/exr_metadata.R 203 100 65 35 2.5 65.00%
R/read_image_stb.R 51 24 16 8 4.7 66.67%
R/handle_image_output.R 28 9 6 3 100.4 66.67%
R/get_file_type.R 68 46 31 15 90.3 67.39%
R/render_white_balance.R 118 41 28 13 1.4 68.29%
R/render_stack.R 158 90 65 25 2.2 72.22%
R/convert_color.R 80 31 23 8 19.0 74.19%
src/load_image_stb.cpp 82 40 31 9 1532.7 77.50%
R/ray_write_image.R 176 92 73 19 23.0 79.35%
R/render_gamma_linear.R 219 102 83 19 6.9 81.37%
R/render_image_overlay.R 434 172 143 29 15.3 83.14%
R/print.R 396 254 221 33 324.6 87.01%
R/render_environment_white_balance.R 171 70 61 9 3.0 87.14%
R/render_alpha_outline.R 419 211 184 27 16.0 87.20%
R/colorspace_helpers.R 150 62 56 6 177.8 90.32%
R/rayimg.R 197 99 90 9 897.8 90.91%
R/render_exposure.R 159 89 81 8 7.1 91.01%
R/render_padding.R 135 72 66 6 22.2 91.67%
R/render_convert_colorspace.R 131 40 37 3 8.1 92.50%
R/prepare_native_raster.R 43 27 26 1 52.1 96.30%
R/render_clamp.R 74 34 33 1 164.9 97.06%
R/render_text_image.R 304 161 157 4 16.2 97.52%
R/render_tagline.R 123 60 59 1 9.1 98.33%
src/bool_distance.cpp 93 54 54 0 67.9 100.00%
R/interpolate_array.R 74 40 40 0 5.7 100.00%
R/colorspace_descriptors.R 162 19 19 0 2.0 100.00%
R/get_string_dimensions.R 37 7 7 0 8.0 100.00%
Total 9749 5084 2714 2370 217.4 53.38%
1
#'@title Add Overlay
2
#'
3
#'@description Takes an RGB array/filename and composites an image overlay over
4
#'the full image. For pixel-positioned sprite, label, glyph, or billboard
5
#'overlays, use [render_sprite_overlay()].
6
#'
7
#'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
8
#'@param image_overlay Default `NULL`. 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
9
#'This image will be resized to the dimensions of `image` if it does not match
10
#'exactly, unless `rescale_original = TRUE`.
11
#'@param rescale_original Default `FALSE`. If `TRUE`, function will resize the original image to match
12
#'the overlay.
13
#'@param convert_overlay_colorspace Default `TRUE`. Whether to convert the overlay's colorspace
14
#'to match the underlying image.
15
#'@param alpha Default `NA`, using overlay's alpha channel. Otherwise, this sets the alpha transparency
16
#'by multiplying the existing alpha channel by this value (between 0 and 1).
17
#'@param filename Default `NULL`. File to save the image to. If `NULL` and `preview = FALSE`,
18
#'returns an RGB array.
19
#'@param preview Default `FALSE`. If `TRUE`, it will display the image in addition
20
#'to returning it.
21
#'@return A `rayimg` RGBA array.
22
#'@import grDevices
23
#'@export
24
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
25
#'#Plot the dragon
26
#'plot_image(dragon)
27
#'#Add an overlay of a red semi-transparent circle:
28
#'circlemat = generate_2d_disk(min(dim(dragon)[1:2]))
29
#'circlemat = circlemat/max(circlemat)
30
#'
31
#'#Create RGBA image, with a transparency of 0.5
32
#'rgba_array = array(1, dim=c(nrow(circlemat),ncol(circlemat),4))
33
#'rgba_array[,,1] = circlemat
34
#'rgba_array[,,2] = 0
35
#'rgba_array[,,3] = 0
36
#'dragon_clipped = dragon
37
#'dragon_clipped[dragon_clipped > 1] = 1
38
#'render_image_overlay(dragon_clipped, image_overlay = rgba_array,
39
#'                  alpha=0.5, preview = TRUE)
40
#'
41
#' 	# Read photo, convert to ACEScg with CAT (scene)
42
#' 	photo = ray_read_image(sunset_image, normalize = FALSE)
43
#' 	photo_aces = render_convert_colorspace(
44
#' 		photo,
45
#' 		to_mats = CS_ACESCG,
46
#' 		adapt_white = TRUE
47
#' 	)
48
#' 	tmp_txt = tempfile(fileext = ".png")
49
#' 	render_text_image(
50
#' 		"Sunset",
51
#' 		size = 60,
52
#' 		filename = tmp_txt,
53
#' 		color = "#c300ff",
54
#' 		background_alpha = 0
55
#' 	)
56
#' 	# Read logo (display-referred), convert primaries only (no CAT)
57
#' 	logo = ray_read_image(tmp_txt, normalize = FALSE) # sRGB/D65
58
#' 	logo_aces = render_convert_colorspace(
59
#' 		logo,
60
#' 		to_mats = CS_ACESCG,
61
#' 		adapt_white = FALSE
62
#' 	)
63
#'
64
#' 	# Composite in ACEScg, then display (plot_image converts to sRGB/D65 + OETF)
65
#' 	# Here, we also turn overlay conversion in [render_image_overlay()] off,
66
#'  # to show what happens when you don't account for the colorspace difference.
67
#'  # By default [render_image_overlay()] will do this for you.
68
#' 	comp1 = render_image_overlay(
69
#' 		photo_aces,
70
#' 		logo_aces,
71
#' 		convert_overlay_colorspace = FALSE
72
#' 	) |>
73
#'    render_title(title_text = "#c300ff: Match",
74
#'                 title_bar_color = "white", title_color = "#c300ff", title_bar_alpha=1)
75
#' 	comp2 = render_image_overlay(
76
#' 		photo_aces,
77
#' 		logo,
78
#' 		convert_overlay_colorspace = FALSE
79
#' 	) |>
80
#' 	 render_title(title_text = "#c300ff: Incorrect",
81
#'                title_bar_color = "white", title_color = "#c300ff", title_bar_alpha=1)
82
#'
83
#' 	plot_image_grid(list(comp1, comp2), dim = c(1, 2))
84
render_image_overlay = function(
85
  image,
86
  image_overlay = NULL,
87
  rescale_original = FALSE,
88
  convert_overlay_colorspace = TRUE,
89
  alpha = NA,
90
  filename = NULL,
91
  preview = FALSE
92
) {
933x
  render_image_overlay_impl(
943x
    image = image,
953x
    image_overlay = image_overlay,
963x
    rescale_original = rescale_original,
973x
    convert_overlay_colorspace = convert_overlay_colorspace,
983x
    alpha = alpha,
993x
    filename = filename,
1003x
    preview = preview
101
  )
102
}
103
104
#'@title Add Sprite Overlay
105
#'
106
#'@description Places an image overlay at a pixel location without resizing it to
107
#'the full destination image. This is intended for sprite-like or billboard-like
108
#'overlays such as labels, icons, glyphs, and screen-space annotations.
109
#'
110
#'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
111
#'@param image_overlay Default `NULL`. 3-layer RGB/4-layer RGBA array, `rayimg`
112
#'class, or filename of the sprite overlay.
113
#'@param convert_overlay_colorspace Default `TRUE`. Whether to convert the overlay's colorspace
114
#'to match the underlying image.
115
#'@param alpha Default `NA`, using overlay's alpha channel. Otherwise, this sets the alpha transparency
116
#'by multiplying the existing alpha channel by this value (between 0 and 1).
117
#'@param overlay_coords Default `c(1, 1)`. Pixel coordinate `c(x, y)` used to
118
#'position the overlay. `x` increases from left to right and `y` from top to
119
#'bottom, starting at 1.
120
#'@param overlay_dims Default `NULL`. Dimensions for the overlay in pixels. If
121
#'provided, the overlay is resized with `render_resized()` before compositing.
122
#'@param overlay_anchor Default `"nw"`. Which corner of the overlay is placed at
123
#'`overlay_coords` when no numeric justification is supplied. Options: `"nw"`,
124
#'`"ne"`, `"sw"`, `"se"`.
125
#'@param overlay_just Default `NULL`. Optional numeric `c(hjust, vjust)`
126
#'justification used to place the overlay relative to `overlay_coords`. If set,
127
#'the overlay's left/top pixel is computed as
128
#'`round(x - hjust * overlay_width)` and
129
#'`round(y - vjust * overlay_height)`.
130
#'@param hjust Default `NULL`. Optional horizontal justification. Overrides the
131
#'first value of `overlay_just`.
132
#'@param vjust Default `NULL`. Optional vertical justification. Overrides the
133
#'second value of `overlay_just`.
134
#'@param preserve_channels Default `TRUE`. If `TRUE`, RGB input images return
135
#'RGB output and RGBA input images return RGBA output.
136
#'@param filename Default `NULL`. File to save the image to. If `NULL` and
137
#'`preview = FALSE`, returns an image array.
138
#'@param preview Default `FALSE`. If `TRUE`, it will display the image in addition
139
#'to returning it.
140
#'
141
#'@return A `rayimg` array.
142
#'@export
143
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
144
#'dragon_clipped = dragon
145
#'dragon_clipped[dragon_clipped > 1] = 1
146
#'
147
#'# Render a transparent dragon emoji and center it on a pixel with hjust/vjust:
148
#'dragon_emoji = render_text_image(
149
#'  "\U0001F409",
150
#'  size = 80,
151
#'  background_alpha = 0,
152
#'  use_ragg = TRUE,
153
#'  trim = TRUE,
154
#'  trim_padding = 8
155
#')
156
#'render_sprite_overlay(
157
#'  dragon_clipped,
158
#'  image_overlay = dragon_emoji,
159
#'  overlay_coords = c(ncol(dragon_clipped) / 2, nrow(dragon_clipped) / 2),
160
#'  hjust = 0.5,
161
#'  vjust = 0.5,
162
#'  preview = TRUE
163
#')
164
#'
165
#'# The same justification can be supplied as overlay_just = c(hjust, vjust):
166
#'render_sprite_overlay(
167
#'  dragon_clipped,
168
#'  image_overlay = dragon_emoji,
169
#'  overlay_coords = c(ncol(dragon_clipped), nrow(dragon_clipped)),
170
#'  overlay_just = c(1, 1),
171
#'  preview = TRUE
172
#')
173
render_sprite_overlay = function(
174
  image,
175
  image_overlay = NULL,
176
  convert_overlay_colorspace = TRUE,
177
  alpha = NA,
178
  overlay_coords = c(1, 1),
179
  overlay_dims = NULL,
180
  overlay_anchor = "nw",
181
  overlay_just = NULL,
182
  hjust = NULL,
183
  vjust = NULL,
184
  preserve_channels = TRUE,
185
  filename = NULL,
186
  preview = FALSE
187
) {
18819x
  render_image_overlay_impl(
18919x
    image = image,
19019x
    image_overlay = image_overlay,
19119x
    rescale_original = FALSE,
19219x
    convert_overlay_colorspace = convert_overlay_colorspace,
19319x
    alpha = alpha,
19419x
    overlay_coords = overlay_coords,
19519x
    overlay_dims = overlay_dims,
19619x
    overlay_anchor = overlay_anchor,
19719x
    overlay_just = overlay_just,
19819x
    hjust = hjust,
19919x
    vjust = vjust,
20019x
    preserve_channels = preserve_channels,
20119x
    filename = filename,
20219x
    preview = preview
203
  )
204
}
205
206
#' @keywords internal
207
render_image_overlay_impl = function(
208
  image,
209
  image_overlay = NULL,
210
  rescale_original = FALSE,
211
  convert_overlay_colorspace = TRUE,
212
  alpha = NA,
213
  overlay_coords = NULL,
214
  overlay_dims = NULL,
215
  overlay_anchor = "nw",
216
  overlay_just = NULL,
217
  hjust = NULL,
218
  vjust = NULL,
219
  preserve_channels = FALSE,
220
  filename = NULL,
221
  preview = FALSE
222
) {
22322x
  if (is.null(image_overlay)) {
224!
    stop("Need to pass in image to image_overlay argument.")
225
  }
226
22722x
  original_channels = {
22822x
    image_dim = dim(image)
22922x
    if (is.null(image_dim)) {
23022x
      NA_integer_
23121x
    } else if (length(image_dim) == 2) {
232!
      1L
233
    } else {
23421x
      image_dim[3]
235
    }
236
  }
237
238
  # Load as rayimg (RGBA + attrs)
23922x
  image = ray_read_image(
24022x
    image,
24122x
    convert_to_array = TRUE,
24222x
    reset_camera_settings = TRUE
243
  )
24422x
  image_colorspace = attr(image, "colorspace")
24522x
  image_whitepoint = attr(image, "white_current")
24622x
  image_overlay = ray_read_image(
24722x
    image_overlay,
24822x
    convert_to_array = TRUE,
24922x
    reset_camera_settings = TRUE
250
  )
25122x
  if (convert_overlay_colorspace) {
2529x
    image_overlay = render_convert_colorspace(
2539x
      image_overlay,
2549x
      to_mats = image_colorspace
255
    )
256
  }
257
25822x
  img_type = attr(image, "filetype")
25922x
  over_type = attr(image_overlay, "filetype")
260
26122x
  if (!is.null(overlay_dims)) {
262!
    stopifnot(length(overlay_dims) >= 2)
263!
    overlay_dims = as.integer(round(overlay_dims[1:2]))
264!
    stopifnot(all(overlay_dims > 0))
265!
    image_overlay = render_resized(image_overlay, dims = overlay_dims)
266
  }
26722x
  placement_mode = !is.null(overlay_coords) ||
26822x
    !is.null(overlay_dims) ||
26922x
    !is.null(overlay_just) ||
27022x
    !is.null(hjust) ||
27122x
    !is.null(vjust)
27222x
  if (rescale_original) {
273!
    target_dims = if (is.null(overlay_dims)) {
274!
      dim(image_overlay)[1:2]
275
    } else {
276!
      overlay_dims
277
    }
278!
    if (!all(dim(image)[1:2] == target_dims)) {
279!
      image = render_resized(image, dims = target_dims)
280
    }
28122x
  } else if (!placement_mode) {
2823x
    if (!all(dim(image)[1:2] == dim(image_overlay)[1:2])) {
2831x
      image_overlay = render_resized(image_overlay, dims = dim(image))
284
    }
285
  }
28622x
  is_matrix_image = length(dim(image)) == 2
28722x
  is_matrix_image_overlay = length(dim(image_overlay)) == 2
28822x
  process_image = function(image_input) {
28944x
    is_matrix_image = length(dim(image_input)) == 2
29044x
    if (is_matrix_image) {
291!
      image_tmp = array(image_input, dim = c(dim(image_input), 4))
292!
      image_tmp[,, 4] = 1
293
    } else {
29444x
      if (dim(image_input)[3] == 2) {
295
        #Greyscale with alpha
296!
        image_tmp = array(image_input[,, 1], dim = c(dim(image_input)[1:2], 4))
297!
        image_tmp[,, 4] = image_input[,, 2]
29844x
      } else if (dim(image_input)[3] == 3) {
299
        #RGB
300!
        image_tmp = array(1, dim = c(dim(image_input)[1:2], 4))
301!
        image_tmp[,, 4] = 1
302
      } else {
30344x
        image_tmp = image_input
304
      }
305
    }
30644x
    return(image_tmp)
307
  }
30822x
  image = process_image(image)
30922x
  image_overlay = process_image(image_overlay)
310
31122x
  if (!is.na(alpha)) {
3128x
    stopifnot(alpha >= 0, alpha <= 1)
3138x
    image_overlay[,, 4] = image_overlay[,, 4] * alpha
314
  }
315
31622x
  Cb = image[,, 1:3]
31722x
  Ab = image[,, 4]
318
319
  # Place overlay on a blank canvas at the requested location, cropping to bounds
32022x
  if (is.null(overlay_coords)) {
3213x
    overlay_coords = c(1, 1)
322
  }
32322x
  stopifnot(length(overlay_coords) >= 2)
32422x
  if (any(!is.finite(overlay_coords))) {
325!
    stop("`overlay_coords` must be finite.")
326
  }
32722x
  overlay_size = dim(image_overlay)[1:2]
32822x
  use_overlay_just = !is.null(overlay_just) ||
32922x
    !is.null(hjust) ||
33022x
    !is.null(vjust)
33122x
  if (use_overlay_just) {
3328x
    if (is.null(overlay_just)) {
3337x
      overlay_just = c(0, 0)
334
    }
3358x
    if (!is.numeric(overlay_just) || length(overlay_just) < 2) {
336!
      stop("`overlay_just` must be a numeric vector of length 2 or greater.")
337
    }
3388x
    overlay_just = overlay_just[1:2]
3398x
    if (!is.null(hjust)) {
3407x
      if (!is.numeric(hjust) || length(hjust) != 1 || !is.finite(hjust)) {
341!
        stop("`hjust` must be a finite numeric scalar.")
342
      }
3437x
      overlay_just[1] = hjust
344
    }
3458x
    if (!is.null(vjust)) {
3467x
      if (!is.numeric(vjust) || length(vjust) != 1 || !is.finite(vjust)) {
347!
        stop("`vjust` must be a finite numeric scalar.")
348
      }
3497x
      overlay_just[2] = vjust
350
    }
3518x
    if (any(!is.finite(overlay_just))) {
352!
      stop("`overlay_just` must be finite.")
353
    }
3548x
    start_col = as.integer(round(
3558x
      overlay_coords[1] - overlay_just[1] * overlay_size[2]
356
    ))
3578x
    start_row = as.integer(round(
3588x
      overlay_coords[2] - overlay_just[2] * overlay_size[1]
359
    ))
360
  } else {
36114x
    valid_anchors = c("nw", "ne", "sw", "se")
36214x
    overlay_anchor = tolower(overlay_anchor)
36314x
    if (!(overlay_anchor %in% valid_anchors)) {
364!
      stop(
365!
        "`overlay_anchor` must be one of: ",
366!
        paste(valid_anchors, collapse = ", ")
367
      )
368
    }
36914x
    overlay_coords = as.integer(round(overlay_coords[1:2]))
37014x
    start_row = overlay_coords[2]
37114x
    start_col = overlay_coords[1]
37214x
    if (overlay_anchor %in% c("sw", "se")) {
3736x
      start_row = overlay_coords[2] - overlay_size[1] + 1
374
    }
37514x
    if (overlay_anchor %in% c("ne", "se")) {
3766x
      start_col = overlay_coords[1] - overlay_size[2] + 1
377
    }
378
  }
37922x
  end_row = start_row + overlay_size[1] - 1
38022x
  end_col = start_col + overlay_size[2] - 1
38122x
  target_rows = seq(start_row, end_row)
38222x
  target_cols = seq(start_col, end_col)
38322x
  rows_in_bounds = target_rows >= 1 & target_rows <= dim(image)[1]
38422x
  cols_in_bounds = target_cols >= 1 & target_cols <= dim(image)[2]
38522x
  overlay_canvas = array(0, dim = dim(image))
38622x
  if (any(rows_in_bounds) && any(cols_in_bounds)) {
38722x
    dest_rows = target_rows[rows_in_bounds]
38822x
    dest_cols = target_cols[cols_in_bounds]
38922x
    src_rows = which(rows_in_bounds)
39022x
    src_cols = which(cols_in_bounds)
39122x
    overlay_canvas[dest_rows, dest_cols, ] = image_overlay[
39222x
      src_rows,
39322x
      src_cols,
394
      ,
39522x
      drop = FALSE
396
    ]
397
  }
39822x
  image_overlay = overlay_canvas
399
40022x
  Cf = image_overlay[,, 1:3]
40122x
  Af = image_overlay[,, 4]
402
40322x
  Af3 = array(Af, dim = c(dim(Af), 3))
40422x
  Ab3 = array(Ab, dim = c(dim(Ab), 3))
405
40622x
  Ao = pmin(pmax(Af + Ab * (1 - Af), 0), 1)
40722x
  num = Cf * Af3 + Cb * Ab3 * array(1 - Af, dim = c(dim(Af), 3))
408
40922x
  eps = 1e-8
41022x
  Co_lin = num / array(pmax(Ao, eps), dim = c(dim(Ao), 3))
411
412
  # ensure fully transparent pixels are black
41322x
  if (any(Ao <= eps)) {
414!
    m = Ao <= eps
415!
    Co_lin[,, 1][m] = 0
416!
    Co_lin[,, 2][m] = 0
417!
    Co_lin[,, 3][m] = 0
418
  }
419
42022x
  composite_image = array(1, dim = dim(image))
42122x
  composite_image[,, 4] = Ao
42222x
  composite_image[,, 1:3] = Co_lin
423
42422x
  composite_image = ray_read_image(
42522x
    composite_image,
42622x
    assume_colorspace = image_colorspace,
42722x
    assume_white = image_whitepoint,
42822x
    source_linear = TRUE
429
  )
43022x
  if (isTRUE(preserve_channels) && identical(original_channels, 3L)) {
43114x
    composite_image = composite_image[,, 1:3, drop = FALSE]
432
  }
43322x
  handle_image_output(composite_image, filename = filename, preview = preview)
434
}
1
#'@title Matrix/Array Interpolation
2
#'
3
#'@description Given a series of X and Y coordinates and an array/matrix, interpolates the Z coordinate
4
#'using bilinear interpolation.
5
#'
6
#'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
7
#'@param x X indices (or fractional index) to interpolate.
8
#'@param y Y indices (or fractional index) to interpolate.
9
#'
10
#'@return Either a vector of values (if image is a matrix) or a list of interpolated values
11
#'from each layer.
12
#'@export
13
#'
14
#'@examples
15
#'#if(interactive()){
16
#'#Interpolate a matrix
17
#'interpolate_array(volcano,c(10,10.1,11),c(30,30.5,33))
18
#'#Interpolate a 3-layer array (returns list for each channel)
19
#'interpolate_array(dragon,c(10,10.1,11),c(30,30.5,33))
20
#'#end}
21
interpolate_array = function(image, x, y) {
2214x
  image = ray_read_image(image) #Always output RGBA array
23
  #Check if file or image before below:
2414x
  is_matrix = length(dim(image)) == 2
2514x
  xy = matrix(c(x, y), nrow = length(x), ncol = 2)
26
2714x
  if (is_matrix) {
282x
    return(apply(xy, 1, (function(x) rayinterp2(image, x[1], x[2]))))
29
  }
30
  #Load and rotate images if image
3112x
  output = list()
3212x
  if (dim(image)[3] == 2) {
334x
    output$grey = apply(
344x
      xy,
354x
      1,
364x
      (function(x) rayinterp2(image[,, 1], x[1], x[2]))
37
    )
384x
    output$alpha = apply(
394x
      xy,
404x
      1,
414x
      (function(x) rayinterp2(image[,, 2], x[1], x[2]))
42
    )
438x
  } else if (dim(image)[3] == 3) {
444x
    output$red = apply(xy, 1, (function(x) rayinterp2(image[,, 1], x[1], x[2])))
454x
    output$green = apply(
464x
      xy,
474x
      1,
484x
      (function(x) rayinterp2(image[,, 2], x[1], x[2]))
49
    )
504x
    output$blue = apply(
514x
      xy,
524x
      1,
534x
      (function(x) rayinterp2(image[,, 3], x[1], x[2]))
54
    )
554x
  } else if (dim(image)[3] == 4) {
564x
    output$red = apply(xy, 1, (function(x) rayinterp2(image[,, 1], x[1], x[2])))
574x
    output$green = apply(
584x
      xy,
594x
      1,
604x
      (function(x) rayinterp2(image[,, 2], x[1], x[2]))
61
    )
624x
    output$blue = apply(
634x
      xy,
644x
      1,
654x
      (function(x) rayinterp2(image[,, 3], x[1], x[2]))
66
    )
674x
    output$alpha = apply(
684x
      xy,
694x
      1,
704x
      (function(x) rayinterp2(image[,, 4], x[1], x[2]))
71
    )
72
  }
7312x
  return(output)
74
}
1
#' Apply exposure compensation and ISO gain
2
#'
3
#' @param image              3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
4
#' @param exposure           Default `0`. Exposure compensation in stops; applied directly to RGB values.
5
#' @param iso                Default `NA`. ISO gain to apply directly to RGB values. `NA` applies no ISO gain
6
#'   and preserves the current informational ISO metadata.
7
#' @param auto               Default `FALSE`. If `TRUE`, automatically add the exposure needed to
8
#'   place a luminance percentile at 1.0 for LDR display/output. `exposure`
9
#'   is then treated as an additional compensation value.
10
#' @param percentile         Default `0.99`. Luminance percentile used when `auto = TRUE`.
11
#'   Must be greater than 0 and less than or equal to 1. Use `1` for max luminance.
12
#' @param verbose            Default `FALSE`. If `TRUE` and `auto = TRUE`, print the
13
#'   automatically computed exposure adjustment.
14
#' @param filename           Default `NA`. Output path.
15
#' @param preview            Default `FALSE`. If `TRUE`, display the image.
16
#' @param ...                Additional args passed to [plot_image()] (when `preview=TRUE`)
17
#'   or to [ray_write_image()] (when `filename` is given).
18
#'
19
#' @return A `rayimg` RGBA array.
20
#' @export
21
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
22
#' # LDR/sRGB (auto): decodes to linear, applies EV, records camera metadata
23
#'   render_exposure(dragon, exposure = +1, preview = TRUE)
24
#' # Force linear/HDR behavior
25
#'   render_exposure(dragon * 2, exposure = -1, preview = TRUE)
26
render_exposure = function(
27
  image,
28
  exposure = 0,
29
  iso = NA,
30
  auto = FALSE,
31
  percentile = 0.99,
32
  verbose = FALSE,
33
  filename = NA,
34
  preview = FALSE,
35
  ...
36
) {
3712x
  img = ray_read_image(image)
3812x
  exposure = rayimg_exposure_value(exposure)
3912x
  if (length(iso) != 1L) {
40!
    stop("render_exposure(): 'iso' must be a single positive number or NA.")
41
  }
4212x
  iso_supplied = !is.na(iso)
4312x
  if (iso_supplied) {
448x
    iso_to_apply = rayimg_iso_value(iso)
458x
    iso_metadata = iso_to_apply
46
  } else {
474x
    iso_to_apply = 100
484x
    iso_metadata = rayimg_iso_value(attr(img, "iso", exact = TRUE))
49
  }
5012x
  if (!is.logical(auto) || length(auto) != 1L || is.na(auto)) {
51!
    stop("render_exposure(): 'auto' must be TRUE or FALSE.")
52
  }
53
  if (
5412x
    !is.numeric(percentile) ||
5512x
      length(percentile) != 1L ||
5612x
      is.na(percentile) ||
5712x
      !is.finite(percentile) ||
5812x
      percentile <= 0 ||
5912x
      percentile > 1
60
  ) {
61!
    stop("render_exposure(): 'percentile' must be a number in (0, 1].")
62
  }
6312x
  if (!is.logical(verbose) || length(verbose) != 1L || is.na(verbose)) {
64!
    stop("render_exposure(): 'verbose' must be TRUE or FALSE.")
65
  }
66
6712x
  current_exposure = rayimg_exposure_value(attr(img, "exposure", exact = TRUE))
6812x
  auto_exposure = 0
6912x
  target_luminance = NA_real_
7012x
  if (auto) {
716x
    img_values = unclass(img)
726x
    d = dim(img_values)
736x
    if (length(d) == 2L) {
741x
      luminance_values = as.numeric(img_values)
75
    } else {
765x
      channels = d[3L]
775x
      color_channels = if (channels %in% c(2L, 4L)) {
78!
        seq_len(channels - 1L)
79
      } else {
805x
        seq_len(channels)
81
      }
825x
      if (length(color_channels) == 1L) {
83!
        luminance_values = as.numeric(img_values[,, color_channels])
84
      } else {
855x
        rgb_values = img_values[,, color_channels, drop = FALSE]
865x
        if (length(color_channels) >= 3L) {
875x
          rgb_values = rgb_values[,, seq_len(3L), drop = FALSE]
885x
          cs = attr(img, "colorspace", exact = TRUE)
895x
          luma_weights = if (
905x
            is.list(cs) &&
915x
              is.matrix(cs$rgb_to_xyz) &&
925x
              all(dim(cs$rgb_to_xyz) >= c(2L, 3L))
93
          ) {
945x
            as.numeric(cs$rgb_to_xyz[2L, seq_len(3L)])
95
          } else {
96!
            c(0.2126, 0.7152, 0.0722)
97
          }
985x
          luminance_values =
995x
            rgb_values[,, 1L] *
1005x
            luma_weights[1L] +
1015x
            rgb_values[,, 2L] * luma_weights[2L] +
1025x
            rgb_values[,, 3L] * luma_weights[3L]
103
        } else {
104!
          luminance_values = as.numeric(rgb_values)
105
        }
106
      }
107
    }
1086x
    luminance_values = luminance_values[is.finite(luminance_values)]
1096x
    if (length(luminance_values)) {
1106x
      target_luminance = as.numeric(stats::quantile(
1116x
        luminance_values,
1126x
        probs = percentile,
1136x
        names = FALSE
114
      ))
1156x
      current_scale = iso_to_apply / 100
1166x
      if (target_luminance > 0 && current_scale > 0) {
1176x
        auto_exposure = -log2(target_luminance * current_scale)
1186x
        exposure = exposure + auto_exposure
119
      }
120
    }
1216x
    if (verbose) {
1221x
      message(sprintf(
1231x
        "Auto exposure: %+.3f EV (luminance p%.3g: %.6g, ISO: %.6g)",
1241x
        auto_exposure,
1251x
        percentile,
1261x
        target_luminance,
1271x
        iso_to_apply
128
      ))
129
    }
130
  }
13112x
  scale = (2^exposure) * (iso_to_apply / 100)
13212x
  out_values = unclass(img)
13312x
  if (!isTRUE(all.equal(scale, 1))) {
13412x
    d = dim(out_values)
13512x
    if (length(d) == 2L) {
1361x
      out_values = out_values * scale
137
    } else {
13811x
      channels = d[3L]
13911x
      color_channels = if (channels %in% c(2L, 4L)) {
1401x
        seq_len(channels - 1L)
141
      } else {
14210x
        seq_len(channels)
143
      }
14411x
      out_values[,, color_channels] = out_values[,, color_channels] * scale
145
    }
146
  }
147
14812x
  out = rayimg(
14912x
    out_values,
15012x
    filetype = attr(img, "filetype", exact = TRUE),
15112x
    source_linear = attr(img, "source_linear", exact = TRUE),
15212x
    colorspace = attr(img, "colorspace", exact = TRUE),
15312x
    white_current = attr(img, "white_current", exact = TRUE),
15412x
    exposure = current_exposure + exposure,
15512x
    iso = iso_metadata
156
  )
15712x
  out = ray_read_image(out)
15812x
  handle_image_output(out, filename = filename, preview = preview)
159
}
1
#' @title Render Alpha Outline
2
#'
3
#' @description Creates a colored RGBA outline or halo from an image alpha
4
#' channel or a supplied mask. When `image` is supplied, the original image is
5
#' composited over the outline by default.
6
#'
7
#' @param image Default `NULL`. Image whose alpha channel will be used as the
8
#' mask. If `mask` is supplied, `image` is only used for metadata.
9
#' @param mask Default `NULL`. Optional logical or numeric matrix to use as the
10
#' outline mask instead of `image` alpha.
11
#' @param expand Default `0`. Number of pixels to expand the mask.
12
#' @param edge_softness Default `0.1`. Width of the softened halo edge
13
#' transition, in pixels.
14
#' @param blur Default `0`. Gaussian blur standard deviation applied to the
15
#' final outline alpha.
16
#' @param gap_fill Default `1`. Maximum alpha gap width, in pixels, to bridge
17
#' in the expanded outline alpha. This fills border-connected breaks and notches
18
#' caused by discrete distance quantization. Set to `0` to disable.
19
#' @param gap_fill_alpha_threshold Default `0.25`. Alpha threshold used to
20
#' classify border gaps. Gap filling only modifies pixels below this threshold
21
#' that are connected to the image exterior; enclosed interior holes surrounded
22
#' by pixels at or above this threshold are left unchanged.
23
#' @param color Default `"black"`. Outline color.
24
#' @param alpha Default `1`. Overall outline alpha multiplier.
25
#' @param pad Default `0`. Padding in pixels before computing the outline. If
26
#' `NULL`, padding is computed from `expand`, `edge_softness`, and `blur`.
27
#' @param composite Default `TRUE`. If `TRUE` and `image` is supplied, composite
28
#' the outline below the original image. Set to `FALSE` to return the outline
29
#' alone.
30
#' @param filename Default `NULL`. File to save the image to. If `NULL` and
31
#' `preview = FALSE`, returns the output image.
32
#' @param preview Default `FALSE`. If `TRUE`, display the outline image.
33
#'
34
#' @return A `rayimg` RGBA output image with a `padding` attribute.
35
#' @export
36
#' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
37
#'txt = render_text_image("\U0001F409",  size = 120, background_alpha = 0)
38
#'render_alpha_outline(txt, expand = 2, blur = 1, color = "purple") |>
39
#'  plot_image()
40
#'
41
#' #Make a rainbow outline
42
#'render_alpha_outline(txt, expand = 2, blur = 0.1, color = "darkgreen") |>
43
#'  render_alpha_outline(expand = 2, blur = 0.1, color = "yellow") |>
44
#'  render_alpha_outline(expand = 2, blur = 0.1, color = "orange") |>
45
#'  render_alpha_outline(expand = 2, blur = 0.1, color = "red") |>
46
#'  render_alpha_outline(expand = 2, blur = 0.1, color = "purple") |>
47
#'  render_alpha_outline(expand = 2, blur = 0.1, color = "blue") |>
48
#'  plot_image()
49
render_alpha_outline = function(
50
  image = NULL,
51
  mask = NULL,
52
  expand = 0,
53
  edge_softness = 0.1,
54
  blur = 0,
55
  gap_fill = 1,
56
  gap_fill_alpha_threshold = 0.25,
57
  color = "black",
58
  alpha = 1,
59
  pad = 0,
60
  composite = TRUE,
61
  filename = NULL,
62
  preview = FALSE
63
) {
649x
  image_supplied = !is.null(image)
659x
  if (!image_supplied && is.null(mask)) {
66!
    stop("Either `image` or `mask` must be provided.")
67
  }
689x
  if (!is.numeric(expand) || length(expand) != 1 || !is.finite(expand)) {
69!
    stop("`expand` must be a finite numeric scalar.")
70
  }
71
  if (
729x
    !is.numeric(edge_softness) ||
739x
      length(edge_softness) != 1 ||
749x
      !is.finite(edge_softness)
75
  ) {
76!
    stop("`edge_softness` must be a finite numeric scalar.")
77
  }
789x
  if (!is.numeric(blur) || length(blur) != 1 || !is.finite(blur)) {
79!
    stop("`blur` must be a finite numeric scalar.")
80
  }
819x
  if (!is.numeric(gap_fill) || length(gap_fill) != 1 || !is.finite(gap_fill)) {
82!
    stop("`gap_fill` must be a finite numeric scalar.")
83
  }
84
  if (
859x
    !is.numeric(gap_fill_alpha_threshold) ||
869x
      length(gap_fill_alpha_threshold) != 1 ||
879x
      !is.finite(gap_fill_alpha_threshold)
88
  ) {
89!
    stop("`gap_fill_alpha_threshold` must be a finite numeric scalar.")
90
  }
919x
  if (!is.numeric(alpha) || length(alpha) != 1 || !is.finite(alpha)) {
92!
    stop("`alpha` must be a finite numeric scalar.")
93
  }
949x
  if (!is.logical(composite) || length(composite) != 1 || is.na(composite)) {
95!
    stop("`composite` must be `TRUE` or `FALSE`.")
96
  }
97
989x
  expand = max(0, expand)
999x
  edge_softness = max(.Machine$double.eps, edge_softness)
1009x
  blur = max(0, blur)
1019x
  gap_fill = as.integer(round(max(0, gap_fill)))
1029x
  if (gap_fill_alpha_threshold < 0 || gap_fill_alpha_threshold > 1) {
103!
    stop("`gap_fill_alpha_threshold` must be in [0,1].")
104
  }
1059x
  alpha = min(max(alpha, 0), 1)
1069x
  if (is.null(pad)) {
107!
    pad = ceiling(expand + edge_softness + 3 * blur)
108
  }
1099x
  pad = normalize_render_padding(pad)
110
1119x
  if (!is.null(mask) && (is.null(dim(mask)) || length(dim(mask)) != 2)) {
112!
    stop("`mask` must be a matrix.")
113
  }
1149x
  if (!image_supplied) {
1157x
    image = array(0, dim = c(nrow(mask), ncol(mask), 4))
116
  }
1179x
  source_image = ray_read_image(image, convert_to_array = TRUE)
1189x
  padded_source = render_padding(
1199x
    source_image,
1209x
    pad = pad,
1219x
    color = "black",
1229x
    alpha = 0
123
  )
124
1259x
  if (is.null(mask)) {
1262x
    alpha_mask = unclass(padded_source[,, 4])
127
  } else {
1287x
    alpha_mask = render_padding(mask, pad = pad, color = "black")
1297x
    alpha_mask = unclass(alpha_mask)
130
  }
1319x
  alpha_mask[alpha_mask > 0] = 1
1329x
  alpha_mask[alpha_mask <= 0] = 0
133
1349x
  if (expand > 0) {
1357x
    booldistance = render_boolean_distance(alpha_mask)
1367x
    inner = expand - edge_softness
1377x
    outer = expand + edge_softness
1387x
    halo_alpha = matrix(
1397x
      0,
1407x
      nrow = nrow(alpha_mask),
1417x
      ncol = ncol(alpha_mask)
142
    )
1437x
    halo_alpha[booldistance <= inner] = 1
1447x
    band = booldistance > inner & booldistance < outer
1457x
    halo_alpha[band] = (outer - booldistance[band]) / (outer - inner)
146
  } else {
1472x
    halo_alpha = alpha_mask
148
  }
1499x
  if (gap_fill > 0 && expand > 0) {
1506x
    halo_alpha = fill_alpha_gaps(
1516x
      halo_alpha,
1526x
      max_gap = gap_fill,
1536x
      alpha_threshold = gap_fill_alpha_threshold
154
    )
155
  }
156
1579x
  halo_color = convert_color(color, single = TRUE)
1589x
  halo_image = array(0, dim = c(dim(alpha_mask), 4))
1599x
  halo_image[,, 1] = halo_color[1]
1609x
  halo_image[,, 2] = halo_color[2]
1619x
  halo_image[,, 3] = halo_color[3]
1629x
  halo_image[,, 4] = halo_alpha * alpha
163
1649x
  halo_image = rayimg(
1659x
    halo_image,
1669x
    filetype = attr(padded_source, "filetype"),
1679x
    source_linear = attr(padded_source, "source_linear"),
1689x
    colorspace = attr(padded_source, "colorspace"),
1699x
    white_current = attr(padded_source, "white_current"),
1709x
    exposure = attr(padded_source, "exposure", exact = TRUE),
1719x
    iso = attr(padded_source, "iso", exact = TRUE)
172
  )
173
1749x
  if (blur > 0) {
175!
    halo_image = render_convolution(
176!
      halo_image,
177!
      kernel = generate_2d_gaussian(
178!
        sd = blur,
179!
        dim = 31,
180!
        width = 30
181
      ),
182!
      include_alpha = TRUE,
183!
      preview = FALSE
184
    )
185!
    halo_image[,, 1] = halo_color[1]
186!
    halo_image[,, 2] = halo_color[2]
187!
    halo_image[,, 3] = halo_color[3]
188
  }
1899x
  attr(halo_image, "padding") = pad
1909x
  if (composite && image_supplied) {
1911x
    if (!all(dim(padded_source)[1:2] == dim(halo_image)[1:2])) {
192!
      stop(
193!
        "`image` and `mask` must have matching dimensions when ",
194!
        "`composite = TRUE`."
195
      )
196
    }
1971x
    halo_image = composite_alpha_outline_image(
1981x
      halo_image = halo_image,
1991x
      source_image = padded_source
200
    )
2011x
    attr(halo_image, "padding") = pad
202
  }
2039x
  handle_image_output(halo_image, filename = filename, preview = preview)
204
}
205
206
#' @title Composite Alpha Outline Image
207
#'
208
#' @description Internal helper that composites the original source image over
209
#' the generated outline using source-over alpha compositing. The outline is the
210
#' backdrop and the source image is the foreground. Colors are treated as
211
#' straight, non-premultiplied alpha, using
212
#' `Ao = Af + Ab * (1 - Af)` and
213
#' `Co = (Cf * Af + Cb * Ab * (1 - Af)) / Ao`. Fully transparent output pixels
214
#' are forced to black to avoid carrying arbitrary color values.
215
#' @param halo_image RGBA outline image used as the compositing backdrop.
216
#' @param source_image RGBA source image, padded to the same dimensions as
217
#' `halo_image`, used as the compositing foreground.
218
#' @return A `rayimg` RGBA image containing the source composited over the
219
#' outline.
220
#'
221
#' @keywords internal
222
composite_alpha_outline_image = function(halo_image, source_image) {
2231x
  halo_array = unclass(halo_image)
2241x
  source_array = unclass(source_image)
225
2261x
  Cf = source_array[,, 1:3]
2271x
  Af = source_array[,, 4]
2281x
  Cb = halo_array[,, 1:3]
2291x
  Ab = halo_array[,, 4]
230
2311x
  Af3 = array(Af, dim = c(dim(Af), 3))
2321x
  Ab3 = array(Ab, dim = c(dim(Ab), 3))
2331x
  Ao = pmin(pmax(Af + Ab * (1 - Af), 0), 1)
2341x
  num = Cf * Af3 + Cb * Ab3 * array(1 - Af, dim = c(dim(Af), 3))
235
2361x
  eps = 1e-8
2371x
  Co = num / array(pmax(Ao, eps), dim = c(dim(Ao), 3))
2381x
  if (any(Ao <= eps)) {
2391x
    transparent = Ao <= eps
2401x
    Co[,, 1][transparent] = 0
2411x
    Co[,, 2][transparent] = 0
2421x
    Co[,, 3][transparent] = 0
243
  }
244
2451x
  output = array(0, dim = dim(halo_array))
2461x
  output[,, 1:3] = Co
2471x
  output[,, 4] = Ao
2481x
  rayimg(
2491x
    output,
2501x
    filetype = attr(halo_image, "filetype"),
2511x
    source_linear = attr(halo_image, "source_linear"),
2521x
    colorspace = attr(halo_image, "colorspace"),
2531x
    white_current = attr(halo_image, "white_current"),
2541x
    exposure = attr(halo_image, "exposure", exact = TRUE),
2551x
    iso = attr(halo_image, "iso", exact = TRUE)
256
  )
257
}
258
259
#' @title Fill Border Alpha Gaps
260
#'
261
#' @description Internal post-process for small distance-transform
262
#' quantization artifacts on outline edges. The algorithm first calls
263
#' `find_border_alpha_gaps()` to mark only low-alpha pixels connected to the
264
#' image exterior. It then scans horizontal, vertical, and diagonal directions.
265
#' For each gap width up to `max_gap`, `offset_alpha()` samples the alpha values
266
#' on opposite sides of each candidate gap. A candidate pixel is raised to the
267
#' weaker of the two neighboring alpha values, and only if that pixel was marked
268
#' as border-connected. This bridges edge notches while leaving enclosed
269
#' interior holes unchanged.
270
#' @param alpha Numeric alpha matrix.
271
#' @param max_gap Default `1`. Maximum low-alpha run width, in pixels, to bridge.
272
#' @param alpha_threshold Default `0.25`. Alpha threshold used to decide which
273
#' pixels are low-alpha border gaps.
274
#' @return Numeric alpha matrix with eligible border gaps filled.
275
#'
276
#' @keywords internal
277
fill_alpha_gaps = function(alpha, max_gap = 1, alpha_threshold = 0.25) {
27810x
  max_gap = as.integer(round(max_gap))
27910x
  if (max_gap <= 0) {
280!
    return(alpha)
281
  }
28210x
  alpha = pmin(pmax(alpha, 0), 1)
28310x
  border_gap = find_border_alpha_gaps(alpha, alpha_threshold)
28410x
  if (!any(border_gap)) {
2852x
    return(alpha)
286
  }
2878x
  directions = list(
2888x
    c(0L, 1L),
2898x
    c(1L, 0L),
2908x
    c(1L, 1L),
2918x
    c(1L, -1L)
292
  )
2938x
  for (direction in directions) {
29432x
    for (gap_width in seq_len(max_gap)) {
29540x
      for (left_distance in seq_len(gap_width)) {
29648x
        right_distance = gap_width + 1L - left_distance
29748x
        left_alpha = offset_alpha(
29848x
          alpha,
29948x
          row_offset = -left_distance * direction[1],
30048x
          col_offset = -left_distance * direction[2]
301
        )
30248x
        right_alpha = offset_alpha(
30348x
          alpha,
30448x
          row_offset = right_distance * direction[1],
30548x
          col_offset = right_distance * direction[2]
306
        )
30748x
        candidate_alpha = pmin(left_alpha, right_alpha)
30848x
        alpha[border_gap] = pmax(alpha[border_gap], candidate_alpha[border_gap])
309
      }
310
    }
311
  }
3128x
  pmin(pmax(alpha, 0), 1)
313
}
314
315
#' @title Find Border Alpha Gaps
316
#'
317
#' @description Internal helper that classifies which low-alpha pixels are part
318
#' of the exterior border region. Pixels below `alpha_threshold` are considered
319
#' low alpha. The algorithm starts from low-alpha pixels on the image boundary
320
#' and performs an 8-connected flood fill through other low-alpha pixels.
321
#' Low-alpha regions enclosed by pixels at or above `alpha_threshold` are not
322
#' reached, so they are protected from `fill_alpha_gaps()`.
323
#' @param alpha Numeric alpha matrix.
324
#' @param alpha_threshold Default `0.25`. Pixels below this alpha are considered
325
#' low-alpha gap pixels.
326
#' @return Logical matrix marking low-alpha pixels connected to the image
327
#' exterior.
328
#'
329
#' @keywords internal
330
find_border_alpha_gaps = function(alpha, alpha_threshold = 0.25) {
33110x
  alpha_threshold = min(max(alpha_threshold, 0), 1)
33210x
  low_alpha = alpha < alpha_threshold
33310x
  border_gap = matrix(FALSE, nrow = nrow(alpha), ncol = ncol(alpha))
33410x
  if (!any(low_alpha)) {
335!
    return(border_gap)
336
  }
337
33810x
  border = matrix(FALSE, nrow = nrow(alpha), ncol = ncol(alpha))
33910x
  border[1, ] = TRUE
34010x
  border[nrow(alpha), ] = TRUE
34110x
  border[, 1] = TRUE
34210x
  border[, ncol(alpha)] = TRUE
34310x
  border_indices = which(low_alpha & border)
34410x
  if (length(border_indices) == 0) {
3452x
    return(border_gap)
346
  }
347
3488x
  nr = nrow(alpha)
3498x
  nc = ncol(alpha)
3508x
  queue = integer(length(alpha))
3518x
  queue[seq_along(border_indices)] = border_indices
3528x
  queue_start = 1L
3538x
  queue_end = length(border_indices)
3548x
  border_gap[border_indices] = TRUE
355
35637x
  while (queue_start <= queue_end) {
35729x
    idx = queue[queue_start]
35829x
    queue_start = queue_start + 1L
35929x
    row = ((idx - 1L) %% nr) + 1L
36029x
    col = ((idx - 1L) %/% nr) + 1L
361
36229x
    row_min = max(1L, row - 1L)
36329x
    row_max = min(nr, row + 1L)
36429x
    col_min = max(1L, col - 1L)
36529x
    col_max = min(nc, col + 1L)
36629x
    for (neighbor_row in row_min:row_max) {
36755x
      for (neighbor_col in col_min:col_max) {
368128x
        if (neighbor_row == row && neighbor_col == col) {
36929x
          next
370
        }
37199x
        neighbor_idx = neighbor_row + (neighbor_col - 1L) * nr
37299x
        if (low_alpha[neighbor_idx] && !border_gap[neighbor_idx]) {
3732x
          queue_end = queue_end + 1L
3742x
          queue[queue_end] = neighbor_idx
3752x
          border_gap[neighbor_idx] = TRUE
376
        }
377
      }
378
    }
379
  }
3808x
  border_gap
381
}
382
383
#' @title Offset Alpha Matrix
384
#'
385
#' @description Internal shift helper used by `fill_alpha_gaps()`. It returns a
386
#' same-size alpha matrix shifted by integer row and column offsets, filling
387
#' newly exposed pixels with zero instead of wrapping. This lets the gap-filling
388
#' scan compare pixels a fixed distance away on opposite sides of a candidate
389
#' gap.
390
#' @param alpha Numeric alpha matrix.
391
#' @param row_offset Integer row offset. Positive values sample from rows below
392
#' each output pixel.
393
#' @param col_offset Integer column offset. Positive values sample from columns
394
#' to the right of each output pixel.
395
#' @return Numeric alpha matrix with the same dimensions as `alpha`.
396
#'
397
#' @keywords internal
398
offset_alpha = function(alpha, row_offset, col_offset) {
39996x
  nr = nrow(alpha)
40096x
  nc = ncol(alpha)
40196x
  output = matrix(0, nrow = nr, ncol = nc)
402
40396x
  row_start = max(1L, 1L - row_offset)
40496x
  row_end = min(nr, nr - row_offset)
40596x
  col_start = max(1L, 1L - col_offset)
40696x
  col_end = min(nc, nc - col_offset)
40796x
  if (row_start > row_end || col_start > col_end) {
40848x
    return(output)
409
  }
41048x
  dest_rows = row_start:row_end
41148x
  dest_cols = col_start:col_end
412
41348x
  output[dest_rows, dest_cols] = alpha[
41448x
    dest_rows + row_offset,
41548x
    dest_cols + col_offset,
41648x
    drop = FALSE
417
  ]
41848x
  output
419
}
1
#'@title Render Convolution FFT
2
#'
3
#'@description Takes an image and applies a convolution operation to it, using
4
#'a user-supplied or built-in kernel. This function uses a fast Fourier transform and
5
#'does the convolution in the frequency domain, so it should be faster for much larger kernels.
6
#'
7
#'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
8
#'@param filename Default `NULL`. The filename of the image to be saved. If this is not given, the image will be plotted instead.
9
#'@param kernel Default `gaussian`. By default, an 11x11 Gaussian kernel with a mean
10
#'of `0` and a standard deviation of `1`, running from `-kernel_extent` to `kernel_extent`.
11
#'If numeric, this will be the standard deviation of the normal distribution. If a
12
#'matrix, it will be used directly as the convolution kernel (but resized always to be an odd number
13
#'of columns and rows).
14
#'@param kernel_dim Default `c(11, 11)`. The dimension of the `gaussian` kernel. Ignored
15
#'if user specifies their own kernel.
16
#'@param kernel_extent Default `3`. Extent over which to calculate the kernel.
17
#'@param absolute Default `TRUE`. Whether to take the absolute value of the convolution.
18
#'@param pad Default `50`. Amount to pad the image to remove edge effects.
19
#'@param include_alpha Default `FALSE`. Whether to include the alpha channel in the convolution.
20
#'@param preview Default `FALSE`. Whether to plot the convolved image, or just to return the values.
21
#'@return A `rayimg` RGBA array.
22
#'@export
23
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
24
#'#Perform a convolution with the default gaussian kernel
25
#'plot_image(dragon)
26
#'#Perform a convolution with the default gaussian kernel
27
#'render_convolution_fft(dragon, kernel=0.1, preview = TRUE)
28
#'#Increase the width of the kernel
29
#'render_convolution_fft(dragon, kernel = 2, kernel_dim=21,kernel_extent=6, preview = TRUE)
30
#'#Use a built-in kernel:
31
#'render_convolution_fft(dragon, kernel = generate_2d_exponential(falloff=2, dim=31, width=21),
32
#'                       preview = TRUE)
33
#'#Perform edge detection
34
#'edge = matrix(c(-1,-1,-1,-1,8,-1,-1,-1,-1),3,3)
35
#'render_convolution_fft(render_bw(dragon), kernel = edge, preview = TRUE)
36
#'#Perform edge detection with Sobel matrices
37
#'sobel1 = matrix(c(1,2,1,0,0,0,-1,-2,-1),3,3)
38
#'sobel2 = matrix(c(1,2,1,0,0,0,-1,-2,-1),3,3,byrow=TRUE)
39
#'sob1 = render_convolution_fft(render_bw(dragon), kernel = sobel1)
40
#'sob2 = render_convolution_fft(render_bw(dragon), kernel = sobel2)
41
#'sob_all = sob1 + sob2
42
#'plot_image(sob1)
43
#'plot_image(sob2)
44
#'plot_image(sob_all)
45
#'#We can also apply this function to matrices:
46
#'volcano |> image()
47
#'volcano |>
48
#'  render_convolution_fft(kernel=generate_2d_gaussian(sd=1,dim=31)) |>
49
#'  image()
50
#'# Because this function uses the fast Fourier transform, large kernels will be much faster
51
#'# than the same size kernels in [render_convolution()]
52
#' render_convolution_fft(dragon, kernel_dim = c(200,200) , preview = TRUE)
53
#'#Use a custom kernel (in this case, an X shape):
54
#'custom = diag(10) + (diag(10)[,10:1])
55
#'#Normalize
56
#'custom = custom / 20
57
#'plot_image(custom*20)
58
#'render_convolution_fft(dragon, kernel = custom, preview = TRUE)
59
render_convolution_fft = function(
60
  image,
61
  kernel = "gaussian",
62
  kernel_dim = c(11, 11),
63
  kernel_extent = 3,
64
  absolute = TRUE,
65
  pad = 50,
66
  include_alpha = FALSE,
67
  filename = NULL,
68
  preview = FALSE
69
) {
70!
  shift_fft = function(fft_mat) {
71!
    nr = dim(fft_mat)[1]
72!
    nc = dim(fft_mat)[2]
73!
    if (nr %% 2 == 0) {
74!
      nr_mid1 = nr / 2
75!
      nr_mid2 = nr / 2 + 1
76
    } else {
77!
      nr_mid1 = floor(nr / 2)
78!
      nr_mid2 = floor(nr / 2) + 1
79
    }
80!
    if (nc %% 2 == 0) {
81!
      nc_mid1 = nc / 2
82!
      nc_mid2 = nc / 2 + 1
83
    } else {
84!
      nc_mid1 = floor(nc / 2)
85!
      nc_mid2 = floor(nc / 2) + 1
86
    }
87!
    fftcorn_nw = fft_mat[1:nr_mid1, 1:nc_mid1]
88!
    fftcorn_ne = fft_mat[1:nr_mid1, nc_mid2:nc]
89!
    fftcorn_sw = fft_mat[nr_mid2:nr, 1:nc_mid1]
90!
    fftcorn_se = fft_mat[nr_mid2:nr, nc_mid2:nc]
91!
    rbind(cbind(fftcorn_se, fftcorn_sw), cbind(fftcorn_ne, fftcorn_nw))
92
  }
93!
  temp_image = ray_read_image(
94!
    image,
95!
    convert_to_array = FALSE,
96!
    reset_camera_settings = TRUE
97
  )
98!
  colorspace = attr(temp_image, "colorspace")
99!
  whitepoint = attr(temp_image, "white_current")
100
101
  #Check if file or image before below:
102!
  if (is.character(kernel)) {
103!
    if (kernel == "gaussian") {
104!
      kernel = generate_2d_gaussian(1, 1, kernel_dim, kernel_extent)
105
    }
106
  }
107!
  if (is.numeric(kernel) && length(kernel) == 1) {
108!
    kernel = generate_2d_gaussian(kernel, 1, kernel_dim, kernel_extent)
109
  }
110
111!
  if (any(dim(kernel)[1:2] != dim(temp_image)[1:2])) {
112!
    if (all(dim(kernel)[1:2] <= dim(temp_image)[1:2])) {
113!
      kernel = expand_to_fit(dim(temp_image)[1:2], kernel)
114
    } else {
115!
      stop("kernel can't have greater dimensions than image")
116
    }
117
  }
118!
  if (pad != 0) {
119!
    temp_image = add_multi_padding(temp_image, pad)
120!
    kernel = add_multi_padding(kernel, pad)
121
  }
122
123!
  if (any(dim(kernel) > dim(temp_image)[1:2] * 2 + 1)) {
124!
    stop(
125!
      "kernel dimensions: ",
126!
      paste0(dim(kernel), collapse = "x"),
127!
      " must not be greater than 2x image dimensions: ",
128!
      paste0(dim(temp_image)[1:2], collapse = "x"),
129!
      ", plus one (here, ",
130!
      paste0(dim(temp_image)[1:2] * 2 + 1, collapse = "x"),
131
      ")."
132
    )
133
  }
134
135!
  temp_fft = temp_image
136!
  if (length(dim(temp_image)) == 2) {
137!
    temp_fft = stats::fft(temp_image)
138!
  } else if (length(dim(temp_image)) == 3) {
139!
    channels = dim(temp_image)[3]
140!
    if (!include_alpha && (channels == 2 || channels == 4)) {
141!
      max_channel = channels - 1
142
    } else {
143!
      max_channel = channels
144
    }
145!
    for (i in seq_len(max_channel)) {
146!
      temp_fft[,, i] = stats::fft(temp_image[,, i])
147
    }
148
  }
149
150!
  kernal_fft = stats::fft(kernel)
151!
  vals = Re(temp_fft)
152!
  if (length(dim(temp_fft)) == 3) {
153!
    channels = dim(temp_image)[3]
154!
    if (!include_alpha && (channels == 2 || channels == 4)) {
155!
      max_channel = channels - 1
156
    } else {
157!
      max_channel = channels
158
    }
159!
    for (i in seq_len(max_channel)) {
160!
      vals[,, i] = shift_fft(
161!
        Re(stats::fft(temp_fft[,, i] * kernal_fft, inverse = TRUE)) /
162!
          length(vals[,, i])
163
      )
164
    }
165
  } else {
166!
    vals = shift_fft(
167!
      Re(stats::fft(temp_fft * kernal_fft, inverse = TRUE)) / length(vals)
168
    )
169
  }
170!
  if (absolute) {
171!
    vals = abs(vals)
172
  }
173
174!
  if (pad != 0) {
175!
    vals = trim_padding(vals, pad)
176
  }
177!
  final_image = ray_read_image(
178!
    vals,
179!
    assume_colorspace = colorspace,
180!
    assume_white = whitepoint,
181!
    source_linear = TRUE
182
  )
183!
  handle_image_output(final_image, filename = filename, preview = preview)
184
}
1
#'@title Resize Image
2
#'
3
#'@description Resizes an image or a matrix, using bilinear interpolation.
4
#'
5
#'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
6
#'@param mag Default `1`. Amount to magnify the image, preserving aspect ratio. Overridden if
7
#'`dim` is not `NULL`.
8
#'@param dims Default `NULL`. Exact resized dimensions.
9
#'@param filename Default `NULL`. The filename of the image to be saved. If this is not given, the image will be plotted instead.
10
#'@param preview Default `FALSE`. Whether to plot the convolved image, or just to return the values.
11
#'@param method Default `trilinear`. Filters to up/downsample the image. Options: `bilinear`, `box`, `trilinear`,
12
#' `catmull`, `mitchell`.
13
#'@return A `rayimg` RGBA array.
14
#'@export
15
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
16
#'#Plot the image with a title
17
#'dragon |>
18
#'  render_title("Dragon", title_offset=c(10,10), title_bar_color="black",
19
#'            title_size=20, title_color = "white") |>
20
#'  plot_image()
21
#'#Half of the resolution
22
#'render_resized(dragon, mag = 1/2) |>
23
#'  render_title("Dragon (half res)", title_offset=c(5,5), title_bar_color="black",
24
#'            title_size=10, title_color = "white") |>
25
#'  plot_image()
26
#'#Double the resolution
27
#'render_resized(dragon, mag = 2) |>
28
#'  render_title("Dragon (2x res)", title_offset=c(20,20), title_bar_color="black",
29
#'            title_size=40, title_color = "white") |>
30
#'  plot_image()
31
#'#Specify the exact resulting dimensions
32
#'render_resized(dragon, dim = c(160,320)) |>
33
#'  render_title("Dragon (custom size)", title_offset=c(10,10), title_bar_color="black",
34
#'            title_size=20, title_color = "white") |>
35
#'  plot_image()
36
render_resized = function(
37
  image,
38
  mag = 1,
39
  dims = NULL,
40
  filename = NULL,
41
  preview = FALSE,
42
  method = "tri"
43
) {
442x
  temp_image = ray_read_image(image)
452x
  orig_dims = dim(temp_image)[1:2]
462x
  downscale = if (!is.null(dims)) {
472x
    any(dims[1:2] < orig_dims)
48
  } else {
49!
    isTRUE(mag < 1)
50
  }
512x
  use_bilinear = method %in% c("bi", "bilinear") && !downscale
522x
  if (!use_bilinear && method %in% c("bi", "bilinear")) {
53!
    method = "box"
54
  }
55
  #Check if file or image before below:
562x
  imagetype = attr(temp_image, "filetype")
572x
  img_source_linear = attr(temp_image, "source_linear")
582x
  colorspace = attr(temp_image, "colorspace")
592x
  white_current = attr(temp_image, "white_current")
60
612x
  if (use_bilinear) {
62!
    if (!is.null(dims)) {
63!
      dims = dims[1:2] / dim(temp_image)[1:2]
64
    }
65!
    temp_list = list()
66!
    if (length(dim(temp_image)) == 3) {
67!
      channels = dim(temp_image)[3]
68!
      for (i in seq_len(channels)) {
69!
        if (is.null(dims)) {
70!
          temp_list[[i]] = resize_image(temp_image[,, i], mag)
71
        } else {
72!
          x1 = seq(1, nrow(temp_image), length.out = nrow(temp_image) * dims[1])
73!
          y1 = seq(1, ncol(temp_image), length.out = ncol(temp_image) * dims[2])
74!
          temp_list[[i]] = resize_image_xy(temp_image[,, i], x1, y1)
75
        }
76
      }
77!
      temp_image = array(
78!
        0,
79!
        dim = c(nrow(temp_list[[1]]), ncol(temp_list[[1]]), channels)
80
      )
81!
      for (i in seq_len(channels)) {
82!
        temp_image[,, i] = temp_list[[i]]
83
      }
84
    } else {
85!
      if (is.null(dims)) {
86!
        temp_image = resize_image(t(flipud(temp_image)), mag)
87
      } else {
88!
        x1 = seq(1, nrow(temp_image), length.out = nrow(temp_image) * dims[1])
89!
        y1 = seq(1, ncol(temp_image), length.out = ncol(temp_image) * dims[2])
90!
        temp_image = resize_image_xy(t(flipud(temp_image)), x1, y1)
91
      }
92
    }
93
  } else {
942x
    method = tolower(method)
952x
    method = switch(
962x
      method,
972x
      "default" = 0,
982x
      "box" = 1,
992x
      "triangle" = 2,
1002x
      "tri" = 3,
1012x
      "trilinear" = 3,
1022x
      "cubic" = 3,
1032x
      "catmull" = 4,
1042x
      "mitchell" = 5,
1052x
      3
106
    )
1072x
    if (is.null(dims)) {
108!
      dims = mag * dim(temp_image)[1:2]
109
    }
1102x
    temp_list = list()
1112x
    if (length(dim(temp_image)) == 3) {
1122x
      for (i in seq_len(dim(temp_image)[3])) {
1138x
        temp_list[[i]] = resize_matrix_stb(
1148x
          unclass(temp_image[,, i]),
1158x
          dims[1],
1168x
          dims[2],
1178x
          method
118
        )
119
      }
1202x
      temp_image = array(0, dim = c(dims[1], dims[2], dim(temp_image)[3]))
1212x
      for (i in seq_len(dim(temp_image)[3])) {
1228x
        temp_image[,, i] = temp_list[[i]]
123
      }
124
    } else {
125!
      bare_matrix = unclass(temp_image)
126!
      temp_image = resize_matrix_stb(
127!
        bare_matrix,
128!
        dims[1],
129!
        dims[2],
130!
        method
131
      )
132
    }
133
  }
1342x
  temp_image = ray_read_image(
1352x
    temp_image,
1362x
    filetype = imagetype,
1372x
    source_linear = img_source_linear,
1382x
    assume_colorspace = colorspace,
1392x
    assume_white = white_current
140
  )
1412x
  handle_image_output(temp_image, filename = filename, preview = preview)
142
}
1
#'@title Render Convolution
2
#'
3
#'@description Takes an image and applies a convolution operation to it, using
4
#'a user-supplied or built-in kernel. Edges are calculated by limiting the size
5
#'of the kernel to only that overlapping the actual image (renormalizing the
6
#'kernel for the edges).
7
#'
8
#'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
9
#'@param filename Default `NULL`. The filename of the image to be saved. If this is not given, the image will be plotted instead.
10
#'@param kernel Default `gaussian`. By default, an 11x11 Gaussian kernel with a mean
11
#'of `0` and a standard deviation of `1`, running from `-kernel_extent` to `kernel_extent`.
12
#'If numeric, this will be the standard deviation of the normal distribution. If a
13
#'matrix, it will be used directly as the convolution kernel (but resized always to be an odd number
14
#'of columns and rows).
15
#'@param kernel_dim Default `11`. The dimension of the `gaussian` kernel. Ignored
16
#'if user specifies their own kernel.
17
#'@param kernel_extent Default `3`. Extent over which to calculate the kernel.
18
#'@param absolute Default `TRUE`. Whether to take the absolute value of the convolution.
19
#'@param min_value Default `NULL`. If numeric, specifies the minimum value (for any color channel)
20
#'for a pixel to have the convolution performed.
21
#'@param include_alpha Default `FALSE`. Whether to include the alpha channel in the convolution.
22
#'@param preview Default `TRUE`. Whether to plot the convolved image, or just to return the values.
23
#'@param progress Default `TRUE`. Whether to display a progress bar.
24
#'@return A `rayimg` RGBA array.
25
#'@export
26
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
27
#'#Perform a convolution with the default gaussian kernel
28
#'plot_image(dragon)
29
#'#Perform a convolution with the default gaussian kernel
30
#'render_convolution(dragon, preview = TRUE)
31
#'#Increase the width of the kernel
32
#'render_convolution(dragon, kernel = 2, kernel_dim=21,kernel_extent=6, preview = TRUE)
33
#'#Perform edge detection using an edge detection kernel
34
#'edge = matrix(c(-1,-1,-1,-1,8,-1,-1,-1,-1),3,3)
35
#'render_convolution(render_bw(dragon), kernel = edge, preview = TRUE, absolute=FALSE)
36
#'#Perform edge detection with Sobel matrices
37
#'sobel1 = matrix(c(1,2,1,0,0,0,-1,-2,-1),3,3)
38
#'sobel2 = matrix(c(1,2,1,0,0,0,-1,-2,-1),3,3,byrow=TRUE)
39
#'sob1 = render_convolution(render_bw(dragon), kernel = sobel1)
40
#'sob2 = render_convolution(render_bw(dragon), kernel = sobel2)
41
#'sob_all = sob1 + sob2
42
#'plot_image(sob1)
43
#'plot_image(sob2)
44
#'plot_image(sob_all)
45
#'
46
#'#Only perform the convolution on bright pixels (bloom)
47
#'render_convolution(dragon, kernel = 5, kernel_dim=24, kernel_extent=24,
48
#'                   min_value=1, preview = TRUE)
49
#'#Use a built-in kernel:
50
#'render_convolution(dragon, kernel = generate_2d_exponential(falloff=2, dim=31, width=21),
51
#'                   preview = TRUE)
52
#'#We can also apply this function to matrices:
53
#'volcano |> image()
54
#'volcano |>
55
#'  render_convolution(kernel=generate_2d_gaussian(sd=1,dim=31)) |>
56
#'  image()
57
#'#Use a custom kernel (in this case, an X shape):
58
#'custom = diag(10) + (diag(10)[,10:1])
59
#'plot_image(custom)
60
#'render_convolution(dragon, kernel = custom, preview = TRUE)
61
render_convolution = function(
62
  image,
63
  kernel = "gaussian",
64
  kernel_dim = 11,
65
  kernel_extent = 3,
66
  absolute = TRUE,
67
  min_value = NULL,
68
  include_alpha = FALSE,
69
  filename = NULL,
70
  preview = FALSE,
71
  progress = FALSE
72
) {
73!
  if (is.character(kernel)) {
74!
    if (kernel == "gaussian") {
75!
      kernel = generate_2d_gaussian(1, 1, kernel_dim, kernel_extent)
76
    }
77
  }
78!
  if (is.numeric(kernel) && length(kernel) == 1) {
79!
    kernel = generate_2d_gaussian(kernel, 1, kernel_dim, kernel_extent)
80
  }
81!
  if (!is.null(dim(kernel)) && all(dim(kernel) >= 2)) {
82!
    if (ncol(kernel) %% 2 == 0) {
83!
      newkernel = matrix(0, ncol = ncol(kernel) + 1, nrow = nrow(kernel))
84!
      newkernel[, 1:ncol(kernel)] = kernel
85!
      kernel = newkernel
86
    }
87!
    if (nrow(kernel) %% 2 == 0) {
88!
      newkernel = matrix(0, ncol = ncol(kernel), nrow = nrow(kernel) + 1)
89!
      newkernel[1:nrow(kernel), ] = kernel
90!
      kernel = newkernel
91
    }
92
  }
93!
  temp_image = ray_read_image(
94!
    image,
95!
    convert_to_array = FALSE,
96!
    reset_camera_settings = TRUE
97
  )
98!
  colorspace = attr(temp_image, "colorspace")
99!
  whitepoint = attr(temp_image, "white_current")
100!
  imagetype = attr(temp_image, "filetype")
101!
  if (any(dim(kernel) > dim(temp_image)[1:2] * 2 + 1)) {
102!
    stop(
103!
      "kernel dimensions: ",
104!
      paste0(dim(kernel), collapse = "x"),
105!
      " must not be greater than 2x image dimensions: ",
106!
      paste0(dim(temp_image)[1:2], collapse = "x"),
107!
      ", plus one (here, ",
108!
      paste0(dim(temp_image)[1:2] * 2 + 1, collapse = "x"),
109
      ")."
110
    )
111
  }
112
113!
  bloom_matrix = matrix(TRUE, nrow = nrow(temp_image), ncol = ncol(temp_image))
114!
  if (length(dim(temp_image)) == 3) {
115!
    if (!is.null(min_value)) {
116!
      bool_value = rep(TRUE, length = length(temp_image[,, 1]))
117!
      for (i in seq_along(dim(temp_image)[3])) {
118!
        bool_value = bool_value & temp_image[,, i] <= min_value
119
      }
120!
      bloom_matrix[bool_value] = FALSE
121
    }
122
  } else {
123!
    if (!is.null(min_value)) {
124!
      bloom_matrix[temp_image <= min_value] = FALSE
125
    }
126
  }
127!
  temp_image_final = temp_image
128!
  if (imagetype != "matrix") {
129!
    channels = dim(temp_image)[3]
130!
    if (!include_alpha && (channels == 2 || channels == 4)) {
131!
      max_channel = channels - 1
132
    } else {
133!
      max_channel = channels
134
    }
135!
    for (i in seq_len(max_channel)) {
136!
      temp_image_final[,, i] = convolution_cpp(
137!
        temp_image[,, i],
138!
        kernel = kernel,
139!
        progbar = progress,
140!
        channel = i,
141!
        bloom_matrix = bloom_matrix
142
      )
143
    }
144
  } else {
145!
    temp_image_final = convolution_cpp(
146!
      temp_image,
147!
      kernel = kernel,
148!
      progbar = progress,
149!
      channel = 1,
150!
      bloom_matrix = bloom_matrix
151
    )
152
  }
153!
  if (absolute) {
154!
    temp_image_final = abs(temp_image_final)
155
  }
156!
  final_image = ray_read_image(
157!
    temp_image_final,
158!
    assume_colorspace = colorspace,
159!
    assume_white = whitepoint,
160!
    source_linear = TRUE
161
  )
162!
  handle_image_output(final_image, filename = filename, preview = preview)
163
}
1
#' Create a rayimg
2
#'
3
#' This class will always be:
4
#'  * A matrix or a 2/3/4 layer array
5
#'  * It tracks whether the source data was linearized
6
#'  * It carries working colorspace/white
7
#'  * It carries informational exposure/ISO metadata
8
#'
9
#' @param x Default `NULL`. The underlying array/matrix to wrap.
10
#' @param filetype Default `NULL`. Original source type to record (e.g., "png").
11
#' @param source_linear Default `FALSE`. Whether the original source was linearized.
12
#' @param colorspace Default `CS_ACESCG`. Working space descriptor (see `make_colorspace()`).
13
#' @param white_current Default `colorspace$white_xyz`. Current assumed scene/display white (XYZ, Y=1).
14
#' @param exposure Default `0`. Informational exposure compensation in stops.
15
#' @param iso Default `100`. Informational ISO value.
16
#'
17
#' @return An object of class `c("rayimg", <original class>)` with attributes.
18
#' @keywords internal
19
rayimg = function(
20
  x = NULL,
21
  filetype = NULL,
22
  source_linear = FALSE,
23
  colorspace = CS_ACESCG,
24
  white_current = colorspace$white_xyz,
25
  exposure = attr(x, "exposure", exact = TRUE),
26
  iso = attr(x, "iso", exact = TRUE)
27
) {
28851x
  if (is.null(x)) {
29!
    stop("rayimg(): 'x' cannot be NULL.")
30
  }
31851x
  stopifnot(is.array(x))
32
33851x
  x_new = rayimg_validate_dimensions(x)
34
35
  # channels attribute
36851x
  if (is.null(attr(x, "channels"))) {
37353x
    attr(x_new, "channels") = rayimg_detect_channels(x_new)
38
  } else {
39498x
    attr(x_new, "channels") = attr(x, "channels")
40
  }
41
42
  # required attrs
43851x
  attr(x_new, "filetype") = filetype
44851x
  attr(x_new, "source_linear") = source_linear
45851x
  attr(x_new, "exposure") = rayimg_exposure_value(exposure)
46851x
  attr(x_new, "iso") = rayimg_iso_value(iso)
47
48
  # new attrs for color mgmt
49851x
  stopifnot(
50851x
    is.list(colorspace),
51851x
    all(c("rgb_to_xyz", "xyz_to_rgb", "white_xyz") %in% names(colorspace))
52
  )
53851x
  attr(x_new, "colorspace") = colorspace
54851x
  attr(x_new, "white_current") = white_current
55851x
  if (!is.null(attr(x, "dng", exact = TRUE))) {
562x
    attr(x_new, "dng") = attr(x, "dng", exact = TRUE)
57
  }
58851x
  if (!is.null(attr(x, "exr", exact = TRUE))) {
592x
    attr(x_new, "exr") = attr(x, "exr", exact = TRUE)
60
  }
61851x
  class(x_new) = c("rayimg", setdiff(class(x), "rayimg"))
62851x
  x_new
63
}
64
65
rayimg_exposure_value = function(exposure) {
66949x
  if (is.null(exposure) || length(exposure) == 0L) {
67241x
    return(0)
68
  }
69
  if (
70708x
    !is.numeric(exposure) ||
71708x
      length(exposure) != 1L ||
72708x
      is.na(exposure) ||
73708x
      !is.finite(exposure)
74
  ) {
75!
    stop("rayimg(): 'exposure' must be a finite numeric value.")
76
  }
77708x
  as.numeric(exposure)
78
}
79
80
rayimg_iso_value = function(iso) {
81937x
  if (is.null(iso) || length(iso) == 0L) {
82241x
    return(100)
83
  }
84
  if (
85696x
    !is.numeric(iso) ||
86696x
      length(iso) != 1L ||
87696x
      is.na(iso) ||
88696x
      !is.finite(iso) ||
89696x
      iso <= 0
90
  ) {
91!
    stop("rayimg(): 'iso' must be a positive finite numeric value.")
92
  }
93696x
  as.numeric(iso)
94
}
95
96
rayimg_channels_from_count = function(n) {
97
  switch(
981736x
    as.character(n),
99!
    "1" = c("Greyscale"),
10020x
    "2" = c("Greyscale", "Alpha"),
101330x
    "3" = c("Red", "Green", "Blue"),
1021386x
    "4" = c("Red", "Green", "Blue", "Alpha"),
103!
    stop("This should never be hit.")
104
  )
105
}
106
107
rayimg_detect_channels = function(x) {
1081824x
  d = dim(x)
1091824x
  if (length(d) < 3L) {
11088x
    return("Greyscale")
111
  }
1121736x
  rayimg_channels_from_count(d[3])
113
}
114
115
#Always return a multidimensional (d[3] = 2,3,4) array, or a matrix.
116
rayimg_validate_dimensions = function(x) {
117851x
  d = dim(x)
118851x
  stopifnot(!is.null(d), length(d) %in% c(2, 3), d[1] > 0, d[2] > 0)
119851x
  if (length(d) == 3) {
120705x
    if (d[3] == 1) {
121!
      x = x[,, 1] # drop extra
122
    } else {
123705x
      stopifnot(d[3] %in% c(2, 3, 4))
124
    }
125
  }
126851x
  x
127
}
128
129
#' @export
130
`[.rayimg` = function(x, ..., drop = TRUE) {
1311471x
  ch = rayimg_detect_channels(x)
1321471x
  caller_env = parent.frame()
1331471x
  mc = match.call(expand.dots = FALSE)
1341471x
  dots_expr = as.list(mc$`...`)
1351471x
  nd = length(dim(x))
136
1371471x
  if (length(dots_expr) < nd) {
138226x
    dots_expr = c(dots_expr, rep(list(quote(expr = )), nd - length(dots_expr)))
139
  }
1401471x
  idx = lapply(dots_expr, function(z) {
1411611x
    if (identical(z, quote(expr = ))) TRUE else eval(z, envir = caller_env)
142
  })
143
1441471x
  if (nd >= 3L) {
1451465x
    if (!isTRUE(idx[[3L]]) && length(idx[[3L]]) > 4L) {
1467x
      stop("A rayimg can only have four or fewer channels selected at once.")
147
    }
1481458x
    if (!isTRUE(idx[[3L]]) && any(idx[[3L]] > 4L)) {
149!
      stop("rayimg: channel index > 4.")
150
    }
151
  }
152
1531464x
  y = NextMethod("[", drop = FALSE)
154
1551464x
  if (drop) {
1561415x
    d = dim(y)
1571415x
    dn = dimnames(y)
1581415x
    drop_idx = which(d == 1L & seq_along(d) >= 3L)
1591415x
    if (length(drop_idx)) {
160570x
      keep = setdiff(seq_along(d), drop_idx)
161570x
      y = array(y, dim = d[keep], dimnames = dn[keep])
162
    }
163
  }
164
165
  # carry attrs
1661464x
  attr(y, "filetype") = attr(x, "filetype")
1671464x
  attr(y, "source_linear") = attr(x, "source_linear")
1681464x
  attr(y, "exposure") = attr(x, "exposure")
1691464x
  attr(y, "iso") = attr(x, "iso")
1701464x
  attr(y, "colorspace") = attr(x, "colorspace")
1711464x
  attr(y, "white_current") = attr(x, "white_current")
1721464x
  if (!is.null(attr(x, "dng", exact = TRUE))) {
173!
    attr(y, "dng") = attr(x, "dng", exact = TRUE)
174
  }
1751464x
  if (!is.null(attr(x, "exr", exact = TRUE))) {
1766x
    attr(y, "exr") = attr(x, "exr", exact = TRUE)
177
  }
178
1791464x
  if (!is.null(ch)) {
1801464x
    if (nd >= 3L) {
1811458x
      ch_idx = idx[[3L]]
1821458x
      if (isTRUE(ch_idx)) {
183265x
        ch_idx = seq_along(ch)
184
      }
1851458x
      attr(y, "channels") = ch[ch_idx]
186
    } else {
1876x
      attr(y, "channels") = ch[seq_len(min(1L, length(ch)))]
188
    }
189
  } else {
190!
    attr(y, "channels") = rayimg_detect_channels(y)
191
  }
192
1931464x
  if (!is.null(dim(y))) {
1941238x
    class(y) = unique(c("rayimg", setdiff(class(y), "rayimg")))
195
  }
1961464x
  y
197
}
1
#' @title Render White Balance (Bradford CAT)
2
#' @description Chromatic-adapt an image from `reference_white` to `target_white` **in its working RGB space**.
3
#'
4
#' When `bake = FALSE` (the default), this should not result in any visible changes to the image when
5
#' plotted in rayimage via [plot_image()], as that function then corrects the white balance for
6
#' display. Set
7
#'
8
#' @param image Default `NULL`. 3-layer RGB/4-layer RGBA array, `rayimg`, or filename.
9
#' @param reference_white Default `NA`. Source white (XYZ Y=1 or named); when `NA`, uses `attr(img, "white_current")`.
10
#' @param target_white Default `"D60"`. Target white (XYZ Y=1 or named).
11
#' @param bake Default `FALSE`. `FALSE` = appearance-preserving
12
#'   (update tag to the new white). When `TRUE`, apply CAT but keep the original tag,
13
#'   producing a visible warmer/cooler result on display.
14
#' @param filename Default `NULL`. Output path.
15
#' @param preview Default `FALSE`. If `TRUE`, display the image.
16
#' @param bake Default `FALSE`. If `TRUE`, this will bake the color change into the image, and return the
17
#' old tag. This can be used for stylistic adjustments.
18
#' @export
19
#' @examples
20
#' # Not specifying a target white balance returns an unchanged image
21
#' render_white_balance(dragon, preview = TRUE)
22
#'
23
#' # Default white "D60", converting to D50 produces a warmer image
24
#' render_white_balance(dragon, preview = TRUE, target_white = "D50", bake = TRUE)
25
#'
26
#' # Default white "D60", converting to "D75" produces a cooler image
27
#' render_white_balance(dragon, preview = TRUE, target_white = "D75", bake = TRUE)
28
#'
29
#' # Set reference white to colder "D75", converting to "D50" produces a very warm image
30
#' render_white_balance(dragon, preview = TRUE,
31
#'                      reference_white= "D75", target_white = "D50", bake = TRUE)
32
#'
33
#' # With a real, non-rendered image:
34
#' render_white_balance(sunset_image, preview=TRUE)
35
#'
36
#' # Cooler
37
#' render_white_balance(sunset_image, preview=TRUE, target_white = "D75", bake = TRUE)
38
#'
39
#' # Warmer
40
#' render_white_balance(sunset_image, preview=TRUE, target_white = "D50", bake = TRUE)
41
render_white_balance = function(
42
  image,
43
  reference_white = NA,
44
  target_white = "D60",
45
  bake = FALSE,
46
  filename = NULL,
47
  preview = FALSE
48
) {
492x
  src = ray_read_image(image, normalize = FALSE)
502x
  cs = attr(src, "colorspace")
51
52
  if (
532x
    is.atomic(reference_white) &&
542x
      length(reference_white) == 1L &&
552x
      is.na(reference_white)
56
  ) {
57!
    reference_white = attr(src, "white_current")
58
  }
59
60
  # If whites are identical, do nothing
61
  if (
622x
    isTRUE(all.equal(
632x
      get_whitepoint_xyz(reference_white)$value,
642x
      get_whitepoint_xyz(target_white)$value
65
    ))
66
  ) {
67!
    return(handle_image_output(src, filename = filename, preview = preview))
68
  }
69
702x
  if (!bake) {
71
    # CAT + update tag (appearance-preserving)
72!
    return(render_convert_colorspace(
73!
      src,
74!
      from_mats = cs,
75!
      to_mats = cs,
76!
      adapt_white = TRUE,
77!
      from_white = reference_white,
78!
      to_white = target_white,
79!
      filename = filename,
80!
      preview = preview
81
    ))
82
  }
83
84
  # bake = TRUE, CAT but keep the original tag ----
852x
  src_wp = get_whitepoint_xyz(reference_white)
862x
  dst_wp = get_whitepoint_xyz(target_white)
87
88
  # Work in linear RGB
892x
  if (!isTRUE(attr(src, "source_linear"))) {
90!
    warning(
91!
      "render_white_balance(bake = TRUE): input not linear; convert with render_gamma_linear(..., TRUE) first."
92
    )
93
  }
94
95
  # RGB(working) -> XYZ
962x
  xyz = apply_color_matrix(src, cs$rgb_to_xyz)
97
  # CAT in XYZ
982x
  CAT = compute_cat_bradford(src_wp$value, dst_wp$value)
992x
  xyz = apply_color_matrix(xyz, CAT)
100
  # XYZ -> RGB(working)
1012x
  out = apply_color_matrix(xyz, cs$xyz_to_rgb)
102
  # preserve alpha
1032x
  d = dim(src)
1042x
  if (length(d) == 3L && d[3] == 4L) {
1052x
    out[,, 4] = src[,, 4]
106
  }
107
1082x
  out = rayimg(
1092x
    out,
1102x
    filetype = attr(src, "filetype"),
1112x
    source_linear = attr(src, "source_linear"),
1122x
    colorspace = cs, # primaries unchanged
1132x
    white_current = src_wp$value, # Keep the original tag to bake in the new color
1142x
    exposure = attr(src, "exposure", exact = TRUE),
1152x
    iso = attr(src, "iso", exact = TRUE)
116
  )
1172x
  handle_image_output(out, filename = filename, preview = preview)
118
}
1
#' Normalize/label a white point
2
#' @param white_point Default `NULL`. Named ("D65","D60","D55","D50","D75","E") or XYZ (length 3, any Y).
3
#' @returns list(value = XYZ with Y=1, white_name = name or "Custom")
4
#' @keywords internal
5
get_whitepoint_xyz = function(white_point = NULL) {
6430x
  std = list(
7430x
    "D65" = c(0.95047, 1, 1.08883),
8430x
    "D60" = c(0.95264, 1, 1.00827),
9430x
    "D55" = c(0.95560, 1, 0.92149),
10430x
    "D50" = c(0.96422, 1, 0.82521),
11430x
    "D75" = c(0.94972, 1, 1.22638),
12430x
    "E" = c(1, 1, 1)
13
  )
14430x
  if (is.null(white_point)) {
15!
    return(NULL)
16
  }
17430x
  if (is.character(white_point) && length(white_point) == 1L) {
1812x
    wp = std[[toupper(white_point)]]
1912x
    if (is.null(wp)) {
20!
      stop("Unknown white: ", white_point)
21
    }
2212x
    return(list(value = wp, white_name = white_point))
23
  }
24418x
  stopifnot(is.numeric(white_point), length(white_point) == 3L)
25418x
  Y = white_point[2]
26418x
  if (!is.finite(Y) || Y <= 0) {
27!
    stop("White Y must be positive and finite.")
28
  }
29418x
  list(value = white_point / Y, white_name = "Custom")
30
}
31
32
#' Bradford CAT matrix from source to target white
33
#' @param source_xyz Default `c(0.95264,1,1.00827)`. Source XYZ white, Y=1.
34
#' @param target_xyz Default `c(0.95047,1,1.08883)`. Target XYZ white, Y=1.
35
#' @param eps Default `1e-8`. Small epsilon.
36
#' @return 3x3 numeric CAT matrix to apply in XYZ.
37
#' @keywords internal
38
compute_cat_bradford = function(
39
  source_xyz = c(0.95264, 1.0, 1.00827),
40
  target_xyz = c(0.95047, 1.0, 1.08883),
41
  eps = 1e-8
42
) {
4386x
  B = matrix(
4486x
    c(
4586x
      0.8951,
4686x
      0.2664,
4786x
      -0.1614,
4886x
      -0.7502,
4986x
      1.7135,
5086x
      0.0367,
5186x
      0.0389,
5286x
      -0.0685,
5386x
      1.0296
54
    ),
5586x
    3,
5686x
    3,
5786x
    byrow = TRUE
58
  )
5986x
  src = B %*% source_xyz
6086x
  dst = B %*% target_xyz
6186x
  if (any(abs(src) < eps)) {
62!
    stop("CAT: source LMS too close to zero")
63
  }
6486x
  S = diag(as.numeric(dst / src))
6586x
  solve(B) %*% S %*% B
66
}
67
68
#' Apply a 3x3 color transform to an image
69
#' @param img 3/4-channel array (RGB/A). 2D (grey) or 2-channel (grey+alpha) pass through.
70
#' @param M 3x3 matrix.
71
#' @return Array with transformed RGB; alpha preserved.
72
#' @keywords internal
73
apply_color_matrix = function(img, M = diag(3)) {
74258x
  stopifnot(is.array(img), is.matrix(M), all(dim(M) == c(3, 3)))
75258x
  d = dim(img)
76258x
  if (length(d) == 2L) {
77!
    return(img)
78
  }
79258x
  ch = d[3]
80258x
  if (ch < 3L) {
81!
    return(img)
82
  }
83258x
  flat = matrix(img[,, 1:3], ncol = 3)
84258x
  flat = flat %*% t(M)
85258x
  out = img
86258x
  out[,, 1:3] = array(flat, dim = c(d[1], d[2], 3))
87258x
  out
88
}
89
90
#' sRGB to Linear
91
#' @param x Values
92
#' @returns Transformed values
93
#' @keywords internal
94
to_linear = function(x) {
9575x
  out = x
9675x
  low = x <= 0.04045
9775x
  out[low] = x[low] / 12.92
9875x
  out[!low] = ((x[!low] + 0.055) / 1.055)^2.4
9975x
  out
100
}
101
102
#' Linear to sRGB
103
#' @param x Values
104
#' @returns Transformed values
105
#' @keywords internal
106
to_srgb = function(x) {
107143x
  x = pmin(pmax(x, 0), 1)
108143x
  out = x
109143x
  low = x <= 0.0031308
110143x
  out[low] = 12.92 * x[low]
111143x
  out[!low] = 1.055 * x[!low]^(1 / 2.4) - 0.055
112143x
  out
113
}
114
115
#' Encode RGB/RGBA to hex (sRGB domain)
116
#' @param x Values. 3 or 4 columns (R,G,B,A) in 0 to 1.
117
#' @return Hex vector (#RRGGBB or #RRGGBBAA).
118
#' @keywords internal
119
rgb_to_hex = function(x) {
120
  if (is.null(dim(x))) {
121
    x = matrix(x, ncol = length(x))
122
  }
123
  if (!(ncol(x) %in% c(3L, 4L))) {
124
    stop("rgb_to_hex(): expected 3 or 4 columns (R,G,B[,A]).")
125
  }
126
  x = pmin(pmax(x, 0), 1)
127
  ints = round(x * 255)
128
  apply(ints, 1, function(row) {
129
    paste0("#", paste(sprintf("%02X", row), collapse = ""))
130
  })
131
}
132
133
#' Array hex vector in column-major order
134
#' @param arr Array with c>=3
135
#' @return Hex vector length h*w
136
#' @keywords internal
137
array_rgb_to_hex_colmajor = function(arr) {
138
  d = dim(arr)
139
  if (length(d) != 3L || d[3] < 3L) {
140
    stop("array_rgb_to_hex_colmajor(): need h*w*(3|4).")
141
  }
142
  R = as.vector(arr[,, 1])
143
  G = as.vector(arr[,, 2])
144
  B = as.vector(arr[,, 3])
145
  if (d[3] >= 4L) {
146
    A = as.vector(arr[,, 4])
147
    return(rgb_to_hex(cbind(R, G, B, A)))
148
  }
149
  rgb_to_hex(cbind(R, G, B))
150
}
1
#' @title Select PNG Device
2
#'
3
#' @description Internal helper to pick the best available PNG graphics
4
#' device. Uses `ragg::agg_png()` by default, then falls back to a
5
#' Cairo-backed `grDevices::png()` device when `use_ragg = FALSE`, and
6
#' finally to the base PNG device.
7
#'
8
#' @param use_ragg Default `TRUE`. If `TRUE`, return `ragg::agg_png()`.
9
#' Set to `FALSE` to skip `ragg`.
10
#'
11
#' @keywords internal
12
#' @importFrom ragg agg_png
13
linear_png_device = function(use_ragg = TRUE) {
1468x
  if (isTRUE(use_ragg)) {
1568x
    return(function(...) {
1667x
      args = list(...)
1767x
      args$family = NULL
1867x
      do.call(agg_png, args)
19
    })
20
  }
21
22!
  if (isTRUE(capabilities("cairo"))) {
23!
    return(function(...) {
24!
      grDevices::png(..., type = "cairo")
25
    })
26
  }
27
28!
  warning(
29!
    "No cairo device available: install the {ragg} package to ensure correct treatment of gamma when adding text to images.",
30!
    call. = FALSE
31
  )
32
33!
  grDevices::png
34
}
1
.libopenexr_available = function() {
23x
  requireNamespace("libopenexr", quietly = TRUE)
3
}
4
5
#'@title Write Image
6
#'
7
#'@description Takes an RGB array/filename and writes it to file.
8
#'
9
#'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
10
#'@param filename File to write to, with filetype determined by extension. Filetype can be
11
#'`PNG`, `JPEG`, `TIFF`, `EXR`, or `DNG`.
12
#'@param clamp Default `FALSE`, automatically determined. Whether to clamp the image to 0-1. If the file extension is `PNG` of `JPEG`,
13
#'this is forced to `TRUE`.
14
#'@param write_linear Default `NA`, automatically determined. By default, images will be gamma corrected (write_linear = FALSE) for
15
#' all file types except `EXR` and `DNG` (which are linear formats), unless otherwise specified.
16
#'@param ... Arguments to pass to either `jpeg::writeJPEG`, `png::writePNG`, `libopenexr::write_exr`, or `tiff::writeTIFF`.
17
#'@return A `rayimg` RGBA array.
18
#'@import grDevices
19
#'@export
20
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
21
#'#Write as a png
22
#'tmparr = tempfile(fileext=".png")
23
#'ray_read_image(dragon) |>
24
#'  ray_write_image(tmparr)
25
#'ray_read_image(tmparr) |>
26
#'  plot_image()
27
#'#Write as a JPEG (passing quality arguments via ...)
28
#'tmparr = tempfile(fileext=".jpg")
29
#'ray_read_image(dragon) |>
30
#'  ray_write_image(tmparr, quality = 0.2)
31
#'ray_read_image(tmparr) |>
32
#'  plot_image()
33
#'#Write as a tiff
34
#'tmparr = tempfile(fileext=".tiff")
35
#'ray_read_image(dragon) |>
36
#'  ray_write_image(tmparr)
37
#'ray_read_image(tmparr) |>
38
#'   plot_image()
39
ray_write_image = function(
40
  image,
41
  filename,
42
  clamp = FALSE,
43
  write_linear = NA,
44
  ...
45
) {
4654x
  if (missing(filename)) {
47!
    stop("`filename` must be specified.")
48
  }
4954x
  image = ray_read_image(image) # rayimg RGBA, linear RGB
5054x
  fileext = tolower(tools::file_ext(filename))
5154x
  if (!fileext %in% c("png", "jpeg", "jpg", "tiff", "exr", "dng")) {
52!
    stop(sprintf(
53!
      "File extension (%s) must be one of `png`, `jpeg`, `jpg`, `exr`, `tiff`, or `dng`",
54!
      fileext
55
    ))
56
  }
57
5854x
  if (fileext == "dng") {
591x
    meta = attr(image, "dng")
601x
    if (is.null(meta)) {
61!
      meta = list()
62
    }
631x
    write_dng_cpp(filename, image, meta = meta)
641x
    return(invisible(image))
65
  }
66
67
  # Auto conversion to sRGB/D65 primaries for LDR outputs
6853x
  is_ldr = fileext %in% c("png", "jpeg", "jpg", "tiff")
6953x
  if (is_ldr && length(dim(image)) == 3 && dim(image)[3] >= 3) {
7049x
    cs_from = attr(image, "colorspace")
7149x
    white_curr = attr(image, "white_current")
72
    if (
7349x
      !is.null(cs_from) &&
7449x
        (!identical(cs_from$name, "sRGB") ||
7549x
          any(abs(white_curr - CS_SRGB$white_xyz) > 1e-8))
76
    ) {
7748x
      xyz = apply_color_matrix(image, cs_from$rgb_to_xyz)
7848x
      if (any(abs(white_curr - CS_SRGB$white_xyz) > 1e-8)) {
7948x
        CAT = compute_cat_bradford(white_curr, CS_SRGB$white_xyz)
8048x
        xyz = apply_color_matrix(xyz, CAT)
81
      }
8248x
      image = apply_color_matrix(xyz, CS_SRGB$xyz_to_rgb)
8348x
      image[,, 1:3][image[,, 1:3] < 0] = 0
84
      # Update attributes to reflect new working space at write boundary
8548x
      attr(image, "colorspace") = CS_SRGB
8648x
      attr(image, "white_current") = CS_SRGB$white_xyz
87
    }
88
  }
89
90
  # Clamp for integer formats
9153x
  if (clamp || fileext %in% c("png", "jpeg", "jpg", "tiff")) {
9249x
    image = render_clamp(image)
93
  }
94
9553x
  if (is.na(write_linear)) {
96
    # LDR formats default to gamma-encoded; EXR stays linear
9752x
    write_linear = !(fileext %in% c("png", "jpeg", "jpg", "tiff"))
98
  }
99
10053x
  is_matrix = length(dim(image)) == 2
10153x
  if (is_matrix) {
102!
    if (!write_linear) image = to_srgb(image)
103
  } else {
10453x
    max_dim = dim(image)[3L]
10553x
    has_alpha = max_dim %in% c(2L, 4L)
10653x
    col_dims = if (has_alpha) seq_len(max_dim - 1L) else seq_len(max_dim)
107
10853x
    if (has_alpha) {
10950x
      alpha_channel = image[,, max_dim]
11050x
      alpha_channel[alpha_channel > 1] = 1
11150x
      alpha_channel[alpha_channel < 0] = 0
11250x
      image[,, max_dim] = alpha_channel
113
    }
11453x
    if (!write_linear) {
11548x
      image[,, col_dims] = to_srgb(image[,, col_dims]) # OETF only on RGB
116
    }
117
  }
118
11953x
  if (fileext %in% c("jpeg", "jpg")) {
1202x
    jpeg::writeJPEG(image, target = filename, ...)
12151x
  } else if (fileext == "png") {
12245x
    png::writePNG(image, target = filename, ...)
1236x
  } else if (fileext == "exr") {
1244x
    if (!.libopenexr_available()) {
1251x
      stop(
1261x
        "The 'libopenexr' package is required to write EXR files.",
1271x
        call. = FALSE
128
      )
129
    }
1303x
    dots = list(...)
1313x
    user_metadata = dots$metadata
1323x
    dots$metadata = NULL
1333x
    rgba = array(1, dim = c(dim(image)[1:2], 4))
1343x
    if (is_matrix) {
135!
      rgba[,, 1:3] = image
1363x
    } else if (dim(image)[3] == 1) {
137!
      rgba[,, 1:3] = image[,, 1]
1383x
    } else if (dim(image)[3] == 2) {
139!
      rgba[,, 1] = image[,, 1]
140!
      rgba[,, 2] = image[,, 1]
141!
      rgba[,, 3] = image[,, 1]
142!
      rgba[,, 4] = image[,, 2]
1433x
    } else if (dim(image)[3] == 3) {
1441x
      rgba[,, 1:3] = image[,, 1:3]
1452x
    } else if (dim(image)[3] == 4) {
1462x
      rgba = image
147
    } else {
148!
      stop(
149!
        "EXR output requires a matrix or an array with 1, 2, 3, or 4 channels.",
150!
        call. = FALSE
151
      )
152
    }
1533x
    write_args = list(
1543x
      path = filename,
1553x
      r = rgba[,, 1],
1563x
      g = rgba[,, 2],
1573x
      b = rgba[,, 3],
1583x
      a = rgba[,, 4]
159
    )
1603x
    metadata = exr_metadata_from_rayimg(image, user_metadata)
1613x
    if (libopenexr_supports_metadata()) {
1623x
      write_args$metadata = metadata
163!
    } else if (!is.null(metadata)) {
164!
      warning(
165!
        "Installed libopenexr does not support EXR metadata; writing pixel data only.",
166!
        call. = FALSE
167
      )
168
    }
1693x
    do.call(libopenexr::write_exr, c(write_args, dots))
170
  } else {
1712x
    tiff::writeTIFF(image, where = filename, ...)
172
  }
173
174
  # return the (possibly converted/encoded) rayimg invisibly
17552x
  invisible(image)
176
}
1
#' @title Render Vibrance
2
#'
3
#' @description
4
#' Adjusts image vibrance (adaptive saturation), similar in spirit to the iPhone "Vibrance" control:
5
#' it boosts muted colors more than already-saturated colors, and reduces saturation more strongly
6
#' in already-saturated regions when negative. Works on HDR arrays as well (values can exceed 1).
7
#'
8
#' @param image Image filename, 3-layer RGB array, 4-layer RGBA array, or matrix. If a filename,
9
#' it will be read via `ray_read_image()`.
10
#' @param vibrance Default `0`. Numeric scalar in -1..1 (values are clamped). Positive values
11
#' increase vibrance primarily in low-saturation regions; negative values decrease vibrance primarily
12
#' in high-saturation regions.
13
#' @param protect_luminance Default `0.25`. Numeric scalar in 0..1. Reduces the vibrance effect
14
#' in deep shadows and bright highlights to avoid harsh color shifts. Set to `0` to disable.
15
#' @param filename Default `NULL`. If not `NULL`, the processed image will be written to this file.
16
#' @param preview Default `FALSE`. Whether to plot the processed image.
17
#'
18
#' @return 4-layer RGBA array (or matrix if passed a matrix and `ray_read_image()` is not used).
19
#' @export
20
#'
21
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
22
#'   dragon |>
23
#'     render_vibrance(vibrance = 0.4, preview = TRUE)
24
render_vibrance = function(
25
  image,
26
  vibrance = 0,
27
  protect_luminance = 0.25,
28
  filename = NULL,
29
  preview = FALSE
30
) {
31!
  if (length(vibrance) != 1 || !is.numeric(vibrance) || !is.finite(vibrance)) {
32!
    stop("`vibrance` must be a single finite numeric value.")
33
  }
34
  if (
35!
    length(protect_luminance) != 1 ||
36!
      !is.numeric(protect_luminance) ||
37!
      !is.finite(protect_luminance)
38
  ) {
39!
    stop("`protect_luminance` must be a single finite numeric value.")
40
  }
41!
  if (protect_luminance < 0 || protect_luminance > 1) {
42!
    stop("`protect_luminance` must be in [0,1].")
43
  }
44
45!
  vibrance = max(min(vibrance, 1), -1)
46
47!
  temp_image = ray_read_image(image, reset_camera_settings = TRUE) # returns RGBA array in rayimage
48
49!
  nr = dim(temp_image)[1]
50!
  nc = dim(temp_image)[2]
51
52!
  r = as.vector(temp_image[,, 1])
53!
  g = as.vector(temp_image[,, 2])
54!
  b = as.vector(temp_image[,, 3])
55
56!
  na_mask = is.na(r) | is.na(g) | is.na(b)
57!
  if (any(na_mask)) {
58!
    r[na_mask] = 0
59!
    g[na_mask] = 0
60!
    b[na_mask] = 0
61
  }
62
63
  # Avoid negative values breaking HSV math; keep HDR highs intact.
64!
  r = pmax(r, 0)
65!
  g = pmax(g, 0)
66!
  b = pmax(b, 0)
67
68!
  maxc = pmax(r, pmax(g, b))
69!
  minc = pmin(r, pmin(g, b))
70!
  delta = maxc - minc
71
72!
  v = maxc
73!
  s = rep(0, length(v))
74!
  nz = maxc > 0
75!
  s[nz] = delta[nz] / maxc[nz]
76
77!
  h = rep(0, length(v))
78!
  idx = delta > 0
79
80!
  if (any(idx)) {
81!
    idx_r = idx & (maxc == r)
82!
    idx_g = idx & (maxc == g) & !idx_r
83!
    idx_b = idx & (maxc == b) & !(idx_r | idx_g)
84
85!
    if (any(idx_r)) {
86!
      h[idx_r] = (g[idx_r] - b[idx_r]) / delta[idx_r]
87!
      h[idx_r][h[idx_r] < 0] = h[idx_r][h[idx_r] < 0] + 6
88
    }
89!
    if (any(idx_g)) {
90!
      h[idx_g] = (b[idx_g] - r[idx_g]) / delta[idx_g] + 2
91
    }
92!
    if (any(idx_b)) {
93!
      h[idx_b] = (r[idx_b] - g[idx_b]) / delta[idx_b] + 4
94
    }
95!
    h[idx] = h[idx] / 6
96!
    h = h - floor(h) # wrap into [0,1)
97
  }
98
99!
  if (protect_luminance > 0) {
100!
    v01 = pmin(v, 1)
101!
    w = 1 - protect_luminance * abs(2 * v01 - 1)
102!
    w = pmax(w, 0)
103
  } else {
104!
    w = 1
105
  }
106
107!
  if (vibrance >= 0) {
108!
    s2 = s + vibrance * (1 - s) * w
109
  } else {
110!
    s2 = s + vibrance * s * w
111
  }
112!
  s2 = pmin(pmax(s2, 0), 1)
113
114
  # HSV -> RGB (vectorized), preserving HDR v
115!
  r2 = v
116!
  g2 = v
117!
  b2 = v
118
119!
  sat = s2
120!
  idx_sat = sat > 0
121
122!
  if (any(idx_sat)) {
123!
    h6 = h * 6
124!
    i = floor(h6)
125!
    f = h6 - i
126
127!
    p = v * (1 - sat)
128!
    q = v * (1 - sat * f)
129!
    t = v * (1 - sat * (1 - f))
130
131!
    im = i %% 6
132
133!
    k0 = idx_sat & (im == 0)
134!
    k1 = idx_sat & (im == 1)
135!
    k2 = idx_sat & (im == 2)
136!
    k3 = idx_sat & (im == 3)
137!
    k4 = idx_sat & (im == 4)
138!
    k5 = idx_sat & (im == 5)
139
140!
    if (any(k0)) {
141!
      r2[k0] = v[k0]
142!
      g2[k0] = t[k0]
143!
      b2[k0] = p[k0]
144
    }
145!
    if (any(k1)) {
146!
      r2[k1] = q[k1]
147!
      g2[k1] = v[k1]
148!
      b2[k1] = p[k1]
149
    }
150!
    if (any(k2)) {
151!
      r2[k2] = p[k2]
152!
      g2[k2] = v[k2]
153!
      b2[k2] = t[k2]
154
    }
155!
    if (any(k3)) {
156!
      r2[k3] = p[k3]
157!
      g2[k3] = q[k3]
158!
      b2[k3] = v[k3]
159
    }
160!
    if (any(k4)) {
161!
      r2[k4] = t[k4]
162!
      g2[k4] = p[k4]
163!
      b2[k4] = v[k4]
164
    }
165!
    if (any(k5)) {
166!
      r2[k5] = v[k5]
167!
      g2[k5] = p[k5]
168!
      b2[k5] = q[k5]
169
    }
170
  }
171
172!
  if (any(na_mask)) {
173!
    r2[na_mask] = NA_real_
174!
    g2[na_mask] = NA_real_
175!
    b2[na_mask] = NA_real_
176
  }
177
178!
  temp_image[,, 1] = matrix(r2, nrow = nr, ncol = nc)
179!
  temp_image[,, 2] = matrix(g2, nrow = nr, ncol = nc)
180!
  temp_image[,, 3] = matrix(b2, nrow = nr, ncol = nc)
181
182!
  handle_image_output(temp_image, filename = filename, preview = preview)
183
}
1
#'@title Plot Image Grid
2
#'
3
#'@description Displays the image in the current device.
4
#'
5
#'@param input_list List of 3-layer RGB/4-layer RGBA array, `rayimg` class, or image filenames.
6
#'@param dim Default `c(1,1)`. Width by height of output grid.
7
#'@param asp Default `1`. Aspect ratio of the pixels(s). For example, an aspect ratio of `4/3` will
8
#'slightly widen the image. This can also be a vector the same length of
9
#'`input_list` to specify an aspect ratio for each image in the grid.
10
#'@param draw_grid Default `FALSE`. If `TRUE`, this will draw a grid in the background to help
11
#'disambiguate the actual image from the device (helpful if the image background is the same as the
12
#'device's background).
13
#'@param gp A `grid::gpar()` object to include for the grid viewport displaying the image.
14
#'@export
15
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
16
#'#Plot the dragon array
17
#'plot_image_grid(list(dragon, 1-dragon), dim = c(1,2))
18
#'plot_image_grid(list(dragon, 1-dragon), dim = c(2,1))
19
#'plot_image_grid(list(dragon, NULL, 1-dragon), dim = c(2,2), asp = c(2,1,1/2))
20
#'plot_image_grid(list(dragon, NULL, NULL, dragon), dim = c(2,2), asp = c(2,1,1,1/2))
21
#'#Plot alongside the depth matrix
22
#'dragon_depth_reoriented = render_reorient(dragondepth,
23
#'                                          transpose = TRUE,
24
#'                                          flipx = TRUE)/2000
25
#'plot_image_grid(list(dragondepth/2000, dragon, dragon, dragondepth/2000),
26
#'                dim = c(2,2))
27
plot_image_grid = function(
28
  input_list,
29
  dim = c(1, 1),
30
  asp = 1,
31
  draw_grid = FALSE,
32
  gp = grid::gpar()
33
) {
34!
  if (length(dim) != 2) {
35!
    stop("length of `dim` argument must equal 2")
36
  }
37!
  if (!inherits(input_list, "list")) {
38!
    stop("`input_list` must be a list of image arrays")
39
  }
40
41!
  if (length(asp) == 1) {
42!
    asp = rep(asp, length(input_list))
43!
  } else if (length(asp) != length(input_list)) {
44!
    stop(sprintf(
45!
      "length of `asp` (%i) not equal to length of `input_list` (%i) or length-1",
46!
      length(asp),
47!
      length(input_list)
48
    ))
49
  }
50
51!
  if (length(input_list) > dim[1] * dim[2]) {
52!
    warning(sprintf(
53!
      "`input_list` of length %i, but grid only has %ix%i=%i slots: truncating list of images",
54!
      length(input_list),
55!
      dim[1],
56!
      dim[2],
57!
      dim[1] * dim[2]
58
    ))
59!
    input_list = input_list[seq_len(dim[1] * dim[2])]
60
  }
61
62!
  grid::grid.newpage()
63
64
  # optional background grid — push, draw, then pop
65!
  if (draw_grid) {
66!
    grid::pushViewport(
67!
      grid::viewport(layout = grid::grid.layout(1, 1), name = "ray_bg_grid")
68
    )
69!
    grid_density = 0.01
70!
    for (i in seq(-2, 2, by = grid_density)) {
71!
      grid::grid.lines(
72!
        x = c(0, 1),
73!
        y = c(i, i + 1),
74!
        default.units = "npc",
75!
        gp = grid::gpar(col = "grey")
76
      )
77!
      grid::grid.lines(
78!
        x = c(0, 1),
79!
        y = c(i, i - 1),
80!
        default.units = "npc",
81!
        gp = grid::gpar(col = "grey")
82
      )
83
    }
84!
    grid::upViewport() # pop "ray_bg_grid"
85
  }
86
87
  # parent layout viewport
88!
  grid::pushViewport(grid::viewport(
89!
    name = "ray_image_grid",
90!
    layout = grid::grid.layout(nrow = dim[1], ncol = dim[2]),
91!
    gp = gp
92
  ))
93!
  on.exit(
94
    {
95
      # ensure we fully unwind no matter what
96!
      try(grid::upViewport(0), silent = TRUE)
97
    },
98!
    add = TRUE
99
  )
100
101!
  layout_idx = data.frame(
102!
    y = rep(seq_len(dim[1]), each = dim[2]),
103!
    x = rep(seq_len(dim[2]), dim[1])
104
  )
105
106!
  for (i in seq_len(length(input_list))) {
107
    # enter the parent (in case caller changed current vp)
108!
    grid::seekViewport("ray_image_grid")
109
    # push cell viewport, draw, then pop it
110!
    grid::pushViewport(grid::viewport(
111!
      layout.pos.row = layout_idx$y[i],
112!
      layout.pos.col = layout_idx$x[i],
113!
      name = sprintf("ray_cell_%i_%i", layout_idx$x[i], layout_idx$y[i]),
114!
      gp = gp
115
    ))
116!
    if (!is.null(input_list[[i]])) {
117!
      rayimage::plot_image(input_list[[i]], asp = asp[i], new_page = FALSE)
118
    }
119!
    grid::upViewport() # pop cell
120
  }
121
122!
  grid::upViewport() # pop "ray_image_grid"
123!
  invisible(NULL)
124
}
1
#'@title Read Image
2
#'
3
#'@description Reads an image from a file/array/matrix. From files, supports
4
#'`JPEG`, `PNG`, `TIFF`, `TGA`, `BMP`, `PSD`, `GIF`, `HDR`, `PIC`, `PNM`, `EXR`,
5
#'and `DNG` images.
6
#'
7
#' @param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
8
#' @param convert_to_array Default `FALSE`. Whether to convert 2D B&W images/matrices to RGBA arrays.
9
#' @param preview Default `FALSE`. If `TRUE`, it will display the image in addition
10
#'to returning it.
11
#' @param source_linear Default `NA`, automatically determined based on the image type.
12
#' Whether the image source is linear data or sRGB. `TRUE` for matrices, arrays, and
13
#' floating-point HDR formats (`EXR`, `HDR`), and `DNG`; `FALSE` for all other file-based formats
14
#' (e.g., `jpeg`, `png`, `tiff`, `tga`, `bmp`, `psd`, `gif`, `pic`, `pnm`).
15
#' @param normalize Default `FALSE`. If `TRUE`, convert to `normalize_to` space on read. Note that
16
#' rayimg inputs will keep their colorspace and ignore this option--use `render_convert_colorspace()`
17
#' to change an existing rayimg to a new colorspace.
18
#' @param dng_normalize Default `FALSE`. If `TRUE`, DNG data is normalized to 0..1,
19
#' using black/white levels; if `FALSE`, raw values are returned.
20
#' @param normalize_to Default `CS_ACESCG`. Target colorspace when `normalize=TRUE`.
21
#' @param normalize_adapt_white Default `TRUE`. If `TRUE`, Bradford-adapt source white to target white.
22
#' @param assume_colorspace Default `NULL`. A colorspace descriptor (e.g., `CS_SRGB`,
23
#'   `CS_ACESCG`). If given, the loaded image will be *tagged* with this space
24
#'   rather than the default inferred by file type. No pixel conversion is performed
25
#'   unless `normalize=TRUE`.
26
#' @param assume_white Default `NULL`. Scene/display white for the loaded image.
27
#'   Either a named white (`"D60","D65","D50","D55","D75","E"`) or XYZ with Y=1.
28
#'   If `NULL`, uses `assume_colorspace$white_xyz`.
29
#' @param reset_camera_settings Default `FALSE`. If `TRUE`, reset informational
30
#'   exposure/ISO metadata to neutral values (`exposure = 0`, `iso = 100`) when
31
#'   wrapping an existing `rayimg` or attributed array.
32
#'
33
#'@param ... Arguments to pass to `jpeg::readJPEG`, `png::readPNG`, `tiff::readTIFF`,
34
#'or `libopenexr::read_exr()` for supported formats.
35
#'
36
#'@return A `rayimg` RGBA array.
37
#'@import grDevices
38
#'@export
39
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
40
#'#Write as a png
41
#'tmparr = tempfile(fileext=".png")
42
#'ray_read_image(dragon) |>
43
#'  ray_write_image(tmparr)
44
#'ray_read_image(tmparr) |>
45
#'  plot_image()
46
#'#Write as a JPEG (passing quality arguments via ...)
47
#'tmparr = tempfile(fileext=".jpg")
48
#'ray_read_image(dragon) |>
49
#'  ray_write_image(tmparr, quality = 0.2)
50
#'ray_read_image(tmparr) |>
51
#'  plot_image()
52
#'#Write as a tiff
53
#'tmparr = tempfile(fileext=".tiff")
54
#'ray_read_image(dragon) |>
55
#'  ray_write_image(tmparr)
56
#'ray_read_image(tmparr) |>
57
#'   plot_image()
58
#'
59
#'#Write as an exr
60
#'tmparr = tempfile(fileext=".exr")
61
#'ray_read_image(dragon) |>
62
#'  ray_write_image(tmparr)
63
#'ray_read_image(tmparr) |>
64
#'   plot_image()
65
ray_read_image = function(
66
  image,
67
  convert_to_array = FALSE,
68
  preview = FALSE,
69
  source_linear = NA,
70
  normalize = FALSE,
71
  dng_normalize = FALSE,
72
  normalize_to = CS_ACESCG,
73
  normalize_adapt_white = TRUE,
74
  assume_colorspace = NULL,
75
  assume_white = NULL,
76
  reset_camera_settings = FALSE,
77
  ...
78
) {
79790x
  decode_if_needed = function(img, linear_flag) {
80395x
    if (isTRUE(linear_flag)) {
81339x
      return(list(image = img, source_linear = TRUE))
82
    }
8356x
    img[is.na(img)] = 0
84
8556x
    if (length(dim(img)) == 3) {
8656x
      if (dim(img)[3] >= 3) {
8756x
        img[,, 1:3] = to_linear(img[,, 1:3])
88
      } else {
89!
        img = to_linear(img)
90
      }
91
    } else {
92!
      img = to_linear(img)
93
    }
9456x
    list(image = img, source_linear = TRUE)
95
  }
96
97790x
  get_wp = function(white_point) {
98398x
    wp = get_whitepoint_xyz(white_point)
99398x
    if (is.null(wp)) {
100!
      return(NULL)
101
    }
102398x
    wp$value
103
  }
104
105790x
  process_image_preview = function(image2) {
106790x
    if (convert_to_array) {
107181x
      image_val = array(1, dim = c(dim(image2)[1:2], 4))
108181x
      if (length(dim(image2)) == 2) {
109!
        image_val[,, 1:3] = image2
110181x
      } else if (length(dim(image2)) == 3) {
111181x
        if (dim(image2)[3] == 2) {
112!
          image_val[,, 1:3] = image2[,, 1]
113!
          image_val[,, 4] = image2[,, 2]
114181x
        } else if (dim(image2)[3] == 3) {
11559x
          image_val[,, 1:3] = image2[,, 1:3]
116122x
        } else if (dim(image2)[3] == 4) {
117122x
          image_val = image2
118
        }
119
      }
120
    } else {
121609x
      image_val = image2
122
    }
123790x
    if (preview) {
124!
      plot_image(image_val)
125
    }
126790x
    image_val
127
  }
128
129790x
  imagetype = if (
130790x
    is.character(image) &&
131790x
      tolower(tools::file_ext(image)) == "dng"
132
  ) {
1331x
    "dng"
134
  } else {
135789x
    get_file_type(image)
136
  }
137790x
  if (is.na(source_linear)) {
138
    # arrays, matrices, and floating-point HDR formats are treated as linear
139587x
    source_linear = imagetype %in% c("array", "matrix", "exr", "hdr", "dng")
140
  }
141
142790x
  finalize_image = function(img, img_type, linear_flag, default_cs) {
143395x
    decoded = decode_if_needed(img, linear_flag)
144395x
    cs = if (!is.null(assume_colorspace)) {
145204x
      assume_colorspace
146
    } else {
147395x
      switch(
148191x
        img_type,
14946x
        png = CS_SRGB,
1502x
        jpg = CS_SRGB,
1512x
        tif = CS_SRGB,
1521x
        tga = CS_SRGB,
1531x
        bmp = CS_SRGB,
1541x
        psd = CS_SRGB,
1551x
        gif = CS_SRGB,
1561x
        pic = CS_SRGB,
1571x
        pnm = CS_SRGB,
1581x
        hdr = CS_ACESCG,
159!
        exr = CS_ACESCG,
160121x
        array = default_cs,
16112x
        matrix = default_cs,
1621x
        CS_ACESCG
163
      )
164
    }
165395x
    wc = get_wp(if (!is.null(assume_white)) assume_white else cs$white_xyz)
166395x
    ri = rayimg(
167395x
      process_image_preview(decoded$image),
168395x
      filetype = img_type,
169395x
      source_linear = decoded$source_linear,
170395x
      colorspace = cs,
171395x
      white_current = wc,
172395x
      exposure = if (reset_camera_settings) {
17354x
        0
174
      } else {
175341x
        attr(img, "exposure", exact = TRUE)
176
      },
177395x
      iso = if (reset_camera_settings) 100 else attr(img, "iso", exact = TRUE)
178
    )
179395x
    if (normalize) {
180!
      ri = render_convert_colorspace(
181!
        ri,
182!
        from_mats = NA,
183!
        to_mats = normalize_to,
184!
        adapt_white = normalize_adapt_white,
185!
        from_white = NA,
186!
        to_white = normalize_to$white_xyz
187
      )
188
    }
189395x
    ri
190
  }
191
192790x
  if (inherits(image, "rayimg")) {
193391x
    cs_assigned = if (!is.null(assume_colorspace)) {
1943x
      assume_colorspace
195
    } else {
196388x
      attr(image, "colorspace")
197
    }
198391x
    wc_assigned = if (!is.null(assume_white)) {
1993x
      get_wp(assume_white)
200
    } else {
201388x
      attr(image, "white_current")
202
    }
203391x
    ri = rayimg(
204391x
      process_image_preview(image),
205391x
      filetype = attr(image, "filetype"),
206391x
      source_linear = attr(image, "source_linear"),
207391x
      colorspace = cs_assigned,
208391x
      white_current = wc_assigned,
209391x
      exposure = if (reset_camera_settings) {
210211x
        0
211
      } else {
212180x
        attr(image, "exposure", exact = TRUE)
213
      },
214391x
      iso = if (reset_camera_settings) 100 else attr(image, "iso", exact = TRUE)
215
    )
216391x
    return(ri) # no normalization on rayimg here
217
  }
218
219399x
  if (imagetype == "array") {
220263x
    return(finalize_image(image, imagetype, source_linear, CS_ACESCG))
221136x
  } else if (imagetype == "matrix") {
22274x
    if (length(dim(image)) == 3) {
223!
      return(finalize_image(
224!
        image[,, 1],
225!
        imagetype,
226!
        source_linear,
227!
        CS_ACESCG
228
      ))
229
    }
23074x
    return(finalize_image(image, imagetype, source_linear, CS_ACESCG))
23162x
  } else if (imagetype == "dng") {
2321x
    out = read_dng_cpp(image, normalize = dng_normalize)
2331x
    pixels = out$pixels
2341x
    meta = out$meta
235
    if (
2361x
      !is.null(meta$orientation) &&
2371x
        !is.na(meta$orientation) &&
2381x
        meta$orientation != 1
239
    ) {
240!
      orientation = as.integer(meta$orientation)
241!
      flipx = FALSE
242!
      flipy = FALSE
243!
      transpose = FALSE
244!
      if (orientation == 2L) {
245!
        flipx = TRUE
246!
      } else if (orientation == 3L) {
247!
        flipx = TRUE
248!
        flipy = TRUE
249!
      } else if (orientation == 4L) {
250!
        flipy = TRUE
251!
      } else if (orientation == 5L) {
252!
        transpose = TRUE
253!
      } else if (orientation == 6L) {
254!
        flipy = TRUE
255!
        transpose = TRUE
256!
      } else if (orientation == 7L) {
257!
        flipx = TRUE
258!
        flipy = TRUE
259!
        transpose = TRUE
260!
      } else if (orientation == 8L) {
261!
        flipx = TRUE
262!
        transpose = TRUE
263
      }
264!
      if (flipx) {
265!
        pixels = fliplr(pixels)
266
      }
267!
      if (flipy) {
268!
        pixels = flipud(pixels)
269
      }
270!
      if (transpose) {
271!
        if (length(dim(pixels)) == 2) {
272!
          pixels = t(pixels)
273
        } else {
274!
          pixels = aperm(pixels, c(2, 1, 3))
275
        }
276!
        if (!is.null(meta$width) && !is.null(meta$height)) {
277!
          tmp_dim = meta$width
278!
          meta$width = meta$height
279!
          meta$height = tmp_dim
280
        }
281
      }
282!
      if (!is.null(meta$cfa_pattern)) {
283!
        cfa = meta$cfa_pattern
284!
        if (flipx) {
285!
          cfa = cfa[, 2:1, drop = FALSE]
286
        }
287!
        if (flipy) {
288!
          cfa = cfa[2:1, , drop = FALSE]
289
        }
290!
        if (transpose) {
291!
          cfa = t(cfa)
292
        }
293!
        meta$cfa_pattern = cfa
294
      }
295!
      meta$orientation = 1L
296
    }
2971x
    attr(pixels, "dng") = meta
2981x
    if (!is.na(source_linear) && !source_linear) {
299!
      pixels = decode_if_needed(pixels, source_linear)$image
300
    }
3011x
    return(finalize_image(pixels, "dng", TRUE, CS_ACESCG))
30261x
  } else if (imagetype == "png") {
30346x
    image = png::readPNG(image, ...)
30446x
    return(finalize_image(image, imagetype, source_linear, CS_SRGB))
30515x
  } else if (imagetype == "tif") {
3062x
    image = tiff::readTIFF(image, ...)
3072x
    return(finalize_image(image, imagetype, source_linear, CS_SRGB))
30813x
  } else if (imagetype == "jpg") {
3092x
    image = jpeg::readJPEG(image, ...)
3102x
    return(finalize_image(image, imagetype, source_linear, CS_SRGB))
31111x
  } else if (imagetype == "hdr") {
3121x
    image = read_image_stb(image, desired_channels = 4L)
3131x
    return(finalize_image(image, imagetype, source_linear, CS_ACESCG))
31410x
  } else if (imagetype %in% c("tga", "bmp", "psd", "gif", "pic", "pnm")) {
3156x
    image = read_image_stb(image, desired_channels = 4L)
3166x
    return(finalize_image(image, imagetype, source_linear, CS_SRGB))
3174x
  } else if (imagetype == "exr") {
3184x
    if (length(find.package("libopenexr", quiet = TRUE)) > 0) {
3194x
      tmp = libopenexr::read_exr(image, ...)
3204x
      metadata = tmp$metadata
3214x
      exr_colorspace = colorspace_from_exr_metadata(metadata)
3224x
      exr_white_current = white_current_from_exr_metadata(metadata)
3234x
      colorspace = if (!is.null(assume_colorspace)) {
324!
        assume_colorspace
3254x
      } else if (!is.null(exr_colorspace)) {
3262x
        exr_colorspace
327
      } else {
3282x
        CS_ACESCG
329
      }
3304x
      white_current = if (!is.null(assume_white)) {
331!
        get_wp(assume_white)
3324x
      } else if (!is.null(exr_white_current)) {
3332x
        exr_white_current
334
      } else {
3352x
        colorspace$white_xyz
336
      }
3374x
      image = array(1, dim = c(tmp$height, tmp$width, 4))
3384x
      image[,, 1] = tmp$r
3394x
      image[,, 2] = tmp$g
3404x
      image[,, 3] = tmp$b
3414x
      ri = rayimg(
3424x
        process_image_preview(image),
3434x
        filetype = imagetype,
3444x
        source_linear = TRUE,
3454x
        colorspace = colorspace,
3464x
        white_current = white_current
347
      )
3484x
      if (is.list(metadata) && length(metadata) > 0L) {
3492x
        preserved_metadata = preserved_exr_metadata(metadata)
3502x
        if (!is.null(preserved_metadata)) {
3511x
          attr(ri, "exr") = preserved_metadata
352
        }
353
      }
3544x
      if (normalize) {
355!
        ri = render_convert_colorspace(
356!
          ri,
357!
          from_mats = NA,
358!
          to_mats = normalize_to,
359!
          adapt_white = normalize_adapt_white,
360!
          from_white = NA,
361!
          to_white = normalize_to$white_xyz
362
        )
363
      }
3644x
      return(ri)
365
    } else {
366!
      stop("The 'libopenexr' package is required for EXR support.")
367
    }
368
  } else {
369!
    stop("Unsupported/unknown input type.")
370
  }
371
}
1
#' @title Render Tonemap
2
#'
3
#' @description Reinhard / Uncharted(Hable) / HBD operators in linear
4
#'
5
#' @param image Default `NULL`. 3/4-channel array, `rayimg`, or filename.
6
#' @param method Default `raw`. One of `"raw"`, `"reinhard"`, `"uncharted"`, `"hbd"`.
7
#' Chooses the global tone-mapping curve. `"raw"` leaves the image unchanged.
8
#' `"reinhard"` applies a classic shoulder that gently compresses highlights.
9
#' `"uncharted"` (Hable filmic) gives a film-style toe/shoulder and keeps mid-tones contrasty.
10
#' `"hbd"` is a fast filmic-like curve with a soft toe/shoulder.
11
#' All methods operate on **linear RGB** and return **display-referred linear** (no OETF).
12
#' @param exposure_bias Default `2`. Only for `"uncharted"`.
13
#' Scalar applied to the linear RGB channels **before** the Uncharted/Hable curve
14
#' (i.e., a pre-curve exposure gain). Values >1 brighten; <1 darken.
15
#' `exposure_bias=2` is about +1 stop; `0.5` is about -1 stop.
16
#' @param W Default `11.2`. White (linear scene value) that maps to 1.0 **after**
17
#' the Uncharted/Hable/Reinhard curve. Acts like a “white point” for the shoulder: larger values
18
#' preserve more highlight detail (later roll-off), smaller values roll off earlier and harder.
19
#' @param filename Default `NULL`. Output path.
20
#' @param preview Default `FALSE`. Show result.
21
#' @return A `rayimg` RGBA array.
22
#' @export
23
#' @examples
24
#' # Plot unchanged image
25
#' render_tonemap(dragon, preview = TRUE)
26
#' # Plot Reinhard tonemapped image
27
#' render_tonemap(dragon, method = "reinhard", preview = TRUE)
28
#' # Plot Uncharted/Hable tonemapped image
29
#' render_tonemap(dragon, method = "uncharted",preview = TRUE)
30
#' # Plot Uncharted/Hable tonemapped image, white point adjusted
31
#' render_tonemap(dragon, method = "uncharted", W=11.4, preview = TRUE)
32
#' # Plot Uncharted/Hable tonemapped image, exposure adjusted
33
#' render_tonemap(dragon, method = "uncharted", exposure_bias = 1,preview = TRUE)
34
#' # Plot Hejl-Burgess-Dawson tonemapped image, exposure adjusted
35
#' render_tonemap(dragon, method = "hbd",preview = TRUE)
36
render_tonemap = function(
37
  image,
38
  method = c("raw", "reinhard", "uncharted", "hbd"),
39
  exposure_bias = 2.0,
40
  W = 11.2,
41
  filename = NULL,
42
  preview = FALSE
43
) {
442x
  method = match.arg(method)
452x
  src = ray_read_image(
462x
    image,
472x
    convert_to_array = TRUE,
482x
    reset_camera_settings = TRUE
49
  )
502x
  imagetype = attr(src, "filetype")
512x
  img_source_linear = attr(src, "source_linear")
522x
  colorspace = attr(src, "colorspace")
532x
  white_current = attr(src, "white_current")
54
552x
  colorspace_luminance_row = attr(src, "colorspace")$rgb_to_xyz[2, ]
562x
  d = dim(src)
572x
  if (length(d) != 3) {
58!
    return(src)
59
  }
60
612x
  rgb = src[,, 1:3]
62
632x
  if (method == "reinhard") {
64!
    eps = 1e-6
65!
    lw = colorspace_luminance_row
66
67!
    L = lw[1] * rgb[,, 1] + lw[2] * rgb[,, 2] + lw[3] * rgb[,, 3]
68
69!
    a = 0.18
70!
    L_log_avg = exp(mean(log(pmax(L, eps))))
71
72!
    Lm = (a / L_log_avg) * L
73!
    Lwhite = W #White point
74!
    Ld = (Lm * (1 + (Lm / (Lwhite * Lwhite)))) / (1 + Lm)
75
76!
    scale = Ld / pmax(L, eps)
77
78!
    rgb[,, 1] = rgb[,, 1] * scale
79!
    rgb[,, 2] = rgb[,, 2] * scale
80!
    rgb[,, 3] = rgb[,, 3] * scale
812x
  } else if (method == "uncharted") {
82!
    A = 0.15
83!
    B = 0.50
84!
    C = 0.10
85!
    D = 0.20
86!
    E = 0.02
87!
    F = 0.30
88!
    eps = 1e-6
89
90!
    lw = colorspace_luminance_row
91!
    L = lw[1] * rgb[,, 1] + lw[2] * rgb[,, 2] + lw[3] * rgb[,, 3]
92
93
    # Key normalization
94!
    a = 0.18
95!
    L_log_avg = exp(mean(log(pmax(L, eps))))
96!
    pre_key = a / L_log_avg
97
98!
    hable = function(x) {
99!
      ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F) - E / F)
100
    }
101
102!
    e = exposure_bias
103!
    whiteScale = 1 / hable(e * W)
104
105!
    Lm = e * pre_key * L
106!
    Ld = hable(Lm) * whiteScale
107!
    scale = Ld / pmax(L, eps)
108
109!
    rgb[,, 1] = rgb[,, 1] * scale
110!
    rgb[,, 2] = rgb[,, 2] * scale
111!
    rgb[,, 3] = rgb[,, 3] * scale
1122x
  } else if (method == "hbd") {
1131x
    for (k in 1:3) {
1143x
      x = pmax(rgb[,, k] - 0.004, 0)
1153x
      encoded = (x * (6.2 * x + 0.5)) / (x * (6.2 * x + 1.7) + 0.06)
116
      # HBD includes display encoding. Return linear pixels, like the other
117
      # operators, so plotting and writing apply the display transfer once.
1183x
      rgb[,, k] = to_linear(encoded)
119
    }
120
  } else {
121
    # Nothing
122
  }
123
1242x
  out = src
1252x
  out[,, 1:3] = rgb
126
1272x
  out = ray_read_image(
1282x
    out,
1292x
    filetype = imagetype,
1302x
    source_linear = img_source_linear,
1312x
    assume_colorspace = colorspace,
1322x
    assume_white = white_current
133
  )
1342x
  handle_image_output(out, filename = filename, preview = preview)
135
}
1
#' Print method for rayimg
2
#'
3
#' Displays the working colorspace and non-neutral camera metadata alongside a numeric preview.
4
#'
5
#' @param x Default `NULL`. A `rayimg` object.
6
#' @param preview_n Default `10`. Max rows/cols to display in numeric preview.
7
#' @param decimals Default `3`. Number of decimal places to display in numeric preview.
8
#' @param color Default `TRUE`. Colorize headers and R/G/B/A numeric cells when supported.
9
#' @param ... Default ``. Ignored.
10
#'
11
#' @return Invisibly returns `x`.
12
#' @export
13
print.rayimg = function(
14
  x = NULL,
15
  preview_n = 10,
16
  decimals = 3,
17
  color = TRUE,
18
  ...
19
) {
2074x
  ft = attr(x, "filetype")
2174x
  if (is.null(ft)) {
22!
    ft = "unknown"
23
  }
2474x
  d = dim(x)
2574x
  image_type = attr(x, "filetype")
2674x
  exposure_attr = rayimg_exposure_value(attr(x, "exposure", exact = TRUE))
2774x
  iso_attr = rayimg_iso_value(attr(x, "iso", exact = TRUE))
28
2974x
  opt_override = getOption("rayimage.color", NA)
3074x
  want_color = isTRUE(color) && !isFALSE(opt_override)
3174x
  have_cli = want_color && requireNamespace("cli", quietly = TRUE)
3274x
  can_color = have_cli &&
3374x
    isTRUE(cli::num_ansi_colors() >= 8) &&
3474x
    isTRUE(cli::is_dynamic_tty()) &&
3574x
    !isTRUE(getOption("knitr.in.progress")) &&
3674x
    !isTRUE(getOption("testthat.in_progress"))
3774x
  truecolor_ok = rayimg_truecolor_supported()
38
3974x
  style_bold = function(z) if (can_color) cli::style_bold(z) else z
4074x
  col_magenta = function(z) if (can_color) cli::col_magenta(z) else z
4174x
  col_yellow = function(z) if (can_color) cli::col_yellow(z) else z
4274x
  col_cyan = function(z) if (can_color) cli::col_cyan(z) else z
4374x
  col_silver = function(z) if (can_color) cli::col_silver(z) else z
4474x
  col_red = function(z) if (can_color) cli::col_red(z) else z
4574x
  col_green = function(z) if (can_color) cli::col_green(z) else z
4674x
  col_blue = function(z) if (can_color) cli::col_blue(z) else z
47
4874x
  print_camera_settings = function() {
4974x
    if (
5074x
      isTRUE(all.equal(exposure_attr, 0)) && isTRUE(all.equal(iso_attr, 100))
51
    ) {
5273x
      return(invisible(NULL))
53
    }
541x
    cat(
55
      "  ",
561x
      col_silver("Exposure: "),
571x
      col_cyan(sprintf("%+.3g EV", exposure_attr)),
58
      "  ",
591x
      col_silver("ISO: "),
601x
      col_cyan(format(iso_attr, trim = TRUE, scientific = FALSE)),
611x
      "\n",
621x
      sep = ""
63
    )
641x
    invisible(NULL)
65
  }
66
6774x
  hell = if (
6874x
    requireNamespace("cli", quietly = TRUE) &&
6974x
      isTRUE(cli::is_utf8_output())
70
  ) {
71!
    cli::symbol$ellipsis
72
  } else {
73
    "..."
74
  }
7574x
  vell = rayimg_vertical_ellipsis(TRUE)
76
77
  # Vector fallback
7874x
  if (is.null(d)) {
79!
    cat(
80!
      col_magenta(style_bold("<rayimg>")),
81
      " ",
82!
      col_silver(sprintf("[length %d]", length(x))),
83
      " ",
84!
      col_yellow("<vector>"),
85
      "  ",
86!
      "filetype: ",
87!
      col_cyan(ft),
88!
      "\n",
89!
      sep = ""
90
    )
91!
    print_camera_settings()
92!
    y_plain = formatC(as.numeric(x), format = "f", digits = decimals)
93!
    print(y_plain, quote = FALSE, right = TRUE)
94!
    return(invisible(x))
95
  }
96
9774x
  h = d[1]
9874x
  w = d[2]
9974x
  c = if (length(d) >= 3) d[3] else 1L
100
10174x
  chan_labels = attr(x, "channels")
102
10374x
  if (!length(chan_labels)) {
104!
    chan_labels = rayimg_detect_channels(x)
105
  }
106
10774x
  type_str = paste0(chan_labels, collapse = " + ")
108
10974x
  cat(
11074x
    col_magenta(style_bold("<rayimg>")),
111
    " ",
11274x
    col_silver(sprintf(
11374x
      "[%d x %d%s]",
11474x
      h,
11574x
      w,
11634x
      if (c > 1) paste0(" x ", c) else ""
117
    )),
118
    " ",
11974x
    col_yellow(paste0("<", type_str, ">")),
120
    "  ",
12174x
    "filetype: ",
12274x
    col_cyan(ft),
12374x
    "  Linear Data: ",
12474x
    col_green(as.character(attr(x, "source_linear"))),
12574x
    "\n",
12674x
    sep = ""
127
  )
12874x
  cs_attr = attr(x, "colorspace")
12974x
  white_attr = attr(x, "white_current")
130
13174x
  describe_colorspace = function(cs) {
13274x
    if (!is.list(cs)) {
133!
      return("unknown")
134
    }
13574x
    nm = cs$name
13674x
    if (is.null(nm) || length(nm) != 1L) {
137!
      nm = "unknown"
138
    }
13974x
    desc = as.character(nm)
14074x
    wn = cs$white_name
14174x
    if (!is.null(wn) && length(wn) == 1L) {
14274x
      desc = paste0(desc, " (white ", wn, ")")
143
    }
14474x
    desc
145
  }
14674x
  describe_white = function(white_vec) {
14774x
    if (
14874x
      is.numeric(white_vec) &&
14974x
        length(white_vec) == 3L &&
15074x
        all(is.finite(white_vec))
151
    ) {
15274x
      paste0(
153
        "[",
15474x
        paste(
15574x
          formatC(as.numeric(white_vec), format = "f", digits = 5),
15674x
          collapse = ", "
157
        ),
158
        "]"
159
      )
160
    } else {
161!
      "unknown"
162
    }
163
  }
16474x
  cs_desc = describe_colorspace(cs_attr)
16574x
  white_desc = describe_white(white_attr)
16674x
  white_col = if (identical(white_desc, "unknown")) col_silver else col_blue
167
16874x
  cat(
169
    "  ",
17074x
    col_silver("Working colorspace: "),
17174x
    col_blue(cs_desc),
172
    "  ",
17374x
    col_silver("White XYZ: "),
17474x
    white_col(white_desc),
17574x
    "\n",
17674x
    sep = ""
177
  )
17874x
  print_camera_settings()
179
180
  # Numeric preview
18174x
  rmax = min(h, preview_n)
18274x
  cmax = min(w, preview_n)
18374x
  more_rows = h > preview_n
18474x
  more_cols = w > preview_n
18574x
  if (more_rows || more_cols) {
18637x
    msg = sprintf(
18737x
      "showing [1:%d, 1:%d]%s plus last row/col",
18837x
      rmax,
18937x
      cmax,
19037x
      if (c > 1) ", all channels" else ""
191
    )
19237x
    cat(col_silver(msg), "\n", sep = "")
193
  }
194
19574x
  ux = unclass(x)
196
197
  # Alpha analysis based on displayed labels; get physical alpha plane correctly
19874x
  has_alpha = "Alpha" %in% chan_labels
19974x
  suppress_alpha = FALSE
20074x
  alpha_idx = -1
20174x
  if (has_alpha && length(dim(ux)) > 2) {
20218x
    alpha_idx = which("Alpha" == chan_labels)
20318x
    aplane = ux[,, alpha_idx, drop = FALSE]
20418x
    alpha_all_one = all(abs(aplane - 1) <= 1e-8, na.rm = TRUE)
20518x
    suppress_alpha = alpha_all_one
206
  }
207
208
  # Colorizers for numeric cells
20974x
  col_fun = function(lbl) {
210126x
    if (!can_color) {
211126x
      return(identity)
212
    }
21374x
    switch(
214!
      lbl,
215!
      "Red" = col_red,
216!
      "Green" = col_green,
217!
      "Blue" = col_blue,
218!
      "Alpha" = col_cyan,
219!
      identity
220
    )
221
  }
22274x
  hdr_col_fun = function(lbl) {
223126x
    if (!can_color) {
224126x
      return(function(z) z)
225
    }
22674x
    switch(
227!
      lbl,
228!
      "Red" = col_red,
229!
      "Green" = col_green,
230!
      "Blue" = col_blue,
231!
      "Alpha" = col_cyan,
232!
      function(z) z
233
    )
234
  }
23574x
  fmt = function(v) formatC(as.numeric(v), format = "f", digits = decimals)
236
23774x
  build_preview_pair = function(mat_numeric, f_color) {
238126x
    mat_numeric = unclass(mat_numeric)
239126x
    if (is.null(dim(mat_numeric))) {
24019x
      print_tl = mat_numeric
241
    } else {
242107x
      print_tl = mat_numeric[seq_len(rmax), seq_len(cmax), drop = TRUE]
243
    }
244126x
    tl_plain = matrix(
245126x
      fmt(print_tl),
246126x
      nrow = rmax,
247126x
      ncol = cmax
248
    )
249126x
    tl_disp = tl_plain
250
251126x
    if (more_cols) {
25231x
      last_col_plain = fmt(mat_numeric[seq_len(rmax), w, drop = TRUE])
25331x
      ell_col_plain = rep(hell, rmax)
25431x
      tl_plain = cbind(tl_plain, ell_col_plain, last_col_plain)
25531x
      tl_disp = cbind(
25631x
        tl_disp,
25731x
        if (can_color) col_silver(ell_col_plain) else ell_col_plain,
25831x
        last_col_plain
259
      )
260
    }
261
262126x
    if (more_rows) {
26346x
      last_row_first_plain = fmt(mat_numeric[h, seq_len(cmax), drop = TRUE])
26446x
      if (more_cols) {
26516x
        last_row_plain = c(
26616x
          last_row_first_plain,
26716x
          hell,
26816x
          fmt(mat_numeric[h, w, drop = TRUE])
269
        )
27016x
        last_row_disp = c(
27116x
          last_row_first_plain,
27216x
          if (can_color) col_silver(hell) else hell,
27316x
          fmt(mat_numeric[h, w, drop = TRUE])
274
        )
275
      } else {
27630x
        last_row_plain = last_row_first_plain
27730x
        last_row_disp = last_row_first_plain
278
      }
27946x
      ell_row_plain = rep(vell, ncol(tl_plain))
28046x
      ell_row_disp = if (can_color) col_silver(ell_row_plain) else ell_row_plain
281
28246x
      tl_plain = rbind(tl_plain, ell_row_plain, last_row_plain)
28346x
      tl_disp = rbind(tl_disp, ell_row_disp, last_row_disp)
284
    }
285
286126x
    cn_base = if (more_cols) {
28731x
      c(
28831x
        paste0("[,", seq_len(cmax), "]"),
28931x
        paste0("[,", hell, "]"),
29031x
        paste0("[,", w, "]")
291
      )
292
    } else {
29395x
      paste0("[,", seq_len(cmax), "]")
294
    }
295126x
    rn_base = if (more_rows) {
29646x
      c(
29746x
        paste0("[", seq_len(rmax), ",]"),
29846x
        paste0("[", vell, ",]"),
29946x
        paste0("[", h, ",]")
300
      )
301
    } else {
30280x
      paste0("[", seq_len(rmax), ",]")
303
    }
304
305126x
    dimnames(tl_plain) = list(rn_base, cn_base)
306126x
    dimnames(tl_disp) = dimnames(tl_plain)
307
308126x
    if (!identical(f_color, identity)) {
309!
      mask_num = !(tl_disp %in% c(hell, vell))
310!
      tl_disp[mask_num] = f_color(tl_disp[mask_num])
311
    }
312
313126x
    list(plain = tl_plain, disp = tl_disp)
314
  }
315
31674x
  print_matrix_ansi = function(mat_plain, mat_disp) {
317126x
    stopifnot(identical(dim(mat_plain), dim(mat_disp)))
318126x
    rn = rownames(mat_plain)
319126x
    cn = colnames(mat_plain)
320126x
    pad = function(s, w) {
32112939x
      vis = if (can_color) {
322!
        cli::ansi_nchar(s, type = "width")
323
      } else {
32412939x
        nchar(s, type = "width")
325
      }
32612939x
      if (vis < w) {
3272966x
        return(paste0(strrep(" ", w - vis), s))
328
      } else {
3299973x
        return(s)
330
      }
331
    }
332126x
    rn_w = max(nchar(rn, type = "width"))
333126x
    col_w = vapply(
334126x
      seq_len(ncol(mat_plain)),
335126x
      function(j) {
3361260x
        max(nchar(c(cn[j], mat_plain[, j]), type = "width"))
337
      },
338126x
      integer(1)
339
    )
340
341126x
    cat(strrep(" ", rn_w + 1))
342126x
    for (j in seq_len(ncol(mat_plain))) {
3431260x
      cat(" ", pad(cn[j], col_w[j]), sep = "")
344
    }
345126x
    cat("\n")
346126x
    for (i in seq_len(nrow(mat_plain))) {
3471034x
      cat(pad(rn[i], rn_w), " ", sep = "")
3481034x
      for (j in seq_len(ncol(mat_plain))) {
34910645x
        cat(" ", pad(mat_disp[i, j], col_w[j]), sep = "")
350
      }
3511034x
      cat("\n")
352
    }
353
  }
354
355
  # ---- 2-D (single-channel) path ----
356
  # This colors slices the appropriate color (e.g. red if it's the red slice)
35774x
  if (length(d) == 2L || c == 1L) {
35834x
    chan_hint = if (length(chan_labels)) chan_labels[1] else "Grayscale"
35934x
    cat(
36034x
      hdr_col_fun(chan_hint)(style_bold(paste0("[", chan_hint, "]"))),
36134x
      "\n",
36234x
      sep = ""
363
    )
36434x
    pair = build_preview_pair(ux, f_color = col_fun(chan_hint))
36534x
    print_matrix_ansi(pair$plain, pair$disp)
36634x
    return(invisible(x))
367
  }
368
36940x
  for (i in seq_along(chan_labels)) {
370108x
    if (has_alpha && suppress_alpha && i == alpha_idx) {
37116x
      next
372
    }
37392x
    lbl = chan_labels[i]
37492x
    cat(hdr_col_fun(lbl)(style_bold(paste0("[", lbl, "]"))), "\n", sep = "")
37592x
    pair = build_preview_pair(
37692x
      ux[,, i, drop = TRUE],
37792x
      f_color = col_fun(lbl)
378
    )
37992x
    print_matrix_ansi(pair$plain, pair$disp)
380
381
    if (
38292x
      i < length(chan_labels) &&
38392x
        !(suppress_alpha && (i + 1L) == alpha_idx)
384
    ) {
38552x
      cat("\n")
386
    }
387
  }
388
  if (
38940x
    suppress_alpha &&
39040x
      chan_labels[length(chan_labels)] == "Alpha"
391
  ) {
39215x
    cat(col_silver(style_bold("[A] No transparency (layer all 1.0)\n")))
393
  }
394
39540x
  invisible(x)
396
}
1
#' @title Add Transparent Padding
2
#'
3
#' @description Expands an image or matrix canvas by adding constant-value
4
#' padding around the original image.
5
#'
6
#' @param image 3-layer RGB/4-layer RGBA array, `rayimg` class, matrix, or
7
#' filename of an image.
8
#' @param pad Default `10`. Padding in pixels. Use a scalar for equal padding on
9
#' all sides, or `c(top, right, bottom, left)`.
10
#' @param color Default `"black"`. Padding color. Can be a scalar, RGB/RGBA
11
#' numeric vector, or R color string.
12
#' @param alpha Default `NULL`. Padding alpha for images with an alpha channel.
13
#' If `NULL`, uses the alpha channel supplied in `color` when present, otherwise
14
#' defaults to `0` when `color` is omitted and `1` when `color` is supplied.
15
#' Ignored for RGB and matrix inputs.
16
#' @param filename Default `NULL`. File to save the image to. If `NULL` and
17
#' `preview = FALSE`, returns the padded image.
18
#' @param preview Default `FALSE`. If `TRUE`, display the padded image.
19
#'
20
#' @return A padded `rayimg` image or matrix.
21
#' @export
22
#' @rdname render_padding
23
#' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
24
#'render_padding(dragon, pad = 20) |>
25
#'  plot_image()
26
render_padding = function(
27
  image,
28
  pad = 10,
29
  color = "black",
30
  alpha = NULL,
31
  filename = NULL,
32
  preview = FALSE
33
) {
3428x
  if (is.null(image)) {
35!
    stop("`image` must be provided.")
36
  }
37
3828x
  color_missing = missing(color)
3928x
  color = convert_color(color, single = TRUE)
4027x
  color_alpha = if (length(color) >= 4 && !color_missing) {
4124x
    color[4]
42
  } else {
433x
    NULL
44
  }
4527x
  if (is.null(alpha)) {
4612x
    alpha = if (!is.null(color_alpha)) {
4710x
      color_alpha
4812x
    } else if (color_missing) {
492x
      0
50
    } else {
51!
      1
52
    }
53
  }
5427x
  if (!is.numeric(alpha) || length(alpha) != 1 || !is.finite(alpha)) {
55!
    stop("`alpha` must be a finite numeric scalar.")
56
  }
5727x
  if (alpha < 0 || alpha > 1) {
58!
    stop("`alpha` must be in [0,1].")
59
  }
6027x
  pad = normalize_render_padding(pad)
6127x
  pad_values = unname(pad)
62
6327x
  temp_image = ray_read_image(image, convert_to_array = FALSE)
6427x
  image_dim = dim(temp_image)
6527x
  channels = if (length(image_dim) == 2) {
667x
    1L
67
  } else {
6820x
    image_dim[3]
69
  }
7027x
  fill = switch(
7127x
    as.character(channels),
7227x
    `1` = color[1],
7327x
    `2` = c(color[1], alpha),
7427x
    `3` = color[1:3],
7527x
    `4` = c(color[1:3], alpha),
7627x
    stop("`image` must have 1, 2, 3, or 4 channels.")
77
  )
78
7927x
  if (length(image_dim) == 2) {
807x
    output = matrix(
817x
      fill[1],
827x
      nrow = image_dim[1] + pad_values[1] + pad_values[3],
837x
      ncol = image_dim[2] + pad_values[2] + pad_values[4]
84
    )
857x
    output[
867x
      (pad_values[1] + 1):(pad_values[1] + image_dim[1]),
877x
      (pad_values[4] + 1):(pad_values[4] + image_dim[2])
887x
    ] = unclass(temp_image)
89
  } else {
9020x
    output = array(
9120x
      0,
9220x
      dim = c(
9320x
        image_dim[1] + pad_values[1] + pad_values[3],
9420x
        image_dim[2] + pad_values[2] + pad_values[4],
9520x
        image_dim[3]
96
      )
97
    )
9820x
    for (i in seq_len(image_dim[3])) {
9980x
      output[,, i] = fill[i]
100
    }
10120x
    output[
10220x
      (pad_values[1] + 1):(pad_values[1] + image_dim[1]),
10320x
      (pad_values[4] + 1):(pad_values[4] + image_dim[2]),
10420x
      seq_len(image_dim[3])
10520x
    ] = unclass(temp_image)
106
  }
107
10827x
  output = rayimg(
10927x
    output,
11027x
    filetype = attr(temp_image, "filetype"),
11127x
    source_linear = attr(temp_image, "source_linear"),
11227x
    colorspace = attr(temp_image, "colorspace"),
11327x
    white_current = attr(temp_image, "white_current"),
11427x
    exposure = attr(temp_image, "exposure", exact = TRUE),
11527x
    iso = attr(temp_image, "iso", exact = TRUE)
116
  )
11727x
  attr(output, "padding") = pad
11827x
  handle_image_output(output, filename = filename, preview = preview)
119
}
120
121
#' @keywords internal
122
normalize_render_padding = function(pad) {
12349x
  if (!is.numeric(pad) || !(length(pad) %in% c(1, 4))) {
124!
    stop("`pad` must be a numeric scalar or length-4 vector.")
125
  }
12649x
  if (any(!is.finite(pad)) || any(pad < 0)) {
127!
    stop("`pad` must contain non-negative finite values.")
128
  }
12949x
  pad = as.integer(round(pad))
13049x
  if (length(pad) == 1) {
13129x
    pad = rep(pad, 4)
132
  }
13349x
  names(pad) = c("top", "right", "bottom", "left")
13449x
  pad
135
}
1
#'@title Preview Focus
2
#'
3
#'@description Displays the focal point
4
#'
5
#'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
6
#'@param depthmap Depth map filename or 1d array.
7
#'@param focus Defaults `0.5`. Depth in which to blur. Minimum 0, maximum 1.
8
#'@keywords internal
9
#'@examples
10
#'#Plot the dragon
11
preview_focus = function(image, depthmap, focus, imagetype, depthtype) {
12!
  image = ray_read_image(image) #Always output RGBA array
13
  #Check if file or image before below:
14!
  depthmap = ray_read_image(depthmap, convert_to_array = FALSE)
15!
  if (length(dim(depthmap)) == 3) {
16!
    depthmap = depthmap[,, 1]
17
  }
18
19!
  isimage = max(depthmap, na.rm = TRUE) == 1
20!
  if (isimage) {
21!
    maxval = max(depthmap[depthmap != 1], na.rm = TRUE)
22
  } else {
23!
    maxval = max(depthmap, na.rm = TRUE)
24
  }
25!
  if (isimage) {
26!
    depthmap[depthmap == 1] = maxval
27
  }
28!
  depthrange = range(depthmap, na.rm = TRUE)
29!
  range_depth_high = focus + depthrange[2] / 200
30!
  range_depth_low = focus - depthrange[1] / 200
31!
  if (range_depth_high >= maxval) {
32!
    range_depth_high = range_depth_high - range(depthmap)[2] / 200
33
  }
34
  if (
35!
    any(depthmap < range_depth_high, na.rm = TRUE) &
36!
      any(depthmap > range_depth_low, na.rm = TRUE)
37
  ) {
38!
    image[,, 1][depthmap < range_depth_high & depthmap > range_depth_low] = 1
39!
    image[,, 2][depthmap < range_depth_high & depthmap > range_depth_low] = 0
40!
    image[,, 3][depthmap < range_depth_high & depthmap > range_depth_low] = 0
41!
    message(sprintf("Focal range: %g-%g", depthrange[1], depthrange[2]))
42!
    plot_image(image)
43
  } else {
44!
    message(sprintf(
45!
      "Focus point (%g) not in focal range: %g-%g",
46!
      focus,
47!
      depthrange[1],
48!
      depthrange[2]
49
    ))
50
  }
51
}
1
#' Vertical ellipsis symbol
2
#'
3
#' @param use_cli Default `TRUE`. If `TRUE`, consult `cli::is_utf8_output()` for Unicode support.
4
#' @return vertical ellipses if supported
5
#' @keywords internal
6
rayimg_vertical_ellipsis = function(use_cli = TRUE) {
774x
  have_cli = use_cli && requireNamespace("cli", quietly = TRUE)
874x
  unicode_ok = if (have_cli) {
974x
    isTRUE(cli::is_utf8_output())
10
  } else {
11!
    isTRUE(l10n_info()[["UTF-8"]])
12
  }
13!
  if (unicode_ok) "\u22EE" else "..."
14
}
15
16
#' @keywords internal
17
rayimg_truecolor_supported = function() {
18
  if (!requireNamespace("cli", quietly = TRUE)) {
19
    return(FALSE)
20
  }
21
  dyn = isTRUE(cli::is_dynamic_tty())
22
  utf8 = isTRUE(cli::is_utf8_output())
23
  ncol = cli::num_ansi_colors()
24
  tc = grepl("truecolor|24bit", Sys.getenv("COLORTERM", ""), ignore.case = TRUE)
25
  dyn && utf8 && (tc || isTRUE(ncol >= 256))
26
}
27
28
#' Compose RGB over checkerboard using alpha
29
#' @keywords internal
30
rayimg_composite_checker = function(
31
  rgb,
32
  alpha = NULL,
33
  light = 0.92,
34
  dark = 0.75
35
) {
36!
  d = dim(rgb)
37!
  H = d[1]
38!
  W = d[2]
39!
  if (is.null(alpha)) {
40!
    return(rgb)
41
  }
42!
  pat = outer(seq_len(H), seq_len(W), function(i, j) (i + j) %% 2L == 0L)
43!
  bg = array(dark, dim = c(H, W, 3))
44!
  bg[pat] = light
45!
  out = array(0, dim = c(H, W, 3))
46!
  for (k in 1:3) {
47!
    out[,, k] = rgb[,, k] * alpha + bg[,, k] * (1 - alpha)
48
  }
49!
  return(out)
50
}
51
52
# Truecolor detection
53
rayimg_truecolor_supported = function() {
5474x
  if (!requireNamespace("cli", quietly = TRUE)) {
55!
    return(FALSE)
56
  }
5774x
  dyn = isTRUE(cli::is_dynamic_tty())
5874x
  utf8 = isTRUE(cli::is_utf8_output())
59
  # Require an explicit hint for 24-bit (COLORTERM), or a TERM that advertises it (rare)
6074x
  tc = grepl("truecolor|24bit", Sys.getenv("COLORTERM", ""), ignore.case = TRUE)
6174x
  term = Sys.getenv("TERM", "")
6274x
  direct = grepl("direct", term, ignore.case = TRUE) # e.g. xterm-direct/kitty-direct
6374x
  dyn && utf8 && (tc || direct)
64
}
65
66
# Map RGB [0, 255] to nearest xterm-256 index
67
rayimg_rgb_to_xterm256 = function(r, g, b) {
68
  # 6x6x6 color cube
69!
  lev = c(0, 95, 135, 175, 215, 255)
70!
  idx = function(x) {
71!
    which.min((lev - x)^2) - 1L
72
  }
73!
  ri = idx(r)
74!
  gi = idx(g)
75!
  bi = idx(b)
76!
  cube_idx = 16L + 36L * ri + 6L * gi + bi
77!
  cube_rgb = c(lev[ri + 1L], lev[gi + 1L], lev[bi + 1L])
78
79
  # grayscale ramp [232-255] (approx [8-238] step 10)
80!
  gray_val = round((r + g + b) / 3)
81!
  gray_i = as.integer(pmin(23L, pmax(0L, round((gray_val - 8) / 10))))
82!
  gray_idx = 232L + gray_i
83!
  gray_rgb = rep(8L + 10L * gray_i, 3L)
84
85
  # choose closer
86!
  d_cube = sum((c(r, g, b) - cube_rgb)^2)
87!
  d_gray = sum((c(r, g, b) - gray_rgb)^2)
88!
  if (d_gray < d_cube) {
89!
    return(gray_idx)
90
  } else {
91!
    return(cube_idx)
92
  }
93
}
94
95
# One ANSI cell with 24-bit or 256-color fallback
96
# style: "auto" pick bg/fg based on luminance; "block"/"bg" force mode; "bg256"/"block256" force 256-color
97
rayimg_ansi_cell = function(
98
  r,
99
  g,
100
  b,
101
  style = c("auto", "block", "bg", "bg256", "block256")
102
) {
103!
  style = match.arg(style)
104!
  r = as.integer(pmin(pmax(round(r), 0L), 255L))
105!
  g = as.integer(pmin(pmax(round(g), 0L), 255L))
106!
  b = as.integer(pmin(pmax(round(b), 0L), 255L))
107
108!
  tc_ok = rayimg_truecolor_supported()
109
110
  # luminance coefs
111!
  Y = 0.2126 * r + 0.7152 * g + 0.0722 * b
112!
  if (style == "auto") {
113!
    style = if (tc_ok) {
114!
      (if (Y < 80) "block" else "bg")
115
    } else {
116!
      (if (Y < 80) "block256" else "bg256")
117
    }
118
  }
119
120
  # 24-bit variants
121!
  if (style == "bg" && tc_ok) {
122!
    return(paste0("\033[48;2;", r, ";", g, ";", b, "m", "  ", "\033[0m"))
123
  }
124!
  if (style == "block" && tc_ok) {
125!
    return(paste0(
126!
      "\033[38;2;",
127!
      r,
128
      ";",
129!
      g,
130
      ";",
131!
      b,
132!
      "m",
133!
      "\u2588\u2588",
134!
      "\033[0m"
135
    ))
136
  }
137
138
  # 256-color fallback
139!
  idx = rayimg_rgb_to_xterm256(r, g, b)
140!
  if (style %in% c("bg256", "bg")) {
141!
    return(paste0("\033[48;5;", idx, "m", "  ", "\033[0m"))
142
  }
143!
  if (style %in% c("block256", "block")) {
144!
    return(paste0("\033[38;5;", idx, "m", "\u2588\u2588", "\033[0m"))
145
  }
146
147
  # last resort
148!
  "\u2588\u2588"
149
}
1
#' Estimate Lat-Long Environment White
2
#'
3
#' @description Estimate the scene white produced by a lat-long environment map.
4
#' The default weighting matches the irradiance seen by an upward-facing diffuse
5
#' surface: `cos(theta) * d_omega` over the upper hemisphere.
6
#'
7
#' @param environment_map Lat-long environment map image, `rayimg`, array, or filename.
8
#' @param weighting Default `"cosine"`. Weighting method. `"cosine"` computes
9
#'   upward diffuse irradiance; `"solid_angle"` computes an unprojected spherical
10
#'   average.
11
#' @param hemisphere Default `"upper"`. Hemisphere to use. `"upper"` uses only
12
#'   rows above the horizon; `"full"` uses the full lat-long map.
13
#' @param environment_colorspace Default `NULL`. Optional colorspace descriptor
14
#'   used to tag `environment_map` on read.
15
#' @param environment_white Default `NULL`. Optional white point used to tag
16
#'   `environment_map` on read.
17
#'
18
#' @return Length-3 XYZ white point normalized to `Y = 1`. The returned vector
19
#'   includes `rgb`, `rgb_ratio`, `xy`, approximate `cct`, `sum_weights`,
20
#'   `weighting`, and `hemisphere` attributes for diagnostics.
21
#' @export
22
estimate_environment_white = function(
23
  environment_map,
24
  weighting = c("cosine", "solid_angle"),
25
  hemisphere = c("upper", "full"),
26
  environment_colorspace = NULL,
27
  environment_white = NULL
28
) {
294x
  weighting = match.arg(weighting)
304x
  hemisphere = match.arg(hemisphere)
31
324x
  env = ray_read_image(
334x
    environment_map,
344x
    normalize = FALSE,
354x
    assume_colorspace = environment_colorspace,
364x
    assume_white = environment_white
37
  )
384x
  d = dim(env)
394x
  if (length(d) != 3L || d[3] < 3L) {
40!
    stop(
41!
      "estimate_environment_white(): environment_map must have RGB channels."
42
    )
43
  }
44
454x
  colorspace = attr(env, "colorspace", exact = TRUE)
464x
  if (!is.list(colorspace) || is.null(colorspace$rgb_to_xyz)) {
47!
    stop(
48!
      "estimate_environment_white(): environment_map is missing colorspace metadata."
49
    )
50
  }
51
524x
  n_theta = d[1]
534x
  n_phi = d[2]
544x
  theta = ((seq_len(n_theta) - 0.5) / n_theta) * pi
554x
  d_theta = pi / n_theta
564x
  d_phi = 2 * pi / n_phi
57
584x
  weights = sin(theta) * d_theta * d_phi
594x
  if (weighting == "cosine") {
604x
    weights = weights * pmax(cos(theta), 0)
61
  }
624x
  if (hemisphere == "upper") {
634x
    weights[theta > pi / 2] = 0
64
  }
65
664x
  row_weight_sum = sum(weights)
674x
  if (!is.finite(row_weight_sum) || row_weight_sum <= 0) {
68!
    stop("estimate_environment_white(): environment weights sum to zero.")
69
  }
70
714x
  weight_matrix = matrix(weights, nrow = n_theta, ncol = n_phi)
724x
  sum_weights = sum(weight_matrix)
734x
  rgb = vapply(
744x
    seq_len(3L),
754x
    function(channel) {
7612x
      sum(env[,, channel] * weight_matrix, na.rm = TRUE)
77
    },
784x
    numeric(1)
79
  )
80
814x
  if (!all(is.finite(rgb)) || sum(rgb) <= 0) {
82!
    stop(
83!
      "estimate_environment_white(): estimated environment RGB is not positive and finite."
84
    )
85
  }
86
874x
  xyz = as.vector(colorspace$rgb_to_xyz %*% rgb)
884x
  if (!all(is.finite(xyz)) || xyz[2] <= 0) {
89!
    stop(
90!
      "estimate_environment_white(): estimated environment XYZ is not positive and finite."
91
    )
92
  }
93
944x
  xyz = xyz / xyz[2]
954x
  xy = c(xyz[1], xyz[2]) / sum(xyz)
964x
  names(xyz) = c("X", "Y", "Z")
974x
  attr(xyz, "rgb") = rgb
984x
  attr(xyz, "rgb_ratio") = rgb / mean(rgb)
994x
  attr(xyz, "xy") = xy
1004x
  attr(xyz, "cct") = xy_to_cct_mccamy(xy)
1014x
  attr(xyz, "sum_weights") = sum_weights
1024x
  attr(xyz, "weighting") = weighting
1034x
  attr(xyz, "hemisphere") = hemisphere
1044x
  xyz
105
}
106
107
#' White Balance with a Lat-Long Environment Map
108
#'
109
#' @description Estimate a lat-long environment map's scene white and pass it to
110
#' [render_white_balance()] as `reference_white`. This is a camera-style white
111
#' balance for renders lit by an environment map.
112
#'
113
#' @param image 3-layer RGB/4-layer RGBA array, `rayimg`, or filename.
114
#' @param environment_map Lat-long environment map image, `rayimg`, array, or filename.
115
#' @param target_white Default `"D65"`. Target white (XYZ Y=1 or named).
116
#' @param bake Default `TRUE`. Passed to [render_white_balance()].
117
#' @param weighting Default `"cosine"`. Passed to the environment white
118
#'   estimator.
119
#' @param hemisphere Default `"upper"`. Passed to the environment white
120
#'   estimator.
121
#' @param environment_colorspace Default `NULL`. Optional colorspace descriptor
122
#'   used to tag `environment_map` on read.
123
#' @param environment_white Default `NULL`. Optional white point used to tag
124
#'   `environment_map` on read.
125
#' @param filename Default `NULL`. Output path.
126
#' @param preview Default `FALSE`. If `TRUE`, display the image.
127
#'
128
#' @return A white-balanced `rayimg`. The estimated white is attached as the
129
#'   `environment_white` attribute.
130
#' @export
131
render_environment_white_balance = function(
132
  image,
133
  environment_map,
134
  target_white = "D65",
135
  bake = TRUE,
136
  weighting = "cosine",
137
  hemisphere = "upper",
138
  environment_colorspace = NULL,
139
  environment_white = NULL,
140
  filename = NULL,
141
  preview = FALSE
142
) {
1431x
  reference_white = estimate_environment_white(
1441x
    environment_map,
1451x
    weighting = weighting,
1461x
    hemisphere = hemisphere,
1471x
    environment_colorspace = environment_colorspace,
1481x
    environment_white = environment_white
149
  )
150
1511x
  out = render_white_balance(
1521x
    image,
1531x
    reference_white = reference_white,
1541x
    target_white = target_white,
1551x
    bake = bake,
1561x
    filename = filename,
1571x
    preview = preview
158
  )
1591x
  attr(out, "environment_white") = reference_white
1601x
  out
161
}
162
163
#' Estimate correlated color temperature from xy chromaticity
164
#' @param xy xy chromaticity coordinates.
165
#' @return Approximate correlated color temperature in Kelvin.
166
#' @keywords internal
167
#' @noRd
168
xy_to_cct_mccamy = function(xy) {
1694x
  n = (xy[1] - 0.3320) / (0.1858 - xy[2])
1704x
  449 * n^3 + 3525 * n^2 + 6823.3 * n + 5520.33
171
}
1
#' Convert XYZ to xy chromaticity coordinates
2
#' @param xyz XYZ vector.
3
#' @return Numeric xy vector.
4
#' @keywords internal
5
xyz_to_xy = function(xyz) {
612x
  stopifnot(is.numeric(xyz), length(xyz) == 3L, all(is.finite(xyz)))
712x
  denom = sum(xyz)
812x
  if (!is.finite(denom) || denom <= 0) {
9!
    stop("XYZ values must have a positive finite sum.")
10
  }
1112x
  unname(c(xyz[1] / denom, xyz[2] / denom))
12
}
13
14
#' Convert xy chromaticity coordinates to XYZ
15
#' @param xy xy chromaticity vector.
16
#' @return XYZ vector normalized to Y=1.
17
#' @keywords internal
18
xy_to_xyz = function(xy) {
192x
  stopifnot(is.numeric(xy), length(xy) == 2L, all(is.finite(xy)))
202x
  if (xy[2] <= 0) {
21!
    stop("xy y-coordinate must be positive.")
22
  }
232x
  unname(c(xy[1] / xy[2], 1, (1 - xy[1] - xy[2]) / xy[2]))
24
}
25
26
#' Check whether libopenexr supports metadata
27
#' @return `TRUE` if `libopenexr::write_exr()` accepts metadata.
28
#' @keywords internal
29
libopenexr_supports_metadata = function() {
303x
  "metadata" %in% names(formals(libopenexr::write_exr))
31
}
32
33
#' Normalize EXR chromaticities metadata
34
#' @param chromaticities EXR chromaticities metadata.
35
#' @return Named chromaticities list.
36
#' @keywords internal
37
normalize_exr_chromaticities = function(chromaticities) {
385x
  if (is.null(chromaticities)) {
39!
    return(NULL)
40
  }
41
425x
  if (is.list(chromaticities)) {
435x
    required = c("red", "green", "blue", "white")
445x
    if (!all(required %in% names(chromaticities))) {
45!
      stop(
46!
        "EXR chromaticities metadata must include red, green, blue, and white."
47
      )
48
    }
495x
    out = chromaticities[required]
50
  } else if (
51!
    is.matrix(chromaticities) && all(dim(chromaticities) == c(4L, 2L))
52
  ) {
53!
    out = list(
54!
      red = chromaticities[1L, ],
55!
      green = chromaticities[2L, ],
56!
      blue = chromaticities[3L, ],
57!
      white = chromaticities[4L, ]
58
    )
59!
  } else if (is.numeric(chromaticities) && length(chromaticities) == 8L) {
60!
    values = matrix(chromaticities, nrow = 4L, byrow = TRUE)
61!
    out = list(
62!
      red = values[1L, ],
63!
      green = values[2L, ],
64!
      blue = values[3L, ],
65!
      white = values[4L, ]
66
    )
67
  } else {
68!
    stop("Unsupported EXR chromaticities metadata shape.")
69
  }
70
715x
  lapply(out, function(x) {
7220x
    stopifnot(is.numeric(x), length(x) == 2L, all(is.finite(x)))
7320x
    unname(c(as.numeric(x[1]), as.numeric(x[2])))
74
  })
75
}
76
77
#' Convert a colorspace descriptor to EXR chromaticities metadata
78
#' @param colorspace Colorspace descriptor.
79
#' @return Named EXR chromaticities list.
80
#' @keywords internal
81
colorspace_to_exr_chromaticities = function(colorspace) {
823x
  if (!is.list(colorspace) || is.null(colorspace$primaries)) {
83!
    return(NULL)
84
  }
853x
  primaries = colorspace$primaries
863x
  if (!all(c("r", "g", "b") %in% names(primaries))) {
87!
    return(NULL)
88
  }
893x
  normalize_exr_chromaticities(list(
903x
    red = primaries$r,
913x
    green = primaries$g,
923x
    blue = primaries$b,
933x
    white = xyz_to_xy(colorspace$white_xyz)
94
  ))
95
}
96
97
#' Build a colorspace descriptor from EXR metadata
98
#' @param metadata EXR metadata list.
99
#' @return Colorspace descriptor, or `NULL` when chromaticities are absent.
100
#' @keywords internal
101
colorspace_from_exr_metadata = function(metadata) {
1024x
  if (!is.list(metadata) || is.null(metadata$chromaticities)) {
1032x
    return(NULL)
104
  }
1052x
  chromaticities = tryCatch(
1062x
    normalize_exr_chromaticities(metadata$chromaticities),
1072x
    error = function(e) {
108!
      warning(
109!
        "Ignoring invalid EXR chromaticities metadata: ",
110!
        conditionMessage(e),
111!
        call. = FALSE
112
      )
113!
      NULL
114
    }
115
  )
1162x
  if (is.null(chromaticities)) {
117!
    return(NULL)
118
  }
1192x
  make_colorspace(
1202x
    name = "OpenEXR",
1212x
    primaries = list(
1222x
      r = chromaticities$red,
1232x
      g = chromaticities$green,
1242x
      b = chromaticities$blue
125
    ),
1262x
    white_xy = chromaticities$white,
1272x
    white_name = "EXR"
128
  )
129
}
130
131
#' Get the adopted neutral white point from EXR metadata
132
#' @param metadata EXR metadata list.
133
#' @return XYZ white point, or `NULL` when absent.
134
#' @keywords internal
135
white_current_from_exr_metadata = function(metadata) {
1364x
  if (!is.list(metadata) || is.null(metadata$adoptedNeutral)) {
1372x
    return(NULL)
138
  }
1392x
  tryCatch(
1402x
    xy_to_xyz(metadata$adoptedNeutral),
1412x
    error = function(e) {
142!
      warning(
143!
        "Ignoring invalid EXR adoptedNeutral metadata: ",
144!
        conditionMessage(e),
145!
        call. = FALSE
146
      )
147!
      NULL
148
    }
149
  )
150
}
151
152
#' Preserve EXR metadata not promoted to rayimg attributes
153
#' @param metadata EXR metadata list.
154
#' @return EXR metadata list, or `NULL` when no metadata remains.
155
#' @keywords internal
156
preserved_exr_metadata = function(metadata) {
1572x
  if (!is.list(metadata) || length(metadata) == 0L) {
158!
    return(NULL)
159
  }
160
1612x
  promoted = c("chromaticities", "adoptedNeutral")
1622x
  out = metadata
1632x
  out[promoted] = NULL
1642x
  if (length(out) == 0L) {
1651x
    return(NULL)
166
  }
1671x
  out
168
}
169
170
#' Build EXR metadata from a rayimg
171
#' @param image A `rayimg`.
172
#' @param metadata Default `NULL`. User-supplied EXR metadata.
173
#' @return EXR metadata list.
174
#' @keywords internal
175
exr_metadata_from_rayimg = function(image, metadata = NULL) {
1763x
  out = attr(image, "exr", exact = TRUE)
1773x
  if (!is.list(out)) {
1782x
    out = list()
179
  }
1803x
  if (!is.null(metadata)) {
1811x
    if (!is.list(metadata)) {
182!
      stop("EXR metadata must be a list.", call. = FALSE)
183
    }
1841x
    out = utils::modifyList(out, metadata)
185
  }
186
1873x
  chromaticities = colorspace_to_exr_chromaticities(
1883x
    attr(image, "colorspace", exact = TRUE)
189
  )
1903x
  if (!is.null(chromaticities)) {
1913x
    out$chromaticities = chromaticities
192
  }
193
1943x
  white_current = attr(image, "white_current", exact = TRUE)
1953x
  if (!is.null(white_current)) {
1963x
    out$adoptedNeutral = xyz_to_xy(white_current)
197
  }
198
1993x
  if (length(out) == 0L) {
200!
    return(NULL)
201
  }
2023x
  out
203
}
1
#' @title Handle Image Output
2
#'
3
#' @description Handles image output logic: returning, saving to a file, or previewing.
4
#'
5
#' @param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
6
#' @param filename Default `NULL`. String specifying the file path to save the image.
7
#' If `NULL`, the image is returned or displayed.
8
#' @param preview Default `FALSE`. If `TRUE`, the image is displayed.
9
#'
10
#' @return If `filename = NULL` and `preview = FALSE`, returns the image array invisibly.
11
#' Otherwise, saves to file or displays the image.
12
#'
13
#' @keywords internal
14
handle_image_output = function(image, filename = NULL, preview = FALSE) {
15301x
  if (is.null(filename) || is.na(filename)) {
16300x
    if (!preview) {
17300x
      return(image) # Return the image data
18
    }
19!
    plot_image(render_clamp(image)) # Display image
20!
    return(invisible(image))
21
  } else {
221x
    ray_write_image(image, filename) # Save the image to file
231x
    if (preview) {
24!
      plot_image(render_clamp(image)) # Display saved image
25
    }
261x
    return(invisible(image))
27
  }
28
}
1
#'@title add_padding
2
#'
3
#'@description Adds padding to the matrix
4
#'
5
#'@param input A two-dimensional matrix or a 3D array (including `rayimg`).
6
#'@return Matrix with edges padded
7
#'@keywords internal
8
add_padding = function(input) {
9!
  is_rayimg = inherits(input, "rayimg")
10!
  input_array = if (is_rayimg) {
11!
    unclass(input)
12
  } else {
13!
    input
14
  }
15
16!
  if (length(dim(input_array)) == 2) {
17!
    temp = matrix(0, nrow = nrow(input_array) + 2, ncol = ncol(input_array) + 2)
18!
    temp[2:(nrow(temp) - 1), 2:(ncol(temp) - 1)] = input_array
19!
    temp[2:(nrow(temp) - 1), 1] = input_array[, 1]
20!
    temp[1, 2:(ncol(temp) - 1)] = input_array[1, ]
21!
    temp[2:(nrow(temp) - 1), ncol(temp)] = input_array[, ncol(input_array)]
22!
    temp[nrow(temp), 2:(ncol(temp) - 1)] = input_array[nrow(input_array), ]
23!
    temp[1, 1] = temp[1, 2]
24!
    temp[1, ncol(temp)] = temp[1, ncol(temp) - 1]
25!
    temp[nrow(temp), 1] = temp[nrow(temp) - 1, 2]
26!
    temp[nrow(temp), ncol(temp)] = temp[nrow(temp) - 1, ncol(temp)]
27
  } else {
28!
    d = dim(input_array)
29!
    temp = array(0, dim = c(d[1] + 2, d[2] + 2, d[3]))
30!
    temp[2:(d[1] + 1), 2:(d[2] + 1), ] = input_array
31!
    temp[2:(d[1] + 1), 1, ] = input_array[, 1, ]
32!
    temp[1, 2:(d[2] + 1), ] = input_array[1, , ]
33!
    temp[2:(d[1] + 1), d[2] + 2, ] = input_array[, d[2], ]
34!
    temp[d[1] + 2, 2:(d[2] + 1), ] = input_array[d[1], , ]
35!
    temp[1, 1, ] = temp[1, 2, ]
36!
    temp[1, d[2] + 2, ] = temp[1, d[2] + 1, ]
37!
    temp[d[1] + 2, 1, ] = temp[d[1] + 1, 2, ]
38!
    temp[d[1] + 2, d[2] + 2, ] = temp[d[1] + 1, d[2] + 2, ]
39
  }
40
41!
  if (is_rayimg) {
42!
    temp = rayimg(
43!
      temp,
44!
      filetype = attr(input, "filetype"),
45!
      source_linear = attr(input, "source_linear"),
46!
      colorspace = attr(input, "colorspace"),
47!
      white_current = attr(input, "white_current"),
48!
      exposure = attr(input, "exposure", exact = TRUE),
49!
      iso = attr(input, "iso", exact = TRUE)
50
    )
51
  }
52!
  temp
53
}
54
55
#'@title add_multi_padding
56
#'
57
#'@description Adds multiple levels padding to the matrix
58
#'
59
#'@param input A two-dimensional matrix or a 3D array (including `rayimg`).
60
#'@param pad Number of padding entries
61
#'@return Matrix with edges padded
62
#'@keywords internal
63
add_multi_padding = function(input, pad = 1) {
64!
  if (length(dim(input)) == 2) {
65!
    temp = matrix(0, nrow = nrow(input) + 2 * pad, ncol = ncol(input) + 2 * pad)
66!
    temp[(1 + pad):(pad + nrow(input)), (1 + pad):(pad + ncol(input))] = input
67!
    temp[(1 + pad):(pad + nrow(input)), 1:pad] = input[, 1]
68!
    for (i in 1:pad) {
69!
      temp[i, (1 + pad):(pad + ncol(input))] = input[1, ]
70
    }
71!
    for (i in (pad + ncol(input) + 1):ncol(temp)) {
72!
      temp[(1 + pad):(pad + nrow(input)), i] = input[, ncol(input)]
73
    }
74!
    for (i in (pad + nrow(input) + 1):nrow(temp)) {
75!
      temp[i, (1 + pad):(pad + ncol(input))] = input[nrow(input), ]
76
    }
77!
    temp[1:pad, 1:pad] = input[1, 1]
78!
    temp[1:pad, (pad + ncol(input) + 1):ncol(temp)] = input[1, ncol(input)]
79!
    temp[(pad + nrow(input) + 1):nrow(temp), 1:pad] = input[nrow(input), 1]
80!
    temp[
81!
      (pad + nrow(input) + 1):nrow(temp),
82!
      (pad + ncol(input) + 1):ncol(temp)
83!
    ] = input[nrow(input), ncol(input)]
84!
    return(temp)
85
  } else {
86!
    temp_height = list()
87!
    for (i in seq_len(dim(input)[3])) {
88!
      temp_height[[i]] = add_multi_padding(input[,, i], pad)
89
    }
90!
    temp_array = array(0, dim = c(dim(temp_height[[i]]), dim(input)[3]))
91!
    for (i in seq_len(dim(input)[3])) {
92!
      temp_array[,, i] = temp_height[[i]]
93
    }
94!
    return(temp_array)
95
  }
96
}
97
98
#'@title trim_padding
99
#'
100
#'@description Trims padding
101
#'
102
#'@param input A two-dimensional matrix.
103
#'@param pad Number of padding entries
104
#'@return Matrix with edges trimmed
105
#'@keywords internal
106
trim_padding = function(input, pad = 1) {
107!
  if (length(dim(input)) == 2) {
108!
    return(input[(1 + pad):(nrow(input) - pad), (1 + pad):(ncol(input) - pad)])
109
  } else {
110!
    return(input[
111!
      (1 + pad):(nrow(input) - pad),
112!
      (1 + pad):(ncol(input) - pad),
113
      ,
114!
      drop = FALSE
115
    ])
116
  }
117
}
118
119
#'@title pad to fit
120
#'
121
#'@description Pads to a rect
122
#'
123
#'@return Hillshade with edges trimmed
124
#'@keywords internal
125
pad_to_fit = function(dim, kernel) {
126!
  whichdim = which.min(dim)
127!
  if (dim[1] != dim[2]) {
128!
    if (whichdim == 1) {
129!
      extra_rows = dim[2] - dim[1]
130!
      if (extra_rows %% 2 == 0) {
131!
        pad = matrix(0, nrow = extra_rows / 2, ncol = ncol(kernel))
132!
        kernel = rbind(pad, kernel, pad)
133
      } else {
134!
        pad1 = matrix(0, nrow = floor(extra_rows / 2) + 1, ncol = ncol(kernel))
135!
        pad2 = matrix(0, nrow = floor(extra_rows / 2), ncol = ncol(kernel))
136!
        kernel = rbind(pad1, kernel, pad2)
137
      }
138
    } else {
139!
      extra_cols = dim[1] - dim[2]
140!
      if (extra_cols %% 2 == 0) {
141!
        pad = matrix(0, nrow = nrow(kernel), ncol = extra_cols / 2)
142!
        kernel = cbind(pad, kernel, pad)
143
      } else {
144!
        pad1 = matrix(0, nrow = nrow(kernel), ncol = floor(extra_cols / 2) + 1)
145!
        pad2 = matrix(0, nrow = nrow(kernel), ncol = floor(extra_cols / 2))
146!
        kernel = cbind(pad1, kernel, pad2)
147
      }
148
    }
149
  }
150!
  return(kernel)
151
}
152
153
#'@title expand to fit
154
#'
155
#'@description Pads to a rect
156
#'
157
#'@return Hillshade with edges trimmed
158
#'@keywords internal
159
expand_to_fit = function(dim, kernel) {
160!
  kdim = dim(kernel)
161!
  if (!all(kdim <= dim)) {
162!
    stop("kernel dimensions must be less than or equal to image")
163
  }
164!
  if (kdim[1] != dim[1]) {
165!
    extra_rows = dim[1] - kdim[1]
166!
    if (extra_rows %% 2 == 0) {
167!
      pad = matrix(0, nrow = extra_rows / 2, ncol = ncol(kernel))
168!
      kernel = rbind(pad, kernel, pad)
169
    } else {
170!
      pad1 = matrix(0, nrow = floor(extra_rows / 2) + 1, ncol = ncol(kernel))
171!
      pad2 = matrix(0, nrow = floor(extra_rows / 2), ncol = ncol(kernel))
172!
      kernel = rbind(pad1, kernel, pad2)
173
    }
174
  }
175!
  if (kdim[2] != dim[2]) {
176!
    extra_cols = dim[2] - kdim[2]
177!
    if (extra_cols %% 2 == 0) {
178!
      pad = matrix(0, nrow = nrow(kernel), ncol = extra_cols / 2)
179!
      kernel = cbind(pad, kernel, pad)
180
    } else {
181!
      pad1 = matrix(0, nrow = nrow(kernel), ncol = floor(extra_cols / 2) + 1)
182!
      pad2 = matrix(0, nrow = nrow(kernel), ncol = floor(extra_cols / 2))
183!
      kernel = cbind(pad1, kernel, pad2)
184
    }
185
  }
186!
  return(kernel)
187
}
1
#'@title Reorient Image
2
#'
3
#'@description Reorients an image or matrix. Transformations are applied in this order: x, y, and transpose.
4
#'
5
#'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
6
#'@param flipx Default `FALSE`. Flip horizontally
7
#'@param flipy Default `FALSE`. Flip vertically.
8
#'@param transpose Default `FALSE`. Transpose image.
9
#'@param filename Default `NULL`. The filename of the image to be saved. If this is not given, the image will be plotted instead.
10
#'@param preview Default `FALSE`. Whether to plot the convolved image, or just to return the values.
11
#'@return 3-layer RGB reoriented array or matrix.
12
#'@export
13
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
14
#'#Original orientation
15
#'plot_image(dragon)
16
#'#Flip the dragon image horizontally
17
#'dragon |>
18
#'  render_reorient(flipx = TRUE) |>
19
#'  plot_image()
20
#'#Flip the dragon image vertically
21
#'dragon |>
22
#'  render_reorient(flipy = TRUE) |>
23
#'  plot_image()
24
#'#Transpose the dragon image
25
#'dragon |>
26
#'  render_reorient(transpose = TRUE) |>
27
#'  plot_image()
28
render_reorient = function(
29
  image,
30
  flipx = FALSE,
31
  flipy = FALSE,
32
  transpose = FALSE,
33
  filename = NULL,
34
  preview = FALSE
35
) {
36
  #Check if file or image before below:
37!
  temp_image = ray_read_image(image, convert_to_array = FALSE)
38!
  imagetype = attr(temp_image, "filetype")
39!
  img_source_linear = attr(temp_image, "source_linear")
40!
  colorspace = attr(temp_image, "colorspace")
41!
  white_current = attr(temp_image, "white_current")
42
43!
  if (flipx) {
44!
    temp_image = fliplr(temp_image)
45
  }
46!
  if (flipy) {
47!
    temp_image = flipud(temp_image)
48
  }
49!
  if (transpose) {
50!
    if (imagetype == "matrix") {
51!
      temp_image = t(temp_image)
52
    } else {
53!
      temp_image = aperm(temp_image, c(2, 1, 3))
54
    }
55
  }
56!
  temp_image = ray_read_image(
57!
    temp_image,
58!
    filetype = imagetype,
59!
    source_linear = img_source_linear,
60!
    assume_colorspace = colorspace,
61!
    assume_white = white_current
62
  )
63
64!
  handle_image_output(temp_image, filename = filename, preview = preview)
65
}
1
#' @title Render a Title on an Image
2
#'
3
#' @description Adds a title with optional styling and a title bar to an image.
4
#' The image can be previewed or saved to a file. Supports both the `grid`-based
5
#' method and (deprecated) `magick` package for rendering the title.
6
#'
7
#' @param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
8
#' @param title_text Default `""`. Text string to be added as the title to the image.
9
#' @param title_offset Default `c(15,15)`. Numeric vector specifying the horizontal
10
#' and vertical offset of the title text, relative to its anchor position.
11
#' @param title_lineheight Default `1`. Multiplier for the lineheight.
12
#' @param title_color Default `"black"`. String specifying the color of the title text.
13
#' @param title_size Default `30`. Numeric value specifying the font size of the title text.
14
#' @param title_font Default `"Arial"`. String specifying the font family for the title text.
15
#' Common options include `"sans"`, `"mono"`, `"serif"`, `"Times"`, `"Helvetica"`, etc.
16
#' @param title_style Default `"plain"`. String specifying the font style, such as
17
#' `"plain"`, `"italic"`, or `"bold"`.
18
#' @param title_bar_color Default `NULL`. Color of the optional title bar. If `NULL`, no bar is added.
19
#' @param title_bar_alpha Default `0.5`. Transparency level of the title bar. A value
20
#' between `0` (fully transparent) and `1` (fully opaque).
21
#' @param title_bar_width Default `NULL`. Numeric value for the height of the title bar in pixels.
22
#' If `NULL`, it is automatically calculated based on the text size and line breaks.
23
#' @param title_position Default `"northwest"`. String specifying the position of the title text.
24
#' Only used when `use_magick = TRUE`. Common options include `"northwest"`, `"center"`, `"south"`, etc.
25
#' @param title_just Default `"left"`. Horizontal alignment of the title text: `"left"`,
26
#' `"center"`, or `"right"`.
27
#' @param use_magick Default `FALSE`. Boolean indicating whether to use the `magick` package for
28
#' rendering titles. This option will be deprecated in future versions.
29
#' @param filename Default `NULL`. String specifying the file path to save the resulting image.
30
#' If `NULL` and `preview = FALSE`, the function returns the processed RGB array.
31
#' @param preview Default `FALSE`. Boolean indicating whether to display the image after processing.
32
#' If `TRUE`, the image is displayed but not saved or returned.
33
#'
34
#' @return A 3-layer RGB array of the processed image if `filename = NULL` and `preview = FALSE`.
35
#' Otherwise, writes the image to the specified file or displays it if `preview = TRUE`.
36
#'
37
#' @note The `use_magick` parameter and all functionality tied to the `magick` package are
38
#' planned for deprecation. It is recommended to use the `grid`-based method for
39
#' future compatibility.
40
#'
41
#' @import grDevices grid
42
#' @export
43
#'
44
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
45
#'#Plot the dragon
46
#'render_title(dragon, preview = TRUE, title_text = "Dragon", title_size=20)
47
#'#That's hard to see--let's add a title bar:
48
#'render_title(dragon, preview = TRUE, title_text = "Dragon", title_size=20,
49
#'          title_bar_color="white")
50
#'#Change the width of the bar:
51
#'render_title(dragon, preview = TRUE, title_text = "Dragon", title_size=20,
52
#'          title_bar_color="white", title_offset = c(8,8))
53
#'#The width of the bar will also automatically adjust for newlines:
54
#'render_title(dragon, preview = TRUE, title_text = "Dragon\n(Blue)", title_size=20,
55
#'          title_bar_color="white")
56
#'#Change the color and title color:
57
#'render_title(dragon, preview = TRUE, title_text = "Dragon", title_size=20,
58
#'          title_bar_color="red", title_color = "white")
59
#'#Change the transparency:
60
#'render_title(dragon, preview = TRUE, title_text = "Dragon",
61
#'             title_size=20, title_bar_alpha = 0.8,
62
#'             title_bar_color="red", title_color = "white")
63
#' #Read directly from a file
64
#' temp_image = tempfile(fileext = ".png")
65
#' ray_write_image(dragon, temp_image)
66
#' render_title(temp_image, preview = TRUE, title_text = "Dragon",
67
#'              title_size=20, title_bar_alpha = 0.8,
68
#'              title_bar_color="red", title_color = "white")
69
render_title = function(
70
  image,
71
  title_text = "",
72
  title_size = 30,
73
  title_offset = rep(title_size / 2, 2),
74
  title_lineheight = 1,
75
  title_color = "black",
76
  title_font = "Arial",
77
  title_style = "plain",
78
  title_bar_color = NA,
79
  title_bar_alpha = 0.5,
80
  title_bar_width = NULL,
81
  title_position = NA,
82
  title_just = "left",
83
  use_magick = FALSE,
84
  filename = NULL,
85
  preview = FALSE
86
) {
87
  #Always output RGBA array, need to ensure alpha is preserved
8825x
  image = ray_read_image(
8925x
    image,
9025x
    convert_to_array = TRUE,
9125x
    reset_camera_settings = TRUE
92
  )
93
9425x
  temp = tempfile(fileext = ".png")
9525x
  ray_write_image(
9625x
    image = ray_read_image(array(0, dim = dim(image))),
9725x
    filename = temp
98
  )
99
10025x
  if (use_magick) {
101!
    if (title_style == "plain") {
102!
      title_style = "normal"
103
    }
104!
    if (is.na(title_bar_color)) {
105!
      title_bar_color = NULL
106
    }
107!
    if (is.na(title_position)) {
108!
      title_position = "northwest"
109
    }
110!
    dimensions = dim(image)
111!
    if (!("magick" %in% rownames(utils::installed.packages()))) {
112!
      stop("`magick` package required for adding title")
113
    }
114
115!
    if (!is.null(title_bar_color)) {
116!
      title_bar_color = col2rgb(title_bar_color) / 255
117!
      title_bar = array(0, c(dimensions[1], dimensions[2], 4))
118!
      if (is.null(title_bar_width)) {
119
        #Detect newlines and adjust title bar width
120!
        char_vector = unlist(strsplit(title_text, ""))
121!
        newline_indices = which(char_vector == "\n")
122!
        newline_indices = newline_indices[
123!
          newline_indices != length(char_vector)
124
        ]
125!
        newlines = length(newline_indices)
126!
        title_bar_width = 2 * title_offset[2] + title_size * (1 + newlines)
127
      }
128!
      if (title_bar_width > dimensions[1]) {
129!
        message(paste0(
130!
          c(
131!
            "Input title_bar_width (",
132!
            title_bar_width,
133!
            ") greater than image height (",
134!
            dimensions[1],
135!
            "), reducing size."
136
          ),
137!
          collapse = ""
138
        ))
139!
        title_bar_width = dimensions[1]
140
      }
141!
      if (title_position %in% c("northwest", "north", "northeast")) {
142!
        title_bar[1:title_bar_width, , 1] = title_bar_color[1]
143!
        title_bar[1:title_bar_width, , 2] = title_bar_color[2]
144!
        title_bar[1:title_bar_width, , 3] = title_bar_color[3]
145!
        title_bar[1:title_bar_width, , 4] = title_bar_alpha
146!
      } else if (title_position %in% c("southwest", "south", "southeast")) {
147!
        title_bar[
148!
          (nrow(title_bar) - title_bar_width):nrow(title_bar),
149
          ,
150!
          1
151!
        ] = title_bar_color[1]
152!
        title_bar[
153!
          (nrow(title_bar) - title_bar_width):nrow(title_bar),
154
          ,
155!
          2
156!
        ] = title_bar_color[2]
157!
        title_bar[
158!
          (nrow(title_bar) - title_bar_width):nrow(title_bar),
159
          ,
160!
          3
161!
        ] = title_bar_color[3]
162!
        title_bar[
163!
          (nrow(title_bar) - title_bar_width):nrow(title_bar),
164
          ,
165!
          4
166!
        ] = title_bar_alpha
167
      } else {
168!
        title_bar[
169!
          (nrow(title_bar) / 2 - title_bar_width / 2):(nrow(title_bar) /
170!
            2 +
171!
            title_bar_width / 2),
172
          ,
173!
          1
174!
        ] = title_bar_color[1]
175!
        title_bar[
176!
          (nrow(title_bar) / 2 - title_bar_width / 2):(nrow(title_bar) /
177!
            2 +
178!
            title_bar_width / 2),
179
          ,
180!
          2
181!
        ] = title_bar_color[2]
182!
        title_bar[
183!
          (nrow(title_bar) / 2 - title_bar_width / 2):(nrow(title_bar) /
184!
            2 +
185!
            title_bar_width / 2),
186
          ,
187!
          3
188!
        ] = title_bar_color[3]
189!
        title_bar[
190!
          (nrow(title_bar) / 2 - title_bar_width / 2):(nrow(title_bar) /
191!
            2 +
192!
            title_bar_width / 2),
193
          ,
194!
          4
195!
        ] = title_bar_alpha
196
      }
197!
      title_bar_temp = paste0(tempfile(), ".png")
198!
      png::writePNG(title_bar, title_bar_temp)
199!
      magick::image_read(temp) |>
200!
        magick::image_composite(magick::image_read(title_bar_temp), ) |>
201!
        magick::image_write(path = temp, format = "png")
202
    }
203!
    magick::image_read(temp) |>
204!
      magick::image_annotate(
205!
        title_text,
206!
        location = paste0("+", title_offset[1], "+", title_offset[2]),
207!
        size = title_size,
208!
        color = title_color,
209!
        style = title_style,
210!
        font = title_font,
211!
        gravity = title_position
212
      ) |>
213!
      magick::image_write(path = temp, format = "png")
214!
    new_image = render_image_overlay(image, temp)
215
  } else {
21625x
    draw_title_card = function(
21725x
      image,
21825x
      title,
21925x
      padding_x = 10,
22025x
      padding_y = 10,
22125x
      gp_text = grid::gpar(col = "white", fontsize = title_size),
22225x
      bg_color = "black",
22325x
      bg_alpha = 0.65,
22425x
      title_just = c("left", "top")
225
    ) {
22625x
      close_device_safely = function(dev_id) {
22725x
        try(grid::upViewport(0), silent = TRUE)
22825x
        devs = grDevices::dev.list()
22925x
        if (!is.null(devs) && dev_id %in% devs) {
23025x
          grDevices::dev.off(dev_id)
231
        }
232
      }
233
23425x
      png_device = linear_png_device()
23525x
      png_device(
23625x
        temp,
23725x
        width = ncol(image),
23825x
        height = nrow(image),
23925x
        pointsize = 12,
24025x
        family = title_font,
24125x
        units = "px",
24225x
        res = 72
243
      )
24425x
      dev_id = grDevices::dev.cur()
24525x
      pushed = 0L
24625x
      on.exit(
247
        {
24825x
          if (pushed > 0L) {
249!
            try(grid::popViewport(pushed), silent = TRUE)
250
          }
25125x
          close_device_safely(dev_id)
252
        },
25325x
        add = TRUE
254
      )
255
25625x
      grid::grid.newpage()
257
25825x
      prepared = prepare_native_raster(image)
25925x
      nr = prepared$native_raster
26025x
      image_dim = prepared$display_dim
261
26225x
      image_width = image_dim[2]
26325x
      image_height = image_dim[1]
264
26525x
      image_vp = grid::viewport(
26625x
        name = "image",
26725x
        xscale = c(0, image_width),
26825x
        yscale = c(image_height, 0),
26925x
        gp = gp_text
270
      )
27125x
      grid::pushViewport(image_vp)
27225x
      pushed = pushed + 1L
273
27425x
      image_grob = grid::rasterGrob(
27525x
        nr,
27625x
        interpolate = FALSE,
27725x
        width = grid::unit(1, "npc"),
27825x
        height = grid::unit(1, "npc")
279
      )
28025x
      grid::grid.draw(image_grob)
281
28225x
      title_hjust = title_just[1]
28325x
      if (!title_hjust %in% c("left", "center", "right")) {
284!
        stop(
285!
          'Invalid title_just value for horizontal alignment. Must be "left", "center", or "right".'
286
        )
287
      }
288
289
      # Available width for text depends on horizontal justification.
290
      # For left/right aligned text, `padding_x` is only applied on one side.
29125x
      available_width = if (identical(title_hjust, "center")) {
292!
        image_width - padding_x * 2
293
      } else {
29425x
        image_width - padding_x
295
      }
29625x
      available_width = max(0, available_width)
297
298
      # Wrap text into lines based on available width
29925x
      wrap_text = function(text, available_width) {
300
        # Split text into segments by newline characters
30125x
        segments = unlist(strsplit(text, "\n"))
30225x
        all_lines = character(0)
303
30425x
        for (segment in segments) {
30525x
          words = strsplit(segment, "\\s+")[[1]]
30625x
          if (length(words) == 0) {
307!
            all_lines = c(all_lines, "") # Add an empty line for consecutive newlines
308!
            next
309
          }
310
31125x
          lines = character(0)
31225x
          current_line = words[1]
313
31425x
          for (word in words[-1]) {
315!
            test_line = paste(current_line, word)
316!
            test_width = grid::convertWidth(
317!
              grid::stringWidth(test_line),
318!
              "native",
319!
              valueOnly = TRUE
320
            )
321!
            if (test_width > available_width) {
322!
              lines = c(lines, current_line)
323!
              current_line = word
324
            } else {
325!
              current_line = test_line
326
            }
327
          }
328
32925x
          lines = c(lines, current_line)
33025x
          all_lines = c(all_lines, lines)
331
        }
332
33325x
        return(all_lines)
334
      }
335
336
      # Wrap the title text
33725x
      lines = wrap_text(title, available_width)
33825x
      lines_with_newlines = paste0(lines, collapse = "\n")
339
34025x
      text_size = systemfonts::shape_string(
34125x
        lines_with_newlines,
34225x
        size = title_size,
34325x
        vjust = 0,
34425x
        res = 72,
34525x
        lineheight = title_lineheight,
34625x
        family = title_font
34725x
      )[["metrics"]]
348
      # Position adjustments
34925x
      if (title_hjust == "left") {
35025x
        x = padding_x
35125x
        just = c("left", "top")
352!
      } else if (title_hjust == "center") {
353!
        x = image_width / 2
354!
        just = c("center", "top")
355!
      } else if (title_hjust == "right") {
356!
        x = image_width - padding_x
357!
        just = c("right", "top")
358
      }
35925x
      height_with_padding = text_size$height -
36025x
        text_size$top_bearing -
36125x
        text_size$bottom_bearing -
36225x
        text_size$top_border +
36325x
        padding_y * 2
364
      # Draw background rectangle
36525x
      grid::grid.rect(
36625x
        x = 0,
36725x
        y = 0,
36825x
        width = image_width,
36925x
        height = height_with_padding,
37025x
        just = c("left", "bottom"),
37125x
        default.units = "native",
37225x
        gp = grid::gpar(
37325x
          fill = grDevices::adjustcolor(bg_color, alpha.f = bg_alpha),
37425x
          col = NA
375
        )
376
      )
37725x
      grid::grid.text(
37825x
        label = lines_with_newlines,
37925x
        x = x,
38025x
        y = padding_y,
38125x
        default.units = "native",
38225x
        just = just,
38325x
        gp = grid::gpar(
38425x
          col = title_color,
38525x
          fontsize = title_size,
38625x
          lineheight = title_lineheight,
38725x
          cex = 1,
38825x
          fontfamily = title_font
389
        )
390
      )
39125x
      grid::popViewport(pushed)
39225x
      pushed = 0L
393
    }
39425x
    if (!is.na(title_position)) {
395!
      warning("Title position is ignored when not using {magick}")
396
    }
39725x
    if (is.null(title_bar_color)) {
398!
      title_bar_color = NA
399
    }
40025x
    if (is.null(title_bar_alpha)) {
401!
      title_bar_alpha = NA
402
    }
40325x
    draw_title_card(
40425x
      image,
40525x
      title = title_text,
40625x
      padding_x = title_offset[1],
40725x
      padding_y = title_offset[2],
40825x
      gp_text = grid::gpar(
40925x
        col = title_color,
41025x
        fontsize = title_size,
41125x
        fontfamily = title_font,
41225x
        lineheight = title_lineheight,
41325x
        fontface = title_style,
41425x
        fill = NA
415
      ),
41625x
      bg_color = title_bar_color,
41725x
      bg_alpha = title_bar_alpha,
41825x
      title_just = title_just
419
    )
42025x
    new_image = ray_read_image(temp)
421
  }
42225x
  handle_image_output(new_image, filename = filename, preview = preview)
423
}
1
#'@title Add Vignette Effect
2
#'
3
#'@description Takes an RGB array/filename and adds a camera vignette effect.
4
#'
5
#'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
6
#'@param filename Default `NULL`. Filename which to save the image. If `NULL` and `preview = FALSE`,
7
#'returns an RGB array.
8
#'@param vignette Default `1`. A camera vignetting effect will be added to the image.
9
#'`1` is the darkest vignetting, while `0` is no vignetting. If vignette is a length-2 vector, the second entry will
10
#'control the blurriness of the vignette effect (`1` is the default, e.g. `2` would double the blurriness but would take
11
#'much longer to compute).
12
#'@param radius Default `1.1`. Multiplier for the size of the vignette. If `1`, the vignette touches
13
#'the edge of the image.
14
#'@param color Default `"#000000"` (black). Color of the vignette.
15
#'@param preview Default `FALSE`. If `TRUE`, it will display the image in addition
16
#'to returning it.
17
#'
18
#'@return A `rayimg` RGBA array.
19
#'@import grDevices
20
#'@export
21
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
22
#'#Plot the dragon
23
#'plot_image(dragon)
24
#'#Add a vignette effect:
25
#'render_vignette(dragon, preview = TRUE, vignette = 1, radius=1.1)
26
#'#Lighten the vignette effect:
27
#'render_vignette(dragon, preview = TRUE, vignette = 0.5)
28
#'#Change the radius:
29
#'render_vignette(dragon, preview = TRUE, vignette = 1, radius=1.5)
30
#'render_vignette(dragon, preview = TRUE, vignette = 0.1, radius=0.8)
31
#'#Change the color:
32
#'render_vignette(dragon, preview = TRUE, vignette = 1, color="white")
33
#'#Increase the width of the blur by 50%:
34
#'render_vignette(dragon, preview = TRUE, vignette = c(1,1.5))
35
render_vignette = function(
36
  image,
37
  vignette = 0.5,
38
  color = "#000000",
39
  radius = 1.1,
40
  filename = NULL,
41
  preview = FALSE
42
) {
43!
  image = ray_read_image(image, reset_camera_settings = TRUE)
44!
  dimensions = dim(image)
45
46!
  if (!("magick" %in% rownames(utils::installed.packages()))) {
47!
    stop("`magick` package required for adding overlay")
48
  }
49!
  if (length(vignette) > 1) {
50!
    if (vignette[2] < 0) {
51!
      stop("vignette[2] must be greater than 0")
52
    }
53!
    radiusval = min(c(dimensions[1], dimensions[2])) / 2 * vignette[2]
54!
    vignette = vignette[1]
55
  } else {
56!
    radiusval = min(c(dimensions[1], dimensions[2])) / 2
57
  }
58!
  if (is.numeric(vignette)) {
59!
    if (vignette[1] > 1 || vignette[1] < 0) {
60!
      stop("vignette value (", vignette[1], ") must be between 0 and 1.")
61
    }
62
  } else {
63!
    vignette = 0.4
64
  }
65!
  image_vignette = make_vignette_overlay(
66!
    width = dimensions[1],
67!
    height = dimensions[2],
68!
    intensity = vignette,
69!
    radius = radiusval,
70!
    radius_multiplier = radius,
71!
    color = color
72
  )
73!
  temp = render_image_overlay(image, image_vignette)
74!
  handle_image_output(temp, filename = filename, preview = preview)
75
}
1
rgb_to_hex = function(x) {
244x
  if (is.null(dim(x))) {
34x
    x = matrix(x, ncol = length(x))
4
  }
544x
  if (!(ncol(x) %in% c(3L, 4L))) {
6!
    stop("rgb_to_hex(): expected 3 or 4 columns (R,G,B[,A]).")
7
  }
844x
  x = pmin(pmax(x, 0), 1)
944x
  ints = round(x * 255)
1044x
  apply(ints, 1, function(row) {
1176x
    paste0("#", paste(sprintf("%02X", row), collapse = ""))
12
  })
13
}
14
15
16
array_rgb_to_hex_colmajor = function(arr) {
173x
  d = dim(arr)
183x
  R = as.vector(arr[,, 1])
193x
  G = as.vector(arr[,, 2])
203x
  B = as.vector(arr[,, 3])
213x
  if (d[3] >= 4L) {
222x
    A = as.vector(arr[,, 4])
232x
    return(rgb_to_hex(cbind(R, G, B, A)))
24
  }
251x
  rgb_to_hex(cbind(R, G, B))
26
}
27
28
#' Render Gamma/Linear
29
#'
30
#' Convert sRGB-encoded color data to linear light (and vice versa).
31
#'
32
#' @param color A `rayimg`, hex color string (or vector), length-3 numeric RGB vector,
33
#'   or RGB/RGBA matrix.
34
#' @param srgb_to_linear Default `TRUE`. If `TRUE`, converts sRGB-encoded data to linear light.
35
#'   If `FALSE`, converts linear-light data to sRGB.
36
#' @param as_hex Default `FALSE`. When `srgb_to_linear = FALSE` and input is an RGB/RGBA
37
#'   matrix or array, returns hex: for matrices a length-`n` vector; for arrays a
38
#'   length-`prod(dim(x)[1:2])` vector in column-major order. Alpha (if present) is passed through.
39
#'
40
#' @return Same shape/type as input unless `as_hex = TRUE` on matrix/array with `srgb_to_linear = FALSE`,
41
#'   in which case a character vector of hex codes is returned.
42
#' @export
43
#' @examples
44
#' # Numeric RGB vector (sRGB -> linear -> back to sRGB)
45
#' srgb_vec = c(0.2, 0.4, 0.6)
46
#' linear_vec = render_gamma_linear(srgb_vec)
47
#' render_gamma_linear(linear_vec, srgb_to_linear = FALSE)
48
#'
49
#' # Hex input (single color)
50
#' linear_from_hex = render_gamma_linear("#336699")
51
#' render_gamma_linear(linear_from_hex, srgb_to_linear = FALSE, as_hex = TRUE)
52
#'
53
#' # Greyscale matrix (treated as image plane)
54
#' grey_image = matrix(c(0.1, 0.5, 0.9, 0.3), nrow = 2)
55
#' linear_grey = render_gamma_linear(grey_image)
56
#' render_gamma_linear(linear_grey, srgb_to_linear = FALSE, as_hex = TRUE)
57
#'
58
#' # Array with a single greyscale channel
59
#' grey_pixels = array(c(0.2, 0.7), dim = c(1, 2, 1))
60
#' linear_grey_arr = render_gamma_linear(grey_pixels)
61
#' render_gamma_linear(linear_grey_arr, srgb_to_linear = FALSE, as_hex = TRUE)
62
#'
63
#' # Array with greyscale + alpha
64
#' grey_alpha = array(c(0.3, 0.9, 0.6, 0.4), dim = c(1, 2, 2))
65
#' linear_grey_alpha = render_gamma_linear(grey_alpha)
66
#' render_gamma_linear(linear_grey_alpha, srgb_to_linear = FALSE, as_hex = TRUE)
67
#'
68
#' # RGB array (3 channels)
69
#' rgb_pixels = array(
70
#'   c(
71
#'     0.2, 0.4, 0.6,
72
#'     0.7, 0.1, 0.3
73
#'   ),
74
#'   dim = c(1, 2, 3)
75
#' )
76
#' linear_rgb = render_gamma_linear(rgb_pixels)
77
#' render_gamma_linear(linear_rgb, srgb_to_linear = FALSE, as_hex = TRUE)
78
#'
79
#' # RGBA array (alpha channel preserved)
80
#' rgba_pixels = array(
81
#'   c(
82
#'     0.2, 0.4, 0.6, 0.5,
83
#'     0.7, 0.1, 0.3, 0.8
84
#'   ),
85
#'   dim = c(1, 2, 4)
86
#' )
87
#' linear_rgba = render_gamma_linear(rgba_pixels)
88
#' render_gamma_linear(linear_rgba, srgb_to_linear = FALSE, as_hex = TRUE)
89
#'
90
#' # rayimg input retains metadata and supports hex conversion
91
#' linear_img = render_gamma_linear(ray_read_image(rgba_pixels))
92
#' render_gamma_linear(linear_img, srgb_to_linear = FALSE, as_hex = TRUE)
93
render_gamma_linear = function(color, srgb_to_linear = TRUE, as_hex = FALSE) {
9428x
  fxn = if (srgb_to_linear) to_linear else to_srgb
95
9628x
  if (inherits(color, "rayimg")) {
974x
    out = color
984x
    d = dim(out)
994x
    if (is.null(d)) {
100!
      out[] = fxn(out[])
101
    } else {
1024x
      arr = unclass(out)
1034x
      c = d[3]
1044x
      if (length(d) == 2L) {
105!
        arr = fxn(arr) # greyscale matrix
1064x
      } else if (length(d) == 3L) {
1074x
        if (c >= 1L) {
1084x
          arr[,, 1] = fxn(arr[,, 1])
109
        } # grey or R
1104x
        if (c >= 3L) {
111
          # RGB
1124x
          arr[,, 2] = fxn(arr[,, 2])
1134x
          arr[,, 3] = fxn(arr[,, 3])
114
        }
115
        # alpha (2nd when c==2, 4th when c==4) untouched
116
      } else {
117!
        stop("render_gamma_linear(): expected 2D matrix or 3D array in rayimg.")
118
      }
1194x
      out[] = arr
120
    }
1214x
    if (!srgb_to_linear && isTRUE(as_hex)) {
1221x
      d = dim(out)
1231x
      if (length(d) == 2L) {
124!
        g = as.vector(unclass(out))
125!
        return(rgb_to_hex(cbind(g, g, g)))
126
      }
1271x
      if (length(d) == 3L && d[3] >= 1L && d[3] <= 4L) {
1281x
        arr = unclass(out)
1291x
        if (d[3] == 1L) {
130!
          g = as.vector(arr[,, 1])
131!
          return(rgb_to_hex(cbind(g, g, g)))
1321x
        } else if (d[3] == 2L) {
133!
          g = as.vector(arr[,, 1])
134!
          a = as.vector(arr[,, 2])
135!
          return(rgb_to_hex(cbind(g, g, g, a)))
136
        } else {
1371x
          return(array_rgb_to_hex_colmajor(arr))
138
        }
139
      }
140!
      stop("render_gamma_linear(): unsupported rayimg shape for hex.")
141
    }
1423x
    attr(out, "source_linear") = srgb_to_linear
1433x
    attr(out, "exposure") = 0
1443x
    attr(out, "iso") = 100
1453x
    return(out)
146
  }
147
14824x
  if (is.character(color)) {
1492x
    if (!length(color)) {
150!
      stop("render_gamma_linear(): character input cannot be empty.")
151
    }
1522x
    if (!srgb_to_linear) {
153!
      stop(
154!
        "render_gamma_linear(): for hex input, only sRGB -> linear is supported."
155
      )
156
    }
1572x
    rgb = t(grDevices::col2rgb(color)) / 255
1582x
    lin = to_linear(rgb)
1591x
    return(if (nrow(lin) == 1L) as.numeric(lin[1, ]) else lin)
160
  }
161
16222x
  if (is.matrix(color)) {
1634x
    if (srgb_to_linear) {
1641x
      return(fxn(color)) # greyscale plane
165
    } else {
1663x
      srgb_grey = fxn(color)
1673x
      if (as_hex) {
1681x
        g = as.vector(srgb_grey)
1691x
        return(rgb_to_hex(cbind(g, g, g)))
170
      }
1712x
      return(srgb_grey)
172
    }
173
  }
174
17518x
  if (is.array(color)) {
17612x
    if (length(dim(color)) != 3L) {
177!
      stop("render_gamma_linear(): array must be h*w*c.")
178
    }
17912x
    d = dim(color)
18012x
    c = d[3]
18112x
    out = color
18212x
    if (c >= 1L) {
18312x
      out[,, 1] = fxn(out[,, 1])
184
    }
18512x
    if (c >= 3L) {
1866x
      out[,, 2] = fxn(out[,, 2])
1876x
      out[,, 3] = fxn(out[,, 3])
188
    }
18912x
    if (!srgb_to_linear && as_hex) {
1904x
      if (c == 1L) {
1911x
        g = as.vector(out[,, 1])
1921x
        return(rgb_to_hex(cbind(g, g, g)))
193
      }
1943x
      if (c == 2L) {
1951x
        g = as.vector(out[,, 1])
1961x
        a = as.vector(out[,, 2])
1971x
        return(rgb_to_hex(cbind(g, g, g, a)))
198
      }
1992x
      return(array_rgb_to_hex_colmajor(out))
200
    }
2018x
    return(out)
202
  }
203
2046x
  if (is.numeric(color)) {
2056x
    if (length(color) != 3L) {
206!
      stop("render_gamma_linear(): numeric input must be length-3 RGB.")
207
    }
2086x
    if (any(!is.finite(color)) || any(color < 0 | color > 1)) {
209!
      stop("render_gamma_linear(): numeric RGB values must be between 0 and 1.")
210
    }
2116x
    out = fxn(color)
2126x
    if (!srgb_to_linear && as_hex) {
2134x
      return(rgb_to_hex(out))
214
    }
2152x
    return(out)
216
  }
217
218!
  stop("render_gamma_linear(): unsupported input type.")
219
}
1
#'@title Crop Image
2
#'
3
#'@description Crops an image (or matrix) either by specifying axis-aligned limits
4
#'(`width_limits`/`height_limits`) or by specifying a centered box size via `center`.
5
#'
6
#'@param image Default `NULL`. 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
7
#'@param width_limits Default `NULL`. Length-2 numeric `(xmin, xmax)` along the width (x/columns).
8
#' Values in 0..1 are treated as fractions of image width; otherwise they are pixel indices.
9
#' Mutually exclusive with `center`. If provided alone, `height_limits` defaults to full height.
10
#'@param height_limits Default `NULL`. Length-2 numeric `(ymin, ymax)` along the height (y/rows).
11
#' Values in 0..1 are treated as fractions of image height; otherwise they are pixel indices.
12
#' Mutually exclusive with `center`. If provided alone, `width_limits` defaults to full width.
13
#'@param center Default `NULL`. Length-2 numeric `(height, width)` for a center-crop.
14
#' Values in (0,1] are treated as fractions of `(image height, image width)`; otherwise pixels.
15
#' Mutually exclusive with `width_limits`/`height_limits`.
16
#'@param filename Default `NULL`. The filename of the image to be saved. If this is not given, the image will be plotted instead.
17
#'@param preview Default `FALSE`. Whether to plot the cropped image, or just to return the values.
18
#'@return A `rayimg` array with the cropped region.
19
#'@export
20
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
21
#'# Left half of the image
22
#'render_crop(dragon,
23
#'            width_limits = c(0, 0.50),
24
#'            height_limits = c(0, 1)) |>
25
#'  plot_image()
26
#'# Right half of the image
27
#'render_crop(dragon,
28
#'            width_limits = c(0.50, 1),
29
#'            height_limits = c(0, 1)) |>
30
#'  plot_image()
31
#'# Top middle of the image (25%–50% height, 25%–75% width)
32
#'render_crop(dragon,
33
#'            height_limits = c(0.25, 0.50),
34
#'            width_limits  = c(0.25, 0.75)) |>
35
#'  plot_image()
36
#'# Top middle, explicit pixel coords (for a 200x200 image)
37
#'render_crop(dragon,
38
#'            height_limits = c(50, 100),
39
#'            width_limits  = c(50, 150)) |>
40
#'  plot_image()
41
#'# Center-crop: 50% height and width of the image
42
#'render_crop(dragon, center = c(0.5, 0.5)) |>
43
#'  plot_image()
44
#'# Center-crop: fixed 50x100 pixels
45
#'render_crop(dragon, center = c(50, 100)) |>
46
#'  plot_image()
47
render_crop = function(
48
  image = NULL,
49
  width_limits = NULL,
50
  height_limits = NULL,
51
  center = NULL,
52
  filename = NULL,
53
  preview = FALSE
54
) {
551x
  if (is.null(image)) {
56!
    stop("`image` must be provided.", call. = FALSE)
57
  }
58
591x
  use_limits = !is.null(width_limits) || !is.null(height_limits)
601x
  use_center = !is.null(center)
61
621x
  if (use_limits && use_center) {
63!
    stop(
64!
      "Provide either `width_limits`/`height_limits` OR `center`, not both.",
65!
      call. = FALSE
66
    )
67
  }
681x
  if (!use_limits && !use_center) {
69!
    stop(
70!
      "You must provide `width_limits`/`height_limits`, or `center`.",
71!
      call. = FALSE
72
    )
73
  }
74
751x
  if (!is.null(filename)) {
76!
    if (tools::file_ext(filename) != "png") {
77!
      filename = paste0(filename, ".png")
78
    }
79
  }
80
81
  # Normalize input and preserve metadata
821x
  temp_image = ray_read_image(image)
831x
  imagetype = attr(temp_image, "filetype")
841x
  img_source_linear = attr(temp_image, "source_linear")
851x
  colorspace = attr(temp_image, "colorspace")
861x
  white_current = attr(temp_image, "white_current")
87
881x
  h = nrow(temp_image)
891x
  w = ncol(temp_image)
90
911x
  to_px_range = function(lims, len) {
922x
    if (length(lims) != 2 || !is.numeric(lims)) {
93!
      stop("Limits must be length-2 numeric.", call. = FALSE)
94
    }
952x
    a = lims[1]
962x
    b = lims[2]
972x
    if (all(a >= 0, a <= 1, b >= 0, b <= 1)) {
982x
      start = floor(min(a, b) * len) + 1L
992x
      end = ceiling(max(a, b) * len)
100
    } else {
101!
      start = floor(min(a, b))
102!
      end = ceiling(max(a, b))
103
    }
1042x
    start = max(1L, start)
1052x
    end = min(len, end)
1062x
    if (end < start) {
107!
      stop(
108!
        "Computed limits are empty after clamping; check your inputs.",
109!
        call. = FALSE
110
      )
111
    }
1122x
    c(start, end)
113
  }
114
1151x
  if (use_limits) {
1161x
    if (is.null(width_limits)) {
117!
      width_limits = c(0, 1)
118
    }
1191x
    if (is.null(height_limits)) {
120!
      height_limits = c(0, 1)
121
    }
122
1231x
    x_rng = to_px_range(width_limits, w)
1241x
    y_rng = to_px_range(height_limits, h)
125
1261x
    x_start = x_rng[1]
1271x
    x_end = x_rng[2]
1281x
    y_start = y_rng[1]
1291x
    y_end = y_rng[2]
130
  } else {
131!
    if (length(center) != 2 || !is.numeric(center)) {
132!
      stop(
133!
        "`center` must be a length-2 numeric vector (height, width).",
134!
        call. = FALSE
135
      )
136
    }
137!
    box_h = center[1]
138!
    box_w = center[2]
139!
    box_h = if (box_h > 0 && box_h <= 1) {
140!
      round(max(1, box_h * h))
141
    } else {
142!
      round(box_h)
143
    }
144!
    box_w = if (box_w > 0 && box_w <= 1) {
145!
      round(max(1, box_w * w))
146
    } else {
147!
      round(box_w)
148
    }
149!
    box_h = min(max(1L, box_h), h)
150!
    box_w = min(max(1L, box_w), w)
151
152!
    y_start = floor((h - box_h) / 2) + 1L
153!
    y_end = y_start + box_h - 1L
154!
    x_start = floor((w - box_w) / 2) + 1L
155!
    x_end = x_start + box_w - 1L
156
  }
157
1581x
  if (imagetype != "matrix") {
1591x
    temp_image = temp_image[y_start:y_end, x_start:x_end, , drop = FALSE]
160
  } else {
161!
    temp_image = temp_image[y_start:y_end, x_start:x_end, drop = FALSE]
162
  }
163
1641x
  temp_image = ray_read_image(
1651x
    temp_image,
1661x
    filetype = imagetype,
1671x
    source_linear = img_source_linear,
1681x
    assume_colorspace = colorspace,
1691x
    assume_white = white_current
170
  )
1711x
  handle_image_output(temp_image, filename = filename, preview = preview)
172
}
1
#' Render To Display
2
#' @description Convert an image from its working space to a display space, and optionally apply sRGB OETF for viewing.
3
#' @param image A `rayimg`, array, or filename.
4
#' @param display Default `CS_SRGB`. Target display RGB space.
5
#' @param encode Default `TRUE`. If `TRUE`, apply sRGB OETF (only valid when `display` is sRGB-like).
6
#' @param adapt_white Default `TRUE`. Whether to perform CAT from working white to display white.
7
#' @return A `rayimg` when `encode=FALSE`, or a `rayimg` with sRGB-encoded RGB when `encode=TRUE`.
8
#' @export
9
render_to_display = function(
10
  image,
11
  display = CS_SRGB,
12
  encode = TRUE,
13
  adapt_white = TRUE
14
) {
15!
  img = ray_read_image(
16!
    image,
17!
    normalize = FALSE,
18!
    reset_camera_settings = TRUE
19
  )
20
  # Ensure linear before color conversion
21!
  if (!isTRUE(attr(img, "source_linear"))) {
22!
    img = render_gamma_linear(img, srgb_to_linear = TRUE)
23
  }
24
  # Move primaries (and optionally white) to display
25!
  moved = render_convert_colorspace(
26!
    img,
27!
    from_mats = NA,
28!
    to_mats = display,
29!
    adapt_white = adapt_white,
30!
    from_white = NA,
31!
    to_white = display$white_xyz
32
  )
33!
  if (!encode) {
34!
    return(moved)
35
  }
36
  # Only sRGB OETF is implemented here
37!
  if (!identical(display$name, CS_SRGB$name)) {
38!
    warning(
39!
      "render_to_display(): encode=TRUE uses sRGB OETF; non-sRGB displays may require a different OETF/transfer."
40
    )
41
  }
42!
  render_gamma_linear(moved, srgb_to_linear = FALSE)
43
}
1
prepare_native_raster = function(image, angle = 0, show_linear = FALSE) {
262x
  img = ray_read_image(image, convert_to_array = TRUE)
3
462x
  display = img
562x
  cs_from = attr(display, "colorspace")
662x
  white_curr = attr(display, "white_current")
7
862x
  display = render_clamp(display)
962x
  display[is.na(display)] = 0
10
1162x
  alpha_channel = unclass(render_clamp(
1262x
    display[,, 4],
1362x
    min_value = 0,
1462x
    max_value = 1
15
  ))
1662x
  display[,, 4] = alpha_channel
17
1862x
  if (!show_linear) {
19
    if (
2062x
      !is.null(cs_from) &&
2162x
        (!identical(cs_from$name, "sRGB") ||
2262x
          any(abs(white_curr - CS_SRGB$white_xyz) > 1e-8))
23
    ) {
2428x
      xyz = apply_color_matrix(display, cs_from$rgb_to_xyz)
2528x
      if (any(abs(white_curr - CS_SRGB$white_xyz) > 1e-8)) {
2628x
        CAT = compute_cat_bradford(white_curr, CS_SRGB$white_xyz)
2728x
        xyz = apply_color_matrix(xyz, CAT)
28
      }
2928x
      display = apply_color_matrix(xyz, CS_SRGB$xyz_to_rgb)
3028x
      display[,, 1:3][display[,, 1:3] < 0] = 0
31
    }
3262x
    display[,, 1:3] = to_srgb(display[,, 1:3])
33
  }
34
3562x
  if (!isTRUE(all.equal(angle %% 360, 0))) {
36!
    display = rotate_image_array(display, angle)
37
  }
38
3962x
  list(
4062x
    native_raster = convert_to_native_raster(display),
4162x
    display_dim = dim(display)
42
  )
43
}
1
#' Rotate an image array around its center
2
#'
3
#' @keywords internal
4
rotate_image_array = function(img, angle) {
5!
  if (length(dim(img)) < 2) {
6!
    stop("rotate_image_array() expects a matrix or array input")
7
  }
8!
  if (is.null(angle) || is.na(angle) || !is.finite(angle)) {
9!
    return(img)
10
  }
11!
  angle = angle %% 360
12!
  if (isTRUE(all.equal(angle, 0))) {
13!
    return(img)
14
  }
15!
  theta = angle * pi / 180
16!
  cos_t = cos(theta)
17!
  sin_t = sin(theta)
18
19!
  dims = dim(img)
20!
  if (length(dims) == 2) {
21!
    img = array(img, dim = c(dims, 1))
22!
    dims = dim(img)
23
  }
24!
  height = dims[1]
25!
  width = dims[2]
26!
  channels = dims[3]
27
28!
  width_rot = abs(width * cos_t) + abs(height * sin_t)
29!
  height_rot = abs(width * sin_t) + abs(height * cos_t)
30!
  new_width = max(1L, as.integer(ceiling(width_rot)))
31!
  new_height = max(1L, as.integer(ceiling(height_rot)))
32
33!
  cx_old = (width + 1) / 2
34!
  cy_old = (height + 1) / 2
35!
  cx_new = (new_width + 1) / 2
36!
  cy_new = (new_height + 1) / 2
37
38!
  x_indices = matrix(
39!
    rep(seq_len(new_width), each = new_height),
40!
    nrow = new_height
41
  )
42!
  y_indices = matrix(
43!
    rep(seq_len(new_height), times = new_width),
44!
    nrow = new_height
45
  )
46
47!
  x_rel = x_indices - cx_new
48!
  y_rel = cy_new - y_indices
49
50!
  x_src = x_rel * cos_t + y_rel * sin_t + cx_old
51!
  y_src_rel = -x_rel * sin_t + y_rel * cos_t
52!
  y_src = cy_old - y_src_rel
53
54!
  x_vec = as.vector(x_src)
55!
  y_vec = as.vector(y_src)
56
57!
  rotated = array(0, dim = c(new_height, new_width, channels))
58!
  for (ch in seq_len(channels)) {
59!
    channel = img[,, ch, drop = TRUE]
60!
    rotated_channel = bilinear_sample_matrix(channel, x_vec, y_vec)
61!
    rotated[,, ch] = matrix(
62!
      rotated_channel,
63!
      nrow = new_height,
64!
      ncol = new_width
65
    )
66
  }
67!
  return(rotated)
68
}
69
70
bilinear_sample_matrix = function(mat, x, y, fill = 0) {
71!
  height = nrow(mat)
72!
  width = ncol(mat)
73!
  result = rep(fill, length(x))
74!
  valid = !is.na(x) & !is.na(y) & x >= 1 & x <= width & y >= 1 & y <= height
75!
  if (!any(valid)) {
76!
    return(result)
77
  }
78!
  xv = x[valid]
79!
  yv = y[valid]
80!
  x0 = floor(xv)
81!
  y0 = floor(yv)
82!
  x1 = pmin(x0 + 1, width)
83!
  y1 = pmin(y0 + 1, height)
84!
  dx = xv - x0
85!
  dy = yv - y0
86
87!
  idx00 = cbind(as.integer(y0), as.integer(x0))
88!
  idx10 = cbind(as.integer(y0), as.integer(x1))
89!
  idx01 = cbind(as.integer(y1), as.integer(x0))
90!
  idx11 = cbind(as.integer(y1), as.integer(x1))
91
92!
  v00 = mat[idx00]
93!
  v10 = mat[idx10]
94!
  v01 = mat[idx01]
95!
  v11 = mat[idx11]
96
97!
  interp = v00 *
98!
    (1 - dx) *
99!
    (1 - dy) +
100!
    v10 * dx * (1 - dy) +
101!
    v01 * (1 - dx) * dy +
102!
    v11 * dx * dy
103!
  result[valid] = interp
104!
  return(result)
105
}
1
#'@title Stack Images
2
#'
3
#'@description Stacks a list of images vertically or horizontally into a single image.
4
#'
5
#'@param input_list List of 3-layer RGB/4-layer RGBA array, `rayimg` class, or image filenames.
6
#'@param stack Default `"v"`. Stack direction: `"v"`/`"vertical"` or `"h"`/`"horizontal"`.
7
#'@param align Default `"center"`. Alignment on the non-stacking axis. Options:
8
#'`"start"`/`"left"`/`"top"`, `"center"`, `"end"`/`"right"`/`"bottom"`.
9
#'@param background Default `c(0,0,0,0)`. Background color for padding, as numeric
10
#'`c(r,g,b[,a])` in 0..1 or a color string.
11
#'@param convert_colorspace Default `TRUE`. Whether to convert all images to match
12
#'the colorspace of the first image in the list.
13
#'@param filename Default `NULL`. File to save the image to. If `NULL` and `preview = FALSE`,
14
#'returns an RGB array.
15
#'@param preview Default `FALSE`. If `TRUE`, it will display the image in addition
16
#'to returning it.
17
#'
18
#'@return A `rayimg` RGBA array.
19
#'@export
20
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
21
#'render_stack(list(dragon, 1 - dragon), stack = "h") |>
22
#'  plot_image()
23
#'render_stack(list(dragon, render_bw(dragon)), stack = "v") |>
24
#'  plot_image()
25
render_stack = function(
26
  input_list,
27
  stack = c("v", "h", "vertical", "horizontal"),
28
  align = c("center", "start", "end", "left", "right", "top", "bottom"),
29
  background = c(0, 0, 0, 0),
30
  convert_colorspace = TRUE,
31
  filename = NULL,
32
  preview = FALSE
33
) {
343x
  if (!inherits(input_list, "list") || length(input_list) == 0) {
35!
    stop("`input_list` must be a non-empty list of images.")
36
  }
373x
  if (any(vapply(input_list, is.null, logical(1)))) {
38!
    stop("`input_list` cannot contain NULL entries.")
39
  }
40
413x
  if (missing(stack)) {
42!
    stack = "v"
43
  } else {
443x
    stack = tolower(stack)
45
  }
463x
  stack = match.arg(stack, c("v", "h", "vertical", "horizontal"))
473x
  is_vertical = stack %in% c("v", "vertical")
483x
  if (missing(align)) {
491x
    align = "center"
50
  } else {
512x
    align = tolower(align)
52
  }
533x
  align = match.arg(
543x
    align,
553x
    c("center", "start", "end", "left", "right", "top", "bottom")
56
  )
573x
  align = switch(
583x
    align,
593x
    left = "start",
603x
    top = "start",
613x
    right = "end",
623x
    bottom = "end",
633x
    align
64
  )
65
663x
  images = lapply(input_list, function(img) {
676x
    ray_read_image(
686x
      img,
696x
      convert_to_array = TRUE,
706x
      reset_camera_settings = TRUE
71
    )
72
  })
73
743x
  base_image = images[[1]]
753x
  base_colorspace = attr(base_image, "colorspace")
763x
  base_white = attr(base_image, "white_current")
77
783x
  if (convert_colorspace) {
79!
    for (i in seq_along(images)) {
80!
      images[[i]] = render_convert_colorspace(
81!
        images[[i]],
82!
        to_mats = base_colorspace,
83!
        to_white = base_white
84
      )
85
    }
86!
    base_white = attr(images[[1]], "white_current")
87
  }
88
893x
  heights = vapply(images, function(img) dim(img)[1], numeric(1))
903x
  widths = vapply(images, function(img) dim(img)[2], numeric(1))
913x
  max_height = max(heights)
923x
  max_width = max(widths)
93
943x
  if (is_vertical) {
953x
    out_height = sum(heights)
963x
    out_width = max_width
97
  } else {
98!
    out_height = max_height
99!
    out_width = sum(widths)
100
  }
101
1023x
  bg = convert_color(background, single = TRUE)
1032x
  if (length(bg) == 3) {
104!
    bg = c(bg, 1)
105
  }
1062x
  stacked = array(0, dim = c(out_height, out_width, 4))
1072x
  stacked[,, 1] = bg[1]
1082x
  stacked[,, 2] = bg[2]
1092x
  stacked[,, 3] = bg[3]
1102x
  stacked[,, 4] = bg[4]
111
1122x
  align_offset = function(total, size) {
1134x
    extra = total - size
1144x
    if (extra < 0) {
115!
      stop("stacked size cannot be smaller than component size.")
116
    }
1172x
    switch(
1184x
      align,
1194x
      start = 1L,
120!
      center = floor(extra / 2) + 1L,
121!
      end = extra + 1L
122
    )
123
  }
124
1252x
  if (is_vertical) {
1262x
    row_start = 1L
1272x
    for (i in seq_along(images)) {
1284x
      img = unclass(images[[i]])
1294x
      h = dim(img)[1]
1304x
      w = dim(img)[2]
1314x
      col_start = align_offset(max_width, w)
1324x
      rows = row_start:(row_start + h - 1L)
1334x
      cols = col_start:(col_start + w - 1L)
1344x
      stacked[rows, cols, ] = img
1354x
      row_start = row_start + h
136
    }
137
  } else {
138!
    col_start = 1L
139!
    for (i in seq_along(images)) {
140!
      img = unclass(images[[i]])
141!
      h = dim(img)[1]
142!
      w = dim(img)[2]
143!
      row_start = align_offset(max_height, h)
144!
      rows = row_start:(row_start + h - 1L)
145!
      cols = col_start:(col_start + w - 1L)
146!
      stacked[rows, cols, ] = img
147!
      col_start = col_start + w
148
    }
149
  }
150
1512x
  stacked = ray_read_image(
1522x
    stacked,
1532x
    assume_colorspace = base_colorspace,
1542x
    assume_white = base_white,
1552x
    source_linear = TRUE
156
  )
1572x
  handle_image_output(stacked, filename = filename, preview = preview)
158
}
1
#' Check Filename
2
#'
3
#' @param file Filename to be checked
4
#' @return Filename
5
#' @keywords internal
6
#'
7
#' @examples
8
#' #Fake example
9
get_file_type = function(file) {
10789x
  if (is.character(file)) {
1161x
    ext = tolower(tools::file_ext(file))
1261x
    if (ext == "png") {
1346x
      imagetype = "png"
1415x
    } else if (ext %in% c("tif", "tiff")) {
152x
      imagetype = "tif"
1613x
    } else if (ext %in% c("jpeg", "jpg")) {
172x
      imagetype = "jpg"
1811x
    } else if (ext == "exr") {
194x
      imagetype = "exr"
207x
    } else if (ext == "hdr") {
211x
      imagetype = "hdr"
226x
    } else if (ext == "dng") {
23!
      imagetype = "dng"
246x
    } else if (ext == "tga") {
251x
      imagetype = "tga"
265x
    } else if (ext == "bmp") {
271x
      imagetype = "bmp"
284x
    } else if (ext == "psd") {
291x
      imagetype = "psd"
303x
    } else if (ext == "gif") {
311x
      imagetype = "gif"
322x
    } else if (ext == "pic") {
331x
      imagetype = "pic"
341x
    } else if (ext %in% c("pnm", "ppm", "pgm")) {
351x
      imagetype = "pnm"
36
    } else {
37!
      stop(
38
        "`",
39!
        file,
40!
        "` not recognized class (png, tiff, jpeg, exr, hdr, dng, tga, bmp, psd, gif, pic, pnm, array, matrix)."
41
      )
42
    }
43728x
  } else if (length(dim(file)) == 3 && dim(file)[3] == 1) {
44!
    imagetype = "matrix"
45728x
  } else if (length(dim(file)) == 3) {
46591x
    imagetype = "array"
47137x
  } else if (length(dim(file)) == 2) {
48137x
    imagetype = "matrix"
49!
  } else if (length(dim(file)) > 3) {
50!
    stop(
51!
      "Images can only be paths to image files, matrices, ",
52!
      "and arrays with fewer than 3 dimensions"
53
    )
54
  } else {
55!
    if (is.character(file)) {
56!
      stop(
57
        "`",
58!
        file,
59!
        "` not recognized class (png, tiff, jpeg, exr, hdr, dng, tga, bmp, psd, gif, pic, pnm, array, matrix)."
60
      )
61
    } else {
62!
      stop(
63!
        "input not recognized class (png, tiff, jpeg, exr, hdr, dng, tga, bmp, psd, gif, pic, pnm, array, matrix)."
64
      )
65
    }
66
  }
67789x
  imagetype
68
}
1
#' Add a Small Corner Tagline
2
#'
3
#' Render a single line of text in a corner without resizing the image. The
4
#' default monospace font and size keep the tagline small across resolutions.
5
#' Text is alpha-composited using the image's colorspace.
6
#'
7
#' @param image RGB/RGBA array, `rayimg`, or image filename.
8
#' @param text Single-line tagline to add.
9
#' @param corner Default `"bottomright"`. One of `"bottomright"`,
10
#'   `"bottomleft"`, `"topright"`, or `"topleft"`.
11
#' @param size Default `NULL`. Font size in pixels at 72 dpi. `NULL` uses
12
#'   the image width divided by 64, rounded, with a minimum of 6.
13
#' @param padding Default `NULL`. Inset from both corner edges in pixels.
14
#'   `NULL` uses the image width divided by 64, rounded, with a minimum of 4.
15
#' @param font Default `"mono"`. Font family; the default is fixed-width.
16
#' @param color Default `"white"`. Text color.
17
#' @param alpha Default `0.7`. Text opacity, between zero and one.
18
#' @param filename Default `NULL`. Optional output image filename.
19
#' @param preview Default `FALSE`. Display the result as well as returning it.
20
#' @return A `rayimg` array, invisibly when saved or previewed. RGB/RGBA array
21
#'   inputs retain their channel count. Text that does not fit raises an error;
22
#'   reduce `size` or `padding`, or shorten `text`.
23
#' @export
24
#' @examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
25
#' render_tagline(dragon, "Created with rayrender", preview = TRUE)
26
render_tagline = function(
27
  image,
28
  text,
29
  corner = "bottomright",
30
  size = NULL,
31
  padding = NULL,
32
  font = "mono",
33
  color = "white",
34
  alpha = .7,
35
  filename = NULL,
36
  preview = FALSE
37
) {
3815x
  corner = match.arg(
3915x
    corner,
4015x
    c("bottomright", "bottomleft", "topright", "topleft")
41
  )
42
  if (
4314x
    !is.character(text) ||
4414x
      length(text) != 1L ||
4514x
      is.na(text) ||
4614x
      !nzchar(trimws(text)) ||
4714x
      grepl("[\r\n]", text)
48
  ) {
492x
    stop("`text` must be one nonempty line.")
50
  }
51
  if (
5212x
    !is.character(font) || length(font) != 1L || is.na(font) || !nzchar(font)
53
  ) {
54!
    stop("`font` must be one nonempty font family.")
55
  }
56
  if (
5712x
    !is.numeric(alpha) ||
5812x
      length(alpha) != 1L ||
5912x
      !is.finite(alpha) ||
6012x
      alpha < 0 ||
6112x
      alpha > 1
62
  ) {
631x
    stop("`alpha` must be a number between zero and one.")
64
  }
6511x
  source = ray_read_image(image, convert_to_array = TRUE)
6611x
  height = dim(source)[1]
6711x
  width = dim(source)[2]
6811x
  if (is.null(size)) {
694x
    size = max(6, round(width / 64))
70
  }
7111x
  if (is.null(padding)) {
726x
    padding = max(4, round(width / 64))
73
  }
74
  if (
7511x
    !is.numeric(size) || length(size) != 1L || !is.finite(size) || size <= 0
76
  ) {
771x
    stop("`size` must be a positive number.")
78
  }
79
  if (
8010x
    !is.numeric(padding) ||
8110x
      length(padding) != 1L ||
8210x
      !is.finite(padding) ||
8310x
      padding < 0 ||
8410x
      padding != round(padding)
85
  ) {
861x
    stop("`padding` must be a nonnegative integer.")
87
  }
889x
  label = render_text_image(
899x
    text,
909x
    size = size,
919x
    font = font,
929x
    color = color,
939x
    background_alpha = 0,
949x
    trim = TRUE
95
  )
969x
  if (ncol(label) + 2 * padding > width || nrow(label) + 2 * padding > height) {
971x
    stop("Tagline does not fit. Reduce `size` or `padding`, or shorten `text`.")
98
  }
998x
  right = corner %in% c("bottomright", "topright")
1008x
  bottom = corner %in% c("bottomright", "bottomleft")
101
  # Sprite anchors use inclusive, one-based pixel coordinates. This leaves
102
  # exactly `padding` untouched rows/columns outside the glyph bounding box.
1038x
  coords = c(
1048x
    if (right) width - padding else padding + 1,
1058x
    if (bottom) height - padding else padding + 1
106
  )
1078x
  anchor = switch(
1088x
    corner,
1098x
    bottomright = "se",
1108x
    bottomleft = "sw",
1118x
    topright = "ne",
1128x
    topleft = "nw"
113
  )
1148x
  render_sprite_overlay(
1158x
    image,
1168x
    label,
1178x
    overlay_coords = coords,
1188x
    overlay_anchor = anchor,
1198x
    alpha = alpha,
1208x
    filename = filename,
1218x
    preview = preview
122
  )
123
}
1
#' @title Render Convert Colorspace
2
#' @description Convert between two RGB spaces via XYZ, with optional white adaptation. Operates on **linear** RGB.
3
#'
4
#' @param image 3-layer RGB/4-layer RGBA array, `rayimg`, or filename.
5
#' @param from_mats Default `NA`. Source space object; when `NA`, pulled from `attr(src,"colorspace")`.
6
#' @param to_mats   Default `CS_ACESCG`. Target space object.
7
#' @param adapt_white Default `TRUE`. Apply Bradford CAT from `from_white` to `to_white`.
8
#' @param from_white Default `NA`. Source white (name or XYZ, Y=1). When `NA`, uses `attr(src,"white_current")`.
9
#' @param to_white   Default `NA`. Target white (name or XYZ, Y=1). When `NA`, uses `to_mats$white_xyz`.
10
#' @param filename Default `NULL`. Output path.
11
#' @param preview  Default `FALSE`. If `TRUE`, display the image.
12
#' @return A `rayimg` RGBA array tagged with the **target** space.
13
#' @export
14
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
15
#' # Read photo, convert to ACEScg with CAT (scene)
16
#' 	photo = ray_read_image(sunset_image, normalize = FALSE)
17
#' 	photo_aces = render_convert_colorspace(
18
#' 		photo,
19
#' 		to_mats = CS_ACESCG,
20
#' 		adapt_white = TRUE
21
#' 	)
22
#' 	tmp_txt = tempfile(fileext = ".png")
23
#' 	render_text_image(
24
#' 		"Sunset",
25
#' 		size = 60,
26
#' 		filename = tmp_txt,
27
#' 		color = "#c300ffff",
28
#' 		background_alpha = 0
29
#' 	)
30
#' 	# Read logo (display-referred), convert primaries only (no CAT)
31
#' 	logo = ray_read_image(tmp_txt, normalize = FALSE) # sRGB/D65
32
#' 	logo_aces = render_convert_colorspace(
33
#' 		logo,
34
#' 		to_mats = CS_ACESCG,
35
#' 		adapt_white = FALSE
36
#' 	)
37
#'
38
#' 	# Composite in ACEScg, then display (plot_image converts to sRGB/D65 + OETF)
39
#' 	# Here, we also turn overlay conversion in [render_image_overlay()] off,
40
#'  # to show what happens when you don't account for the colorspace difference.
41
#'  # By default [render_image_overlay()] will do this for you.
42
#' 	comp1 = render_image_overlay(
43
#' 		photo_aces,
44
#' 		logo_aces,
45
#' 		convert_overlay_colorspace = FALSE
46
#' 	)
47
#' 	comp2 = render_image_overlay(
48
#' 		photo_aces,
49
#' 		logo,
50
#' 		convert_overlay_colorspace = FALSE
51
#' 	)
52
#'   #Note the color differences, which arise from the mismatched colorspace on the right.
53
#' 	 plot_image_grid(list(comp1, comp2), dim = c(1, 2))
54
render_convert_colorspace = function(
55
  image,
56
  from_mats = NA,
57
  to_mats = CS_ACESCG,
58
  adapt_white = TRUE,
59
  from_white = NA,
60
  to_white = NA,
61
  filename = NULL,
62
  preview = FALSE
63
) {
6410x
  og_src = ray_read_image(image, normalize = FALSE)
6510x
  d = dim(og_src)
6610x
  if (length(d) != 3L || d[3] < 3L) {
67!
    return(handle_image_output(og_src, filename = filename, preview = preview))
68
  }
6910x
  src = ray_read_image(image, normalize = FALSE)
70
7110x
  if (is.atomic(from_mats) && length(from_mats) == 1L && is.na(from_mats)) {
7210x
    from_mats = attr(src, "colorspace")
73
  }
7410x
  stopifnot(is.list(from_mats), is.list(to_mats))
75
7610x
  if (is.atomic(from_white) && length(from_white) == 1L && is.na(from_white)) {
7710x
    from_white = attr(src, "white_current")
78
  }
7910x
  if (is.atomic(to_white) && length(to_white) == 1L && is.na(to_white)) {
8010x
    to_white = to_mats$white_xyz
81
  }
82
8310x
  src_wp = get_whitepoint_xyz(from_white)
8410x
  dst_wp = get_whitepoint_xyz(to_white)
85
86
  # Idempotence: same primaries, no CAT, and equal whites
8710x
  same_mats = isTRUE(all.equal(from_mats$rgb_to_xyz, to_mats$rgb_to_xyz)) &&
8810x
    isTRUE(all.equal(from_mats$xyz_to_rgb, to_mats$xyz_to_rgb))
8910x
  same_white = isTRUE(all.equal(src_wp$value, dst_wp$value))
9010x
  if (same_mats && (!adapt_white || same_white)) {
912x
    return(handle_image_output(src, filename = filename, preview = preview))
92
  }
93
94
  # Assert linear data
958x
  if (!isTRUE(attr(src, "source_linear"))) {
96!
    warning(
97!
      "render_convert_colorspace(): input is not linear; convert with render_gamma_linear(..., TRUE) first."
98
    )
99
  }
100
101
  # RGB(from) -> XYZ
1028x
  xyz = apply_color_matrix(src, from_mats$rgb_to_xyz)
103
104
  # Optional CAT in XYZ
1058x
  if (adapt_white && !isTRUE(all.equal(src_wp$value, dst_wp$value))) {
1068x
    CAT = compute_cat_bradford(src_wp$value, dst_wp$value)
1078x
    xyz = apply_color_matrix(xyz, CAT)
108
  }
109
110
  # XYZ -> RGB(to)
1118x
  out = apply_color_matrix(xyz, to_mats$xyz_to_rgb)
1128x
  if (d[3] == 4L) {
1137x
    out[,, 4] = src[,, 4]
114
  } # preserve alpha
115
116
  # Tag with the target space
1178x
  white_tag = if (adapt_white) dst_wp else src_wp
1188x
  to_mats$white_name = white_tag$white_name
119
1208x
  out = rayimg(
1218x
    out,
1228x
    filetype = attr(src, "filetype"),
1238x
    source_linear = TRUE,
1248x
    colorspace = to_mats,
1258x
    white_current = white_tag$value,
1268x
    exposure = attr(src, "exposure", exact = TRUE),
1278x
    iso = attr(src, "iso", exact = TRUE)
128
  )
129
1308x
  handle_image_output(out, filename = filename, preview = preview)
131
}
1
#' @title Render Color Correction Matrix (3x3, linear RGB)
2
#'
3
#' @description Apply a technical/look 3x3 matrix to an image
4
#'
5
#' @param image Default `NULL`. 3-layer RGB/4-layer RGBA array, `rayimg`, or filename.
6
#' @param matrix Default `diag(3)`. 3x3 numeric matrix.
7
#' @param filename Default `NULL`. Output path.
8
#' @param preview Default `FALSE`. If `TRUE`, display the image.
9
#' @return A `rayimg` RGBA array.
10
#' @export
11
#' @examples
12
#' # We will start with an image that's too warm--we want to correct it to
13
#' # match the color of the second as closely as possible.
14
#' dragon_D50 = render_white_balance(dragon, target_white = "D50", bake = TRUE)
15
#' dragon_D75 = render_white_balance(dragon, target_white = "D75", bake = TRUE)
16
#' plot_image(dragon_D50)
17
#' plot_image(dragon_D75)
18
#'
19
#' # Fucntion to fit a color correction matrix
20
#' fit_cc_matrix = function(src, tgt) {
21
#' 	stopifnot(ncol(src) == 3, ncol(tgt) == 3, nrow(src) == nrow(tgt))
22
#' 	M_t = apply(tgt, 2, function(y) qr.solve(src, y))
23
#' 	t(M_t)
24
#' }
25
#'
26
#' # Sample N RGBs from an image for fit
27
#' rand_samples = function(img, n = 5000, seed=1) {
28
#' 	set.seed(seed)
29
#' 	d = dim(img)
30
#' 	ys = sample.int(d[1], n, TRUE); xs = sample.int(d[2], n, TRUE)
31
#' 	cbind(img[cbind(ys,xs,1)], img[cbind(ys,xs,2)], img[cbind(ys,xs,3)])
32
#' }
33
#'
34
#' S = rand_samples(dragon_D50)
35
#' T = rand_samples(dragon_D75)
36
#'
37
#' M = fit_cc_matrix(S, T)
38
#' # Optionally, regularize toward identity to avoid overfitting
39
#' #  M = 0.8 * M + 0.2 * diag(3)
40
#'
41
#' updated_source = render_color_correction(dragon_D50, matrix = M)
42
#'
43
#' # Matching the old image (grey) to the target image (orange),
44
#' # giving a new image (black).
45
#' plot(S,pch=16,cex=0.5,col="grey")
46
#' points(T,pch=16,cex=0.5,col="orange")
47
#' points(rand_samples(updated_source,seed=2),pch=16,cex=0.5,col="black")
48
#'
49
#' # Plot the images
50
#' plot_image(render_title(dragon_D50, "OG Image",
51
#'            title_color = "white", title_size = 12))
52
#' plot_image(render_title(dragon_D75, "Target Image",
53
#'            title_color = "white", title_size = 12))
54
#' plot_image(render_title(updated_source, "Corrected OG Image",
55
#'            title_color = "white", title_size = 12))
56
render_color_correction = function(
57
  image,
58
  matrix = diag(3),
59
  filename = NULL,
60
  preview = FALSE
61
) {
62!
  stopifnot(is.matrix(matrix), all(dim(matrix) == c(3, 3)), is.numeric(matrix))
63!
  src = ray_read_image(
64!
    image,
65!
    convert_to_array = TRUE,
66!
    normalize = FALSE,
67!
    reset_camera_settings = TRUE
68
  )
69!
  imagetype = attr(src, "filetype")
70!
  img_source_linear = attr(src, "source_linear")
71!
  colorspace = attr(src, "colorspace")
72!
  white_current = attr(src, "white_current")
73
74!
  if (!isTRUE(attr(src, "source_linear"))) {
75!
    warning(
76!
      "render_color_correction(): input is not linear; convert with render_gamma_linear(..., TRUE) first."
77
    )
78
  }
79!
  d = dim(src)
80!
  if (length(d) != 3L) {
81!
    return(src)
82
  }
83!
  out = apply_color_matrix(src, matrix)
84!
  out[,, 1:3][out[,, 1:3] < 0] = 0
85!
  out = ray_read_image(
86!
    out,
87!
    filetype = imagetype,
88!
    source_linear = img_source_linear,
89!
    assume_colorspace = colorspace,
90!
    assume_white = white_current
91
  )
92!
  handle_image_output(out, filename = filename, preview = preview)
93
}
1
#' @title Generate Text Image
2
#'
3
#' @description Generates an image which tightly fits text.
4
#'
5
#' @param text Text to turn into an image.
6
#' @param color Default `"black"`. String specifying the color of the text.
7
#' @param size Default `12`. Numeric value specifying the font size of the text.
8
#' @param font Default `"sans"`. String specifying the font family for the text.
9
#' Common options include `"sans"`, `"mono"`, `"serif"`, `"Times"`, `"Helvetica"`, etc.
10
#' @param just Default `"left"`. Horizontal alignment of the text: `"left"`,
11
#' `"center"`, or `"right"`.
12
#' @param lineheight Default `1`. Multiplier for the lineheight.
13
#' @param background_color Default `"white"`. Color of the background.
14
#' @param background_alpha Default `1`. Transparency of the background. A value
15
#' between `0` (fully transparent) and `1` (fully opaque).
16
#' @param use_ragg Default `TRUE`. Whether to use the `ragg` package as the graphics device. Required for emojis.
17
#' @param width Default `NA`. User-defined textbox width.
18
#' @param height Default `NA`. User-defined textbox height.
19
#' @param check_text_width Default `TRUE`. Whether to manually adjust the bounding
20
#' box of the resulting image to ensure the string bbox is wide enough for the text.
21
#' Not all systems provide accurate font sizes: this ensures the string is not cut off
22
#' at the edges, at the cost of needing to repeatedly render the image internally until
23
#' a suitable image is found.
24
#' @param check_text_height Default `FALSE`. Whether to manually adjust the bounding
25
#' box of the resulting image to ensure the string bbox is tall enough for the text.
26
#' This will ensure a tight vertical bounding box on the text.
27
#' @param trim Default `FALSE`. If `TRUE`, post-process the rendered image by
28
#' cropping it to the tight bounding box of the text or emoji pixels. The
29
#' bounding box is measured from a transparent text mask, so this can also trim
30
#' images with opaque backgrounds.
31
#' @param trim_padding Default `0`. Padding in pixels to add after trimming. Use
32
#' a scalar for equal padding on all sides, or `c(top, right, bottom, left)`.
33
#' Nonzero padding implies `trim = TRUE`.
34
#' @param filename Default `NULL`. String specifying the file path to save the resulting image.
35
#' If `NULL` and `preview = FALSE`, the function returns the processed RGB array.
36
#' @param preview Default `FALSE`. Boolean indicating whether to display the image after processing.
37
#' If `TRUE`, the image is displayed but not saved or returned.
38
#'
39
#' @return A 3-layer RGB array of the processed image if `filename = NULL` and `preview = FALSE`.
40
#' Otherwise, writes the image to the specified file or displays it if `preview = TRUE`.
41
#'
42
#'
43
#' @import grDevices grid
44
#' @export
45
#'
46
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
47
#'   #Generate an image of some text
48
#'   render_text_image("Some text", preview = TRUE)
49
#'   #Change the font size
50
#'   render_text_image("Some text", size = 100, preview = TRUE)
51
#'   #Change the font color
52
#'   render_text_image("Some text", size = 100, color="red",preview = TRUE)
53
#'   #Change the background color and transparency
54
#'   render_text_image("Some text", size = 50, color="purple",
55
#'                       background_color="purple", background_alpha = 0.5,
56
#'                       preview = TRUE)
57
#'   # Plot an emoji with the agg device.
58
#'   render_text_image("\U0001F600\U0001F680", size = 50, color = "purple", use_ragg = TRUE,
59
#'                     background_alpha = 0,
60
#'                     preview = TRUE)
61
#'
62
#'   # Plot an emoji with the agg device and adjust the height and width (which
63
#'   # is on by default) to be a tight fit.
64
#'   render_text_image("\U0001F600\U0001F680", size = 50, color = "purple", use_ragg = TRUE,
65
#'                     background_alpha = 0, check_text_width = TRUE,
66
#'                     check_text_height = TRUE,
67
#'                     preview = TRUE)
68
#'
69
#'   # Trim the image to the rendered glyphs and then add transparent padding.
70
#'   render_text_image("\U0001F409", size = 80, use_ragg = TRUE,
71
#'                     background_alpha = 0, trim = TRUE, trim_padding = 8,
72
#'                     preview = TRUE)
73
render_text_image = function(
74
  text,
75
  lineheight = 1,
76
  color = "black",
77
  size = 12,
78
  font = "sans",
79
  just = "left",
80
  background_color = "white",
81
  background_alpha = 1,
82
  use_ragg = TRUE,
83
  width = NA,
84
  height = NA,
85
  filename = NULL,
86
  check_text_width = TRUE,
87
  check_text_height = TRUE,
88
  trim = FALSE,
89
  trim_padding = 0,
90
  preview = FALSE
91
) {
9213x
  if (!is.logical(trim) || length(trim) != 1 || is.na(trim)) {
93!
    stop("`trim` must be `TRUE` or `FALSE`.")
94
  }
9513x
  trim_padding = normalize_render_padding(trim_padding)
9613x
  trim_padding_values = unname(trim_padding)
9713x
  if (any(trim_padding_values > 0)) {
982x
    trim = TRUE
99
  }
10013x
  text_metrics = systemfonts::shape_string(
10113x
    text,
10213x
    size = size,
10313x
    vjust = 0.5,
10413x
    res = 72,
10513x
    lineheight = lineheight,
10613x
    family = font
10713x
  )[["metrics"]]
10813x
  bg_col = convert_color(background_color, as_hex = TRUE)
10913x
  metrics_string = systemfonts::string_metrics_dev(
11013x
    text,
11113x
    unit = "inches",
11213x
    size = size
113
  ) *
11413x
    72
11513x
  max_total_width = ceiling(metrics_string$width) + 2
11613x
  max_total_height = ceiling(text_metrics$height)
11713x
  n_newlines = sum(strsplit(text, "") == "\n")
11813x
  if (!is.na(width)) {
1194x
    max_total_width = width
120
  }
12113x
  if (!is.na(height)) {
1224x
    max_total_height = height
123
  }
12413x
  final_array = array(
12513x
    1,
12613x
    dim = c(
12713x
      max_total_height,
12813x
      max_total_width,
12913x
      4
130
    )
131
  )
13213x
  temp_filename = tempfile(fileext = ".png")
13313x
  ray_write_image(final_array, temp_filename)
134
13513x
  temp_image = png::readPNG(temp_filename)
13613x
  image_width = ncol(temp_image)
13713x
  image_height = nrow(temp_image)
138
13913x
  render_text_alpha_mask = function(image_width, image_height) {
14029x
    png_device = linear_png_device(use_ragg = use_ragg)
14129x
    png_device(
14229x
      temp_filename,
14329x
      width = image_width,
14429x
      height = image_height,
14529x
      units = "px",
14629x
      pointsize = size,
14729x
      family = font,
14829x
      res = 72,
14929x
      bg = NA
150
    )
15129x
    dev_id = grDevices::dev.cur()
15229x
    close_device = function() {
15358x
      devs = grDevices::dev.list()
15458x
      if (!is.null(devs) && dev_id %in% devs) {
15529x
        grDevices::dev.off(which = dev_id)
156
      }
157
    }
15829x
    on.exit(close_device(), add = TRUE)
159
160
    #First write with no background
16129x
    grid::grid.newpage()
16229x
    grid::grid.rect(
16329x
      x = 0.5,
16429x
      y = 0.5,
16529x
      width = 1,
16629x
      height = 1,
16729x
      just = c("center"),
16829x
      default.units = "npc",
16929x
      gp = grid::gpar(
17029x
        fill = grDevices::adjustcolor("black", alpha.f = 0),
17129x
        col = NA
172
      )
173
    )
17429x
    grid::grid.text(
17529x
      label = text,
17629x
      x = 0.5,
17729x
      y = 0.5,
17829x
      default.units = "npc",
17929x
      just = c("center", "center"),
18029x
      gp = grid::gpar(
18129x
        fontsize = size,
18229x
        lineheight = lineheight,
18329x
        cex = 1,
18429x
        col = "black",
18529x
        fontfamily = font
186
      )
187
    )
18829x
    close_device()
18929x
    temp = png::readPNG(temp_filename)
19029x
    temp[,, 4]
191
  }
192
19313x
  test_edges = function(image_width, image_height) {
19417x
    text_alpha = render_text_alpha_mask(image_width, image_height)
19517x
    side_edges = text_alpha[c(1, nrow(text_alpha)), ]
19617x
    vert_edges = text_alpha[, c(1, ncol(text_alpha))]
19717x
    return(c(any(vert_edges > 0), any(side_edges > 0)))
198
  }
199
200
  #First write with no background
20113x
  if (check_text_width || check_text_height) {
2029x
    test_edge_vec = test_edges(image_width, image_height)
2039x
    if (!check_text_height) {
204!
      test_edge_vec[2] = FALSE
205
    }
2069x
    if (!check_text_width) {
207!
      test_edge_vec[1] = FALSE
208
    }
20917x
    while (any(test_edge_vec)) {
2108x
      if (test_edge_vec[1]) {
2118x
        image_width = image_width * 2
212
      }
2138x
      if (check_text_height) {
2148x
        if (test_edge_vec[2]) {
215!
          image_height = image_height * 2
216
        }
217
      }
2188x
      test_edge_vec = test_edges(image_width, image_height)
219
    }
220
2219x
    temp = png::readPNG(temp_filename)
2229x
    stopifnot(any(temp[,, 4] != 0))
223
2249x
    vert_bbox = range(which(apply(temp[,, 4], 1, sum) != 0))
2259x
    hori_bbox = range(which(apply(temp[,, 4], 2, sum) != 0))
226
2279x
    vert_blank = (vert_bbox[1] - 1) + (image_height - vert_bbox[2])
2289x
    hori_blank = (hori_bbox[1] - 1) + (image_width - hori_bbox[2])
2299x
    if (check_text_height) {
2309x
      image_height = image_height - vert_blank + size
231
    }
2329x
    image_width = image_width - hori_blank + size
233
  }
234
235
  #If no edges, proceed with normal render
23613x
  png_device = linear_png_device(use_ragg = use_ragg)
23713x
  png_device(
23813x
    temp_filename,
23913x
    width = image_width,
24013x
    height = image_height,
24113x
    units = "px",
24213x
    pointsize = size,
24313x
    family = font,
24413x
    res = 72,
24513x
    bg = NA
246
  )
247
24813x
  dev_id = grDevices::dev.cur()
24913x
  grid::grid.newpage()
25013x
  grid::grid.rect(
25113x
    x = 0.5,
25213x
    y = 0.5,
25313x
    width = 1,
25413x
    height = 1,
25513x
    just = c("center"),
25613x
    default.units = "npc",
25713x
    gp = grid::gpar(
25813x
      fill = grDevices::adjustcolor(bg_col, alpha.f = background_alpha),
25913x
      col = NA
260
    )
261
  )
262
26313x
  grid::grid.text(
26413x
    label = text,
26513x
    x = 0.5,
26613x
    y = 0.5,
26713x
    default.units = "npc",
26813x
    just = c("center", "center"),
26913x
    gp = grid::gpar(
27013x
      fontsize = size,
27113x
      lineheight = lineheight,
27213x
      cex = 1,
27313x
      col = convert_color(color, as_hex = TRUE),
27413x
      fontfamily = font
275
    )
276
  )
27713x
  grDevices::dev.off(which = dev_id)
278
27913x
  temp = ray_read_image(temp_filename, reset_camera_settings = TRUE)
28013x
  if (trim) {
28112x
    text_alpha = render_text_alpha_mask(image_width, image_height)
28212x
    text_rows = which(rowSums(text_alpha > 0) > 0)
28312x
    text_cols = which(colSums(text_alpha > 0) > 0)
28412x
    if (length(text_rows) > 0 && length(text_cols) > 0) {
28512x
      temp = temp[
28612x
        min(text_rows):max(text_rows),
28712x
        min(text_cols):max(text_cols),
288
        ,
28912x
        drop = FALSE
290
      ]
291
    }
292
  }
29313x
  if (any(trim_padding_values > 0)) {
2942x
    temp = render_padding(
2952x
      temp,
2962x
      pad = trim_padding,
2972x
      color = background_color,
2982x
      alpha = background_alpha,
2992x
      preview = FALSE
300
    )
301
  }
302
30313x
  handle_image_output(temp, filename = filename, preview = preview)
304
}
1
#'@title Render Boolean Distance
2
#'
3
#'@description Takes a logical matrix and returns the nearest distance to each TRUE value.
4
#'
5
#'@param boolean Logical matrix (or matrix of 1s and 0s), where distance will be measured to the `TRUE` values.
6
#'@param rescale Default `FALSE`. Rescales the calculated distance to a range of 0-1.
7
#'Useful for visualizing the distance matrix.
8
#'@return Matrix of distance values.
9
#'@export
10
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
11
#'#Measure distance to
12
#'plot_image(render_boolean_distance(t(volcano) > 150))
13
#'plot_image(render_boolean_distance(t(volcano) < 150))
14
#'#If we want to rescale this to zero to one (to visualize like an image), set rescale=TRUE
15
#'plot_image(render_boolean_distance(t(volcano) > 150,rescale=TRUE))
16
render_boolean_distance = function(boolean, rescale = FALSE) {
177x
  if (any(is.na(boolean))) {
18!
    stop("`boolean` must not have any NA values")
19
  }
207x
  distval = get_boolean_distance(boolean)
217x
  if (rescale) {
22!
    if (min(distval) != max(distval)) {
23!
      distval = (distval - min(distval)) / (max(distval) - min(distval))
24
    }
25!
    return(distval)
26
  } else {
277x
    return(distval)
28
  }
29
}
1
#'@title Render Bokeh
2
#'
3
#'@description Takes an image and a depth map to render the image with depth of field
4
#'(i.e. similar to "Portrait Mode" in an iPhone). User can specify a custom bokeh shape,
5
#'or use one of the built-in bokeh types.
6
#'
7
#'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
8
#'@param depthmap Depth map filename or 1d array.
9
#'@param focus Defaults `0.5`. Depth in which to blur.
10
#'@param focallength Default `100`. Focal length of the virtual camera.
11
#'@param fstop Default `4`. F-stop of the virtual camera.
12
#'@param filename Default `NULL`. The filename of the image to be saved. If this is not given, the image will be plotted instead.
13
#'@param preview Default `TRUE`. If `FALSE`, it will not display the image and just return the RGB array.
14
#'@param preview_focus Default `FALSE`. If `TRUE`, a red line will be drawn across the image
15
#'showing where the camera will be focused.
16
#'@param bokehshape Default `circle`. Also built-in: `hex`. The shape of the bokeh. If the user
17
#'passes in a 2D matrix, that matrix will control the shape of the bokeh.
18
#'@param bokehintensity Default `1`. Intensity of the bokeh when the pixel intensity is greater than `bokehlimit`.
19
#'@param bokehlimit Default `0.8`. Limit after which the bokeh intensity is increased by `bokehintensity`.
20
#'@param rotation Default `0`. Number of degrees to rotate the hexagonal bokeh shape.
21
#'@param aberration Default `0`. Adds chromatic aberration to the image. Maximum of `1`.
22
#'@param progress Default `TRUE`. Whether to display a progress bar.
23
#'@param ... Additional arguments to pass to [plot_image()] if `preview = TRUE`.
24
#'@return A `rayimg` RGBA array.
25
#'@export
26
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
27
#'#Plot the dragon
28
#'plot_image(dragon)
29
#'#Plot the depth map
30
#' plot_image(dragondepth/1500)
31
#'#Preview the focal plane:
32
#'render_bokeh(dragon, dragondepth, focus=950, preview_focus = TRUE)
33
#'#Change the focal length:
34
#'render_bokeh(dragon, dragondepth, focus=950, focallength=300)
35
#'#Add chromatic aberration:
36
#'render_bokeh(dragon, dragondepth, focus=950, focallength=300, aberration = 0.5)
37
#'#Change the focal distance:
38
#'render_bokeh(dragon, dragondepth, focus=600, focallength=300)
39
#'render_bokeh(dragon, dragondepth, focus=1300, focallength=300)
40
#'#Change the bokeh shape to a hexagon:
41
#'render_bokeh(dragon, dragondepth, bokehshape = "hex",
42
#'             focallength=300, focus=600)
43
#'#Change the bokeh intensity:
44
#'render_bokeh(dragon, dragondepth,
45
#'             focallength=400, focus=900, bokehintensity = 1)
46
#'render_bokeh(dragon, dragondepth,
47
#'             focallength=400, focus=900, bokehintensity = 3)
48
#'#Rotate the hexagonal shape:
49
#'render_bokeh(dragon, dragondepth, bokehshape = "hex", rotation=15, bokehintensity=3,
50
#'             focallength=400, focus=800)
51
render_bokeh = function(
52
  image,
53
  depthmap,
54
  focus = 0.5,
55
  focallength = 100,
56
  fstop = 4,
57
  filename = NULL,
58
  preview = TRUE,
59
  preview_focus = FALSE,
60
  bokehshape = "circle",
61
  bokehintensity = 1,
62
  bokehlimit = 0.8,
63
  rotation = 0,
64
  aberration = 0,
65
  progress = interactive(),
66
  ...
67
) {
68!
  temp_image = ray_read_image(image, reset_camera_settings = TRUE) #Always output RGBA array
69
  #Check if file or image before below:
70!
  imagetype = attr(temp_image, "filetype")
71
72!
  depthmap = ray_read_image(
73!
    depthmap,
74!
    convert_to_array = FALSE,
75!
    reset_camera_settings = TRUE
76
  )
77!
  depthtype = attr(depthmap, "filetype")
78
79!
  if (preview_focus) {
80!
    preview_focus(image, depthmap, focus, imagetype, depthtype)
81!
    return(invisible())
82
  }
83!
  if (is.matrix(bokehshape)) {
84!
    custombokeh = bokehshape
85!
    bokehshape = 2L
86
  } else {
87!
    if (bokehshape == "circle") {
88!
      bokehshape = 0L
89
    } else {
90!
      bokehshape = 1L
91
    }
92!
    custombokeh = matrix(1, 1, 1)
93
  }
94!
  if (aberration >= 1 || aberration <= -1) {
95!
    stop("aberration value must be less than 1 and greater than -1")
96
  }
97
98!
  if (length(dim(depthmap)) == 3) {
99!
    depthmap = depthmap[,, 1]
100
  }
101
102!
  depthmap[is.na(depthmap)] = max(depthmap, na.rm = TRUE) * 2
103
104!
  for (i in 1:3) {
105!
    max_size = min(c(max(dim(depthmap)), 500))
106!
    if (i == 1) {
107!
      depthmap2 = calc_bokeh_size(
108!
        depthmap,
109!
        focus,
110!
        focallength,
111!
        fstop,
112!
        1 + aberration
113
      )
114!
    } else if (i == 2) {
115!
      depthmap2 = calc_bokeh_size(depthmap, focus, focallength, fstop, 1)
116
    } else {
117!
      depthmap2 = calc_bokeh_size(
118!
        depthmap,
119!
        focus,
120!
        focallength,
121!
        fstop,
122!
        1 - aberration
123
      )
124
    }
125!
    if (any(dim(depthmap2)[1:2] != dim(temp_image)[1:2])) {
126!
      stop(sprintf(
127!
        "{rayimage}: dimensions of image (%ix%i) and depth map (%ix%i) don't match",
128!
        dim(temp_image)[1],
129!
        dim(temp_image)[2],
130!
        dim(depthmap2)[1],
131!
        dim(depthmap2)[2]
132
      ))
133
    }
134!
    depthmap2[depthmap2 > max_size] = max_size
135!
    temp_image[,, i] = psf(
136!
      temp_image[,, i],
137!
      depthmap2,
138!
      depthmap,
139!
      focus,
140!
      bokehshape,
141!
      custombokeh = custombokeh,
142!
      bokehintensity,
143!
      bokehlimit,
144!
      rotation,
145!
      progbar = progress,
146!
      channel = i
147
    )
148
  }
149!
  handle_image_output(temp_image, filename = filename, preview = preview)
150
}
1
#' @title Build RGB-to-XYZ matrices from primaries + white
2
#' @param primaries Default `list(r=c(0.713,0.293), g=c(0.165,0.830), b=c(0.128,0.044))`. xy chromaticities (AP1).
3
#' @param white_xy Default `c(0.32168,0.33767)`. White xy (D60).
4
#' @return List with 3x3 numeric matrices: `rgb_to_xyz`, `xyz_to_rgb`.
5
#' @keywords internal
6
make_rgb_xyz_matrices = function(
7
  primaries = list(
8
    r = c(0.713, 0.293),
9
    g = c(0.165, 0.830),
10
    b = c(0.128, 0.044)
11
  ),
12
  white_xy = c(0.32168, 0.33767) # D60
13
) {
142x
  xy_to_XYZ = function(xy) c(xy[1] / xy[2], 1, (1 - xy[1] - xy[2]) / xy[2])
152x
  Xr = xy_to_XYZ(primaries$r)
162x
  Xg = xy_to_XYZ(primaries$g)
172x
  Xb = xy_to_XYZ(primaries$b)
182x
  M = cbind(Xr, Xg, Xb)
192x
  W = xy_to_XYZ(white_xy)
202x
  S = solve(M, W)
212x
  rgb_to_xyz = M %*% diag(S)
222x
  xyz_to_rgb = solve(rgb_to_xyz)
232x
  list(rgb_to_xyz = rgb_to_xyz, xyz_to_rgb = xyz_to_rgb)
24
}
25
26
#' @title Build a colorspace descriptor
27
#' @param name Default `"ACEScg"`.
28
#' @param primaries Default AP1.
29
#' @param white_xy Default D60.
30
#' @return list(name, rgb_to_xyz, xyz_to_rgb, white_xyz, white_name)
31
#' @keywords internal
32
make_colorspace = function(
33
  name = "ACEScg",
34
  primaries = list(
35
    r = c(0.713, 0.293),
36
    g = c(0.165, 0.830),
37
    b = c(0.128, 0.044)
38
  ),
39
  white_xy = c(0.32168, 0.33767), # D60
40
  white_name = "D60"
41
) {
422x
  mats = make_rgb_xyz_matrices(primaries = primaries, white_xy = white_xy)
432x
  xy_to_XYZ = function(xy) c(xy[1] / xy[2], 1, (1 - xy[1] - xy[2]) / xy[2])
442x
  list(
452x
    name = name,
462x
    primaries = primaries,
472x
    rgb_to_xyz = mats$rgb_to_xyz,
482x
    xyz_to_rgb = mats$xyz_to_rgb,
492x
    white_xyz = xy_to_XYZ(white_xy),
502x
    white_name = white_name
51
  )
52
}
53
54
#' Prebuilt RGB Working/Display Color Spaces
55
#'
56
#' @title Prebuilt RGB Working/Display Color Spaces
57
#'
58
#' @description
59
#' These objects are **color space descriptors** used by `rayimage` to tag images
60
#' and to convert between RGB spaces. Each descriptor is a named list with:
61
#'
62
#' - `name`: Character. Human-readable name of the space.
63
#' - `primaries`: List with `r`, `g`, `b` entries giving xy chromaticities.
64
#' - `rgb_to_xyz`: 3x3 numeric matrix (linear RGB -> CIE XYZ, Y=1 white).
65
#' - `xyz_to_rgb`: 3x3 numeric matrix (CIE XYZ -> linear RGB).
66
#' - `white_xyz`: Length-3 numeric XYZ of the reference white (normalized s.t. Y = 1).
67
#' - `white_name`: Character label for the white (e.g., `"D60"`, `"D65"`).
68
#'
69
#' These are used as:
70
#' - `attr(img, "colorspace")`: the current working/display space for an image.
71
#' - `attr(img, "white_current")`: the current assumed scene/display white (XYZ, Y=1).
72
#'
73
#' @details
74
#' - **CS_ACESCG**: ACEScg (AP1 primaries, D60, scene-linear). Recommended working space.
75
#' - **CS_SRGB**: sRGB/Rec.709 (D65). Typical display space; used for PNG/JPEG/TIFF output.
76
#' - **CS_P3D65**: Display P3 (D65). Wide-gamut display space.
77
#' - **CS_BT2020**: BT.2020 (D65). Very wide-gamut; common for HDR mastering.
78
#' - **CS_ADOBE**: Adobe RGB (D65). Photo workflows.
79
#'
80
#' @seealso
81
#' - [render_convert_colorspace()] to convert images between spaces.
82
#' - [render_white_balance()] for Bradford CAT within a working space.
83
#' - [plot_image()], [ray_write_image()] for display/output conversion.
84
#'
85
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
86
#'   # Tag a raw array as sRGB, then convert to ACEScg:
87
#'   arr = array(runif(64*64*4), dim = c(64, 64, 4))
88
#'   ri  = ray_read_image(arr, assume_colorspace = CS_SRGB, assume_white = CS_SRGB$white_xyz)
89
#'   riA = render_convert_colorspace(ri, to_mats = CS_ACESCG)
90
#'   plot_image(riA) # display-converted to sRGB automatically
91
#'
92
#'   # Convert an sRGB JPEG to ACEScg on ingest:
93
#'   # img = ray_read_image("photo.jpg", normalize = FALSE)
94
#'   # img_aces = render_convert_colorspace(img, to_mats = CS_ACESCG)
95
#'
96
#' @name colorspace_descriptors
97
NULL
98
99
#' @rdname colorspace_descriptors
100
#' @export
101
CS_ACESCG = make_colorspace(
102
  name = "ACEScg",
103
  primaries = list(
104
    r = c(0.713, 0.293),
105
    g = c(0.165, 0.830),
106
    b = c(0.128, 0.044)
107
  ),
108
  white_xy = c(0.32168, 0.33767), # D60
109
  white_name = "D60"
110
)
111
112
#' @rdname colorspace_descriptors
113
#' @export
114
CS_SRGB = make_colorspace(
115
  name = "sRGB",
116
  primaries = list(
117
    r = c(0.64, 0.33),
118
    g = c(0.30, 0.60),
119
    b = c(0.15, 0.06)
120
  ),
121
  white_xy = c(0.3127, 0.3290), # D65
122
  white_name = "D65"
123
)
124
125
#' @rdname colorspace_descriptors
126
#' @export
127
CS_P3D65 = make_colorspace(
128
  name = "P3-D65",
129
  primaries = list(
130
    r = c(0.680, 0.320),
131
    g = c(0.265, 0.690),
132
    b = c(0.150, 0.060)
133
  ),
134
  white_xy = c(0.3127, 0.3290), # D65
135
  white_name = "D65"
136
)
137
138
#' @rdname colorspace_descriptors
139
#' @export
140
CS_BT2020 = make_colorspace(
141
  name = "BT.2020",
142
  primaries = list(
143
    r = c(0.708, 0.292),
144
    g = c(0.170, 0.797),
145
    b = c(0.131, 0.046)
146
  ),
147
  white_xy = c(0.3127, 0.3290), # D65
148
  white_name = "D65"
149
)
150
151
#' @rdname colorspace_descriptors
152
#' @export
153
CS_ADOBE = make_colorspace(
154
  name = "AdobeRGB",
155
  primaries = list(
156
    r = c(0.64, 0.33),
157
    g = c(0.21, 0.71),
158
    b = c(0.15, 0.06)
159
  ),
160
  white_xy = c(0.3127, 0.3290), # D65
161
  white_name = "D65"
162
)
1
#'@title Plot Native Raster with Custom Aspect Ratio
2
#'
3
#'@keywords internal
4
plot_asp_native_raster = function(
5
  nr,
6
  asp = 1,
7
  show = FALSE,
8
  return_grob = FALSE,
9
  gp = grid::gpar(),
10
  angle = 0
11
) {
1236x
  stopifnot(asp > 0)
1336x
  native_dim = dim(nr)
1436x
  image_width = native_dim[2]
1536x
  image_height = native_dim[1]
1636x
  asp = asp * image_width / image_height
1736x
  if (asp > 1) {
18!
    gl = grid::grid.layout(
19!
      1,
20!
      1,
21!
      widths = grid::unit(1, "null"),
22!
      heights = grid::unit(1 / asp, "null"),
23!
      respect = TRUE
24
    )
25
  } else {
2636x
    gl = grid::grid.layout(
2736x
      1,
2836x
      1,
2936x
      widths = grid::unit(1 * asp, "null"),
3036x
      heights = grid::unit(1, "null"),
3136x
      respect = TRUE
32
    )
33
  }
34
3536x
  needs_rotation = !isTRUE(all.equal(angle %% 360, 0))
3636x
  clip_setting = if (needs_rotation) "off" else "inherit"
37
3836x
  top.vp = grid::viewport(
3936x
    layout = gl,
4036x
    name = "grid_asp_container",
4136x
    clip = clip_setting
42
  )
4336x
  image_vp = grid::viewport(
4436x
    name = "image",
4536x
    layout.pos.col = 1,
4636x
    layout.pos.row = 1,
4736x
    xscale = c(0, image_width),
4836x
    yscale = c(image_height, 0),
4936x
    gp = gp,
5036x
    clip = clip_setting
51
  )
52
5336x
  image_grob = grid::rasterGrob(
5436x
    nr,
5536x
    interpolate = FALSE,
5636x
    width = grid::unit(1, "npc"),
5736x
    height = grid::unit(1, "npc"),
5836x
    gp = gp
59
  )
6036x
  if (needs_rotation) {
61!
    angle_norm = abs(angle) %% 180
62!
    if (angle_norm > 90) {
63!
      angle_norm = 180 - angle_norm
64
    }
65!
    angle_rad = angle_norm * pi / 180
66!
    width_rot = image_width * cos(angle_rad) + image_height * sin(angle_rad)
67!
    height_rot = image_width * sin(angle_rad) + image_height * cos(angle_rad)
68!
    scale_factor = max(width_rot / image_width, height_rot / image_height)
69!
    if (!is.finite(scale_factor) || scale_factor <= 0) {
70!
      scale_factor = 1
71
    }
72!
    image_grob = grid::editGrob(
73!
      image_grob,
74!
      vp = grid::viewport(
75!
        angle = angle,
76!
        clip = "off",
77!
        width = grid::unit(1 / scale_factor, "npc"),
78!
        height = grid::unit(1 / scale_factor, "npc")
79
      )
80
    )
81
  }
82
8336x
  if (return_grob) {
84!
    image_tree = grid::gTree(
85!
      children = grid::gList(image_grob),
86!
      vp = image_vp
87
    )
88!
    return(grid::gTree(
89!
      children = grid::gList(image_tree),
90!
      vp = top.vp
91
    ))
92
  }
93
9436x
  pushed = 0L
9536x
  grid::pushViewport(top.vp)
9636x
  pushed = pushed + 1L
97
9836x
  grid::pushViewport(image_vp)
9936x
  pushed = pushed + 1L
100
10136x
  on.exit(
102
    {
10336x
      if (pushed > 0L) {
10436x
        try(grid::popViewport(pushed), silent = TRUE)
105
      }
106
    },
10736x
    add = TRUE
108
  )
109
11036x
  grid::grid.draw(image_grob)
11136x
  invisible()
112
}
1
#'@title Generate 2D Gaussian Distribution
2
#'
3
#'@description Generates a 2D gaussian distribution, with an optional
4
#'argument to take the gaussian to a user-defined power.
5
#'
6
#'@param sd Default `1`. Standard deviation of the normal distribution
7
#'@param power Default `1`. Power to take the distribution. Higher values will result in a sharper peak.
8
#'@param dim Default `c(11, 11)`. The dimensions of the matrix.
9
#'@param width Default `3` (`-10` to `10`). The range in which to compute the distribution.
10
#'@param rescale_unity Default `FALSE`. If `TRUE`, this will rescale the max value to one. Useful
11
#'if wanting to plot the distribution with [plot_image()].
12
#'@import stats
13
#'@export
14
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
15
#'image(generate_2d_gaussian(1,1,31), asp=1)
16
generate_2d_gaussian = function(
17
  sd = 1,
18
  power = 1,
19
  dim = c(11, 11),
20
  width = 3,
21
  rescale_unity = FALSE
22
) {
23!
  if (length(dim) == 1) {
24!
    dim = c(dim, dim)
25
  }
26!
  mindim = min(dim)
27!
  xy_ratio = dim[1] / dim[2]
28!
  if (xy_ratio > 1) {
29!
    x = seq(-width * xy_ratio, width * xy_ratio, length.out = dim[1])
30!
    y = seq(-width, width, length.out = dim[2])
31
  } else {
32!
    x = seq(-width, width, length.out = dim[1])
33!
    y = seq(-width / xy_ratio, width / xy_ratio, length.out = dim[2])
34
  }
35!
  testmat = matrix(0, length(x), length(y))
36!
  if (sd == 0) {
37!
    sd == 0.00001
38
  }
39!
  if (length(x) > 0 && length(y) > 0) {
40!
    for (i in 1:length(x)) {
41!
      for (j in 1:length(y)) {
42!
        testmat[i, j] = (dnorm(power * x[i], mean = 0, sd = sd) *
43!
          dnorm(power * y[j], mean = 0, sd = sd))
44
      }
45
    }
46
  } else {
47!
    stop("Kernel dimension too small")
48
  }
49!
  if (rescale_unity) {
50!
    temp = testmat / sum(testmat)
51!
    return(temp / max(temp))
52
  }
53!
  testmat / sum(testmat)
54
}
1
#' Flip Left-Right
2
#'
3
#' @param x Matrix
4
#'
5
#' @return Flipped matrix
6
#' @keywords internal
7
#'
8
#' @examples
9
#' #Fake example
10
fliplr = function(x) {
11!
  if (length(dim(x)) == 2) {
12!
    x[, ncol(x):1]
13
  } else {
14!
    x[, ncol(x):1, ]
15
  }
16
}
17
18
19
#' Flip Up-Down
20
#'
21
#' @param x Matrix
22
#'
23
#' @return Flipped matrix
24
#' @keywords internal
25
#'
26
#' @examples
27
#' #Fake example
28
flipud = function(x) {
29!
  if (length(dim(x)) == 2) {
30!
    x[nrow(x):1, ]
31
  } else {
32!
    x[nrow(x):1, , ]
33
  }
34
}
1
rgb_to_hex = function(x) {
2
  if (is.null(dim(x))) {
3
    x = matrix(x, ncol = length(x), byrow = TRUE)
4
  }
5
  if (!(ncol(x) %in% c(3, 4))) {
6
    stop("rgb_to_hex(): expected 3 or 4 columns (R,G,B[,A]).")
7
  }
8
  x = pmin(pmax(x, 0), 1)
9
  ints = round(x * 255)
10
  paste0(
11
    "#",
12
    apply(ints, 1, function(row) {
13
      paste(sprintf("%02X", row), collapse = "")
14
    })
15
  )
16
}
17
18
#' Convert Color
19
#'
20
#' @param color The color to convert. Can be either an R color string, or a
21
#' numeric scalar, RGB vector, RGBA vector, or RGB/RGBA matrix with values
22
#' between `0` and `1`.
23
#' @param as_hex Default `FALSE`. If `TRUE`, return hex colors.
24
#' @param single Default `FALSE`. If `TRUE`, require exactly one color.
25
#'
26
#' @return RGB or RGBA color vector, or a color matrix for multiple colors.
27
#' @keywords internal
28
#'
29
#' @examples
30
#' #none
31
convert_color = function(color, as_hex = FALSE, single = FALSE) {
3267x
  if (is.null(color) || length(color) == 0) {
33!
    stop("invalid color")
34
  }
3567x
  if (is.character(color)) {
3658x
    color = t(grDevices::col2rgb(color, alpha = TRUE)) / 255
37
  } else {
389x
    if (!is.numeric(color)) {
39!
      stop("invalid color")
40
    }
419x
    color_dim = dim(color)
429x
    if (is.null(color_dim)) {
439x
      if (length(color) == 1) {
441x
        color = rep(color, 3)
45
      }
46
      if (
479x
        !(length(color) %in%
489x
          c(3, 4) ||
499x
          length(color) %% 3 == 0 ||
509x
          length(color) %% 4 == 0)
51
      ) {
522x
        stop("invalid color")
53
      }
547x
      color_channels = if (length(color) %% 3 == 0) 3 else 4
557x
      color = matrix(
567x
        color,
577x
        ncol = color_channels,
587x
        byrow = TRUE
59
      )
60
    } else {
61!
      if (length(color_dim) != 2 || !(color_dim[2] %in% c(3, 4))) {
62!
        stop("invalid color")
63
      }
64
    }
65
  }
6665x
  if (!all(is.finite(color))) {
67!
    stop("invalid color")
68
  }
6965x
  if (!all(color >= 0 & color <= 1)) {
70!
    stop("invalid color")
71
  }
7265x
  if (isTRUE(single) && nrow(color) != 1L) {
73!
    stop("invalid color")
74
  }
7565x
  if (as_hex) {
7627x
    return(rgb_to_hex(color))
77
  }
78
  # return vector for single row, matrix otherwise
79!
  if (nrow(color) == 1L) as.numeric(color[1, ]) else color
80
}
1
#'@title Generate 2D Disk
2
#'
3
#'@description Generates a 2D disk with a gradual falloff.
4
#'
5
#'Disk generated using the following formula:
6
#'
7
#'\ifelse{html}{\out{(-22.35 * cos(1.68 * r<sup>2</sup>) + 85.91 * sin(1.68 * r<sup>2</sup>) ) * exp(-4.89 * r<sup>2</sup>) +
8
#'(35.91 * cos(4.99 * r<sup>2</sup>) - 28.87 * sin(4.99 * r<sup>2</sup>)) * exp(-4.71 * r<sup>2</sup>) +
9
#'(-13.21 * cos(8.24 * r<sup>2</sup>) - 1.57 * sin(8.24 * r<sup>2</sup>)) * exp(-4.05 * r<sup>2</sup>) +
10
#'(0.50 * cos(11.90 * r<sup>2</sup>) + 1.81 * sin(11.90 * r<sup>2</sup>)) * exp(-2.92 * r<sup>2</sup>) +
11
#'(0.13 * cos(16.11 * r<sup>2</sup>) - 0.01 * sin(16.11 * r<sup>2</sup>)) * exp(-1.51 * r<sup>2</sup>)}}{(-22.35 cos(1.68 r^2) + 85.91 sin(1.68 r^2) ) exp(-4.89 r^2) +
12
#'(35.91 cos(4.99 r^2) - 28.87 sin(4.99 r^2)) exp(-4.71 r^2) +
13
#'(-13.21 cos(8.24 r^2) - 1.57 sin(8.24 r^2)) exp(-4.05 r^2) +
14
#'(0.50 cos(11.90 r^2) + 1.81 sin(11.90 r^2)) exp(-2.92 r^2) +
15
#'(0.13 cos(16.11 r^2) - 0.01 sin(16.11 r^2)) exp(-1.51 r^2)}
16
#'
17
#'The origin of the coordinate system is the center of the matrix.
18
#'
19
#'@param dim Default `c(11, 11)`. The dimensions of the matrix.
20
#'@param radius Default `1`. Radius of the disk, compared to the dimensions. Should be less than one.
21
#'@param rescale_unity Default `FALSE`. If `TRUE`, this will rescale the max value to one. Useful
22
#'if wanting to plot the distribution with [plot_image()].
23
#'@export
24
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
25
#'image(generate_2d_disk(101), asp=1)
26
generate_2d_disk = function(
27
  dim = c(11, 11),
28
  radius = 1,
29
  rescale_unity = FALSE
30
) {
31!
  dim = rev(dim)
32!
  mindim = min(dim)
33!
  add_offset_x = FALSE
34!
  add_offset_y = FALSE
35!
  if (length(dim) == 2) {
36!
    if (dim[2] - dim[1] > 0) {
37!
      if (abs(dim[2] - dim[1]) %% 2 != 0) {
38!
        add_offset_x = TRUE
39
      }
40!
    } else if (dim[2] - dim[1] < 0) {
41!
      if (abs(dim[2] - dim[1]) %% 2 != 0) {
42!
        add_offset_y = TRUE
43
      }
44
    }
45
  }
46!
  disk = generate_disk((1 / radius) * 1.18, mindim, add_offset_x, add_offset_y)
47!
  if (length(dim) == 2) {
48!
    disk = pad_to_fit(dim, disk)
49
  }
50!
  disk = (disk - min(disk)) / (max(disk) - min(disk))
51!
  disk = disk / sum(disk)
52!
  if (rescale_unity) {
53!
    return(disk / max(disk))
54
  }
55!
  return(disk)
56
}
1
#' Internal wrapper for stb_image C++ loader
2
#'
3
#' @description
4
#' Internal helper that loads an image via the C++ `load_image_stb()` function
5
#' and returns a 3D RGBA numeric array with dimensions `c(height, width, channels)`.
6
#'
7
#' @param filename Default `NULL`. Path to an image file to load.
8
#' @param desired_channels Default `4L`. Number of channels to request from the loader.
9
#'
10
#' @return A numeric 3D array (height, width, `desired_channels`).
11
#' @keywords internal
12
#' @noRd
13
read_image_stb = function(filename = NULL, desired_channels = 4L) {
147x
  if (!is.character(filename) || length(filename) != 1L) {
15!
    stop("'read_image_stb' expects a single filename string.")
16
  }
17
187x
  filename = normalizePath(filename, winslash = "/", mustWork = TRUE)
19
20
  # Dummy values required by the Rcpp-exported interface
217x
  width = 0L
227x
  height = 0L
237x
  channels = 0L
24
257x
  img = load_image_stb(
267x
    filename = filename,
277x
    width = width,
287x
    height = height,
297x
    channels = channels,
307x
    desired_channels = as.integer(desired_channels)
31
  )
32
337x
  if (!is.numeric(img)) {
34!
    stop("stb loader did not return a numeric array.")
35
  }
367x
  if (is.null(dim(img)) || length(dim(img)) != 3L) {
37!
    stop("stb loader did not return a 3D array.")
38
  }
397x
  if (dim(img)[3L] != desired_channels) {
40!
    stop(
41!
      sprintf(
42!
        "stb loader returned %d channels; expected %d.",
43!
        dim(img)[3L],
44!
        desired_channels
45
      )
46
    )
47
  }
48
497x
  storage.mode(img) = "double"
507x
  img
51
}
1
#'@title Make Vignette Overlay
2
#'
3
#'@description Makes an overlay to simulate vignetting in a camera
4
#'
5
#'@param width Width of the image.
6
#'@param height Height of the image.
7
#'@param intensity Default `0.4`. `1` is max intensity, `0` is min.
8
#'@param radius Default `NULL`. Max of height or width, divided by 2.
9
#'@param radius_multiplier Default `1.3`.
10
#'@param color Default `black`.
11
#'@keywords internal
12
make_vignette_overlay = function(
13
  width,
14
  height,
15
  intensity = 0.3,
16
  radius_multiplier = 1.3,
17
  radius = NULL,
18
  color = "#000000"
19
) {
20!
  value = array(
21!
    0,
22!
    dim = c(
23!
      floor(width * radius_multiplier),
24!
      floor(height * radius_multiplier),
25!
      4
26
    )
27
  )
28!
  hex_color = convert_color(color, as_hex = TRUE)
29!
  color = convert_color(color)
30!
  value[,, 4] = gen_ellipse(
31!
    intensity,
32!
    floor(width * radius_multiplier),
33!
    floor(height * radius_multiplier)
34
  )
35!
  value[,, 1] = color[1]
36!
  value[,, 2] = color[2]
37!
  value[,, 3] = color[3]
38
39!
  tempcircle = tempfile(fileext = ".png")
40!
  png::writePNG(value, tempcircle)
41!
  imageval = magick::image_read(tempcircle)
42!
  if (radius_multiplier >= 1) {
43!
    imageval |>
44!
      magick::image_blur(radius = radius / 2, sigma = radius / 4) |>
45!
      magick::image_crop(sprintf(
46!
        "%ix%i+%i+%i",
47!
        height,
48!
        width,
49!
        floor((height * radius_multiplier - height) / 2),
50!
        floor((width * radius_multiplier - width) / 2)
51
      )) |>
52!
      magick::image_write(tempcircle)
53
  } else {
54!
    imageval |>
55!
      magick::image_border(
56!
        geometry = sprintf(
57!
          "%ix%i",
58!
          (height - floor(height * radius_multiplier)) / 2,
59!
          (width - floor(width * radius_multiplier)) / 2
60
        ),
61!
        color = hex_color
62
      ) |>
63!
      magick::image_blur(radius = radius / 2, sigma = radius / 4) |>
64!
      magick::image_write(tempcircle)
65
  }
66!
  return(tempcircle)
67
}
1
#'@title Clamp Image
2
#'
3
#'@description Clamps an image to a user-specified range, ignoring the alpha channel.
4
#'
5
#'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
6
#'@param min_value Default `0`. Minimum value to clamp the RGB channels in the image to.
7
#'@param max_value Default `1`. Maximum value to clamp the RGB channels in the image to.
8
#'@param filename Default `NA`. Filename
9
#'@param preview Default `FALSE`. If `TRUE`, it will display the image in addition
10
#'to returning it.
11
#'@param ... Arguments to pass to either `jpeg::readJPEG`, `png::readPNG`, or `tiff::readTIFF`.
12
#'
13
#'@return A `rayimg` RGBA array.
14
#'@import grDevices
15
#'@export
16
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
17
#'#The image of the unchanged image
18
#'range(dragon)
19
#'#Clamp the maximum and minimum values to one and zero
20
#'render_clamp(dragon) |>
21
#'  range()
22
render_clamp = function(
23
  image,
24
  min_value = 0,
25
  max_value = 1,
26
  filename = NA,
27
  preview = FALSE,
28
  ...
29
) {
30174x
  image = ray_read_image(image, reset_camera_settings = TRUE) #Always output RGBA array
31174x
  imagetype = attr(image, "filetype")
32174x
  img_source_linear = attr(image, "source_linear")
33174x
  colorspace = attr(image, "colorspace")
34174x
  white_current = attr(image, "white_current")
35
36174x
  d = dim(image)
37174x
  alpha_idx = NA
38174x
  if (length(d) == 3) {
39112x
    if (d[3] == 4) {
40111x
      alpha_idx = 4
41
    }
42112x
    if (d[3] == 2) {
43!
      alpha_idx = 2
44
    }
45
  }
46174x
  array_image = unclass(image)
47174x
  if (length(d) == 2) {
4862x
    array_image[image < min_value] = min_value
4962x
    array_image[image > max_value] = max_value
5062x
    array_image = array(array_image, dim = d)
51
  } else {
52112x
    if (is.na(alpha_idx)) {
531x
      num_chans = 1:3
54
    } else {
55111x
      num_chans = seq_len(alpha_idx - 1)
56
    }
57112x
    array_image = unclass(image)
58112x
    for (chan in num_chans) {
59336x
      tmp_chan = array_image[,, chan]
60336x
      mat_d = dim(tmp_chan)
61336x
      tmp_chan[array_image[,, chan] < min_value] = min_value
62336x
      tmp_chan[array_image[,, chan] > max_value] = max_value
63336x
      array_image[,, chan] = array(tmp_chan, dim = mat_d)
64
    }
65
  }
66174x
  new_image = ray_read_image(
67174x
    array_image,
68174x
    filetype = imagetype,
69174x
    source_linear = img_source_linear,
70174x
    assume_colorspace = colorspace,
71174x
    assume_white = white_current
72
  )
73174x
  handle_image_output(new_image, filename = filename, preview = preview)
74
}
1
#'@title Render Black and White
2
#'
3
#'@description Transforms an image to black and white, preserving luminance.
4
#'
5
#'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
6
#'@param rgb_coef Default `c(0.2126, 0.7152, 0.0722)`.
7
#'Length-3 numeric vector listing coefficients to convert RGB to luminance.
8
#'@param filename Default `NULL`. The filename of the image to be saved. If this is not given, the image will be plotted instead.
9
#'@param preview Default `FALSE`. Whether to plot the convolved image, or just to return the values.
10
#'@return A `rayimg` RGBA array.
11
#'@export
12
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
13
#'#Plot the image with a title
14
#'dragon |>
15
#'  render_title("Dragon", title_offset=c(10,10), title_bar_color="black",
16
#'            title_size=20, title_color = "white") |>
17
#'  render_bw(preview = TRUE)
18
render_bw = function(
19
  image,
20
  rgb_coef = c(0.2126, 0.7152, 0.0722),
21
  filename = NULL,
22
  preview = FALSE
23
) {
24!
  stopifnot(length(rgb_coef) == 3 && is.numeric(rgb_coef))
25!
  src = ray_read_image(image, reset_camera_settings = TRUE)
26!
  imagetype = attr(src, "filetype")
27!
  img_source_linear = attr(src, "source_linear")
28!
  colorspace = attr(src, "colorspace")
29!
  white_current = attr(src, "white_current")
30
31!
  d = dim(src)
32!
  is_array = length(d) == 3
33
34!
  if (attr(src, "filetype") == "matrix" || (is_array && d[3] == 2)) {
35!
    return(handle_image_output(src, filename = filename, preview = preview))
36
  }
37
38
  # luminance
39!
  lum = rgb_coef[1] *
40!
    src[,, 1] +
41!
    rgb_coef[2] * src[,, 2] +
42!
    rgb_coef[3] * src[,, 3]
43
44!
  if (length(dim(src)) == 2) {
45!
    out = lum
46
  } else {
47!
    out = array(1, dim = c(d[1], d[2], 2))
48!
    out[,, 1] = lum
49!
    out[,, 2] = if (d[3] == 4L) src[,, 4] else 1
50
  }
51
52!
  out = ray_read_image(
53!
    out,
54!
    filetype = imagetype,
55!
    source_linear = img_source_linear,
56!
    assume_colorspace = colorspace,
57!
    assume_white = white_current
58
  )
59
60!
  handle_image_output(out, filename = filename, preview = preview)
61
}
1
#'@title Generate 2D exponential Distribution
2
#'
3
#'@description Generates a 2D exponential distribution, with an optional
4
#'argument to take the exponential to a user-defined power.
5
#'
6
#'@param falloff Default `1`. Falloff of the exponential.
7
#'@param dim Default `c(11, 11)`. The dimensions of the matrix.
8
#'@param width Default `3` (`-10` to `10`). The range in which to compute the distribution.
9
#'@param rescale_unity Default `FALSE`. If `TRUE`, this will rescale the max value to one. Useful
10
#'if wanting to plot the distribution with [plot_image()].
11
#'@import stats
12
#'@export
13
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
14
#'image(generate_2d_exponential(1,31,3), asp=1)
15
generate_2d_exponential = function(
16
  falloff = 1,
17
  dim = c(11, 11),
18
  width = 3,
19
  rescale_unity = FALSE
20
) {
21!
  if (length(dim) == 1) {
22!
    dim = c(dim, dim)
23
  }
24!
  xy_ratio = dim[1] / dim[2]
25!
  if (xy_ratio > 1) {
26!
    x = seq(-width * xy_ratio, width * xy_ratio, length.out = dim[1])
27!
    y = seq(-width, width, length.out = dim[2])
28
  } else {
29!
    x = seq(-width, width, length.out = dim[1])
30!
    y = seq(-width / xy_ratio, width / xy_ratio, length.out = dim[2])
31
  }
32!
  testmat = matrix(0, dim[1], dim[2])
33!
  for (i in 1:length(x)) {
34!
    for (j in 1:length(y)) {
35!
      testmat[i, j] = (dexp(sqrt(x[i]^2 + y[j]^2), rate = 1 / falloff))
36
    }
37
  }
38!
  if (rescale_unity) {
39!
    temp = testmat / sum(testmat)
40!
    return(temp / max(temp))
41
  }
42!
  testmat / sum(testmat)
43
}
1
#' @title Convert to Native Raster
2
#'
3
#' @description Converts a matrix or image array to a native raster.
4
#'
5
#' @param input Matrix or image array to convert to a native raster.
6
#' @keywords internal
7
convert_to_native_raster = function(input) {
862x
  ncol = ncol(input)
962x
  nrow = nrow(input)
1062x
  if (length(dim(input)) == 3) {
1162x
    if (dim(input)[3] == 3) {
12!
      channels = 3
13!
      nr = encode_native_image_rcpp_3(input[,, 1], input[,, 2], input[,, 3])
1462x
    } else if (dim(input)[3] == 4) {
1562x
      channels = 4
1662x
      nr = encode_native_image_rcpp_4(
1762x
        input[,, 1],
1862x
        input[,, 2],
1962x
        input[,, 3],
2062x
        input[,, 4]
21
      )
22!
    } else if (dim(input)[3] == 2) {
23!
      channels = 3
24!
      nr = encode_native_image_rcpp_4(
25!
        input[,, 1],
26!
        input[,, 1],
27!
        input[,, 1],
28!
        input[,, 2]
29
      )
30
    } else {
31!
      stop(sprintf(
32!
        "Dimension of array (%d/%d/%d) do not correspond to any image types",
33!
        dim(input)[1],
34!
        dim(input)[2],
35!
        dim(input)[3]
36
      ))
37
    }
38!
  } else if (length(dim(input)) == 2) {
39!
    channels = 3
40!
    nr = encode_native_image_rcpp_1(input)
41
  } else {
42!
    stop(sprintf("Dimensions of array do not correspond to any image types"))
43
  }
4462x
  class(nr) = "nativeRaster"
4562x
  dim(nr) = c(nrow, ncol)
4662x
  attr(nr, "channels") = channels
4762x
  return(nr)
48
}
1
#'@title Plot Image
2
#'
3
#'@description Displays the image in the current device.
4
#'
5
#'@param image 3-layer RGB/4-layer RGBA array, `rayimg` class, or filename of an image.
6
#'@param draw_grid Default `FALSE`. If `TRUE`, this will draw a grid in the background to help
7
#'disambiguate the actual image from the device (helpful if the image background is the same as the
8
#'device's background).
9
#'@param asp Default `1`. Aspect ratio of the pixels in the plot. For example, an aspect ratio of `4/3` will
10
#'slightly widen the image.
11
#'@param new_page  Default `TRUE`. Whether to call `grid::grid.newpage()` before plotting the image.
12
#'@param ignore_alpha Default `FALSE`. Whether to ignore the alpha channel when plotting.
13
#'@param return_grob Default `FALSE`. Whether to return the grob object.
14
#'@param gp A `grid::gpar()` object to include for the grid viewport displaying the image.
15
#'@param angle Default `0`. Counter-clockwise rotation (in degrees) applied before plotting.
16
#'@param show_linear Default `FALSE`. Most data should be gamma corrected before displaying on a screen.
17
#' Set to `TRUE` to turn off this gamma correction.
18
#'@export
19
#'@examplesIf interactive() || identical(Sys.getenv("IN_PKGDOWN"), "true")
20
#'#Plot the dragon array
21
#'plot_image(dragon)
22
#'#Make pixels twice as wide as tall
23
#'plot_image(dragon, asp = 2)
24
#'#Plot non-square images
25
#'plot_image(dragon[1:100,,])
26
#'#Make pixels twice as tall as wide
27
#'plot_image(dragon[1:100,,], asp = 1/2)
28
plot_image = function(
29
  image,
30
  draw_grid = FALSE,
31
  ignore_alpha = FALSE,
32
  asp = 1,
33
  new_page = TRUE,
34
  return_grob = FALSE,
35
  gp = grid::gpar(),
36
  angle = 0,
37
  show_linear = FALSE
38
) {
3936x
  prepared = prepare_native_raster(
4036x
    image,
4136x
    angle = angle,
4236x
    show_linear = show_linear
43
  )
4436x
  nr = prepared$native_raster
45
4636x
  if (new_page) {
4736x
    grid::grid.newpage()
48
  }
4936x
  image_dim = prepared$display_dim
50
5136x
  if (draw_grid) {
52!
    draw_grid_fxn = function() {
53!
      grid::pushViewport(
54!
        grid::viewport(
55!
          layout = grid::grid.layout(
56!
            1,
57!
            1,
58!
            widths = grid::unit(image_dim[1], "pt"),
59!
            heights = grid::unit(image_dim[2], "pt")
60
          ),
61!
          gp = gp
62
        )
63
      )
64!
      grid_density = 0.01
65!
      for (i in seq(-2, 2, by = grid_density)) {
66!
        grid::grid.lines(
67!
          x = c(0, 1),
68!
          y = c(i, i + 1),
69!
          default.units = "npc",
70!
          gp = grid::gpar(col = "grey")
71
        )
72!
        grid::grid.lines(
73!
          x = c(0, 1),
74!
          y = c(i, i - 1),
75!
          default.units = "npc",
76!
          gp = grid::gpar(col = "grey")
77
        )
78
      }
79!
      grid::popViewport()
80
    }
81!
    draw_grid_fxn()
82
  }
8336x
  return(plot_asp_native_raster(
8436x
    nr,
8536x
    asp = asp,
8636x
    return_grob = return_grob,
8736x
    gp = gp
88
  ))
89
}
1
#' @title Get String Dimensions
2
#'
3
#' @description
4
#' Calculates font metrics for a specified font, font size, and style.
5
#'
6
#' @param string The string to be measured.
7
#' @param font Default `"sans"`.
8
#' @param size A numeric value specifying the size of the font in points.
9
#' @param align Default `"left"``. The string alignment.
10
#' @param ... Other arguments to pass to `systemfonts::shape_string()``
11
#'
12
#' @return A data.frame listing the string dimensions.
13
#'
14
#' @details
15
#' The function renders specific characters (`"d"` for ascender, `"g"` for descender, `"x"` for neutral) using the specified font parameters. It calculates the bounding box of each character to determine the necessary adjustments for accurate text positioning.
16
#'
17
#' @import grDevices grid png
18
#' @export
19
#' @examples
20
#' # Get height of basic sans font
21
#' get_string_dimensions("This is a string", size=24)
22
get_string_dimensions = function(
23
  string,
24
  font = "sans",
25
  size = 12,
26
  align = "center",
27
  ...
28
) {
298x
  size_metrics = systemfonts::shape_string(
308x
    string,
318x
    family = font,
328x
    size = size,
338x
    align = align,
34
    ...
358x
  )[["metrics"]]
368x
  return(size_metrics)
37
}
1
#'@title Calculate Bokeh Size
2
#'
3
#'@description Calculates the amount of blurring at each point with camera characteristics.
4
#'
5
#'@param z Depth matrix.
6
#'@param zfocus Depth in which to blur. Minimum 0, maximum 1.
7
#'@param f Focal length of the virtual camera. .
8
#'@param N F-stop. Focal length of the virtual camera.
9
#'@keywords internal
10
#'@return Matrix of bokeh sizes.
11
calc_bokeh_size = function(z, zfocus, f, N, ramp) {
12!
  ifelse(
13!
    z - zfocus < 0,
14!
    abs(f^2 * abs(z - zfocus) * ramp / ((zfocus - f) * z * N)),
15!
    abs(f^2 * abs(z - zfocus) / ((zfocus - f) * z * N * ramp))
16
  )
17
}
1
#include <Rcpp.h>
2
using namespace Rcpp;
3
4
//Boolean distance code partly derived from "Distance Transforms of Sampled Functions"
5
//(Pedro F. Felzenszwalb and Daniel P. Huttenlocher)
6
7
#define INF 1E20;
8
9
template <class T>
10414x
inline T square(const T &x) { return x*x; };
11
1248x
static NumericVector dt(NumericVector f, int n) {
1348x
  NumericVector d(n);
1448x
  IntegerVector v(n);
1548x
  NumericVector z(n+1);
1648x
  int k = 0;
1748x
  v[0] = 0;
1848x
  z[0] = -INF;
1948x
  z[1] = +INF;
20146x
  for (int q = 1; q <= n-1; q++) {
2198x
    float s  = ((f[q]+square(q))-(f[v[k]]+square(v[k])))/(2*q-2*v[k]);
22134x
    while (s <= z[k]) {
2336x
      k--;
2436x
      s  = ((f[q]+square(q))-(f[v[k]]+square(v[k])))/(2*q-2*v[k]);
25
    }
2698x
    k++;
2798x
    v[k] = q;
2898x
    z[k] = s;
2998x
    z[k+1] = +INF;
30
  }
31
3248x
  k = 0;
33194x
  for (int q = 0; q <= n-1; q++) {
34200x
    while (z[k+1] < q) {
3554x
      k++;
36
    }
37146x
    d[q] = square(q-v[k]) + f[v[k]];
38
  }
3948x
  return(d);
40
}
41
427x
static void dt(NumericMatrix& im) {
437x
  int width = im.nrow();
447x
  int height = im.ncol();
457x
  NumericVector f(std::max(width,height));
46
47
  // transform along columns
4826x
  for (int x = 0; x < width; x++) {
4992x
    for (int y = 0; y < height; y++) {
5073x
      f(y) = im(x, y);
51
    }
5219x
    NumericVector d = dt(f, height);
5392x
    for (int y = 0; y < height; y++) {
5473x
      im(x, y) = d(y);
55
    }
56
  }
57
58
  // transform along rows
5936x
  for (int y = 0; y < height; y++) {
60102x
    for (int x = 0; x < width; x++) {
6173x
      f(x) = im(x, y);
62
    }
6329x
    NumericVector d = dt(f, width);
64102x
    for (int x = 0; x < width; x++) {
6573x
      im(x, y) = d(x);
66
    }
67
  }
68
}
69
70
// [[Rcpp::export]]
717x
NumericMatrix get_boolean_distance(LogicalMatrix input) {
727x
  int width = input.nrow();
737x
  int height = input.ncol();
74
757x
  NumericMatrix out(width, height);
7636x
  for (int y = 0; y < height; y++) {
77102x
    for (int x = 0; x < width; x++) {
7873x
      if (input(x, y) == 1) {
7926x
        out(x, y) = 0;
80
      } else {
8147x
        out(x, y) = INF;
82
      }
83
    }
84
  }
857x
  dt(out);
8626x
  for(int i = 0; i < width; i++) {
8792x
    for(int j = 0; j < height; j++) {
8873x
      out(i,j) = sqrt(out(i,j));
89
    }
90
  }
917x
  return(out);
92
}
93
1
#include <Rcpp.h>
2
using namespace Rcpp;
3
4
#define R_RGBA(r,g,b,a) ((r)|((g)<<8)|((b)<<16)|((a)<<24))
5
6
// [[Rcpp::export]]
7!
IntegerVector encode_native_image_rcpp_1(NumericMatrix& bw_image) {
8!
  int n = bw_image.nrow() * bw_image.ncol();
9!
  IntegerVector native_vector(n);
10!
  for (int i = 0; i < bw_image.ncol(); i++) {
11!
    for (int j = 0; j < bw_image.nrow(); j++) {
12!
      native_vector[i + j * bw_image.ncol()] = R_RGBA(
13
        int(bw_image(j,i) * 255),
14
        int(bw_image(j,i) * 255),
15
        int(bw_image(j,i) * 255),
16
        255);
17
    }
18
  }
19!
  return native_vector;
20
}
21
22
// [[Rcpp::export]]
23!
IntegerVector encode_native_image_rcpp_3(NumericMatrix& r_image,
24
                                         NumericMatrix& g_image,
25
                                         NumericMatrix& b_image) {
26!
  int n = r_image.nrow() * r_image.ncol();
27!
  IntegerVector native_vector(n);
28!
  for (int i = 0; i < r_image.ncol(); i++) {
29!
    for (int j = 0; j < r_image.nrow(); j++) {
30!
      native_vector[i + j * r_image.ncol()] = R_RGBA(
31
        int(r_image(j,i) * 255),
32
        int(g_image(j,i) * 255),
33
        int(b_image(j,i) * 255),
34
        255);
35
    }
36
  }
37!
  return native_vector;
38
}
39
40
// [[Rcpp::export]]
4162x
IntegerVector encode_native_image_rcpp_4(NumericMatrix& r_image,
42
                                         NumericMatrix& g_image,
43
                                         NumericMatrix& b_image,
44
                                         NumericMatrix& a_image) {
4562x
  int n = r_image.nrow() * r_image.ncol();
4662x
  IntegerVector native_vector(n);
473430x
  for (int i = 0; i < r_image.ncol(); i++) {
48210752x
    for (int j = 0; j < r_image.nrow(); j++) {
49207384x
      native_vector[i + j * r_image.ncol()] = R_RGBA(
50
        int(r_image(j,i) * 255),
51
        int(g_image(j,i) * 255),
52
        int(b_image(j,i) * 255),
53
        int(a_image(j,i) * 255));
54
    }
55
  }
5662x
  return native_vector;
57
}
1
#include <algorithm>
2
#include <cmath>
3
#include <cstddef>
4
#include <cstdint>
5
#include <cstring>
6
#include <string>
7
#include <vector>
8
9
#include <Rcpp.h>
10
11
#define TINY_DNG_LOADER_IMPLEMENTATION
12
#define TINY_DNG_LOADER_NO_STB_IMAGE_INCLUDE
13
#define TINY_DNG_LOADER_USE_STB_IMAGE
14
#include <stbimageheaders/stb_image.h>
15
#include <tinydng/tiny_dng_loader.h>
16
17
#define TINY_DNG_WRITER_IMPLEMENTATION
18
#include <tinydng/tiny_dng_writer.h>
19
20
namespace {
21
2214x
bool HasListElement(const Rcpp::List& list, const char* name) {
2314x
  return list.containsElementNamed(name);
24
}
25
262x
Rcpp::NumericVector GetNumericVector(const Rcpp::List& list, const char* name) {
272x
  if (!HasListElement(list, name)) {
28!
    return Rcpp::NumericVector();
29
  }
304x
  return Rcpp::as<Rcpp::NumericVector>(list[name]);
31
}
32
33!
Rcpp::IntegerVector GetIntegerVector(const Rcpp::List& list, const char* name) {
34!
  if (!HasListElement(list, name)) {
35!
    return Rcpp::IntegerVector();
36
  }
37!
  return Rcpp::as<Rcpp::IntegerVector>(list[name]);
38
}
39
40!
bool HasNaNumeric(const Rcpp::NumericVector& vec, int required) {
41!
  if (vec.size() < required) {
42!
    return true;
43
  }
44!
  for (int i = 0; i < required; ++i) {
45!
    if (Rcpp::NumericVector::is_na(vec[i])) {
46!
      return true;
47
    }
48
  }
49!
  return false;
50
}
51
52!
bool HasNaInteger(const Rcpp::IntegerVector& vec, int required) {
53!
  if (vec.size() < required) {
54!
    return true;
55
  }
56!
  for (int i = 0; i < required; ++i) {
57!
    if (vec[i] == NA_INTEGER) {
58!
      return true;
59
    }
60
  }
61!
  return false;
62
}
63
64512x
double Clamp01(double v) {
65512x
  if (v < 0.0) return 0.0;
66512x
  if (v > 1.0) return 1.0;
67512x
  return v;
68
}
69
702x
double DefaultWhiteLevel(int bits_per_sample) {
712x
  if (bits_per_sample <= 0) {
72!
    return 0.0;
73
  }
742x
  return std::pow(2.0, static_cast<double>(bits_per_sample)) - 1.0;
75
}
76
77
const int kTagLinearizationTable = 50712;
78
const int kTagBaselineExposure = 50730;
79
801x
void AppendWarn(std::string* warn, const std::string& msg) {
811x
  if (!warn || msg.empty()) {
82!
    return;
83
  }
841x
  if (!warn->empty()) {
85!
    (*warn) += " ";
86
  }
871x
  (*warn) += msg;
88
}
89
9010x
const tinydng::FieldData* FindCustomField(const tinydng::DNGImage& image,
91
                                          int tag) {
9220x
  for (const auto& field : image.custom_fields) {
93!
    if (field.tag == tag) {
94!
      return &field;
95
    }
96
  }
9710x
  return nullptr;
98
}
99
1005x
const tinydng::FieldData* FindCustomFieldAny(
101
    const std::vector<tinydng::DNGImage>& images,
102
    int tag,
103
    std::size_t* image_idx) {
10410x
  for (std::size_t i = 0; i < images.size(); ++i) {
1055x
    const tinydng::FieldData* field = FindCustomField(images[i], tag);
1065x
    if (field) {
107!
      if (image_idx) {
108!
        *image_idx = i;
109
      }
110!
      return field;
111
    }
112
  }
1135x
  return nullptr;
114
}
115
116!
bool ReadCustomShort(const tinydng::FieldData& field, uint16_t* value) {
117!
  if ((field.type != tinydng::TYPE_SHORT) &&
118!
      (field.type != tinydng::TYPE_SSHORT)) {
119!
    return false;
120
  }
121!
  if (field.data.size() < sizeof(uint16_t)) {
122!
    return false;
123
  }
124!
  uint16_t out = 0;
125!
  std::memcpy(&out, field.data.data(), sizeof(uint16_t));
126!
  if (value) {
127!
    *value = out;
128
  }
129!
  return true;
130
}
131
132!
bool ReadCustomRational(const tinydng::FieldData& field,
133
                        double* value,
134
                        bool signed_value) {
135!
  if (field.data.size() < sizeof(uint32_t) * 2) {
136!
    return false;
137
  }
138!
  uint32_t num_u = 0;
139!
  uint32_t den_u = 0;
140!
  std::memcpy(&num_u, field.data.data(), sizeof(uint32_t));
141!
  std::memcpy(&den_u, field.data.data() + sizeof(uint32_t), sizeof(uint32_t));
142!
  if (den_u == 0) {
143!
    return false;
144
  }
145!
  double num = signed_value ? static_cast<double>(static_cast<int32_t>(num_u))
146!
                            : static_cast<double>(num_u);
147!
  double den = signed_value ? static_cast<double>(static_cast<int32_t>(den_u))
148!
                            : static_cast<double>(den_u);
149!
  if (value) {
150!
    *value = num / den;
151
  }
152!
  return true;
153
}
154
155!
std::vector<uint16_t> ExtractLinearizationTable(
156
    const tinydng::FieldData& field) {
157!
  std::vector<uint16_t> table;
158!
  if (field.type != tinydng::TYPE_SHORT) {
159!
    return table;
160
  }
161!
  if (field.data.size() < sizeof(uint16_t)) {
162!
    return table;
163
  }
164!
  std::size_t count = field.data.size() / sizeof(uint16_t);
165!
  table.reserve(count);
166!
  for (std::size_t i = 0; i < count; ++i) {
167!
    uint16_t value = 0;
168!
    std::memcpy(&value, field.data.data() + i * sizeof(uint16_t),
169
                sizeof(uint16_t));
170!
    table.push_back(value);
171
  }
172!
  return table;
173
}
174
1754x
std::vector<double> RowMajorToR(const std::vector<double>& values,
176
                                int width,
177
                                int height,
178
                                int spp) {
1794x
  std::vector<double> out(values.size());
18026x
  for (int y = 0; y < height; ++y) {
181292x
    for (int x = 0; x < width; ++x) {
182540x
      for (int c = 0; c < spp; ++c) {
183270x
        std::size_t src_idx = (static_cast<std::size_t>(y) *
184270x
          static_cast<std::size_t>(width) + static_cast<std::size_t>(x)) *
185270x
          static_cast<std::size_t>(spp) + static_cast<std::size_t>(c);
186270x
        std::size_t dst_idx = static_cast<std::size_t>(y) +
187270x
          static_cast<std::size_t>(height) *
188270x
          (static_cast<std::size_t>(x) + static_cast<std::size_t>(width) *
189270x
          static_cast<std::size_t>(c));
190270x
        out[dst_idx] = values[src_idx];
191
      }
192
    }
193
  }
1944x
  return out;
195
}
196
1973x
std::vector<double> RToRowMajor(const Rcpp::NumericVector& pixels,
198
                                int width,
199
                                int height,
200
                                int spp) {
2013x
  std::vector<double> out(static_cast<std::size_t>(width) *
2023x
    static_cast<std::size_t>(height) * static_cast<std::size_t>(spp));
20311x
  for (int y = 0; y < height; ++y) {
20436x
    for (int x = 0; x < width; ++x) {
20556x
      for (int c = 0; c < spp; ++c) {
20628x
        std::size_t src_idx = static_cast<std::size_t>(y) +
20728x
          static_cast<std::size_t>(height) *
20828x
          (static_cast<std::size_t>(x) + static_cast<std::size_t>(width) *
20928x
          static_cast<std::size_t>(c));
21028x
        std::size_t dst_idx = (static_cast<std::size_t>(y) *
21128x
          static_cast<std::size_t>(width) + static_cast<std::size_t>(x)) *
21228x
          static_cast<std::size_t>(spp) + static_cast<std::size_t>(c);
21328x
        out[dst_idx] = pixels[src_idx];
214
      }
215
    }
216
  }
2173x
  return out;
218
}
219
2201x
bool ActiveAreaValid(const int active_area[4], int width, int height) {
2211x
  int top = active_area[0];
2221x
  int left = active_area[1];
2231x
  int bottom = active_area[2];
2241x
  int right = active_area[3];
2251x
  if (top < 0 || left < 0 || bottom <= top || right <= left) {
226!
    return false;
227
  }
2281x
  if (bottom > height || right > width) {
229!
    return false;
230
  }
2311x
  return true;
232
}
233
2341x
bool ApplyActiveAreaCrop(const std::vector<double>& values,
235
                         int width,
236
                         int height,
237
                         int spp,
238
                         const int active_area[4],
239
                         std::vector<double>* out_values,
240
                         int* out_width,
241
                         int* out_height) {
2421x
  if (!ActiveAreaValid(active_area, width, height)) {
243!
    return false;
244
  }
2451x
  int top = active_area[0];
2461x
  int left = active_area[1];
2471x
  int bottom = active_area[2];
2481x
  int right = active_area[3];
2491x
  int crop_height = bottom - top;
2501x
  int crop_width = right - left;
251
2521x
  std::vector<double> cropped(static_cast<std::size_t>(crop_width) *
2531x
    static_cast<std::size_t>(crop_height) * static_cast<std::size_t>(spp));
254
2553x
  for (int y = 0; y < crop_height; ++y) {
2562x
    int src_y = y + top;
2578x
    for (int x = 0; x < crop_width; ++x) {
2586x
      int src_x = x + left;
25912x
      for (int c = 0; c < spp; ++c) {
2606x
        std::size_t src_idx = (static_cast<std::size_t>(src_y) *
2616x
          static_cast<std::size_t>(width) + static_cast<std::size_t>(src_x)) *
2626x
          static_cast<std::size_t>(spp) + static_cast<std::size_t>(c);
2636x
        std::size_t dst_idx = (static_cast<std::size_t>(y) *
2646x
          static_cast<std::size_t>(crop_width) + static_cast<std::size_t>(x)) *
2656x
          static_cast<std::size_t>(spp) + static_cast<std::size_t>(c);
2666x
        cropped[dst_idx] = values[src_idx];
267
      }
268
    }
269
  }
270
2711x
  if (out_values) {
2721x
    *out_values = std::move(cropped);
273
  }
2741x
  if (out_width) {
2751x
    *out_width = crop_width;
276
  }
2771x
  if (out_height) {
2781x
    *out_height = crop_height;
279
  }
2801x
  return true;
281
}
282
283!
double SampleGainMap(const tinydng::GainMap& gmap,
284
                     int x,
285
                     int y,
286
                     int plane,
287
                     std::string* warn) {
288!
  if (gmap.map_points_v == 0 || gmap.map_points_h == 0 ||
289!
      gmap.map_planes == 0) {
290!
    AppendWarn(warn, "GainMap has invalid dimensions.");
291!
    return 1.0;
292
  }
293!
  if (gmap.map_spacing_h <= 0.0 || gmap.map_spacing_v <= 0.0) {
294!
    AppendWarn(warn, "GainMap spacing is invalid.");
295!
    return 1.0;
296
  }
297!
  double fx = (static_cast<double>(x) - gmap.map_origin_h) / gmap.map_spacing_h;
298!
  double fy = (static_cast<double>(y) - gmap.map_origin_v) / gmap.map_spacing_v;
299
300!
  if (fx < 0.0) fx = 0.0;
301!
  if (fy < 0.0) fy = 0.0;
302!
  double max_x = static_cast<double>(gmap.map_points_h - 1);
303!
  double max_y = static_cast<double>(gmap.map_points_v - 1);
304!
  if (fx > max_x) fx = max_x;
305!
  if (fy > max_y) fy = max_y;
306
307!
  int x0 = static_cast<int>(std::floor(fx));
308!
  int y0 = static_cast<int>(std::floor(fy));
309!
  int x1 = std::min(x0 + 1, static_cast<int>(gmap.map_points_h - 1));
310!
  int y1 = std::min(y0 + 1, static_cast<int>(gmap.map_points_v - 1));
311!
  double tx = fx - static_cast<double>(x0);
312!
  double ty = fy - static_cast<double>(y0);
313
314!
  auto idx = [&](int gx, int gy, int gp) {
315!
    return (static_cast<std::size_t>(gy) *
316!
      static_cast<std::size_t>(gmap.map_points_h) +
317!
      static_cast<std::size_t>(gx)) *
318!
      static_cast<std::size_t>(gmap.map_planes) +
319!
      static_cast<std::size_t>(gp);
320
  };
321
322!
  if (plane < 0 || plane >= static_cast<int>(gmap.map_planes)) {
323!
    return 1.0;
324
  }
325
326!
  float g00 = gmap.pixels[idx(x0, y0, plane)];
327!
  float g10 = gmap.pixels[idx(x1, y0, plane)];
328!
  float g01 = gmap.pixels[idx(x0, y1, plane)];
329!
  float g11 = gmap.pixels[idx(x1, y1, plane)];
330
331!
  double gx0 = g00 + (g10 - g00) * tx;
332!
  double gx1 = g01 + (g11 - g01) * tx;
333!
  return gx0 + (gx1 - gx0) * ty;
334
}
335
336!
bool ApplyGainMaps(const std::vector<tinydng::GainMap>& gainmaps,
337
                   int width,
338
                   int height,
339
                   int spp,
340
                   std::vector<double>* values,
341
                   std::string* warn) {
342!
  if (!values || gainmaps.empty()) {
343!
    return false;
344
  }
345
346!
  bool applied = false;
347!
  for (const auto& gmap : gainmaps) {
348!
    if (gmap.pixels.empty()) {
349!
      continue;
350
    }
351
352!
    int top = static_cast<int>(gmap.top);
353!
    int left = static_cast<int>(gmap.left);
354!
    int bottom = static_cast<int>(gmap.bottom);
355!
    int right = static_cast<int>(gmap.right);
356
357!
    if (bottom <= top || right <= left) {
358!
      top = 0;
359!
      left = 0;
360!
      bottom = height;
361!
      right = width;
362
    }
363
364!
    int plane_start = static_cast<int>(gmap.plane);
365!
    int plane_count = static_cast<int>(gmap.planes);
366!
    if (plane_count <= 0) {
367!
      plane_start = 0;
368!
      plane_count = spp;
369
    }
370
371!
    for (int y = top; y < bottom; ++y) {
372!
      if (y < 0 || y >= height) {
373!
        continue;
374
      }
375!
      for (int x = left; x < right; ++x) {
376!
        if (x < 0 || x >= width) {
377!
          continue;
378
        }
379!
        for (int c = 0; c < spp; ++c) {
380!
          if (c < plane_start || c >= plane_start + plane_count) {
381!
            continue;
382
          }
383!
          int plane = (gmap.map_planes == 1)
384!
            ? 0
385
            : (c - plane_start);
386!
          double gain = SampleGainMap(gmap, x, y, plane, warn);
387!
          std::size_t idx = (static_cast<std::size_t>(y) *
388!
            static_cast<std::size_t>(width) + static_cast<std::size_t>(x)) *
389!
            static_cast<std::size_t>(spp) + static_cast<std::size_t>(c);
390!
          (*values)[idx] *= gain;
391
        }
392
      }
393
    }
394!
    applied = true;
395
  }
396!
  return applied;
397
}
398
399
}  // namespace
400
401
// [[Rcpp::export]]
4021x
Rcpp::List read_dng_cpp(const std::string& filename,
403
                        bool normalize = true,
404
                        std::string pick = "largest") {
4051x
  std::vector<tinydng::FieldInfo> custom_fields;
4061x
  std::vector<tinydng::DNGImage> images;
4071x
  std::string warn;
4081x
  std::string err;
409
4105x
  auto add_custom_field = [&](int tag, tinydng::DataType type, const char* name) {
4115x
    tinydng::FieldInfo field;
4125x
    field.tag = tag;
4135x
    field.type = type;
4145x
    field.name = name;
4155x
    custom_fields.push_back(field);
416
  };
417
4181x
  add_custom_field(kTagLinearizationTable, tinydng::TYPE_SHORT,
419
                   "LinearizationTable");
4201x
  add_custom_field(kTagBaselineExposure, tinydng::TYPE_SRATIONAL,
421
                   "BaselineExposure");
4221x
  add_custom_field(tinydng::TAG_EXPOSURE_TIME, tinydng::TYPE_RATIONAL,
423
                   "ExposureTime");
4241x
  add_custom_field(tinydng::TAG_ISO, tinydng::TYPE_SHORT, "ISOSpeedRatings");
4251x
  add_custom_field(tinydng::TAG_F_NUMBER, tinydng::TYPE_RATIONAL, "FNumber");
426
4271x
  bool ok = tinydng::LoadDNG(filename.c_str(), custom_fields, &images, &warn, &err);
4281x
  if (!ok) {
429!
    throw std::runtime_error(err.empty() ? "Failed to load DNG." : err);
430
  }
431
4321x
  std::string pick_lower = pick;
4331x
  std::transform(pick_lower.begin(), pick_lower.end(), pick_lower.begin(),
4347x
                 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
4351x
  if (pick_lower != "largest") {
436!
    throw std::runtime_error("Only pick = \"largest\" is supported.");
437
  }
438
4391x
  std::size_t best_idx = images.size();
4401x
  std::size_t best_pixels = 0;
4412x
  for (std::size_t i = 0; i < images.size(); ++i) {
4421x
    const tinydng::DNGImage& img = images[i];
4431x
    if (img.data.empty()) {
444!
      continue;
445
    }
4461x
    std::size_t pixels = static_cast<std::size_t>(img.width) *
4471x
      static_cast<std::size_t>(img.height);
4481x
    if (pixels > best_pixels) {
4491x
      best_pixels = pixels;
4501x
      best_idx = i;
451
    }
452
  }
453
4541x
  if (best_idx == images.size()) {
455!
    std::string msg = "No DNG image data found.";
456!
    if (!warn.empty()) {
457!
      msg += " Warning: " + warn;
458
    }
459!
    if (!err.empty()) {
460!
      msg += " Error: " + err;
461
    }
462!
    throw std::runtime_error(msg);
463
  }
464
4651x
  const tinydng::DNGImage& image = images[best_idx];
4661x
  short orientation = image.orientation;
4671x
  if (orientation <= 0 || orientation == 1) {
4682x
    for (std::size_t i = 0; i < images.size(); ++i) {
4691x
      short candidate = images[i].orientation;
4701x
      if (candidate > 1 && candidate <= 8) {
471!
        orientation = candidate;
472!
        break;
473
      }
474
    }
475
  }
4761x
  if (image.width <= 0 || image.height <= 0 || image.samples_per_pixel <= 0) {
477!
    throw std::runtime_error("Invalid DNG image dimensions.");
478
  }
479
4801x
  int width = image.width;
4811x
  int height = image.height;
4821x
  int spp = image.samples_per_pixel;
4831x
  int bps = image.bits_per_sample;
4841x
  bool processing = normalize;
485
4861x
  std::string warn_out = warn;
4871x
  bool linearization_present = false;
4881x
  bool linearization_applied = false;
4891x
  bool active_area_applied = false;
4901x
  bool opcodes_present = !image.opcodelist2_gainmap.empty();
4911x
  bool opcodes_applied = false;
4921x
  bool baseline_exposure_seen = false;
4931x
  bool baseline_exposure_undone = false;
4941x
  double baseline_exposure = NA_REAL;
4951x
  double exposure_time = NA_REAL;
4961x
  double iso = NA_REAL;
4971x
  double f_number = NA_REAL;
4981x
  bool exposure_normalized_applied = false;
499
5001x
  std::vector<uint16_t> linearization_table;
501
  const tinydng::FieldData* linear_field =
5021x
    FindCustomField(image, kTagLinearizationTable);
5031x
  if (!linear_field) {
5041x
    linear_field = FindCustomFieldAny(images, kTagLinearizationTable, nullptr);
505
  }
5061x
  if (linear_field) {
507!
    linearization_present = true;
508!
    linearization_table = ExtractLinearizationTable(*linear_field);
509
  }
510
511
  const tinydng::FieldData* baseline_field =
5121x
    FindCustomField(image, kTagBaselineExposure);
5131x
  if (!baseline_field) {
5141x
    baseline_field = FindCustomFieldAny(images, kTagBaselineExposure, nullptr);
515
  }
5161x
  if (baseline_field) {
517!
    double value = 0.0;
518!
    if (ReadCustomRational(*baseline_field, &value, true)) {
519!
      baseline_exposure = value;
520!
      baseline_exposure_seen = true;
521
    } else {
522!
      AppendWarn(&warn_out, "BaselineExposure tag present but could not be read.");
523
    }
524
  }
525
526
  const tinydng::FieldData* exposure_field =
5271x
    FindCustomField(image, tinydng::TAG_EXPOSURE_TIME);
5281x
  if (!exposure_field) {
5291x
    exposure_field = FindCustomFieldAny(images, tinydng::TAG_EXPOSURE_TIME,
530
                                        nullptr);
531
  }
5321x
  if (exposure_field) {
533!
    double value = 0.0;
534!
    if (ReadCustomRational(*exposure_field, &value, false)) {
535!
      exposure_time = value;
536
    } else {
537!
      AppendWarn(&warn_out, "ExposureTime tag present but could not be read.");
538
    }
539
  }
540
541
  const tinydng::FieldData* iso_field =
5421x
    FindCustomField(image, tinydng::TAG_ISO);
5431x
  if (!iso_field) {
5441x
    iso_field = FindCustomFieldAny(images, tinydng::TAG_ISO, nullptr);
545
  }
5461x
  if (iso_field) {
547!
    uint16_t value = 0;
548!
    if (ReadCustomShort(*iso_field, &value)) {
549!
      iso = static_cast<double>(value);
550
    } else {
551!
      AppendWarn(&warn_out, "ISOSpeedRatings tag present but could not be read.");
552
    }
553
  }
554
555
  const tinydng::FieldData* fnum_field =
5561x
    FindCustomField(image, tinydng::TAG_F_NUMBER);
5571x
  if (!fnum_field) {
5581x
    fnum_field = FindCustomFieldAny(images, tinydng::TAG_F_NUMBER, nullptr);
559
  }
5601x
  if (fnum_field) {
561!
    double value = 0.0;
562!
    if (ReadCustomRational(*fnum_field, &value, false)) {
563!
      f_number = value;
564
    }
565
  }
566
5671x
  int bytes_per_sample = 0;
5681x
  if (image.sample_format == tinydng::SAMPLEFORMAT_UINT) {
5691x
    if (bps <= 8) {
570!
      bytes_per_sample = 1;
5711x
    } else if (bps <= 16) {
5721x
      bytes_per_sample = 2;
573
    } else {
574!
      throw std::runtime_error("Unsupported integer bit depth.");
575
    }
576!
  } else if (image.sample_format == tinydng::SAMPLEFORMAT_IEEEFP) {
577!
    if (bps == 32) {
578!
      bytes_per_sample = 4;
579
    } else {
580!
      throw std::runtime_error("Unsupported float bit depth.");
581
    }
582
  } else {
583!
    throw std::runtime_error("Unsupported sample format.");
584
  }
585
5861x
  std::size_t n_samples = static_cast<std::size_t>(width) *
5871x
    static_cast<std::size_t>(height) * static_cast<std::size_t>(spp);
5881x
  if (image.data.size() < n_samples * static_cast<std::size_t>(bytes_per_sample)) {
589!
    throw std::runtime_error("DNG data buffer is smaller than expected.");
590
  }
591
5922x
  std::vector<double> values(n_samples);
593
5941x
  std::vector<double> black_levels(static_cast<std::size_t>(spp), 0.0);
595
  std::vector<double> white_levels(static_cast<std::size_t>(spp),
5961x
                                   DefaultWhiteLevel(bps));
5971x
  double default_white = DefaultWhiteLevel(bps);
5982x
  for (int c = 0; c < spp; ++c) {
5991x
    if (c < 4) {
6001x
      double black = static_cast<double>(image.black_level[c]);
6011x
      double white = static_cast<double>(image.white_level[c]);
6021x
      if (white > black) {
6031x
        black_levels[c] = black;
6041x
        white_levels[c] = white;
605
      } else {
606!
        black_levels[c] = 0.0;
607!
        white_levels[c] = default_white;
608
      }
609
    } else {
610!
      black_levels[c] = 0.0;
611!
      white_levels[c] = default_white;
612
    }
613
  }
614
615
  // Processing order: linearization -> black/white normalize -> gain map ->
616
  // baseline exposure handling -> active area crop -> exposure normalization.
6171x
  const unsigned char* data = image.data.data();
6181x
  bool linearization_warned = false;
61917x
  for (int y = 0; y < height; ++y) {
620272x
    for (int x = 0; x < width; ++x) {
621512x
      for (int c = 0; c < spp; ++c) {
622256x
        std::size_t sample_idx = (static_cast<std::size_t>(y) *
623256x
          static_cast<std::size_t>(width) + static_cast<std::size_t>(x)) *
624256x
          static_cast<std::size_t>(spp) + static_cast<std::size_t>(c);
625256x
        std::size_t offset = sample_idx * static_cast<std::size_t>(bytes_per_sample);
626
627256x
        double raw_value = 0.0;
628256x
        uint32_t int_value = 0;
629256x
        if (image.sample_format == tinydng::SAMPLEFORMAT_UINT) {
630256x
          if (bytes_per_sample == 1) {
631!
            int_value = static_cast<uint32_t>(data[offset]);
632!
            if (bps < 8) {
633!
              int_value &= ((1u << bps) - 1u);
634
            }
635
          } else {
636256x
            int_value = static_cast<uint32_t>(data[offset]) |
637256x
              (static_cast<uint32_t>(data[offset + 1]) << 8);
638256x
            if (bps < 16) {
639!
              int_value &= ((1u << bps) - 1u);
640
            }
641
          }
642256x
          raw_value = static_cast<double>(int_value);
643256x
          if (processing && linearization_present &&
644!
              linearization_table.size() > 1) {
645!
            if (int_value < linearization_table.size()) {
646!
              raw_value = static_cast<double>(linearization_table[int_value]);
647!
              linearization_applied = true;
648!
            } else if (!linearization_warned) {
649!
              AppendWarn(&warn_out,
650!
                         "Linearization table is smaller than sample range.");
651!
              linearization_warned = true;
652
            }
653
          }
654
        } else {
655!
          float value = 0.0f;
656!
          std::memcpy(&value, data + offset, sizeof(float));
657!
          raw_value = static_cast<double>(value);
658!
          if (processing && linearization_present && !linearization_warned) {
659!
            AppendWarn(&warn_out,
660!
                       "Linearization table present but samples are float.");
661!
            linearization_warned = true;
662
          }
663
        }
664
665256x
        double out_value = raw_value;
666256x
        if (processing) {
667256x
          double denom = white_levels[c] - black_levels[c];
668256x
          if (denom <= 0.0) {
669!
            out_value = 0.0;
670
          } else {
671256x
            out_value = (raw_value - black_levels[c]) / denom;
672
          }
673256x
          out_value = Clamp01(out_value);
674
        }
675
676256x
        values[sample_idx] = out_value;
677
      }
678
    }
679
  }
680
6811x
  if (linearization_present && !linearization_applied && processing &&
682!
      linearization_table.size() <= 1) {
683!
    AppendWarn(&warn_out,
684!
               "Linearization table present but not available for use.");
685
  }
686
6871x
  if (processing && opcodes_present) {
688!
    opcodes_applied = ApplyGainMaps(image.opcodelist2_gainmap, width, height,
689
                                    spp, &values, &warn_out);
690!
    if (!opcodes_applied) {
691!
      AppendWarn(&warn_out, "OpcodeList2 gain maps present but not applied.");
692
    }
6931x
  } else if (opcodes_present && !processing) {
694!
    AppendWarn(&warn_out, "OpcodeList2 gain maps present but skipped.");
695
  }
696
6971x
  if (baseline_exposure_seen && baseline_exposure != 0.0) {
698!
    AppendWarn(&warn_out,
699!
               "BaselineExposure present; value not applied or undone.");
700
  }
701
7021x
  if (image.has_active_area) {
703
    int active_area_vals[4] = {
704!
      image.active_area[0],
705!
      image.active_area[1],
706!
      image.active_area[2],
707!
      image.active_area[3]
708
    };
709!
    std::vector<double> cropped;
710!
    int crop_w = width;
711!
    int crop_h = height;
712!
    if (ApplyActiveAreaCrop(values, width, height, spp, active_area_vals,
713
                            &cropped, &crop_w, &crop_h)) {
714!
      values.swap(cropped);
715!
      width = crop_w;
716!
      height = crop_h;
717!
      active_area_applied = true;
718
    }
719
  }
720
7211x
  bool iso_ok = !Rcpp::NumericVector::is_na(iso) && iso > 0.0;
7221x
  bool exposure_ok = !Rcpp::NumericVector::is_na(exposure_time) &&
723!
    exposure_time > 0.0;
7241x
  if (iso_ok && exposure_ok) {
725!
    if (processing) {
726!
      double scale = (100.0 / iso) * (1.0 / exposure_time);
727!
      for (double& v : values) {
728!
        v *= scale;
729
      }
730!
      exposure_normalized_applied = true;
731
    } else {
732!
      AppendWarn(&warn_out,
733!
                 "Exposure normalization skipped because normalize is FALSE.");
734
    }
735
  } else {
7361x
    AppendWarn(&warn_out,
7373x
               "Exposure normalization skipped due to missing ISO or ExposureTime.");
738
  }
739
7401x
  std::vector<double> r_values = RowMajorToR(values, width, height, spp);
7411x
  Rcpp::NumericVector pixels(r_values.begin(), r_values.end());
7421x
  if (spp == 1) {
7431x
    Rcpp::IntegerVector dim = Rcpp::IntegerVector::create(height, width);
7441x
    pixels.attr("dim") = dim;
745
  } else {
746!
    Rcpp::IntegerVector dim = Rcpp::IntegerVector::create(height, width, spp);
747!
    pixels.attr("dim") = dim;
748
  }
749
7501x
  Rcpp::IntegerMatrix cfa_pattern(2, 2);
7511x
  cfa_pattern(0, 0) = image.cfa_pattern[0][0];
7521x
  cfa_pattern(0, 1) = image.cfa_pattern[0][1];
7531x
  cfa_pattern(1, 0) = image.cfa_pattern[1][0];
7541x
  cfa_pattern(1, 1) = image.cfa_pattern[1][1];
755
7561x
  Rcpp::IntegerVector cfa_plane_color(4);
7575x
  for (int i = 0; i < 4; ++i) {
7584x
    cfa_plane_color[i] = static_cast<int>(
7594x
      static_cast<unsigned char>(image.cfa_plane_color[i]));
760
  }
761
7621x
  Rcpp::IntegerVector black_level(4);
7631x
  Rcpp::IntegerVector white_level(4);
7645x
  for (int i = 0; i < 4; ++i) {
7654x
    black_level[i] = image.black_level[i];
7664x
    white_level[i] = image.white_level[i];
767
  }
768
7691x
  Rcpp::NumericVector as_shot_neutral(3, NA_REAL);
7704x
  for (int i = 0; i < 3; ++i) {
7713x
    if (image.has_as_shot_neutral) {
772!
      as_shot_neutral[i] = image.as_shot_neutral[i];
773
    }
774
  }
775
7761x
  Rcpp::NumericVector analog_balance(3, NA_REAL);
7774x
  for (int i = 0; i < 3; ++i) {
7783x
    if (image.has_analog_balance) {
779!
      analog_balance[i] = image.analog_balance[i];
780
    }
781
  }
782
7831x
  Rcpp::NumericVector color_matrix1(9);
7841x
  Rcpp::NumericVector color_matrix2(9);
7851x
  int idx = 0;
7864x
  for (int r = 0; r < 3; ++r) {
78712x
    for (int c = 0; c < 3; ++c) {
7889x
      color_matrix1[idx] = image.color_matrix1[r][c];
7899x
      color_matrix2[idx] = image.color_matrix2[r][c];
7909x
      idx++;
791
    }
792
  }
793
7941x
  Rcpp::IntegerVector active_area(4);
7955x
  for (int i = 0; i < 4; ++i) {
7964x
    active_area[i] = image.has_active_area ? image.active_area[i] : NA_INTEGER;
797
  }
798
799
  Rcpp::List meta = Rcpp::List::create(
8002x
    Rcpp::Named("width") = width,
8012x
    Rcpp::Named("height") = height,
8023x
    Rcpp::Named("samples_per_pixel") = image.samples_per_pixel,
8033x
    Rcpp::Named("bits_per_sample") = image.bits_per_sample,
8043x
    Rcpp::Named("bits_per_sample_original") = image.bits_per_sample_original,
8053x
    Rcpp::Named("sample_format") = static_cast<int>(image.sample_format),
8062x
    Rcpp::Named("cfa_pattern") = cfa_pattern,
8072x
    Rcpp::Named("cfa_plane_color") = cfa_plane_color,
8083x
    Rcpp::Named("cfa_layout") = image.cfa_layout,
8092x
    Rcpp::Named("black_level") = black_level,
8102x
    Rcpp::Named("white_level") = white_level,
8112x
    Rcpp::Named("as_shot_neutral") = as_shot_neutral,
8123x
    Rcpp::Named("has_as_shot_neutral") = image.has_as_shot_neutral,
8132x
    Rcpp::Named("analog_balance") = analog_balance,
8143x
    Rcpp::Named("has_analog_balance") = image.has_analog_balance,
8152x
    Rcpp::Named("color_matrix1") = color_matrix1,
8162x
    Rcpp::Named("color_matrix2") = color_matrix2,
8173x
    Rcpp::Named("orientation") = static_cast<int>(orientation),
8182x
    Rcpp::Named("active_area") = active_area,
8193x
    Rcpp::Named("has_active_area") = image.has_active_area,
8202x
    Rcpp::Named("active_area_applied") = active_area_applied,
8212x
    Rcpp::Named("linearization_present") = linearization_present,
8222x
    Rcpp::Named("linearization_applied") = linearization_applied,
8232x
    Rcpp::Named("opcodes_present") = opcodes_present,
8242x
    Rcpp::Named("opcodes_applied") = opcodes_applied,
8252x
    Rcpp::Named("baseline_exposure") = baseline_exposure,
8262x
    Rcpp::Named("baseline_exposure_seen") = baseline_exposure_seen,
8272x
    Rcpp::Named("baseline_exposure_undone") = baseline_exposure_undone,
8282x
    Rcpp::Named("iso") = iso,
8292x
    Rcpp::Named("exposure_time") = exposure_time,
8302x
    Rcpp::Named("f_number") = f_number,
8313x
    Rcpp::Named("exposure_normalized_applied") = exposure_normalized_applied
832
  );
833
834
  return Rcpp::List::create(
8352x
    Rcpp::Named("pixels") = pixels,
8362x
    Rcpp::Named("meta") = meta,
8372x
    Rcpp::Named("warn") = warn_out
838
  );
839
}
840
841
// [[Rcpp::export]]
8421x
Rcpp::NumericVector dng_apply_active_area_cpp(Rcpp::NumericVector pixels,
843
                                              Rcpp::IntegerVector active_area) {
8441x
  Rcpp::IntegerVector dims = pixels.attr("dim");
8451x
  if (dims.size() < 2) {
846!
    Rcpp::stop("pixels must have dim.");
847
  }
8481x
  int height = dims[0];
8491x
  int width = dims[1];
8501x
  int spp = (dims.size() >= 3) ? dims[2] : 1;
8511x
  if (active_area.size() < 4) {
852!
    Rcpp::stop("active_area must have 4 values.");
853
  }
854
8551x
  int area[4] = {active_area[0], active_area[1], active_area[2], active_area[3]};
8561x
  std::vector<double> row_major = RToRowMajor(pixels, width, height, spp);
8571x
  std::vector<double> cropped;
8581x
  int crop_w = width;
8591x
  int crop_h = height;
8601x
  if (!ApplyActiveAreaCrop(row_major, width, height, spp, area, &cropped,
861
                           &crop_w, &crop_h)) {
862!
    return pixels;
863
  }
864
8651x
  std::vector<double> out = RowMajorToR(cropped, crop_w, crop_h, spp);
8661x
  Rcpp::NumericVector out_vec(out.begin(), out.end());
8671x
  if (spp == 1) {
8683x
    out_vec.attr("dim") = Rcpp::IntegerVector::create(crop_h, crop_w);
869
  } else {
870!
    out_vec.attr("dim") = Rcpp::IntegerVector::create(crop_h, crop_w, spp);
871
  }
8721x
  return out_vec;
873
}
874
875
// [[Rcpp::export]]
8761x
Rcpp::NumericVector dng_exposure_normalize_cpp(Rcpp::NumericVector pixels,
877
                                               double iso,
878
                                               double exposure_time) {
8791x
  if (iso <= 0.0 || exposure_time <= 0.0) {
880!
    Rcpp::stop("iso and exposure_time must be positive.");
881
  }
8821x
  Rcpp::IntegerVector dims = pixels.attr("dim");
8831x
  if (dims.size() < 2) {
884!
    Rcpp::stop("pixels must have dim.");
885
  }
8861x
  int height = dims[0];
8871x
  int width = dims[1];
8881x
  int spp = (dims.size() >= 3) ? dims[2] : 1;
8891x
  double scale = (100.0 / iso) * (1.0 / exposure_time);
890
8911x
  std::vector<double> row_major = RToRowMajor(pixels, width, height, spp);
8926x
  for (double& v : row_major) {
8934x
    v *= scale;
894
  }
8951x
  std::vector<double> out = RowMajorToR(row_major, width, height, spp);
8961x
  Rcpp::NumericVector out_vec(out.begin(), out.end());
8971x
  out_vec.attr("dim") = dims;
8981x
  return out_vec;
899
}
900
901
// [[Rcpp::export]]
9021x
Rcpp::NumericVector dng_undo_baseline_exposure_cpp(Rcpp::NumericVector pixels,
903
                                                   double baseline_exposure) {
9041x
  Rcpp::IntegerVector dims = pixels.attr("dim");
9051x
  if (dims.size() < 2) {
906!
    Rcpp::stop("pixels must have dim.");
907
  }
9081x
  int height = dims[0];
9091x
  int width = dims[1];
9101x
  int spp = (dims.size() >= 3) ? dims[2] : 1;
9111x
  double scale = std::pow(2.0, baseline_exposure);
9121x
  if (scale == 0.0) {
913!
    Rcpp::stop("baseline_exposure scale is invalid.");
914
  }
915
9161x
  std::vector<double> row_major = RToRowMajor(pixels, width, height, spp);
9176x
  for (double& v : row_major) {
9184x
    v /= scale;
919
  }
9201x
  std::vector<double> out = RowMajorToR(row_major, width, height, spp);
9211x
  Rcpp::NumericVector out_vec(out.begin(), out.end());
9221x
  out_vec.attr("dim") = dims;
9231x
  return out_vec;
924
}
925
926
// [[Rcpp::export]]
9271x
bool write_dng_cpp(const std::string& filename,
928
                   SEXP pixels,
929
                   Rcpp::List meta,
930
                   int bitdepth = 16,
931
                   bool compress = true) {
9321x
  if (!Rf_isNumeric(pixels)) {
933!
    Rcpp::stop("pixels must be numeric.");
934
  }
935
9361x
  Rcpp::RObject pix_obj(pixels);
9371x
  if (bitdepth < 1 || bitdepth > 16) {
938!
    Rcpp::stop("bitdepth must be between 1 and 16.");
939
  }
940
9411x
  Rcpp::NumericVector pix = Rcpp::as<Rcpp::NumericVector>(pix_obj);
9421x
  Rcpp::IntegerVector dims = pix.attr("dim");
9431x
  if (dims.size() == 0) {
944!
    Rcpp::stop("pixels must be a matrix or 3D array.");
945
  }
946
9471x
  int height = dims[0];
9481x
  int width = dims[1];
9491x
  int spp = 1;
9501x
  bool is_mosaic = false;
951
9521x
  if (dims.size() == 2) {
9531x
    spp = 1;
9541x
    is_mosaic = true;
955!
  } else if (dims.size() == 3 && dims[2] == 3) {
956!
    spp = 3;
957
  } else {
958!
    Rcpp::stop("pixels must have dim (h,w) or (h,w,3).");
959
  }
960
9611x
  std::size_t n_samples = static_cast<std::size_t>(width) *
9621x
    static_cast<std::size_t>(height) * static_cast<std::size_t>(spp);
9631x
  std::vector<uint16_t> buf(n_samples);
9641x
  double max_val = std::pow(2.0, static_cast<double>(bitdepth)) - 1.0;
965
96617x
  for (int y = 0; y < height; ++y) {
967272x
    for (int x = 0; x < width; ++x) {
968512x
      for (int c = 0; c < spp; ++c) {
969256x
        std::size_t r_idx = static_cast<std::size_t>(y) +
970256x
          static_cast<std::size_t>(height) *
971256x
          (static_cast<std::size_t>(x) + static_cast<std::size_t>(width) *
972256x
          static_cast<std::size_t>(c));
973
974256x
        double v = pix[r_idx];
975256x
        if (Rcpp::NumericVector::is_na(v)) {
976!
          v = 0.0;
977
        }
978256x
        v = Clamp01(v);
979256x
        uint16_t q = static_cast<uint16_t>(std::lround(v * max_val));
980
981256x
        std::size_t sample_idx = (static_cast<std::size_t>(y) *
982256x
          static_cast<std::size_t>(width) + static_cast<std::size_t>(x)) *
983256x
          static_cast<std::size_t>(spp) + static_cast<std::size_t>(c);
984256x
        buf[sample_idx] = q;
985
      }
986
    }
987
  }
988
9891x
  tinydngwriter::DNGImage dng_image;
9901x
  dng_image.SetBigEndian(false);
9911x
  if (!dng_image.SetSubfileType(false, false, false)) {
992!
    Rcpp::stop("Failed to set DNG SubfileType.");
993
  }
9941x
  if (!dng_image.SetImageWidth(static_cast<unsigned int>(width)) ||
9952x
      !dng_image.SetImageLength(static_cast<unsigned int>(height)) ||
9961x
      !dng_image.SetRowsPerStrip(static_cast<unsigned int>(height))) {
997!
    Rcpp::stop("Failed to set DNG image dimensions.");
998
  }
9991x
  if (!dng_image.SetSamplesPerPixel(static_cast<unsigned short>(spp))) {
1000!
    Rcpp::stop("Failed to set DNG samples per pixel.");
1001
  }
1002
1003
  std::vector<unsigned short> bps(static_cast<std::size_t>(spp),
10041x
                                  static_cast<unsigned short>(bitdepth));
10051x
  if (!dng_image.SetBitsPerSample(static_cast<unsigned int>(spp), bps.data())) {
1006!
    Rcpp::stop("Failed to set DNG bits per sample.");
1007
  }
1008
10091x
  if (!dng_image.SetPlanarConfig(tinydngwriter::PLANARCONFIG_CONTIG)) {
1010!
    Rcpp::stop("Failed to set DNG planar configuration.");
1011
  }
1012
10131x
  if (is_mosaic) {
10141x
    if (!dng_image.SetPhotometric(tinydngwriter::PHOTOMETRIC_CFA)) {
1015!
      Rcpp::stop("Failed to set DNG photometric interpretation.");
1016
    }
10171x
    if (!dng_image.SetCFARepeatPatternDim(2, 2)) {
1018!
      Rcpp::stop("Failed to set CFA repeat pattern.");
1019
    }
1020
10211x
    unsigned char cfa_vals[4] = {0, 1, 1, 2};
10221x
    if (HasListElement(meta, "cfa_pattern")) {
10231x
      Rcpp::IntegerMatrix cfa = Rcpp::as<Rcpp::IntegerMatrix>(meta["cfa_pattern"]);
10241x
      if (cfa.nrow() == 2 && cfa.ncol() == 2) {
10251x
        cfa_vals[0] = static_cast<unsigned char>(cfa(0, 0));
10261x
        cfa_vals[1] = static_cast<unsigned char>(cfa(0, 1));
10271x
        cfa_vals[2] = static_cast<unsigned char>(cfa(1, 0));
10281x
        cfa_vals[3] = static_cast<unsigned char>(cfa(1, 1));
1029
      }
1030
    }
1031
10321x
    if (!dng_image.SetCFAPattern(4, cfa_vals)) {
1033!
      Rcpp::stop("Failed to set CFA pattern.");
1034
    }
1035
  } else {
1036!
    if (!dng_image.SetPhotometric(tinydngwriter::PHOTOMETRIC_RGB)) {
1037!
      Rcpp::stop("Failed to set DNG photometric interpretation.");
1038
    }
1039
  }
1040
10411x
  if (HasListElement(meta, "black_level")) {
10421x
    Rcpp::NumericVector black = GetNumericVector(meta, "black_level");
10431x
    if (black.size() > 0) {
10441x
      std::vector<unsigned short> black_vals(static_cast<std::size_t>(black.size()));
10455x
      for (R_xlen_t i = 0; i < black.size(); ++i) {
10464x
        double v = black[i];
10474x
        if (Rcpp::NumericVector::is_na(v)) v = 0.0;
10484x
        if (v < 0.0) v = 0.0;
10494x
        if (v > max_val) v = max_val;
10504x
        black_vals[static_cast<std::size_t>(i)] = static_cast<unsigned short>(v);
1051
      }
10521x
      if (black.size() == 4) {
10531x
        dng_image.SetBlackLevelRepeatDim(2, 2);
1054
      }
10551x
      dng_image.SetBlackLevel(static_cast<unsigned int>(black_vals.size()),
10561x
                              black_vals.data());
1057
    }
1058
  }
1059
10601x
  if (HasListElement(meta, "white_level")) {
10611x
    Rcpp::NumericVector white = GetNumericVector(meta, "white_level");
10621x
    if (white.size() > 0) {
10631x
      std::vector<double> white_vals(static_cast<std::size_t>(white.size()));
10645x
      for (R_xlen_t i = 0; i < white.size(); ++i) {
10654x
        double v = white[i];
10664x
        if (Rcpp::NumericVector::is_na(v)) v = max_val;
10674x
        if (v < 0.0) v = 0.0;
10684x
        if (v > max_val) v = max_val;
10694x
        white_vals[static_cast<std::size_t>(i)] = v;
1070
      }
10711x
      dng_image.SetWhiteLevelRational(static_cast<unsigned int>(white_vals.size()),
10721x
                                      white_vals.data());
1073
    }
1074
  }
1075
10761x
  bool allow_as_shot = true;
10771x
  if (HasListElement(meta, "has_as_shot_neutral")) {
1078
    Rcpp::LogicalVector has_as_shot = Rcpp::as<Rcpp::LogicalVector>(
1079!
      meta["has_as_shot_neutral"]);
1080!
    allow_as_shot = has_as_shot.size() > 0 && has_as_shot[0] == TRUE;
1081
  }
10821x
  if (allow_as_shot && HasListElement(meta, "as_shot_neutral")) {
1083!
    Rcpp::NumericVector as_shot = GetNumericVector(meta, "as_shot_neutral");
1084!
    if (!HasNaNumeric(as_shot, 3)) {
1085!
      dng_image.SetAsShotNeutral(3, as_shot.begin());
1086
    }
1087
  }
1088
10891x
  if (HasListElement(meta, "color_matrix1")) {
1090!
    Rcpp::NumericVector cm1 = GetNumericVector(meta, "color_matrix1");
1091!
    if (!HasNaNumeric(cm1, 9)) {
1092!
      dng_image.SetColorMatrix1(3, cm1.begin());
1093
    }
1094
  }
1095
10961x
  if (HasListElement(meta, "color_matrix2")) {
1097!
    Rcpp::NumericVector cm2 = GetNumericVector(meta, "color_matrix2");
1098!
    if (!HasNaNumeric(cm2, 9)) {
1099!
      dng_image.SetColorMatrix2(3, cm2.begin());
1100
    }
1101
  }
1102
11031x
  bool allow_analog_balance = true;
11041x
  if (HasListElement(meta, "has_analog_balance")) {
1105
    Rcpp::LogicalVector has_analog = Rcpp::as<Rcpp::LogicalVector>(
1106!
      meta["has_analog_balance"]);
1107!
    allow_analog_balance = has_analog.size() > 0 && has_analog[0] == TRUE;
1108
  }
11091x
  if (allow_analog_balance && HasListElement(meta, "analog_balance")) {
1110!
    Rcpp::NumericVector ab = GetNumericVector(meta, "analog_balance");
1111!
    if (!HasNaNumeric(ab, 3)) {
1112!
      dng_image.SetAnalogBalance(3, ab.begin());
1113
    }
1114
  }
1115
11161x
  bool allow_active_area = true;
11171x
  if (HasListElement(meta, "has_active_area")) {
1118
    Rcpp::LogicalVector has_active = Rcpp::as<Rcpp::LogicalVector>(
1119!
      meta["has_active_area"]);
1120!
    allow_active_area = has_active.size() > 0 && has_active[0] == TRUE;
1121
  }
11221x
  if (allow_active_area && HasListElement(meta, "active_area")) {
1123!
    Rcpp::IntegerVector area = GetIntegerVector(meta, "active_area");
1124!
    if (!HasNaInteger(area, 4)) {
1125
      unsigned int values[4] = {
1126!
        static_cast<unsigned int>(area[0]),
1127!
        static_cast<unsigned int>(area[1]),
1128!
        static_cast<unsigned int>(area[2]),
1129!
        static_cast<unsigned int>(area[3])
1130
      };
1131!
      dng_image.SetActiveArea(values);
1132
    }
1133
  }
1134
11351x
  if (HasListElement(meta, "orientation")) {
1136!
    Rcpp::IntegerVector orientation = GetIntegerVector(meta, "orientation");
1137!
    if (orientation.size() >= 1 && orientation[0] != NA_INTEGER) {
1138!
      dng_image.SetOrientation(static_cast<unsigned short>(orientation[0]));
1139
    }
1140
  }
1141
11421x
  if (is_mosaic && compress) {
11431x
    if (!dng_image.SetCompression(tinydngwriter::COMPRESSION_NEW_JPEG)) {
1144!
      Rcpp::stop("Failed to set DNG compression.");
1145
    }
11461x
    if (!dng_image.SetImageDataJpeg(buf.data(),
1147
                                    static_cast<unsigned int>(width),
1148
                                    static_cast<unsigned int>(height),
1149
                                    static_cast<unsigned int>(bitdepth))) {
1150!
      Rcpp::stop("Failed to set DNG JPEG image data.");
1151
    }
1152
  } else {
1153!
    if (!dng_image.SetCompression(tinydngwriter::COMPRESSION_NONE)) {
1154!
      Rcpp::stop("Failed to set DNG compression.");
1155
    }
1156!
    if (!dng_image.SetImageData(reinterpret_cast<unsigned char*>(buf.data()),
1157!
                                buf.size() * sizeof(uint16_t))) {
1158!
      Rcpp::stop("Failed to set DNG image data.");
1159
    }
1160
  }
1161
11621x
  tinydngwriter::DNGWriter writer(false);
11631x
  writer.AddImage(&dng_image);
11641x
  std::string err;
11651x
  if (!writer.WriteToFile(filename.c_str(), &err)) {
1166!
    Rcpp::stop(err.empty() ? "Failed to write DNG." : err);
1167
  }
1168
11691x
  return true;
1170
}
1
#include <vector>
2
#include <memory>
3
#include <string>
4
#include "Rcpp.h"
5
#include <filesystem>
6
7
#define STB_IMAGE_IMPLEMENTATION
8
#include <stbimageheaders/stb_image.h>
9
10
namespace fs = std::filesystem;
11
12
// [[Rcpp::export]]
137x
Rcpp::NumericVector load_image_stb(const std::string& filename,
14
                                   int& width,
15
                                   int& height,
16
                                   int& channels,
17
                                   int desired_channels) {
187x
  width = height = channels = 0;
19
207x
  const fs::path filepath(filename);
217x
  const std::string filepath_string = filepath.string();
22
237x
  float* data = stbi_loadf(filepath_string.c_str(), &width, &height, &channels,
24
                           desired_channels);
257x
  if (!data) {
26
    throw std::runtime_error(
27!
        "Loading of '" + filename + "' (float) failed: " +
28!
          std::string(stbi_failure_reason()) +
29!
          " -- nx/ny/channels: " + std::to_string(width) + "/" +
30!
          std::to_string(height) + "/" + std::to_string(channels));
31
  }
32
337x
  if (desired_channels != 0) {
347x
    channels = desired_channels;
35
  }
36
377x
  if (width == 0 || height == 0 || channels == 0) {
38!
    stbi_image_free(data);
39!
    throw std::runtime_error("Could not find " + filename);
40
  }
41
42
  // Enforce RGBA
437x
  if (channels != 4) {
44!
    stbi_image_free(data);
45
    throw std::runtime_error(
46!
        "Expected 4 channels (RGBA) but got " + std::to_string(channels) +
47!
          ". Call with desired_channels = 4.");
48
  }
49
50
  // Allocate R array: dim = c(height, width, 4) (RGBA in the 3rd dimension)
517x
  std::size_t n_pixels = static_cast<std::size_t>(width) *
527x
    static_cast<std::size_t>(height);
537x
  std::size_t n_vals = n_pixels * 4;
54
557x
  Rcpp::NumericVector arr_return(n_vals);
567x
  Rcpp::IntegerVector dim(3);
577x
  dim[0] = height;   // rows (y)
587x
  dim[1] = width;    // cols (x)
597x
  dim[2] = 4;        // RGBA
607x
  arr_return.attr("dim") = dim;
61
62
  // Reorder from STB layout (y, x, c; row-major) to R layout (y, x, c; column-major)
63119x
  for (int y = 0; y < height; ++y) {
641904x
    for (int x = 0; x < width; ++x) {
658960x
      for (int c = 0; c < 4; ++c) {
667168x
        std::size_t stb_idx =
677168x
          (static_cast<std::size_t>(y) * width + x) * 4 + c;
68
69
        // R index: y + height * (x + width * c)
707168x
        std::size_t r_idx =
717168x
          static_cast<std::size_t>(y) +
727168x
          static_cast<std::size_t>(height) *
737168x
          (x + static_cast<std::size_t>(width) * c);
74
757168x
        arr_return[r_idx] = static_cast<double>(data[stb_idx]);
76
      }
77
    }
78
  }
79
807x
  stbi_image_free(data);
817x
  return arr_return;
82
}
1
#define STB_IMAGE_RESIZE_IMPLEMENTATION
2
3
#include <RcppArmadillo.h>
4
#include <RProgress.h>
5
#include <stbimageheaders/stb_image_resize2.h>
6
// [[Rcpp::depends(RcppArmadillo)]]
7
using namespace Rcpp;
8
9
// [[Rcpp::export]]
10!
arma::mat subsample(arma::mat& circle, int size) {
11!
  int binsize = circle.n_cols/size;
12!
  arma::mat subsampled(size,size,arma::fill::zeros);
13!
  if(size == 1) {
14!
    subsampled(0,0) = 1;
15!
    return(subsampled);
16
  }
17!
  arma::mat temp;
18!
  for(int i = 0; i < size; i++) {
19!
    for(int j = 0; j < size; j++) {
20!
      if(i != size - 1 && j != size - 1) {
21!
        temp = circle.submat(binsize*i,binsize*j,binsize*(i+1),binsize*(j+1));
22!
        subsampled(i,j) = accu(temp)/(temp.n_elem);
23!
      } else if (i == size - 1 && j != size - 1) {
24!
        temp = circle.submat(binsize*i,binsize*j,circle.n_rows-1,binsize*(j+1));
25!
        subsampled(i,j) = accu(temp)/(temp.n_elem);
26!
      } else if (j == size - 1 && i != size - 1) {
27!
        temp = circle.submat(binsize*i,binsize*j,binsize*(i+1),circle.n_cols-1);
28!
        subsampled(i,j) = accu(temp)/(temp.n_elem);
29!
      } else if (i == size - 1 && j == size - 1) {
30!
        temp = circle.submat(binsize*i,binsize*j,circle.n_rows-1,circle.n_cols-1);
31!
        subsampled(i,j) = accu(temp)/(temp.n_elem);
32
      }
33
    }
34
  }
35!
  return(subsampled);
36
}
37
38!
arma::mat subsample_interpolate(arma::mat& circle, float mag) {
39
  //Create two vectors ranging from 1 to ncol/nrow
40!
  arma::vec X = arma::regspace(1, circle.n_cols);
41!
  arma::vec Y = arma::regspace(1, circle.n_rows);
42
  //Create two vectors ranging from 1 to the ncol/nrow, with step mag
43
  //e.g. (1 + 0*mag, 1 + mag, 1+2*mag, ... , 1 + floor(end-1)/mag, so that
44
  // start + floor(end-1) * mag < ncol/nrow
45
46
  //These are our new, interpolated values
47!
  arma::vec XI = arma::regspace(X.min(), mag, X.max());
48!
  arma::vec YI = arma::regspace(Y.min(), mag, Y.max());
49
50
  //If X1.n_elem is even, remove one element to make it odd
51!
  if(XI.n_elem % 2 == 0) {
52!
    XI.set_size(XI.n_elem-1);
53
  }
54
  //If Y1.n_elem is even, remove one element to make it odd
55
56!
  if(YI.n_elem % 2 == 0) {
57!
    YI.set_size(YI.n_elem-1);
58
  }
59!
  arma::mat ZI;
60
  //Interpolate the `circle` values given on the XY grid on the new grid ZI specified
61
  //by XI and YI
62!
  arma::interp2(X, Y, circle, XI, YI, ZI);
63!
  return(ZI);
64
}
65
66
// [[Rcpp::export]]
6795x
arma::mat rayinterp2(arma::mat& image, arma::vec& XI, arma::vec& YI) {
6895x
  arma::vec X = arma::regspace(1, image.n_cols);
6995x
  arma::vec Y = arma::regspace(1, image.n_rows);
7095x
  arma::mat ZI;
7195x
  arma::interp2(X, Y, image, XI, YI, ZI);
7295x
  return(ZI);
73
}
74
75
76
// [[Rcpp::export]]
77!
arma::mat resize_image(arma::mat& image, float mag) {
78!
  arma::vec X = arma::regspace(1, image.n_cols);
79!
  arma::vec Y = arma::regspace(1, image.n_rows);
80!
  arma::vec XI = arma::regspace(X.min(), 1.0/mag, X.max());
81!
  arma::vec YI = arma::regspace(Y.min(), 1.0/mag, Y.max());
82!
  arma::mat ZI;
83!
  arma::interp2(X, Y, image, XI, YI, ZI);
84!
  return(ZI);
85
}
86
87
// [[Rcpp::export]]
88!
arma::mat resize_image_xy(arma::mat& image, arma::vec XI, arma::vec YI) {
89!
  arma::vec X = arma::regspace(1, image.n_cols);
90!
  arma::vec Y = arma::regspace(1, image.n_rows);
91!
  arma::mat ZI;
92!
  arma::interp2(X, Y, image, XI, YI, ZI);
93!
  return(ZI);
94
}
95
96
// [[Rcpp::export]]
978x
NumericMatrix resize_matrix_stb(NumericMatrix image, int width, int height, int method) {
988x
  float* resized_image = new float[width * height];
998x
  float* original_image = new float[image.ncol() * image.nrow()];
100
101816x
  for(int i = 0; i < image.nrow(); i++ ) {
102160824x
    for(int j = 0; j < image.ncol(); j++) {
103160016x
      original_image[i + image.nrow() * j] = image(i,j);
104
    }
105
  }
106
  stbir_filter interp_type;
1078x
  switch(method) {
108!
    case 0:
109!
      interp_type = STBIR_FILTER_DEFAULT;
110!
      break;
111!
    case 1:
112!
      interp_type = STBIR_FILTER_BOX;
113!
      break;
114!
    case 2:
115!
      interp_type = STBIR_FILTER_TRIANGLE;
116!
      break;
1178x
    case 3:
1188x
      interp_type = STBIR_FILTER_CUBICBSPLINE;
1198x
      break;
120!
    case 4:
121!
      interp_type = STBIR_FILTER_CATMULLROM;
122!
      break;
123!
    case 5:
124!
      interp_type = STBIR_FILTER_MITCHELL;
125!
      break;
126!
  default:
127!
    interp_type = STBIR_FILTER_MITCHELL;
128
  }
129
1308x
  void* resized = stbir_resize(
131
    original_image, image.nrow(), image.ncol(), 0,
132
    resized_image, width, height, 0,
133
    STBIR_1CHANNEL, STBIR_TYPE_FLOAT,
134
    STBIR_EDGE_WRAP, interp_type);
1358x
  if (resized == nullptr) {
136!
    delete[] resized_image;
137!
    delete[] original_image;
138!
    stop("stb image resize failed.");
139
  }
1408x
  NumericMatrix resized_mat(width,height);
141280x
  for(int i = 0; i < width; i++ ) {
14216736x
    for(int j = 0; j < height; j++) {
14316464x
      resized_mat(i,j) = resized_image[i + width * j];
144
    }
145
  }
1468x
  delete[] resized_image;
1478x
  delete[] original_image;
148
1498x
  return(resized_mat);
150
}
151
152!
float evaluate_disk(float x) {
153!
  return((cos(x*1.685979) * -22.356787 + sin(x*1.685979) * 85.912460) * exp(-4.892608 *x) +
154!
    (cos(x*4.998496) * 35.918936 + sin(x*4.998496) * -28.875618) * exp(-4.711870 *x) +
155!
    (cos(x*8.244168) * -13.212253 + sin(x*8.244168) * -1.578428) * exp(-4.052795 *x) +
156!
    (cos(x*11.900859) * 0.507991 + sin(x*11.900859) * 1.816328) * exp(-2.929212* x) +
157!
    (cos(x*16.116382) * 0.138051 + sin(x*16.116382) * -0.010000) * exp(-1.512961 *x));
158
}
159
160
// [[Rcpp::export]]
161!
arma::mat generate_disk(float radius, int dim, bool offsetx, bool offsety) {
162!
  arma::mat testmat(dim,dim);
163!
  arma::vec x = arma::linspace(-1,1,dim) * radius;
164!
  arma::vec y = arma::linspace(-1,1,dim) * radius;
165!
  if(offsetx) {
166!
    x -= radius/dim + radius/dim/8;
167
  }
168!
  if(offsety) {
169!
    y -= radius/dim + radius/dim/8;
170
  }
171!
  for(arma::uword i = 0; i < testmat.n_rows; i++) {
172!
    for(arma::uword j = 0; j < testmat.n_cols; j++) {
173!
      testmat(i,j) = fabs(evaluate_disk(pow(x[i],2.0) + pow(y[j],2.0)));
174
    }
175
  }
176!
  return(testmat);
177
}
178
179
// [[Rcpp::export]]
180!
arma::mat gen_ellipse(const double intensity, double width, double height) {
181!
  arma::mat ellipse(width,height);
182!
  for (int i = 0; i < width; ++i) {
183!
    for (int j = 0; j < height; ++j) {
184!
      ellipse(i,j) = pow(((double)i - width/2 + 0.5), 2.0) * pow(height/2,2.0) +
185!
        pow(((double)j - height/2 + 0.5),2.0) * pow(width/2,2.0) > pow(width * height, 2.0)/16 ? intensity : 0.0;
186
    }
187
  }
188!
  return(ellipse);
189
}
190
191
// [[Rcpp::export]]
192!
arma::mat subsample_rect(arma::mat& rect, int binsx, int binsy) {
193!
  int binsizex = rect.n_rows/binsx;
194!
  int binsizey = rect.n_cols/binsy;
195!
  arma::mat subsampled(binsx,binsy,arma::fill::zeros);
196!
  arma::mat temp;
197!
  for(int i = 0; i < binsx; i++) {
198!
    for(int j = 0; j < binsy; j++) {
199!
      if(i != binsx - 1 && j != binsy - 1) {
200!
        temp = rect.submat(binsizex*i,binsizey*j,binsizex*(i+1),binsizey*(j+1));
201!
        subsampled(i,j) = accu(temp)/(temp.n_elem);
202!
      } else if (i == binsx - 1 && j != binsy - 1) {
203!
        temp = rect.submat(binsizex*i,binsizey*j,rect.n_rows-1,binsizey*(j+1));
204!
        subsampled(i,j) = accu(temp)/(temp.n_elem);
205!
      } else if (j == binsy - 1 && i != binsx - 1) {
206!
        temp = rect.submat(binsizex*i,binsizey*j,binsizex*(i+1),rect.n_cols-1);
207!
        subsampled(i,j) = accu(temp)/(temp.n_elem);
208!
      } else if (i == binsx - 1 && j == binsy - 1) {
209!
        temp = rect.submat(binsizex*i,binsizey*j,rect.n_rows-1,rect.n_cols-1);
210!
        subsampled(i,j) = accu(temp)/(temp.n_elem);
211
      }
212
    }
213
  }
214!
  return(subsampled);
215
}
216
217
// [[Rcpp::export]]
218!
arma::mat gen_circle_psf(const double radius) {
219!
  int size = ceil(radius * 2);
220!
  if(size < 6) {
221!
    size = 7;
222
  }
223!
  if((size % 2) == 0) {
224!
    size++;
225
  }
226!
  arma::mat kernel(size,size);
227!
  if(radius == 0) {
228!
    arma::mat zero(1,1,arma::fill::ones);
229!
    return(zero);
230
  }
231!
  double mean = (size-1)/2;
232!
  for (int i = 0; i < size; ++i) {
233!
    for (int j = 0; j < size; ++j) {
234!
      kernel(i,j) = pow(((double)i - mean),2.0) + pow(((double)j - mean),2.0) < pow(radius,2.0) ? 1.0 : 0.0;
235
    }
236
  }
237!
  return(kernel);
238
}
239
240
// [[Rcpp::export]]
241!
bool is_inside(double sizehex, double positionx, double positiony, double sinval, double cosval) {
242!
  double num1 = fabs(cosval* (positionx - sizehex) - sinval* (positiony - sizehex));
243!
  double num2 = fabs(sinval* (positionx - sizehex) + cosval* (positiony - sizehex));
244!
  double minval = sizehex - num1 < sizehex / 2 ?  sizehex - num1 : sizehex / 2;
245!
  return(num2 < sqrt(3.0) * minval);
246
}
247
248
// [[Rcpp::export]]
249!
arma::mat gen_hex_psf(const double radius, const double rotation) {
250!
  int size = ceil(radius * 2);
251!
  if(size < 6) {
252!
    size = 7;
253
  }
254!
  if((size % 2) == 0) {
255!
    size++;
256
  }
257!
  arma::mat kernel(size,size);
258!
  if(radius == 0) {
259!
    arma::mat zero(1,1,arma::fill::zeros);
260!
    return(zero);
261
  }
262!
  const double sinval = sin(rotation);
263!
  const double cosval = cos(rotation);
264!
  double mean = (size-1)/2;
265!
  for (int i = 0; i < size; ++i) {
266!
    for (int j = 0; j < size; ++j) {
267!
      kernel(i,j) = is_inside(mean, i, j, sinval, cosval) ? 1.0 : 0.0;
268
    }
269
  }
270!
  return(kernel);
271
}
272
273
// [[Rcpp::export]]
274!
arma::mat psf(const arma::mat& image, const IntegerMatrix blurmatrix,
275
              const arma::mat& depthmap, double depth, const arma::mat custombokeh,
276
              int type, double bokehintensity, double bokehlimit,
277
              double rotation, bool progbar, int channel) {
278!
  int maxsteps = max(blurmatrix);
279!
  int rows = image.n_rows;
280!
  int cols = image.n_cols;
281!
  arma::mat tempkernel;
282!
  std::vector<arma::mat> kernels;
283!
  arma::mat mask;
284!
  if(type == 0) {
285!
    mask = generate_disk(1.18, 501, false, false);
286!
  } else if (type == 1) {
287!
    mask = gen_hex_psf(500, rotation);
288!
  } else if (type == 2) {
289!
    mask = custombokeh;
290
  }
291!
  int counter = 0;
292!
  int max_dim = mask.n_cols > mask.n_rows ?  mask.n_cols : mask.n_rows;
293!
  for(int i = 0; i < maxsteps+1; i++) {
294!
    tempkernel = subsample_interpolate(mask, (float)max_dim/(float)(i+1));
295!
    tempkernel = tempkernel/accu(tempkernel);
296!
    kernels.push_back(tempkernel);
297!
    counter++;
298
  }
299!
  int halfwidth = (kernels[counter-1].n_cols-1)/2;
300!
  arma::mat temp;
301!
  arma::mat temp2;
302!
  arma::mat depthmask;
303!
  arma::mat blurmask;
304!
  arma::mat result(image.n_rows, image.n_cols, arma::fill::zeros);
305!
  arma::mat normalize(result.n_rows, result.n_cols, arma::fill::zeros);
306!
  std::string pbtext;
307!
  if(channel == 1) {
308!
    pbtext =  "Rendering Bokeh 1/3 [:bar] ETA: :eta";
309!
  } else if(channel == 2) {
310!
    pbtext =  "Rendering Bokeh 2/3 [:bar] ETA: :eta";
311!
  } else if(channel == 3) {
312!
    pbtext =  "Rendering Bokeh 3/3 [:bar] ETA: :eta";
313
  }
314!
  RProgress::RProgress pb(pbtext);
315!
  if(progbar) {
316!
    pb.set_total(rows*cols);
317
  }
318
319
  int begini, beginj, endi, endj, temphalfi, temphalfj;
320
  int beginslicei, endslicei, beginslicej, endslicej;
321!
  for (int i = halfwidth; i < rows-halfwidth; ++i) {
322
323!
    Rcpp::checkUserInterrupt();
324!
    for (int j = halfwidth; j < cols-halfwidth; ++j) {
325!
      if(progbar) {
326!
        pb.tick();
327
      }
328!
      temp = kernels[blurmatrix(i,j)]/pow(depthmap(i,j),2);
329!
      if(temp.n_cols == 1) {
330!
        normalize(i,j) += 1/pow(depthmap(i,j),2);
331!
        result(i,j) += image(i,j)/pow(depthmap(i,j),2);
332!
        continue;
333
      }
334!
      begini = i - (temp.n_rows-1)/2;
335!
      beginj = j - (temp.n_cols-1)/2;
336!
      endi = i + (temp.n_rows-1)/2;
337!
      endj = j + (temp.n_cols-1)/2;
338!
      if(image(i,j) > bokehlimit) {
339!
        temp = temp * bokehintensity;
340
      }
341
342!
      result.submat(begini, beginj, endi, endj) += image(i,j) * temp;
343!
      normalize.submat(begini, beginj, endi, endj) += temp;
344
    }
345
  }
346
347!
  for (int i = 0; i < halfwidth; ++i) {
348!
    Rcpp::checkUserInterrupt();
349!
    for (int j = 0; j < cols; ++j) {
350!
      if(progbar) {
351!
        pb.tick();
352
      }
353!
      temp = kernels[blurmatrix(i,j)]/pow(depthmap(i,j),2);
354!
      if(temp.n_cols == 1) {
355!
        normalize(i,j) += 1/pow(depthmap(i,j),2);
356!
        result(i,j) += image(i,j)/pow(depthmap(i,j),2);
357!
        continue;
358
      }
359!
      temphalfi =  (temp.n_rows-1)/2;
360!
      temphalfj =  (temp.n_cols-1)/2;
361!
      beginslicei = 0;
362!
      endslicei = temp.n_rows-1;
363!
      beginslicej = 0;
364!
      endslicej = temp.n_cols-1;
365!
      endi = i + temphalfi;
366!
      endj = j + temphalfj;
367!
      begini =  i - temphalfi;
368!
      beginj =  j - temphalfj;
369!
      if(i  - temphalfi < 0) {
370!
        beginslicei = temphalfi - i;
371!
        begini = 0;
372
      }
373!
      if(i  + temphalfi > rows - 1) {
374!
        endslicei = endslicei - (i  + temphalfi - rows + 1);
375!
        endi = rows - 1;
376
      }
377!
      if(j  - temphalfj < 0) {
378!
        beginslicej = temphalfj - j;
379!
        beginj = 0;
380
      }
381!
      if(j  + temphalfj > cols - 1) {
382!
        endslicej = endslicej - (j  + temphalfj - cols + 1);
383!
        endj = cols - 1;
384
      }
385!
      if(image(i,j) > bokehlimit) {
386!
        temp = temp * bokehintensity;
387
      }
388!
      temp2 = temp.submat(beginslicei,beginslicej,endslicei,endslicej);
389!
      result.submat(begini, beginj, endi, endj) += image(i,j) * temp2;
390!
      normalize.submat(begini, beginj, endi, endj) += temp2;
391
    }
392
  }
393!
  for (int i = halfwidth; i < rows-halfwidth; ++i) {
394!
    Rcpp::checkUserInterrupt();
395!
    for (int j = 0; j < halfwidth; ++j) {
396!
      if(progbar) {
397!
        pb.tick();
398
      }
399!
      temp = kernels[blurmatrix(i,j)]/pow(depthmap(i,j),2);
400!
      if(temp.n_cols == 1) {
401!
        normalize(i,j) += 1/pow(depthmap(i,j),2);
402!
        result(i,j) += image(i,j)/pow(depthmap(i,j),2);
403!
        continue;
404
      }
405!
      temphalfi =  (temp.n_rows-1)/2;
406!
      temphalfj =  (temp.n_cols-1)/2;
407!
      beginslicei = 0;
408!
      endslicei = temp.n_rows-1;
409!
      beginslicej = 0;
410!
      endslicej = temp.n_cols-1;
411!
      endi = i + temphalfi;
412!
      endj = j + temphalfj;
413!
      begini =  i - temphalfi;
414!
      beginj =  j - temphalfj;
415!
      if(i  - temphalfi < 0) {
416!
        beginslicei = temphalfi - i;
417!
        begini = 0;
418
      }
419!
      if(i  + temphalfi > rows - 1) {
420!
        endslicei = endslicei - (i  + temphalfi - rows + 1);
421!
        endi = rows - 1;
422
      }
423!
      if(j  - temphalfj < 0) {
424!
        beginslicej = temphalfj - j;
425!
        beginj = 0;
426
      }
427!
      if(j  + temphalfj > cols - 1) {
428!
        endslicej = endslicej - (j  + temphalfj - cols + 1);
429!
        endj = cols - 1;
430
      }
431!
      if(image(i,j) > bokehlimit) {
432!
        temp = temp * bokehintensity;
433
      }
434!
      temp2 = temp.submat(beginslicei,beginslicej,endslicei,endslicej);
435!
      result.submat(begini, beginj, endi, endj) += image(i,j) * temp2;
436!
      normalize.submat(begini, beginj, endi, endj) += temp2;
437
    }
438
  }
439!
  for (int i = halfwidth; i < rows-halfwidth; ++i) {
440!
    Rcpp::checkUserInterrupt();
441!
    for (int j = cols-halfwidth; j < cols; ++j) {
442!
      if(progbar) {
443!
        pb.tick();
444
      }
445!
      temp = kernels[blurmatrix(i,j)]/pow(depthmap(i,j),2);
446!
      if(temp.n_cols == 1) {
447!
        normalize(i,j) += 1/pow(depthmap(i,j),2);
448!
        result(i,j) += image(i,j)/pow(depthmap(i,j),2);
449!
        continue;
450
      }
451!
      temphalfi =  (temp.n_rows-1)/2;
452!
      temphalfj =  (temp.n_cols-1)/2;
453!
      beginslicei = 0;
454!
      endslicei = temp.n_rows-1;
455!
      beginslicej = 0;
456!
      endslicej = temp.n_cols-1;
457!
      endi = i + temphalfi;
458!
      endj = j + temphalfj;
459!
      begini =  i - temphalfi;
460!
      beginj =  j - temphalfj;
461!
      if(i  - temphalfi < 0) {
462!
        beginslicei = temphalfi - i;
463!
        begini = 0;
464
      }
465!
      if(i  + temphalfi > rows - 1) {
466!
        endslicei = endslicei - (i  + temphalfi - rows + 1);
467!
        endi = rows - 1;
468
      }
469!
      if(j  - temphalfj < 0) {
470!
        beginslicej = temphalfj - j;
471!
        beginj = 0;
472
      }
473!
      if(j  + temphalfj > cols - 1) {
474!
        endslicej = endslicej - (j  + temphalfj - cols + 1);
475!
        endj = cols - 1;
476
      }
477!
      if(image(i,j) > bokehlimit) {
478!
        temp = temp * bokehintensity;
479
      }
480!
      temp2 = temp.submat(beginslicei,beginslicej,endslicei,endslicej);
481!
      result.submat(begini, beginj, endi, endj) += image(i,j) * temp2;
482!
      normalize.submat(begini, beginj, endi, endj) += temp2;
483
    }
484
  }
485!
  for (int i = rows-halfwidth; i < rows; ++i) {
486!
    Rcpp::checkUserInterrupt();
487!
    for (int j = 0; j < cols; ++j) {
488!
      if(progbar) {
489!
        pb.tick();
490
      }
491!
      temp = kernels[blurmatrix(i,j)]/pow(depthmap(i,j),2);
492!
      if(temp.n_cols == 1) {
493!
        normalize(i,j) += 1/pow(depthmap(i,j),2);
494!
        result(i,j) += image(i,j)/pow(depthmap(i,j),2);
495!
        continue;
496
      }
497!
      temphalfi =  (temp.n_rows-1)/2;
498!
      temphalfj =  (temp.n_cols-1)/2;
499!
      beginslicei = 0;
500!
      endslicei = temp.n_rows-1;
501!
      beginslicej = 0;
502!
      endslicej = temp.n_cols-1;
503!
      endi = i + temphalfi;
504!
      endj = j + temphalfj;
505!
      begini =  i - temphalfi;
506!
      beginj =  j - temphalfj;
507!
      if(i  - temphalfi < 0) {
508!
        beginslicei = temphalfi - i;
509!
        begini = 0;
510
      }
511!
      if(i  + temphalfi > rows - 1) {
512!
        endslicei = endslicei - (i  + temphalfi - rows + 1);
513!
        endi = rows - 1;
514
      }
515!
      if(j  - temphalfj < 0) {
516!
        beginslicej = temphalfj - j;
517!
        beginj = 0;
518
      }
519!
      if(j  + temphalfj > cols - 1) {
520!
        endslicej = endslicej - (j  + temphalfj - cols + 1);
521!
        endj = cols - 1;
522
      }
523!
      if(image(i,j) > bokehlimit) {
524!
        temp = temp * bokehintensity;
525
      }
526!
      temp2 = temp.submat(beginslicei,beginslicej,endslicei,endslicej);
527!
      result.submat(begini, beginj, endi, endj) += image(i,j) * temp2;
528!
      normalize.submat(begini, beginj, endi, endj) += temp2;
529
    }
530
  }
531!
  return(result/normalize);
532
}
533
534
// [[Rcpp::export]]
535!
arma::mat convolution_cpp(const arma::mat& image, const arma::mat kernel,
536
                      bool progbar, int channel, arma::mat& bloom_matrix) {
537!
  int rows = image.n_rows;
538!
  int cols = image.n_cols;
539!
  arma::mat mask;
540
  //kernel needs to have odd number of cols
541!
  int halfwidth = (kernel.n_cols-1)/2;
542!
  arma::mat temp;
543!
  arma::mat temp2;
544!
  arma::mat result(image.n_rows, image.n_cols, arma::fill::zeros);
545!
  arma::mat normalize(result.n_rows, result.n_cols, arma::fill::zeros);
546!
  std::string pbtext;
547!
  if(channel == 1) {
548!
    pbtext =  "Rendering Bokeh 1/3 [:bar] ETA: :eta";
549!
  } else if(channel == 2) {
550!
    pbtext =  "Rendering Bokeh 2/3 [:bar] ETA: :eta";
551!
  } else if(channel == 3) {
552!
    pbtext =  "Rendering Bokeh 3/3 [:bar] ETA: :eta";
553
  }
554!
  RProgress::RProgress pb(pbtext);
555!
  if(progbar) {
556!
    pb.set_total(rows*cols);
557
  }
558!
  bool norm = false;
559!
  if(arma::accu(kernel) != 0) {
560!
    norm = true;
561
  }
562
563
  int begini, beginj, endi, endj, temphalfi, temphalfj;
564
  int beginslicei, endslicei, beginslicej, endslicej;
565!
  temphalfi =  (kernel.n_rows-1)/2;
566!
  temphalfj =  (kernel.n_cols-1)/2;
567
568!
  for (int i = halfwidth; i < rows-halfwidth; ++i) {
569!
    Rcpp::checkUserInterrupt();
570!
    for (int j = halfwidth; j < cols-halfwidth; ++j) {
571!
      if(bloom_matrix(i,j)) {
572!
        if(progbar) {
573!
          pb.tick();
574
        }
575!
        if(kernel.n_cols == 1) {
576!
          normalize(i,j) += 1;
577!
          result(i,j) += image(i,j);
578!
          continue;
579
        }
580!
        begini = i - (kernel.n_rows-1)/2;
581!
        beginj = j - (kernel.n_cols-1)/2;
582!
        endi = i + (kernel.n_rows-1)/2;
583!
        endj = j + (kernel.n_cols-1)/2;
584!
        result.submat(begini, beginj, endi, endj) += image(i,j) * kernel;
585!
        normalize.submat(begini, beginj, endi, endj) += kernel;
586
      } else {
587!
        result(i,j) += image(i,j);
588!
        normalize(i,j) += 1;
589
      }
590
    }
591
  }
592
593!
  for (int i = 0; i < halfwidth; ++i) {
594!
    Rcpp::checkUserInterrupt();
595!
    for (int j = 0; j < cols; ++j) {
596!
      if(bloom_matrix(i,j)) {
597!
        if(progbar) {
598!
          pb.tick();
599
        }
600!
        if(kernel.n_cols == 1) {
601!
          normalize(i,j) += 1;
602!
          result(i,j) += image(i,j);
603!
          continue;
604
        }
605!
        beginslicei = 0;
606!
        endslicei = kernel.n_rows-1;
607!
        beginslicej = 0;
608!
        endslicej = kernel.n_cols-1;
609!
        endi = i + temphalfi;
610!
        endj = j + temphalfj;
611!
        begini =  i - temphalfi;
612!
        beginj =  j - temphalfj;
613!
        if(i  - temphalfi < 0) {
614!
          beginslicei = temphalfi - i;
615!
          begini = 0;
616
        }
617!
        if(i  + temphalfi > rows - 1) {
618!
          endslicei = endslicei - (i  + temphalfi - rows + 1);
619!
          endi = rows - 1;
620
        }
621!
        if(j  - temphalfj < 0) {
622!
          beginslicej = temphalfj - j;
623!
          beginj = 0;
624
        }
625!
        if(j  + temphalfj > cols - 1) {
626!
          endslicej = endslicej - (j  + temphalfj - cols + 1);
627!
          endj = cols - 1;
628
        }
629!
        temp2 = kernel.submat(beginslicei,beginslicej,endslicei,endslicej);
630!
        result.submat(begini, beginj, endi, endj) += image(i,j) * temp2;
631!
        normalize.submat(begini, beginj, endi, endj) += temp2;
632
      } else {
633!
        result(i,j) += image(i,j);
634!
        normalize(i,j) += 1;
635
      }
636
    }
637
  }
638!
  for (int i = halfwidth; i < rows-halfwidth; ++i) {
639!
    Rcpp::checkUserInterrupt();
640!
    for (int j = 0; j < halfwidth; ++j) {
641!
      if(bloom_matrix(i,j)) {
642!
        if(progbar) {
643!
          pb.tick();
644
        }
645!
        if(kernel.n_cols == 1) {
646!
          normalize(i,j) += 1;
647!
          result(i,j) += image(i,j);
648!
          continue;
649
        }
650!
        beginslicei = 0;
651!
        endslicei = kernel.n_rows-1;
652!
        beginslicej = 0;
653!
        endslicej = kernel.n_cols-1;
654!
        endi = i + temphalfi;
655!
        endj = j + temphalfj;
656!
        begini =  i - temphalfi;
657!
        beginj =  j - temphalfj;
658!
        if(i  - temphalfi < 0) {
659!
          beginslicei = temphalfi - i;
660!
          begini = 0;
661
        }
662!
        if(i  + temphalfi > rows - 1) {
663!
          endslicei = endslicei - (i  + temphalfi - rows + 1);
664!
          endi = rows - 1;
665
        }
666!
        if(j  - temphalfj < 0) {
667!
          beginslicej = temphalfj - j;
668!
          beginj = 0;
669
        }
670!
        if(j  + temphalfj > cols - 1) {
671!
          endslicej = endslicej - (j  + temphalfj - cols + 1);
672!
          endj = cols - 1;
673
        }
674!
        temp2 = kernel.submat(beginslicei,beginslicej,endslicei,endslicej);
675!
        result.submat(begini, beginj, endi, endj) += image(i,j) * temp2;
676!
        normalize.submat(begini, beginj, endi, endj) += temp2;
677
      } else {
678!
        result(i,j) += image(i,j);
679!
        normalize(i,j) += 1;
680
      }
681
    }
682
  }
683!
  for (int i = halfwidth; i < rows-halfwidth; ++i) {
684!
    Rcpp::checkUserInterrupt();
685!
    for (int j = cols-halfwidth; j < cols; ++j) {
686!
      if(bloom_matrix(i,j)) {
687!
        if(progbar) {
688!
          pb.tick();
689
        }
690!
        if(kernel.n_cols == 1) {
691!
          normalize(i,j) += 1;
692!
          result(i,j) += image(i,j);
693!
          continue;
694
        }
695!
        beginslicei = 0;
696!
        endslicei = kernel.n_rows-1;
697!
        beginslicej = 0;
698!
        endslicej = kernel.n_cols-1;
699!
        endi = i + temphalfi;
700!
        endj = j + temphalfj;
701!
        begini =  i - temphalfi;
702!
        beginj =  j - temphalfj;
703!
        if(i  - temphalfi < 0) {
704!
          beginslicei = temphalfi - i;
705!
          begini = 0;
706
        }
707!
        if(i  + temphalfi > rows - 1) {
708!
          endslicei = endslicei - (i  + temphalfi - rows + 1);
709!
          endi = rows - 1;
710
        }
711!
        if(j  - temphalfj < 0) {
712!
          beginslicej = temphalfj - j;
713!
          beginj = 0;
714
        }
715!
        if(j  + temphalfj > cols - 1) {
716!
          endslicej = endslicej - (j  + temphalfj - cols + 1);
717!
          endj = cols - 1;
718
        }
719!
        temp2 = kernel.submat(beginslicei,beginslicej,endslicei,endslicej);
720!
        result.submat(begini, beginj, endi, endj) += image(i,j) * temp2;
721!
        normalize.submat(begini, beginj, endi, endj) += temp2;
722
      } else {
723!
        result(i,j) += image(i,j);
724!
        normalize(i,j) += 1;
725
      }
726
    }
727
  }
728!
  for (int i = rows-halfwidth; i < rows; ++i) {
729!
    Rcpp::checkUserInterrupt();
730!
    for (int j = 0; j < cols; ++j) {
731!
      if(bloom_matrix(i,j)) {
732!
        if(progbar) {
733!
          pb.tick();
734
        }
735!
        if(kernel.n_cols == 1) {
736!
          normalize(i,j) += 1;
737!
          result(i,j) += image(i,j);
738!
          continue;
739
        }
740!
        beginslicei = 0;
741!
        endslicei = kernel.n_rows-1;
742!
        beginslicej = 0;
743!
        endslicej = kernel.n_cols-1;
744!
        endi = i + temphalfi;
745!
        endj = j + temphalfj;
746!
        begini =  i - temphalfi;
747!
        beginj =  j - temphalfj;
748!
        if(i  - temphalfi < 0) {
749!
          beginslicei = temphalfi - i;
750!
          begini = 0;
751
        }
752!
        if(i  + temphalfi > rows - 1) {
753!
          endslicei = endslicei - (i  + temphalfi - rows + 1);
754!
          endi = rows - 1;
755
        }
756!
        if(j  - temphalfj < 0) {
757!
          beginslicej = temphalfj - j;
758!
          beginj = 0;
759
        }
760!
        if(j  + temphalfj > cols - 1) {
761!
          endslicej = endslicej - (j  + temphalfj - cols + 1);
762!
          endj = cols - 1;
763
        }
764!
        temp2 = kernel.submat(beginslicei,beginslicej,endslicei,endslicej);
765!
        result.submat(begini, beginj, endi, endj) += image(i,j) * temp2;
766!
        normalize.submat(begini, beginj, endi, endj) += temp2;
767
      } else {
768!
        result(i,j) += image(i,j);
769!
        normalize(i,j) += 1;
770
      }
771
    }
772
  }
773!
  if(norm) {
774!
    return(result/normalize);
775
  } else {
776!
    return(result);
777
  }
778
}