raybevel coverage - 59.50%

R/generate_bevel.R 345 147 0 147 0.0 0.00%
R/plot_skeleton.R 177 82 0 82 0.0 0.00%
R/modify_bevel_with_skeleton.R 50 27 0 27 0.0 0.00%
R/math-functions.R 68 11 0 11 0.0 0.00%
R/find_dangling_nodes.R 20 6 0 6 0.0 0.00%
R/zzz.R 7 3 0 3 0.0 0.00%
R/timer.R 35 12 3 9 85.4 25.00%
R/generate_roof.R 1089 466 163 303 50.2 34.98%
R/skeletonize.R 311 181 122 59 70.1 67.40%
R/plot_offset_polygon.R 179 72 55 17 21.2 76.39%
src/rayskeleton.cpp 155 59 52 7 10375.2 88.14%
R/remove_node_duplicates.R 39 19 17 2 838.7 89.47%
R/convert_ss_to_polygons.R 22 10 9 1 52.0 90.00%
R/generate_offset_links_nodes.R 233 149 138 11 1131.5 92.62%
src/generate_offset_links_nodes_rcpp.cpp 442 243 227 16 296934.6 93.42%
R/extrude_polygon.R 64 42 40 2 126.3 95.24%
src/convert_ss_to_polygons_rcpp.cpp 212 103 100 2 321111.6 97.09%
R/generate_offset_polygon.R 102 44 44 0 26.0 100.00%
R/merge_nodes_within_tolerance.R 46 22 22 0 1429.3 100.00%
R/identify_maxima_nodes.R 30 12 12 0 4688.4 100.00%
R/recalculate_ordered_ids.R 16 11 11 0 203.0 100.00%
R/remove_reversed_links.R 20 7 7 0 139.0 100.00%
R/arrange_base.R 16 4 4 0 417.0 100.00%
R/swap_yz.R 15 4 4 0 118.0 100.00%
src/math.cpp 11 4 4 0 178141.5 100.00%
R/run_documentation.R 15 3 3 0 321.0 100.00%
Total 3719 1743 1037 705 61318.7 59.50%
1
#' Get Face IDs
2
#'
3
#' @param ss
4
#'
5
#' @keywords internal
6
get_n_cores = function() {
765x
  n_cores = getOption("cores", default = getOption("Ncpus", default = parallel::detectCores()))
865x
  if (is.null(n_cores) || length(n_cores) == 0) {
9!
    return(1L)
10
  }
1165x
  n_cores = suppressWarnings(as.integer(n_cores[[1]]))
1265x
  if (is.na(n_cores) || n_cores < 1L) {
131x
    return(1L)
14
  }
1564x
  n_cores
16
}
17
18
convert_ss_to_polygons = function(ss, progress = FALSE) {
1965x
  n_cores = get_n_cores()
2065x
  list_all_polygons = convert_ss_to_polygons_rcpp(ss, n_cores, progress = progress)
2165x
  return(list_all_polygons)
22
}
1
#' Generate a 3D roof model
2
#'
3
#' This function generates a 3D roof model from a straight skeleton.
4
#'
5
#' @param skeleton Default `NULL`. A straight skeleton generated from the `skeletonize` function.
6
#' @param angle Default `45`. Angle of the roof.
7
#' @param max_height Default `NA`. The maximum height of the roof.
8
#' @param vertical_offset Default `0`. The vertical offset of the roof.
9
#' @param base Default `TRUE`. A logical flag that controls whether to generate the bottom of the roof.
10
#' @param base_height Default `vertical_offset`. Height of the base.
11
#' @param sides Default `FALSE`. A logical flag on whether to draw the sides. This will automatically be set to `TRUE`
12
#' if `base = TRUE` and the `base_height` is less than `vertical_offset`.
13
#' @param double_sided Default `FALSE`. A logical flag that controls whether the polygon should be double-sided.
14
#' @param swap_yz Default `TRUE`. A logical flag that controls whether to swap the y and z coordinates in the resulting mesh.
15
#' If `TRUE`, the y and z coordinates will be swapped.
16
#' @param progress Default `TRUE`. A logical flag to control whether a progress bar is displayed during roof generation.
17
#' @param verbose Default `FALSE`. A logical flag to control whether additional timing information should be displayed.
18
#' @param scale_all_max Default `FALSE`. If passing in a list of multiple skeletons with polygons, whether to scale each polygon to the overall
19
#' max height, or whether to scale each max height to the maximum internal distance in the polygon.
20
#' @param material Default `material_list()`. Interface to set the color/appearance/material options for the resulting `ray_mesh` mesh.
21
#' @param roof_material Default `NA`, uses the material specified in `material`. Interface to set the color/appearance/material options for the resulting `ray_mesh` rooftop mesh.
22
#'
23
#' @return A 3D mesh of the roof model.
24
#'
25
#' @import rayvertex
26
#'
27
#' @export
28
#' @examples
29
#' #Generate vertices and holes
30
#' vertices = matrix(c(0,0, 7,0, 7,7, 0,7, 0,0), ncol = 2, byrow = TRUE)-3.5
31
#' hole_1 = matrix(c(1,1, 2,1, 2,2, 1,2, 1,1), ncol = 2, byrow = TRUE)[5:1,]-3.5
32
#' hole_2 = matrix(c(5,5, 6,5, 6,6, 5,6, 5,5), ncol = 2, byrow = TRUE)[5:1,]-3.5
33
#' skeleton = skeletonize(vertices, holes = list(hole_1, hole_2))
34
#' if(run_docs_raybevel()) {
35
#' plot_skeleton(skeleton)
36
#' }
37
#'
38
#' #Generate a roof model and specify the material
39
#' if(run_docs_raybevel()) {
40
#'   library(rayrender)
41
#'   library(rayvertex)
42
#'   roof_model = generate_roof(skeleton, material = material_list(diffuse="purple"))
43
#'   scene_base = xz_rect(xwidth=100,zwidth=100,
44
#'                        material=diffuse(color="grey20", checkercolor="white")) |>
45
#'     add_object(sphere(y=8,z=10,x=-3,material=light(intensity=100))) |>
46
#'     add_object(sphere(y=800,z=10,x=-3,radius=100,material=light(intensity=5)))
47
#'
48
#'   raymesh_model(roof_model, override_material = FALSE) |>
49
#'     add_object(scene_base) |>
50
#'     render_scene(lookfrom=c(10,30,20), samples=16,
51
#'                  width=800,height=800,fov=0,ortho_dimensions=c(10,10))
52
#' }
53
#'
54
#' # Change the maximum height of the roof
55
#' if(run_docs_raybevel()) {
56
#'   roof_model = generate_roof(skeleton, max_height=5)
57
#'   raymesh_model(roof_model, material = diffuse(color="purple")) |>
58
#'     add_object(scene_base) |>
59
#'     render_scene(lookfrom=c(10,30,20), samples=16,
60
#'                  width=800,height=800,fov=0,ortho_dimensions=c(10,10))
61
#' }
62
#'
63
#' #Add a vertical_offset to the roof, without a base
64
#' if(run_docs_raybevel()) {
65
#'   roof_model = generate_roof(skeleton, vertical_offset = 2, base = FALSE)
66
#'   raymesh_model(roof_model, material = diffuse(color="purple")) |>
67
#'     add_object(scene_base) |>
68
#'     render_scene(lookfrom=c(10,10,20), lookat=c(0,2,0), samples=16,
69
#'                  width=800,height=800,fov=0,ortho_dimensions=c(10,10))
70
#' }
71
#'
72
#' # Add a base
73
#' if(run_docs_raybevel()) {
74
#'   roof_model = generate_roof(skeleton, vertical_offset = 2, base = TRUE)
75
#'   raymesh_model(roof_model, material = diffuse(color="purple")) |>
76
#'     add_object(scene_base) |>
77
#'     render_scene(lookfrom=c(10,10,20), lookat=c(0,2,0), samples=16,
78
#'                  width=800,height=800,fov=0,ortho_dimensions=c(10,10))
79
#' }
80
#'
81
#' # Change the base height (note that the vertical_offset is measured from the base, not from zero)
82
#' if(run_docs_raybevel()) {
83
#'   roof_model = generate_roof(skeleton, vertical_offset = 2, base = TRUE, base_height=1)
84
#'   raymesh_model(roof_model, material = diffuse(color="purple")) |>
85
#'     add_object(scene_base) |>
86
#'     render_scene(lookfrom=c(10,10,20), lookat=c(0,2,0), samples=16,
87
#'                  width=800,height=800,fov=0,ortho_dimensions=c(10,10))
88
#' }
89
#'
90
#'
91
#' # Skeletonize and turn an {sf} object into a roof
92
#' if(run_docs_raybevel()) {
93
#'   us_states = spData::us_states
94
#'   cali = us_states[us_states$NAME == "California",]
95
#'   cali_skeleton = skeletonize(cali)
96
#'   plot_skeleton(cali_skeleton)
97
#'   roof_model_cali = generate_roof(cali_skeleton, max_height = 2) |>
98
#'     center_mesh() |>
99
#'     translate_mesh(c(0,1,0))
100
#'
101
#'   raymesh_model(roof_model_cali, material = diffuse(color="purple")) |>
102
#'     add_object(scene_base) |>
103
#'     add_object(sphere(x=-10,z=-10,y=4,material=light(color="red", intensity=40))) |>
104
#'     add_object(sphere(x=10,z=-10,y=4,material=light(color="orange", intensity=40))) |>
105
#'     render_scene(lookfrom=c(0,10,-1), samples=16, ambient_light=TRUE,
106
#'                  width=800,height=800,fov=0, ortho_dimensions=c(12,12))
107
#' }
108
generate_roof = function(skeleton, max_height = NA, vertical_offset = 0,
109
                         base = FALSE, base_height = 0, angle = 45,
110
                         sides = FALSE, double_sided = FALSE, scale_all_max = FALSE,
111
                         swap_yz = TRUE, progress = TRUE,
112
                         material = material_list(),
113
                         roof_material = NA,
114
                         verbose = FALSE) {
1151x
  if(run_docs_raybevel() || !interactive()) {
1161x
    progress = FALSE
117
  }
1181x
  if(!is.list(roof_material)) {
119!
    roof_material = material
120
  }
1211x
  if(inherits(skeleton, "rayskeleton_list")) {
122!
    pb = progress::progress_bar$new(
123!
      format = ":current/:total Generating roof [:bar] eta: :eta",
124!
      total = length(skeleton), clear = TRUE, width = 60)
125!
    meshlist = list()
126!
    counter  = 1
127!
    vec_default = function(length_skeleton, value) {
128!
      if(length(value) == 1) {
129!
        return(rep(value,length(skeleton)))
130
      } else {
131!
        stopifnot(length(value) == length_skeleton)
132!
        return(value)
133
      }
134
    }
135!
    len_s = length(skeleton)
136!
    vertical_offset = vec_default(len_s, vertical_offset)
137!
    base_height = vec_default(len_s, base_height)
138!
    angle = vec_default(len_s, angle)
139!
    if(!is.na(max_height)) {
140!
      if(length(max_height) == 1) {
141!
        if(scale_all_max) {
142!
          max_height = rep(max_height,length(skeleton))
143
        } else {
144
          #Calculate proportional maximum heights
145!
          single_max_heights = unlist(lapply(skeleton, \(x) max(x$nodes$time)))
146!
          max_height = single_max_heights/max(single_max_heights) * max_height
147
        }
148
      } else {
149!
        stopifnot(length(max_height) == length(skeleton))
150
      }
151
    }
152!
    for(j in seq_len(length(skeleton))) {
153!
      if(progress) {
154!
        pb$tick()
155
      }
156!
      meshlist[[counter]] = generate_roof(skeleton[[j]],
157!
                                          base = base,
158!
                                          max_height = max_height[j],
159!
                                          sides = sides,
160!
                                          double_sided = double_sided,
161!
                                          base_height = base_height[j],
162!
                                          vertical_offset = vertical_offset[j],
163!
                                          angle = angle[j],
164!
                                          swap_yz = swap_yz,
165!
                                          material = material,
166!
                                          roof_material = roof_material,
167!
                                          progress = FALSE)
168!
      counter = counter + 1
169
    }
170!
    return(scene_from_list(meshlist))
171
  }
1721x
  if(!inherits(skeleton, "rayskeleton")) {
173!
    stop("`skeleton` must be of class `rayskeleton`")
174
  }
1751x
  angle_slope = tanpi(angle/180)
1761x
  if(is.na(max_height)) {
177!
    max_height = max(skeleton$nodes$time) * angle_slope
178
  }
179
1801x
  polygon_ind = convert_ss_to_polygons(skeleton, progress = progress)
1811x
  nodes = skeleton$nodes
1821x
  index_list = list()
1831x
  for(i in seq_len(length(polygon_ind))) {
1844x
    tmp_ind = polygon_ind[[i]]
1854x
    tmp_poly = nodes[tmp_ind,2:3]
1864x
    index_list[[i]] = matrix(tmp_ind[decido::earcut(tmp_poly)],byrow=TRUE,ncol=3)
187
  }
1881x
  indices_all = do.call("rbind",index_list)
1891x
  xyz = nodes[,2:4]
1901x
  colnames(xyz) = c("x","y","z")
1911x
  if(!is.na(max_height)) {
1921x
    stopifnot(max_height >= 0)
1931x
    xyz[,3] = xyz[,3]/max(xyz[,3]) * max_height
194
  }
1951x
  original_verts = attr(skeleton,"original_vertices")
1961x
  original_holes = attr(skeleton,"original_holes")
1971x
  side_top = vertical_offset
198
1991x
  mesh = construct_mesh(vertices = as.matrix(xyz),
2001x
                                   indices = as.matrix(indices_all)-1) |>
2011x
    translate_mesh(c(0,0,vertical_offset)) |>
2021x
    set_material(roof_material)
203
2041x
  if(double_sided) {
205!
    xyzflip = xyz
206!
    xyzflip[,3] = -xyzflip[,3]
207!
    indices_flip = indices_all[,3:1,drop=FALSE]
208!
    double_mesh = construct_mesh(vertices = as.matrix(xyzflip),
209!
                                 indices = as.matrix(indices_flip)-1) |>
210!
      set_material(roof_material)
211
  }
2121x
  if(base && !double_sided) {
2131x
    if(length(original_holes) > 0) {
214!
      holes = c(0,utils::head(cumsum(unlist(lapply(original_holes,nrow))),-1)) + nrow(original_verts) + 1
215!
      hole_mat = do.call("rbind", original_holes)
216!
      original_verts_holes = rbind(original_verts, hole_mat)
217
    } else {
2181x
      holes = 0
2191x
      original_verts_holes = original_verts
220
    }
2211x
    base_indices = matrix(decido::earcut(original_verts_holes, holes = holes), byrow = TRUE, ncol=3)
2221x
    base_indices = base_indices[,3:1,drop = FALSE]
2231x
    original_verts_base = cbind(original_verts_holes, rep(0, nrow(original_verts_holes)))
2241x
    base_mesh = construct_mesh(vertices = as.matrix(original_verts_base),
2251x
                               indices = as.matrix(base_indices)-1) |>
2261x
      set_material(material)
227
2281x
    mesh = mesh |>
2291x
      add_shape(base_mesh)
230
  }
2311x
  if(double_sided) {
232!
    mesh = add_shape(mesh, double_mesh)
233
  }
2341x
  if((sides || base || double_sided) &&
2351x
     ((!double_sided && side_top > 0) || (double_sided && side_top > 0))) {
2361x
    if(!double_sided) {
2371x
      side_mesh = extrude_sides(original_verts, original_holes, bottom = 0, top = side_top)
238
    } else {
239!
      side_mesh = extrude_sides(original_verts, original_holes, bottom = -side_top, top = side_top)
240
    }
2411x
    side_mesh = side_mesh |>
2421x
      set_material(material)
2431x
    mesh = add_shape(mesh, side_mesh)
244
  }
2451x
  if(!is.na(base_height)) {
2461x
    mesh = translate_mesh(mesh, c(0,0,base_height))
247
  }
2481x
  if(swap_yz) {
2491x
    mesh = swap_yz(mesh)
250
  }
2511x
  print_time(verbose, "Generated mesh")
2521x
  return(mesh)
253
}
254
255
#' Generate a beveled 3D polygon
256
#'
257
#' This function generates a beveled 3D polygon from a straight skeleton.
258
#'
259
#' @param skeleton Default `NULL`. A straight skeleton generated from the `skeletonize` function.
260
#' @param bevel_offsets Default `NULL`. The offset(s) of the bevel.
261
#' @param max_height Default `1`. The maximum height of the polygon.
262
#' @param bevel_heights Default is set to `bevel_offsets`. Numeric vector specifying the heights of the bevels. Must be of the same length as `bevel_offsets`.
263
#' @param set_max_height Default `FALSE`. A logical flag that controls whether to set the max height of the roof based on the `max_height` argument.
264
#' @param swap_yz Default `TRUE`. A logical flag that controls whether to swap the y and z coordinates in the resulting mesh. If `TRUE`, the y and z coordinates will be swapped.
265
#' @param progress Default `TRUE`. A logical flag to control whether a progress bar is displayed during roof generation.
266
#' @param vertical_offset Default `0`. The vertical offset of the polygon.
267
#' @param base Default `TRUE`. A logical flag that controls whether to generate the bottom of the polygon.
268
#' @param base_height Default `NA`. Height of the base, defaulting to `min(bevel_heights) + vertical_offset` .
269
#' @param sides Default `FALSE`. A logical flag on whether to draw the sides. This will automatically be set to `TRUE`
270
#' if `base = TRUE` and the `base_height` is less than `vertical_offset`.
271
#' @param scale_all_max Default `FALSE`. If passing in a list of multiple skeletons with polygons, whether to scale each polygon to the overall
272
#' max height, or whether to scale each max height to the maximum internal distance in the polygon.
273
#' @param verbose Default `FALSE`. A logical flag to control whether additional timing information should be displayed.
274
#' @param raw_offsets Default `FALSE`. A logical flag indicating whether the `bevel_offsets` are already in raw format and do not need to be multiplied by the maximum time of the skeleton.
275
#' @param raw_heights Default `FALSE`. A logical flag indicating whether the `bevel_heights` are already in raw format and do not need to be multiplied by the maximum time of the skeleton.
276
#' @param double_sided Default `FALSE`. A logical flag that controls whether the polygon should be double-sided.
277
#' @param return_skeleton_polygons Default `FALSE`. A logical flag that controls whether to return the skeleton polygons along with the 3D mesh.
278
#' @param material Default `material_list()`. Interface to set the color/appearance/material options for the resulting `ray_mesh` mesh.
279
#' @param bevel_material Default `NA`, uses the material specified in `material`. Interface to set the color/appearance/material options for the resulting `ray_mesh` bevel mesh.
280
#'
281
#' @return A 3D mesh of the beveled polygon model.
282
#'
283
#' @import rayvertex
284
#'
285
#' @export
286
#' @examples
287
#' #Generate vertices and holes
288
#' vertices = matrix(c(0,0, 7,0, 7,7, 0,7, 0,0), ncol = 2, byrow = TRUE)-3.5
289
#' hole_1 = matrix(c(1,1, 2,1, 2,2, 1,2, 1,1), ncol = 2, byrow = TRUE)[5:1,]-3.5
290
#' hole_2 = matrix(c(5,5, 6,5, 6,6, 5,6, 5,5), ncol = 2, byrow = TRUE)[5:1,]-3.5
291
#' skeleton = skeletonize(vertices, holes = list(hole_1, hole_2))
292
#' if(run_docs_raybevel()) {
293
#' plot_skeleton(skeleton)
294
#' }
295
#'
296
#' #Generate a roof model and specify the material
297
#' if(run_docs_raybevel()) {
298
#'   library(rayrender)
299
#'   library(rayvertex)
300
#'
301
#'   scene_base = xz_rect(xwidth=100,zwidth=100,
302
#'                        material=diffuse(color="grey20", checkercolor="white")) |>
303
#'     add_object(sphere(y=8,z=10,x=-3,material=light(intensity=100))) |>
304
#'     add_object(sphere(y=800,z=10,x=-3,radius=100,material=light(intensity=5))) |>
305
#'     add_object(sphere(x=-10,z=-10,y=5,material=light(color="red", intensity=40))) |>
306
#'     add_object(sphere(x=10,z=-10,y=5,material=light(color="orange", intensity=40)))
307
#'
308
#'   bevel = generate_bevel("angled", bevel_start = 0, bevel_end = 0.2, max_height=0.25)
309
#'   roof_model = generate_beveled_polygon(skeleton,
310
#'                                         bevel_offsets = bevel,
311
#'                                         material = material_list(diffuse="purple"))
312
#'   #Visualize with rayvertex
313
#'   roof_model |>
314
#'     add_shape(xz_rect_mesh(scale=c(20,1,20)) ) |>
315
#'     rasterize_scene(lookfrom=c(10,10,10),fov=40,
316
#'                     light_info = directional_light(c(-0.5,0.7,0.8)))
317
#'
318
#'   #Visualize with rayrender
319
#'   raymesh_model(roof_model, override_material = FALSE) |>
320
#'     add_object(scene_base) |>
321
#'     render_scene(lookfrom=c(10,30,20),samples=16,
322
#'                  width=800,height=800,fov=0,ortho_dimensions=c(10,10), verbose=TRUE)
323
#' }
324
#'
325
#' # Change the bevel to be circular
326
#' if(run_docs_raybevel()) {
327
#'   bevel = generate_bevel("circular", bevel_start = 0, bevel_end = 0.2, max_height=0.25)
328
#'   roof_model = generate_beveled_polygon(skeleton,
329
#'                                         bevel_offsets = bevel,
330
#'                                         material = material_list(diffuse="purple"))
331
#'
332
#'   raymesh_model(roof_model, override_material = FALSE) |>
333
#'     add_object(scene_base) |>
334
#'     render_scene(lookfrom=c(10,30,20), samples=16,
335
#'                  width=800,height=800,fov=0,ortho_dimensions=c(10,10))
336
#' }
337
#'
338
#' # Change the bevel to type "bump", change the max height, and raise it off the surface
339
#' if(run_docs_raybevel()) {
340
#'   bevel = generate_bevel("bump", bevel_start = 0, bevel_end = 0.4, max_height=0.25)
341
#'   roof_model = generate_beveled_polygon(skeleton, base_height=1,
342
#'                                         bevel_offsets = bevel,
343
#'                                         material = material_list(diffuse="purple"))
344
#'
345
#'   raymesh_model(roof_model, override_material = FALSE) |>
346
#'     add_object(scene_base) |>
347
#'     render_scene(lookfrom=c(10,30,20), samples=16,
348
#'                  width=800,height=800,fov=0,ortho_dimensions=c(10,10))
349
#' }
350
#'
351
#' # Generate a complex bevel and use the exact specified heights
352
#' if(run_docs_raybevel()) {
353
#'   bevel = generate_complex_bevel(c("bump", "exp", "circular","step"),
354
#'                                  bevel_start = c(0,0.3,0.7,0.95),
355
#'                                  bevel_end = c(0.1,0.6,0.95,1),
356
#'                                  reverse = c(F,F,T,F),
357
#'                                  segment_height = c(0.25,0.5,0.5,4),
358
#'                                  plot_bevel = TRUE)
359
#'
360
#'   roof_model = generate_beveled_polygon(skeleton, vertical_offset=0.1,
361
#'                                         bevel_offsets = bevel,
362
#'                                         raw_heights = TRUE,
363
#'                                         material = material_list(diffuse="purple"))
364
#'
365
#'   raymesh_model(roof_model, override_material = FALSE) |>
366
#'     add_object(scene_base) |>
367
#'     render_scene(lookfrom=c(10,30,20), samples=16,
368
#'                  width=800,height=800,fov=0,ortho_dimensions=c(10,10))
369
#' }
370
#'
371
#' # Turn the polygon into a ziggurat, using the step bevel type
372
#' if(run_docs_raybevel()) {
373
#'   offs = seq(0, 1, by = 0.05)
374
#'   bevel = generate_complex_bevel("step",
375
#'                                  bevel_start = offs[-length(offs)],
376
#'                                  bevel_end = offs[-1],
377
#'                                  segment_height = 0.2)
378
#'
379
#'   roof_model = generate_beveled_polygon(skeleton, vertical_offset=0.2,
380
#'                                         bevel_offsets = bevel,
381
#'                                         raw_heights = TRUE,
382
#'                                         material = material_list(diffuse = "purple"))
383
#'
384
#'   raymesh_model(roof_model, override_material = FALSE) |>
385
#'     add_object(scene_base) |>
386
#'     render_scene(lookfrom = c(10,30,20), samples=16,
387
#'                  width = 800, height = 800, fov = 0, ortho_dimensions = c(10,10))
388
#' }
389
#'
390
#' # Turn the polygon into a smooth wavy slide, taking advantage of vector recycling to flip/reverse
391
#' if(run_docs_raybevel()) {
392
#'   offs = seq(0, 1, by = 0.1)
393
#'   bevel = generate_complex_bevel("exp",
394
#'                                  bevel_start = offs[-length(offs)],
395
#'                                  bevel_end = offs[-1],
396
#'                                  reverse = c(TRUE, FALSE),
397
#'                                  flip = c(TRUE, FALSE),
398
#'                                  segment_height = 0.25)
399
#'
400
#'   roof_model = generate_beveled_polygon(skeleton, vertical_offset=0.2,
401
#'                                         bevel_offsets = bevel,
402
#'                                         raw_heights = TRUE,
403
#'                                         material = material_list(diffuse = "purple"))
404
#'
405
#'   raymesh_model(roof_model, override_material = FALSE) |>
406
#'     add_object(scene_base) |>
407
#'     render_scene(lookfrom = c(10,30,20), samples=16,
408
#'                  width = 800, height = 800, fov = 0, ortho_dimensions = c(10,10))
409
#' }
410
#'
411
#' # Skeletonize and turn an {sf} object into a beveled polygon
412
#' if(run_docs_raybevel()) {
413
#'   us_states = spData::us_states
414
#'   texas = us_states[us_states$NAME == "Texas",]
415
#'   texas_skeleton = skeletonize(texas)
416
#'   plot_skeleton(texas_skeleton)
417
#'
418
#'   bevel = generate_bevel("angled" , bevel_end=0.3, max_height = 0.3)
419
#'   roof_model_texas = generate_beveled_polygon(texas_skeleton,
420
#'                                         bevel_offsets = bevel,
421
#'                                         material = material_list(diffuse = "purple")) |>
422
#'     center_mesh() |>
423
#'     translate_mesh(c(0,0.3,0))
424
#'
425
#'   raymesh_model(roof_model_texas, material = diffuse(color="purple")) |>
426
#'     add_object(scene_base) |>
427
#'     add_object(sphere(x=-10,z=-10,y=5,material=light(color="red", intensity=40))) |>
428
#'     add_object(sphere(x=10,z=-10,y=5,material=light(color="orange", intensity=40))) |>
429
#'     render_scene(lookfrom=c(0,10,0),camera_up=c(0,0,1), samples=16,
430
#'                  width=800,height=800,fov=0, ortho_dimensions=c(15,15))
431
#' }
432
#'
433
#' # Generate a smooth bevel
434
#' if(run_docs_raybevel()) {
435
#'   bevel = generate_bevel("exp", bevel_start = 0, bevel_end=0.5, max_height=2)
436
#'   roof_model_texas = generate_beveled_polygon(texas_skeleton,
437
#'                                         bevel_offsets = bevel,
438
#'                                         material = material_list(diffuse = "purple")) |>
439
#'     center_mesh() |>
440
#'     translate_mesh(c(0,0.5,0))
441
#'
442
#'   raymesh_model(roof_model_texas, material = diffuse(color="purple")) |>
443
#'     add_object(scene_base) |>
444
#'     add_object(sphere(x=-10,z=-10,y=5,material=light(color="red", intensity=40))) |>
445
#'     add_object(sphere(x=10,z=-10,y=5,material=light(color="orange", intensity=40))) |>
446
#'     render_scene(lookfrom=c(0,10,0),camera_up=c(0,0,1), samples=16,
447
#'                  width=800,height=800,fov=0, ortho_dimensions=c(15,15))
448
#' }
449
generate_beveled_polygon = function(skeleton,
450
                                    bevel_offsets = generate_bevel(),
451
                                    bevel_heights = NULL,
452
                                    set_max_height = FALSE,
453
                                    max_height = NA,
454
                                    vertical_offset = 0,
455
                                    base = TRUE,
456
                                    base_height = 0,
457
                                    raw_offsets = FALSE,
458
                                    raw_heights = FALSE,
459
                                    swap_yz = TRUE,
460
                                    progress = TRUE,
461
                                    double_sided = FALSE,
462
                                    sides = FALSE,
463
                                    return_skeleton_polygons = FALSE,
464
                                    scale_all_max = FALSE,
465
                                    material = material_list(),
466
                                    bevel_material = NA,
467
                                    verbose = FALSE) {
468320x
  if(run_docs_raybevel() || !interactive()) {
469320x
    progress = FALSE
470
  }
471320x
  if(!is.list(bevel_material)) {
472320x
    bevel_material = material
473
  }
474320x
  init_time()
475320x
  if(inherits(skeleton, "rayskeleton_list")) {
476!
    pb = progress::progress_bar$new(
477!
      format = ":current/:total Generating bevel [:bar] eta: :eta",
478!
      total = length(skeleton), clear = TRUE, width = 60)
479!
    meshlist = list()
480!
    counter  = 1
481!
    vec_default = function(length_skeleton, value) {
482!
      if(length(value) == 1) {
483!
        return(rep(value,length(skeleton)))
484
      } else {
485!
        stopifnot(length(value) == length_skeleton)
486!
        return(value)
487
      }
488
    }
489!
    len_s = length(skeleton)
490!
    vertical_offset = vec_default(len_s, vertical_offset)
491!
    base_height = vec_default(len_s, base_height)
492!
    if(length(max_height) == 1) {
493!
      if(scale_all_max) {
494!
        max_height = rep(max_height,length(skeleton))
495
      } else {
496
        #Calculate proportional maximum heights
497!
        single_max_heights = unlist(lapply(skeleton, \(x) max(x$nodes$time)))
498!
        max_height = single_max_heights/max(single_max_heights) * max_height
499
      }
500
    }
501!
    for(j in seq_len(length(skeleton))) {
502!
      if(progress) {
503!
        pb$tick()
504
      }
505!
      meshlist[[counter]] = generate_beveled_polygon(skeleton[[j]],
506!
                                                     bevel_offsets = bevel_offsets,
507!
                                                     bevel_heights = bevel_heights,
508!
                                                     bevel_material = bevel_material,
509!
                                                     base = base,
510!
                                                     vertical_offset = vertical_offset[j],
511!
                                                     max_height = max_height[j],
512!
                                                     raw_offsets = raw_offsets,
513!
                                                     raw_heights = raw_heights,
514!
                                                     sides = sides,
515!
                                                     double_sided = double_sided,
516!
                                                     base_height = base_height[j],
517!
                                                     set_max_height = set_max_height,
518!
                                                     return_skeleton_polygons = return_skeleton_polygons,
519!
                                                     swap_yz = swap_yz,
520!
                                                     progress = progress,
521!
                                                     material = material)
522!
      counter = counter + 1
523
    }
524!
    if(return_skeleton_polygons) {
525!
      class(meshlist) = c("rayskeleton_list_polygons", "list")
526!
      return(meshlist)
527
    }
528!
    return(scene_from_list(meshlist))
529
  }
530320x
  if(!inherits(skeleton, "rayskeleton")) {
531!
    stop("`skeleton` must be of class `rayskeleton`")
532
  }
533320x
  max_time = max(skeleton$links$destination_time)
534320x
  if(is.list(bevel_offsets) &&
535320x
     !is.null(bevel_offsets$x) &&
536320x
     !is.null(bevel_offsets$y)) {
537!
    bevel_heights = bevel_offsets$y
538!
    bevel_offsets = bevel_offsets$x
539
  }
540
541320x
  if(!raw_offsets) {
542!
    if(any(bevel_offsets > 1 | bevel_offsets < 0)) {
543!
      stop("If using percentage offsets, all `bevel_offsets` must be between 0 and 1.")
544
    }
545!
    bevel_offsets = bevel_offsets * max_time
546
  }
547320x
  non_zero_offsets = bevel_offsets[bevel_offsets > 0]
548320x
  if(all(non_zero_offsets >= max_time)) {
549!
    message(sprintf("All `bevel_offset` greater than max offset in polygon of %f, calculating full polygon model",
550!
                    max(skeleton$nodes[,4])))
551!
    interpolated_data = stats::approx(x = c(bevel_offsets),
552!
                                      y = c(bevel_heights),
553!
                                      xout =  max_time)
554!
    max_height = max(interpolated_data$y)
555!
    return(generate_roof(skeleton,
556!
                         max_height = max_height,
557!
                         base_height = base_height,
558!
                         vertical_offset = vertical_offset,
559!
                         swap_yz = swap_yz,
560!
                         base = base,
561!
                         sides = sides,
562!
                         double_sided = double_sided,
563!
                         progress = progress,
564!
                         roof_material = bevel_material,
565!
                         material = material))
566
  }
567320x
  if(!raw_heights) {
568!
    bevel_heights = bevel_heights * max_time
569
  }
570
571320x
  bevel_heights = bevel_heights[order(bevel_offsets)]
572320x
  bevel_offsets = bevel_offsets[order(bevel_offsets)]
573
574320x
  height_range = range(bevel_heights)
575320x
  height_range = height_range[2]-height_range[1]
576320x
  if(set_max_height && !is.na(max_height)) {
577160x
    stopifnot(max_height > 0)
578160x
    min_height = min(bevel_heights)
579160x
    offset_bevel_heights = bevel_heights - min_height
580160x
    offset_bevel_heights = max_height * offset_bevel_heights / height_range + min_height
581160x
    height_range = max_height
582160x
    bevel_heights = offset_bevel_heights
583
  }
584320x
  stopifnot(length(vertical_offset) == 1)
585320x
  stopifnot(vertical_offset >= 0)
58664x
  bevel_heights = bevel_heights + vertical_offset
587
58864x
  valid_bevels = bevel_offsets <= max_time & bevel_offsets > 0
58964x
  zero_height_val = bevel_heights[1]
59064x
  bevel_offsets_polys = bevel_offsets[valid_bevels]
59164x
  bevel_heights_polys = bevel_heights[valid_bevels]
592
59364x
  stopifnot(length(bevel_offsets_polys) == length(bevel_heights_polys))
594
595
  #Remove extremely close offsets (usually arising from floating point error)
59664x
  for(i in rev(seq_len(length(bevel_offsets_polys)))) {
597320x
    all_other_offsets = bevel_offsets_polys[-i]
598320x
    if(any(abs(bevel_offsets_polys[i] - all_other_offsets) < 1e-14, na.rm = TRUE)) {
599!
      bevel_offsets_polys[i] = NA
600
    }
601
  }
60264x
  remove_close_vals = !is.na(bevel_offsets_polys)
60364x
  bevel_offsets_polys = bevel_offsets_polys[remove_close_vals]
60464x
  bevel_heights_polys = bevel_heights_polys[remove_close_vals]
605
606
  #Generate new nodes
60764x
  beveled_ss = generate_offset_links_nodes(skeleton, bevel_offsets_polys, verbose = verbose, progress = progress)
60864x
  print_time(verbose, "Generated offset links")
609
61064x
  reordered_new_ss = recalculate_ordered_ids(beveled_ss)
61164x
  print_time(verbose, "Recalculated ordered IDs")
612
61364x
  polygon_ind = convert_ss_to_polygons(reordered_new_ss, progress = progress)
61464x
  print_time(verbose, "Converted to polygons")
615
61664x
  nodes = reordered_new_ss$nodes
61764x
  index_list = list()
61864x
  for(i in seq_len(length(polygon_ind))) {
6193584x
    tmp_ind = polygon_ind[[i]]
6203584x
    tmp_poly = nodes[tmp_ind,2:3]
6213584x
    index_list[[i]] = matrix(tmp_ind[decido::earcut(tmp_poly)],byrow=TRUE,ncol=3)
622
  }
62364x
  print_time(verbose, "Triangulated polygons")
624
62564x
  if(length(index_list) == 1) {
626!
    indices_all = matrix(unlist(index_list),ncol=3, byrow = TRUE)
627
  } else {
62864x
    indices_all = do.call("rbind",index_list)
629
  }
63064x
  xyz = nodes[,2:4]
63164x
  new_xyz = xyz
63264x
  bevel_offsets_polys = c(0,bevel_offsets_polys)
63364x
  bevel_heights_polys = c(zero_height_val,bevel_heights_polys)
634
63564x
  if(bevel_offsets_polys[length(bevel_offsets_polys)] != max_time) {
63664x
    bevel_offsets_with_max = c(bevel_offsets_polys, max_time)
63764x
    bevel_heights_with_max = c(bevel_heights_polys, max(bevel_heights_polys))
638
  } else {
639!
    bevel_offsets_with_max = bevel_offsets_polys
640!
    bevel_heights_with_max = bevel_heights_polys
641
  }
64264x
  side_top = bevel_heights_with_max[1]
643
64464x
  if(return_skeleton_polygons) {
645!
    attr(reordered_new_ss, "polygons") = polygon_ind
646
    #These offsets should always be normalized
647!
    attr(reordered_new_ss, "bevel_offsets") = bevel_offsets_with_max / max_time
648!
    attr(reordered_new_ss, "raw_offsets") = raw_offsets
649!
    class(reordered_new_ss) = c("rayskeleton_polygon")
650!
    return(reordered_new_ss)
651
  }
652
  #Need to account for non-zero offsets--not all start at 0
65364x
  new_xyz[,3] = stats::approx(x=bevel_offsets_with_max,y=bevel_heights_with_max, xout = xyz[,3], rule=2)$y
654
65564x
  xyz = new_xyz
65664x
  colnames(xyz) = c("x","y","z")
65764x
  original_verts = attr(skeleton,"original_vertices")
65864x
  original_holes = attr(skeleton,"original_holes")
65964x
  mesh = construct_mesh(vertices = as.matrix(xyz),
66064x
                        indices = as.matrix(indices_all)-1) |>
66164x
    set_material(bevel_material)
662
66364x
  if(double_sided) {
66432x
    xyzflip = xyz
66532x
    xyzflip[,3] = -xyzflip[,3]
66632x
    indices_flip = indices_all[,3:1,drop=FALSE]
66732x
    double_mesh = construct_mesh(vertices = as.matrix(xyzflip),
66832x
                                 indices = as.matrix(indices_flip)-1) |>
66932x
      set_material(bevel_material)
670
  }
67164x
  if(base && !double_sided) {
67216x
    if(length(original_holes) > 0) {
67316x
      holes = c(0,utils::head(cumsum(unlist(lapply(original_holes,nrow))),-1)) + nrow(original_verts) + 1
67416x
      hole_mat = do.call("rbind", original_holes)
67516x
      original_verts_holes = rbind(original_verts, hole_mat)
676
    } else {
677!
      holes = 0
678!
      original_verts_holes = original_verts
679
    }
68016x
    base_indices = matrix(decido::earcut(original_verts_holes, holes = holes), byrow = TRUE, ncol=3)
68116x
    base_indices = base_indices[,3:1,drop = FALSE]
68216x
    original_verts_base = cbind(original_verts_holes, rep(0, nrow(original_verts_holes)))
68316x
    base_mesh = construct_mesh(vertices = as.matrix(original_verts_base),
68416x
                               indices = as.matrix(base_indices)-1) |>
68516x
      set_material(material)
686
68716x
    mesh = mesh |>
68816x
      add_shape(base_mesh)
689
  }
69064x
  if(double_sided) {
69132x
    mesh = add_shape(mesh, double_mesh)
692
  }
69364x
  if((sides || base || double_sided) &&
69464x
     ((!double_sided && side_top > 0) || (double_sided && side_top > 0))) {
69556x
    if(!double_sided) {
69624x
      side_mesh = extrude_sides(original_verts, original_holes, bottom = 0, top = side_top)
697
    } else {
69832x
      side_mesh = extrude_sides(original_verts, original_holes, bottom = -side_top, top = side_top)
699
    }
70056x
    side_mesh = side_mesh |>
70156x
      set_material(material)
70256x
    mesh = add_shape(mesh, side_mesh)
703
  }
70464x
  if(swap_yz) {
70564x
    mesh = swap_yz(mesh)
706
  }
70764x
  if(!is.na(base_height)) {
70848x
    if(swap_yz) {
70948x
      mesh = translate_mesh(mesh, c(0,base_height,0))
710
    } else {
711!
      mesh = translate_mesh(mesh, c(0,0,base_height))
712
    }
713
  }
71464x
  print_time(verbose, "Generated mesh")
715
71664x
  return(mesh)
717
}
718
719
#' Change an existing polygon bevel's bevel profile.
720
#'
721
#' This function generates a beveled 3D polygon model from the modified straight skeleton with
722
#' pre-existing polygons generated from the `generate_beveled_polygon` function when
723
#' `return_skeleton_polygons = TRUE`.
724
#'
725
#' @param skeleton_polygons Default `NULL`. A straight skeleton generated from the `generate_beveled_polygon` function when
726
#' `return_skeleton_polygons = TRUE`.
727
#' @param bevel_offsets Default `NULL`. The offset(s) of the bevel.
728
#' @param bevel_heights Default is set to `bevel_offsets`. Numeric vector specifying the heights of the bevels. Must be of the same length as `bevel_offsets`.
729
#' @param max_height Default `1`. The maximum height of the polygon.
730
#' @param set_max_height Default `FALSE`. A logical flag that controls whether to set the max height of the polygon based on the `max_height` argument.
731
#' @param swap_yz Default `TRUE`. A logical flag that controls whether to swap the y and z coordinates in the resulting mesh.
732
#' If `TRUE`, the y and z coordinates will be swapped.
733
#' @param sides Default `FALSE`. A logical flag on whether to draw the sides. This will automatically be set to `TRUE`
734
#' if `base = TRUE` and the `base_height` is less than `vertical_offset`.
735
#' @param vertical_offset Default `0`. The vertical offset of the polygon.
736
#' @param base Default `TRUE`. A logical flag that controls whether to generate the bottom of the polygon.
737
#' @param base_height Default `NA`. Height of the base, defaulting to the `min(bevel_heights) + vertical_offset` .
738
#' @param progress Default `TRUE`. Whether to display a progress bar.
739
#' @param verbose Default `FALSE`. A logical flag to control whether additional timing information should be displayed.
740
#' @param scale_all_max Default `FALSE`. If passing in a list of multiple skeletons with polygons, whether to scale each polygon to the overall
741
#' max height, or whether to scale each max height to the maximum internal distance in the polygon.
742
#' @param raw_offsets Default `FALSE`. A logical flag indicating whether the `bevel_offsets` are already in raw format and do not need to be multiplied by the maximum time of the skeleton.
743
#' @param raw_heights Default `FALSE`. A logical flag indicating whether the `bevel_heights` are already in raw format and do not need to be multiplied by the maximum time of the skeleton.
744
#' @param double_sided Default `FALSE`. A logical flag that controls whether the polygon should be double-sided.
745
#' @param material Default `material_list()`. Interface to set the color/appearance/material options for the resulting `ray_mesh` mesh.
746
#' @param bevel_material Default `NA`, uses the material specified in `material`. Interface to set the color/appearance/material options for the resulting `ray_mesh` bevel mesh.
747
#'
748
#' @return A 3D mesh of the beveled polygon model.
749
#'
750
#' @import rayvertex
751
#'
752
#' @export
753
#' @examples
754
#' # Skeletonize a complex {sf} object and set return_skeleton_polygons = TRUE in
755
#' # generate_beveled_polygon(). This returns skeleton object with polygons included, which
756
#' # allows for quickly generating 3D models with different bevels.
757
#' if(run_docs_raybevel()) {
758
#'   library(rayrender)
759
#'   library(rayvertex)
760
#'   us_states = spData::us_states
761
#'   cali = us_states[us_states$NAME == "California",]
762
#'   cali_skeleton = skeletonize(cali)
763
#'   plot_skeleton(cali_skeleton)
764
#'   # We add manual offsets to ensure that the polygon can be morphed all along its interior
765
#'   bevel = generate_bevel(manual_offsets = seq(0,1,by=0.01), max_height=0.5)
766
#'   bevel_model_cali = generate_beveled_polygon(cali_skeleton,
767
#'                                               bevel_offsets = bevel,
768
#'                                               return_skeleton_polygons = TRUE)
769
#'
770
#'   bevel_new = change_polygon_bevel(bevel_model_cali,
771
#'                                    bevel_offsets = generate_bevel(max_height=0.5,
772
#'                                    bevel_end=0.5)) |>
773
#'     center_mesh()
774
#'
775
#'   scene_base = xz_rect(xwidth=100,zwidth=100,
776
#'                        material=diffuse(color="grey20", checkercolor="white")) |>
777
#'     add_object(sphere(y=8,z=10,x=-3,material=light(intensity=100))) |>
778
#'     add_object(sphere(y=800,z=10,x=-3,radius=100,material=light(intensity=5)))
779
#'
780
#'   raymesh_model(bevel_new, y=0.5, override_material = TRUE,
781
#'                 material = diffuse(color="purple")) |>
782
#'     add_object(scene_base) |>
783
#'     render_scene(lookfrom=c(0,30,-10), samples=16,
784
#'                  width=800,height=800,fov=0,ortho_dimensions=c(12,12))
785
#' }
786
#' # Change to a smooth bevel
787
#' if(run_docs_raybevel()) {
788
#'   new_bevel = generate_bevel("circular", bevel_start = 0, bevel_end=1)
789
#'   bevel_new = change_polygon_bevel(bevel_model_cali,
790
#'                                    bevel_offsets = new_bevel, solid ) |>
791
#'     center_mesh()
792
#'   raymesh_model(bevel_new, override_material = TRUE, y=1,material = diffuse(color="purple")) |>
793
#'     add_object(scene_base) |>
794
#'     render_scene(lookfrom=c(0,30,-10), samples=16,
795
#'                  width=800,height=800,fov=0,ortho_dimensions=c(12,12))
796
#' }
797
#'
798
#' # Make a complex bevel
799
#' if(run_docs_raybevel()) {
800
#'   complex_coords = generate_complex_bevel(
801
#'     bevel_type  = c("angled","flat", "angled", "flat"),
802
#'     bevel_start = head(seq(0,1,by=0.05),-1),
803
#'     bevel_end   = tail(seq(0,1,by=0.05),-1),
804
#'     overall_height = 1,
805
#'     angle = c(45,45,15,15),
806
#'     reverse = c(FALSE, FALSE,TRUE,TRUE),
807
#'     plot_bevel = TRUE
808
#'   )
809
#'   bevel_new = change_polygon_bevel(bevel_model_cali,
810
#'                                    bevel_offsets = complex_coords) |>
811
#'     center_mesh()
812
#'   raymesh_model(bevel_new, override_material = TRUE, y=1,material = diffuse(color="purple")) |>
813
#'     add_object(scene_base) |>
814
#'     render_scene(lookfrom=c(0,30,-20), samples=16,
815
#'                  width=800,height=800,fov=0,ortho_dimensions=c(12,12))
816
#' }
817
#'
818
#' # Quickly generate new bevels to inflate California like a balloon using the arctan function.
819
#' if(run_docs_raybevel()) {
820
#'   inflate_california = function(magnitudes) {
821
#'   for(val in magnitudes) {
822
#'     bevel_new = change_polygon_bevel(bevel_model_cali,
823
#'                                      bevel_heights = 1/2*atan(seq(0,val,length.out=100)),
824
#'                                      bevel_offsets = seq(0,1, length.out=100),
825
#'                                      base = TRUE) |>
826
#'       translate_mesh(c(-120.49,0,-38.72))
827
#'     raymesh_model(bevel_new, y = 0, override_material = TRUE,
828
#'                   material = glossy(color="darkred")) |>
829
#'       add_object(scene_base) |>
830
#'       add_object(sphere(x=-30,z=30,y=18,radius=30,material=light(color="white", intensity=5))) |>
831
#'       render_scene(lookfrom=c(-1, 28, -20.32), lookat=c(-1, 1.46, -2),
832
#'                    samples=16, width=800, height=800, fov=20)
833
#'     }
834
#'   }
835
#'   inflate_california(c(1,4,16,64))
836
#' }
837
change_polygon_bevel = function(skeleton_polygons,
838
                                bevel_offsets = NULL,
839
                                bevel_heights = NULL,
840
                                set_max_height = FALSE,
841
                                max_height = 1,
842
                                vertical_offset = 0,
843
                                base = TRUE,
844
                                base_height = NA,
845
                                raw_offsets = FALSE,
846
                                raw_heights = FALSE,
847
                                swap_yz = TRUE,
848
                                progress = TRUE,
849
                                sides = FALSE,
850
                                double_sided = FALSE,
851
                                scale_all_max = FALSE,
852
                                material = material_list(),
853
                                bevel_material = NA,
854
                                verbose = FALSE) {
855!
  if(run_docs_raybevel() || !interactive()) {
856!
    progress = FALSE
857
  }
858!
  if(!is.list(bevel_material)) {
859!
    bevel_material = material
860
  }
861!
  init_time()
862!
  if(inherits(skeleton_polygons, "rayskeleton_list_polygons")) {
863!
    pb = progress::progress_bar$new(
864!
      format = ":current/:total Generating polygon [:bar] eta: :eta",
865!
      total = length(skeleton_polygons), clear = TRUE, width = 60)
866!
    meshlist = list()
867!
    counter  = 1
868!
    if(length(vertical_offset) == 1) {
869!
      vertical_offset = rep(vertical_offset,length(skeleton_polygons))
870
    }
871!
    if(length(max_height) == 1) {
872!
      if(scale_all_max) {
873!
        max_height = rep(max_height,length(skeleton_polygons))
874
      } else {
875
        #Calculate proportional maximum heights
876!
        single_max_heights = unlist(lapply(skeleton_polygons, \(x) max(x$nodes$time)))
877!
        max_height = single_max_heights/max(single_max_heights) * max_height
878
      }
879
    }
880!
    for(j in seq_len(length(skeleton_polygons))) {
881!
      if(progress) {
882!
        pb$tick()
883
      }
884!
      meshlist[[counter]] = change_polygon_bevel(skeleton_polygons[[j]],
885!
                                                 bevel_offsets = bevel_offsets,
886!
                                                 bevel_heights = bevel_heights,
887!
                                                 base = base,
888!
                                                 vertical_offset = vertical_offset[j],
889!
                                                 max_height = max_height[j],
890!
                                                 raw_offsets = raw_offsets,
891!
                                                 raw_heights = raw_heights,
892!
                                                 sides = sides,
893!
                                                 progress = FALSE,
894!
                                                 double_sided = double_sided,
895!
                                                 base_height = base_height,
896!
                                                 bevel_material = bevel_material,
897!
                                                 material = material,
898!
                                                 swap_yz = swap_yz)
899!
      counter = counter + 1
900
    }
901!
    return(scene_from_list(meshlist))
902
  }
903!
  if(inherits(skeleton_polygons, "ray_mesh")) {
904!
    return(skeleton_polygons)
905
  }
906!
  if(!inherits(skeleton_polygons, "rayskeleton_polygon")) {
907!
    stop("`skeleton_polygon` must be of class `rayskeleton_polygon`")
908
  }
909!
  max_time = max(skeleton_polygons$links$destination_time)
910!
  if(is.list(bevel_offsets) &&
911!
     !is.null(bevel_offsets$x) &&
912!
     !is.null(bevel_offsets$y)) {
913!
    bevel_heights = bevel_offsets$y
914!
    bevel_offsets = bevel_offsets$x
915
    # if(set_max_height) {
916
    #   warning("`set_max_height` is ignored when passing in bevel curve--set the max height when generating the bevel.")
917
    #   set_max_height = FALSE
918
    # }
919
  }
920!
  if(!raw_offsets) {
921!
    if(any(bevel_offsets > 1 | bevel_offsets < 0)) {
922!
      stop("If using percentage offsets, all `bevel_offsets` must be between 0 and 1.")
923
    }
924!
    bevel_offsets_pct = bevel_offsets
925!
    bevel_offsets = bevel_offsets * max_time
926
  } else {
927!
    bevel_offsets_pct = bevel_offsets / max_time
928
  }
929
  #Offsets should be in units of the coordinate system at this point
930!
  non_zero_offsets = bevel_offsets[bevel_offsets > 0]
931!
  if(all(non_zero_offsets >= max_time)) {
932!
    interpolated_data = stats::approx(x = bevel_offsets, y = bevel_heights,
933!
                                      xout =  c(0,max_time))
934!
    bevel_offsets = c(0,max_time)
935!
    bevel_offsets_pct = c(0,1)
936!
    bevel_heights = interpolated_data$y
937
  }
938!
  if(!raw_heights) {
939!
    bevel_heights = bevel_heights * max_time
940
  }
941!
  if(is.na(base_height)) {
942!
    height_range = range(bevel_heights)
943!
    if(base || double_sided) {
944!
      min_offset = (height_range[2]-height_range[1]) * 1e-6
945
    } else {
946!
      min_offset = 0
947
    }
948!
    base_height = min(bevel_heights) + min_offset + vertical_offset
949
  }
950
951!
  stopifnot(length(vertical_offset) == 1)
952
953!
  reordered_new_ss = skeleton_polygons
954!
  old_bevel_offsets = unique(attr(reordered_new_ss, "bevel_offsets"))
955!
  polygon_ind = attr(reordered_new_ss, "polygons")
956!
  last_height = bevel_heights[length(bevel_heights)]
957!
  if(bevel_offsets_pct[length(bevel_offsets_pct)] != 1 ) {
958!
    bevel_offsets_pct = c(bevel_offsets_pct,1)
959!
    bevel_heights_with_last = c(bevel_heights,last_height)
960
  } else {
961!
    bevel_heights_with_last = bevel_heights
962
  }
963!
  interpolated_data = stats::approx(x = bevel_offsets_pct, y = bevel_heights_with_last, xout = old_bevel_offsets,
964!
                                    rule = 2)
965!
  bevel_heights = interpolated_data$y
966!
  bevel_offsets = old_bevel_offsets * max_time
967!
  bevel_offsets = bevel_offsets[order(bevel_offsets)]
968!
  bevel_heights = bevel_heights[order(bevel_offsets)]
969
970!
  height_range = range(bevel_heights)
971!
  height_range = height_range[2]-height_range[1]
972!
  if(set_max_height) {
973!
    min_height = min(bevel_heights)
974!
    offset_bevel_heights = bevel_heights - min_height
975!
    offset_bevel_heights = max_height * offset_bevel_heights / height_range + min_height
976!
    height_range = max_height
977!
    bevel_heights = offset_bevel_heights
978
  }
979!
  stopifnot(length(vertical_offset) == 1)
980!
  stopifnot(vertical_offset >= 0)
981!
  bevel_heights = bevel_heights + vertical_offset
982
983!
  valid_bevels = bevel_offsets <= max_time & bevel_offsets > 0
984!
  zero_height_val = bevel_heights[1]
985!
  bevel_offsets_valid = bevel_offsets[valid_bevels]
986!
  bevel_heights_valid = bevel_heights[valid_bevels]
987!
  stopifnot(length(bevel_offsets_valid) == length(bevel_heights_valid))
988
  #Remove extremely close offsets (usually arising from floating point error)
989!
  for(i in rev(seq_len(length(bevel_offsets_valid)))) {
990!
    all_other_offsets = bevel_offsets_valid[-i]
991!
    if(any(abs(bevel_offsets_valid[i] - all_other_offsets) < 1e-14, na.rm = TRUE)) {
992!
      bevel_offsets_valid[i] = NA
993
    }
994
  }
995!
  remove_close_vals = !is.na(bevel_offsets_valid)
996!
  bevel_offsets_valid = bevel_offsets_valid[remove_close_vals]
997!
  bevel_heights_valid = bevel_heights_valid[remove_close_vals]
998
999!
  nodes = reordered_new_ss$nodes
1000!
  index_list = list()
1001!
  for(i in seq_len(length(polygon_ind))) {
1002!
    tmp_ind = polygon_ind[[i]]
1003!
    tmp_poly = nodes[tmp_ind,2:3]
1004!
    index_list[[i]] = matrix(tmp_ind[decido::earcut(tmp_poly)], byrow = TRUE, ncol = 3)
1005
  }
1006!
  indices_all = do.call("rbind",index_list)
1007!
  xyz = nodes[,2:4]
1008
1009!
  new_xyz = xyz
1010
1011!
  bevel_offsets_polys = c(0,bevel_offsets_valid)
1012!
  bevel_heights_polys = c(zero_height_val,bevel_heights_valid)
1013
1014!
  if(bevel_offsets_polys[length(bevel_offsets_polys)] != max_time) {
1015!
    bevel_offsets_with_max = c(bevel_offsets_polys, max_time)
1016!
    bevel_heights_with_max = c(bevel_heights_polys, max(bevel_heights_polys))
1017
  } else {
1018!
    bevel_offsets_with_max = bevel_offsets_polys
1019!
    bevel_heights_with_max = bevel_heights_polys
1020
  }
1021!
  side_top = bevel_heights_with_max[1]
1022
1023!
  new_xyz[,3] = stats::approx(x=bevel_offsets_with_max,y=bevel_heights_with_max, xout = xyz[,3], rule=2)$y
1024
1025!
  xyz = new_xyz
1026!
  colnames(xyz) = c("x","y","z")
1027
1028!
  original_verts = attr(reordered_new_ss,"original_vertices")
1029!
  original_holes = attr(reordered_new_ss,"original_holes")
1030
1031!
  mesh = construct_mesh(vertices = as.matrix(xyz),
1032!
                                   indices = as.matrix(indices_all)-1)|>
1033!
    set_material(bevel_material)
1034
1035!
  if(double_sided) {
1036!
    xyzflip = xyz
1037!
    xyzflip[,3] = -xyzflip[,3]
1038!
    indices_flip = indices_all[,3:1,drop=FALSE]
1039!
    double_mesh = construct_mesh(vertices = as.matrix(xyzflip),
1040!
                                 indices = as.matrix(indices_flip)-1)|>
1041!
      set_material(bevel_material)
1042
  }
1043!
  if(base && !double_sided) {
1044!
    if(length(original_holes) > 0) {
1045!
      holes = c(0,utils::head(cumsum(unlist(lapply(original_holes,nrow))),-1)) + nrow(original_verts) + 1
1046!
      hole_mat = do.call("rbind", original_holes)
1047!
      original_verts_holes = rbind(original_verts, hole_mat)
1048
    } else {
1049!
      holes = 0
1050!
      original_verts_holes = original_verts
1051
    }
1052!
    base_indices = matrix(decido::earcut(original_verts_holes, holes = holes), byrow = TRUE, ncol=3)
1053!
    base_indices = base_indices[,3:1,drop = FALSE]
1054!
    original_verts_base = cbind(original_verts_holes, rep(0, nrow(original_verts_holes)))
1055!
    base_mesh = construct_mesh(vertices = as.matrix(original_verts_base),
1056!
                               indices = as.matrix(base_indices)-1) |>
1057!
      set_material(material)
1058
1059!
    mesh = mesh |>
1060!
      add_shape(base_mesh)
1061
  }
1062!
  if(double_sided) {
1063!
    mesh = add_shape(mesh, double_mesh)
1064
  }
1065!
  if((sides || base || double_sided) &&
1066!
     ((!double_sided && side_top > 0) || (double_sided && side_top > 0))) {
1067!
    if(!double_sided) {
1068!
      side_mesh = extrude_sides(original_verts, original_holes, bottom = 0, top = side_top)
1069
    } else {
1070!
      side_mesh = extrude_sides(original_verts, original_holes, bottom = -side_top, top = side_top)
1071
    }
1072!
    side_mesh = side_mesh |>
1073!
      set_material(material)
1074!
    mesh = add_shape(mesh, side_mesh)
1075
  }
1076!
  if(swap_yz) {
1077!
    mesh = swap_yz(mesh)
1078
  }
1079!
  if(!is.na(base_height)) {
1080!
    if(swap_yz) {
1081!
      mesh = translate_mesh(mesh, c(0,base_height,0))
1082
    } else {
1083!
      mesh = translate_mesh(mesh, c(0,0,base_height))
1084
    }
1085
  }
1086!
  print_time(verbose, "Generated mesh")
1087
1088!
  return(mesh)
1089
}
1
#' @title Run Documentation
2
#'
3
#' @description This function determines if the examples are being run in pkgdown. It is not meant to be called by the user.
4
#'
5
#' @export
6
#'
7
#' @return Boolean value.
8
#' @examples
9
#' # See if the documentation should be run.
10
#' run_docs_raybevel()
11
run_docs_raybevel = function() {
12321x
  return(identical(Sys.getenv("IN_PKGDOWN"), "true") && 
13321x
         length(find.package("ggplot2",quiet = TRUE)) > 0 &&
14321x
         length(find.package("spData",quiet = TRUE)) > 0)
15
}
1
#' Modify bevel data using straight skeleton
2
#'
3
#'
4
#' @keywords internal
5
#' @return list. Modified bevel_height and bevel_offset vectors.
6
modify_bevel_with_skeleton = function(bevel_offsets, bevel_heights, straight_skeleton) {
7!
  if(is.list(bevel_offsets) &&
8!
     !is.null(bevel_offsets$x) &&
9!
     !is.null(bevel_offsets$y)) {
10!
    bevel_heights = bevel_offsets$y
11!
    bevel_offsets = bevel_offsets$x
12
  }
13
  # Extract skeleton's nodes that are not already in the bevel
14!
  unique_times = unique(straight_skeleton$nodes$time)
15!
  unique_times = setdiff(unique_times, bevel_offsets)
16!
  unique_times = unique_times[unique_times < max(bevel_offsets)]
17
18
  # Initialize new bevel data vectors
19!
  new_bevel_height = bevel_heights
20!
  new_bevel_offset = bevel_offsets
21
22!
  for(time in unique_times) {
23
    # Identify the indices where new values should be inserted
24!
    insert_idx = sum(new_bevel_offset < time) + 1
25
26
    # Compute interpolated bevel height
27!
    if (insert_idx > 1 && insert_idx <= length(new_bevel_height)) {
28!
      prev_height = new_bevel_height[insert_idx - 1]
29!
      next_height = new_bevel_height[insert_idx]
30!
      prev_offset = new_bevel_offset[insert_idx - 1]
31!
      next_offset = new_bevel_offset[insert_idx]
32!
      offset_range = next_offset - prev_offset
33!
      height_range = next_height - prev_height
34!
      if(height_range == 0) {
35!
        next
36
      }
37!
      t = (time - prev_offset)/offset_range
38!
      interpolated_height = (1 - t) * prev_height + t * next_height
39
    } else {
40
      # If the new time is outside the existing range, no interpolation is needed
41!
      interpolated_height = time
42
    }
43
44
    # Insert new data points into the bevel vectors
45!
    new_bevel_height = c(new_bevel_height[1:(insert_idx - 1)], interpolated_height, new_bevel_height[insert_idx:length(new_bevel_height)])
46!
    new_bevel_offset = c(new_bevel_offset[1:(insert_idx - 1)], time, new_bevel_offset[insert_idx:length(new_bevel_offset)])
47
  }
48
49!
  return(list(x = new_bevel_offset, y = new_bevel_height))
50
}
1
#' Plot the Straight Skeleton of a Polygon
2
#'
3
#' This function visualizes the straight skeleton derived from a given polygon.
4
#' The original polygon (with holes if present) is plotted in black, while the
5
#' straight skeleton is plotted in red.
6
#'
7
#' @param skeleton A list object of class 'rayskeleton' containing the straight
8
#'        skeleton details. It should have 'nodes' and 'links' as its primary components.
9
#' @param use_arrow Default `TRUE`. A logical value indicating whether or not to use arrows
10
#'        to represent the links of the straight skeleton. Default is TRUE.
11
#' @param use_points Default `TRUE`. Whether to plot the vertex points as well.
12
#' @param xlim Default`c(0,1)`. A numeric vector of length 2 specifying the x-limits of the
13
#'        plot in the form `c(min, max)`. These are proportional limits relative
14
#'        to the bounding box around the skeleton.
15
#' @param ylim  Default `c(0,1)`. A numeric vector of length 2 specifying the y-limits of the
16
#'        plot in the form c(min, max). These are proportional limits relative
17
#'        to the bounding box around the skeleton.
18
#' @param arrow_color Default `"red"`. Color of the arrows.
19
#' @param polygon_color Default `"black"`. Color of the polygon.
20
#' @param size Default `1`. Size of the vertex points.
21
#' @param arrow_size Default `1`. Scales the arrow size.
22
#' @param highlight_links Default `NULL`. A numeric vector indicating which links
23
#'        (by their index) to highlight. If specified, the corresponding links will
24
#'        be colored with the `highlight_color`.
25
#' @param highlight_color Default `"purple"`. Color of the highlighted links.
26
#' @param return_layers Default `FALSE`, plots the figure. If `TRUE`, this will instead
27
#' return a list of the ggplot layers.
28
#'
29
#' @details The function uses the `ggplot2` package for plotting. The straight skeleton
30
#'          is visualized based on the details provided in the `skeleton` object.
31
#'          The original polygon and holes are plotted based on attributes stored
32
#'          in the `skeleton` object.
33
#'
34
#' @return A ggplot object visualizing the straight skeleton and the original polygon.
35
#' @export
36
#' @examples
37
#' # Assuming skeleton1 is already defined as in the previous example
38
#' # Outer polygon
39
#' vertices = matrix(c(0,0, 7,0, 7,7, 0,7, 0,0), ncol = 2, byrow = TRUE)
40
#' # Holes inside the polygon
41
#' hole1 = matrix(c(1,1, 1,2, 2,2, 2,1, 1,1), ncol = 2, byrow = TRUE)
42
#' hole2 = matrix(c(5,5, 5,6, 6,6, 6,5, 5,5), ncol = 2, byrow = TRUE)
43
#' skeleton = skeletonize(vertices, holes = list(hole1, hole2))
44
#' if(run_docs_raybevel()) {
45
#'   plot_skeleton(skeleton)
46
#' }
47
#' # Skeletonize and plot an {sf} object
48
#' if(run_docs_raybevel()) {
49
#'   us_states = spData::us_states
50
#'   texas = us_states[us_states$NAME == "Texas",]
51
#'   plot_skeleton(skeletonize(texas))
52
#' }
53
#' # Highlighting certain links in the skeleton
54
#' max_links =which(skeleton$links$destination_time == max(skeleton$links$destination_time))
55
#' if(run_docs_raybevel()) {
56
#'   plot_skeleton(skeleton, highlight_links = max_links, highlight_color = "green")
57
#' }
58
plot_skeleton = function(skeleton, use_arrow = TRUE, use_points = TRUE, xlim = c(0,1), ylim = c(0,1),
59
                         arrow_color = "red", polygon_color = "black", size = 1,
60
                         arrow_size = 0.05, highlight_links = NULL, highlight_color = "green",
61
                         return_layers = FALSE) {
62!
  if(!(length(find.package("ggplot2", quiet = TRUE)) > 0)) {
63!
    stop("{ggplot2} package required for plot_skeleton()")
64
  }
65!
  is_highlighted = mid_x = mid_y = x = y = xend = yend = NULL
66
67
  # Check if skeleton is valid
68!
  if (!inherits(skeleton, c("rayskeleton","rayskeleton_polygon", "rayskeleton_list"))) {
69!
    stop(sprintf("Invalid input: The input is not of class: '%s'",
70!
                 paste0(c("rayskeleton","rayskeleton_polygon", "rayskeleton_list"), collapse=", ")))
71
  }
72
73
  #Import external functions from suggested packages
74!
  aes = ggplot2::aes
75!
  ggplot = ggplot2::ggplot
76!
  theme_void = ggplot2::theme_void
77!
  geom_point = ggplot2::geom_point
78!
  geom_segment = ggplot2::geom_segment
79!
  geom_point = ggplot2::geom_point
80!
  scale_color_manual = ggplot2::scale_color_manual
81!
  geom_polygon = ggplot2::geom_polygon
82!
  theme = ggplot2::theme
83!
  coord_fixed = ggplot2::coord_fixed
84
85
  # Create base ggplot object
86
  # p = ggplot() + theme_void()
87!
  p = list()
88!
  if(!inherits(skeleton, "rayskeleton_list")) {
89!
    skeleton_all = list(skeleton)
90
  } else {
91!
    skeleton_all = skeleton
92
  }
93!
  final_links_list = list()
94!
  final_nodes_list = list()
95!
  for(i in seq_along(skeleton_all)) {
96!
    skeleton = skeleton_all[[i]]
97!
    final_nodes_list[[i]] = skeleton$nodes
98
99!
    skeleton$links$mid_x = (skeleton$nodes[skeleton$links$source, 'x'] + skeleton$nodes[skeleton$links$destination, 'x']) / 2
100!
    skeleton$links$mid_y = (skeleton$nodes[skeleton$links$source, 'y'] + skeleton$nodes[skeleton$links$destination, 'y']) / 2
101!
    skeleton$links$x = skeleton$nodes[skeleton$links$source, 'x']
102!
    skeleton$links$y = skeleton$nodes[skeleton$links$source, 'y']
103!
    skeleton$links$xend = skeleton$nodes[skeleton$links$destination, 'x']
104!
    skeleton$links$yend = skeleton$nodes[skeleton$links$destination, 'y']
105!
    skeleton$links$is_highlighted <- ifelse(seq_len(nrow(skeleton$links)) %in% highlight_links, TRUE, FALSE)
106!
    final_links_list[[i]] = skeleton$links
107
  }
108!
  final_links = do.call("rbind", final_links_list)
109!
  final_nodes = do.call("rbind", final_nodes_list)
110
111
  # Plot skeleton nodes
112!
  if(use_points) {
113!
    p[[length(p) + 1]] = geom_point(data = final_nodes,
114!
                       aes(x = x, y = y),
115!
                       color = polygon_color, size = size)
116
  }
117
118
  # Plot skeleton links (arrows or segments)
119!
  if (use_arrow) {
120!
    p[[length(p) + 1]] = geom_segment(data = final_links,
121!
                          aes(x = x,
122!
                              y = y,
123!
                              xend = mid_x,
124!
                              yend = mid_y,
125!
                              color = is_highlighted),
126!
                          arrow = grid::arrow(type = "closed", length = grid::unit(arrow_size, "inches")))
127!
    p[[length(p) + 1]] =   geom_segment(data = final_links,
128!
                 aes(x = mid_x,
129!
                     y = mid_y,
130!
                     xend = xend,
131!
                     yend = yend,
132!
                     color = is_highlighted))
133
  } else {
134!
    p[[length(p) + 1]] = geom_segment(data = final_links,
135!
                         aes(x = x,
136!
                             y = y,
137!
                             xend = xend,
138!
                             yend = yend,
139!
                             color = is_highlighted))
140
  }
141!
  p[[length(p) + 1]] = scale_color_manual(values=c(arrow_color, highlight_color))
142!
  p[[length(p) + 1]] =   theme(legend.position = "none")
143
144
  # Plot original polygon
145!
  for(i in seq_along(skeleton_all)) {
146!
    skeleton = skeleton_all[[i]]
147!
    original_vertices = attr(skeleton, "original_vertices")
148!
    colnames(original_vertices) = c("x","y")
149!
    p[[length(p) + 1]] = geom_polygon(data = data.frame(original_vertices),
150!
                          aes(x = x, y = y),
151!
                          color = polygon_color, fill = NA)
152
153
    # Plot holes if any
154!
    original_holes = attr(skeleton, "original_holes")
155!
    if (length(original_holes) > 0) {
156!
      for (hole in original_holes) {
157!
        hole = data.frame(hole)
158!
        colnames(hole) = c("x","y")
159
160!
        p[[length(p) + 1]] = geom_polygon(data = hole,
161!
                              aes(x = x, y = y),
162!
                              color = polygon_color, fill = NA)
163
      }
164
    }
165
  }
166!
  if(!return_layers) {
167
    # Adjust plot limits and maintain aspect ratio
168!
    p[[length(p) + 1]] = coord_fixed(ratio = 1)
169!
    p[[length(p) + 1]] = theme_void()
170!
    p[[length(p) + 1]] = theme(legend.position = "none")
171
172!
    return(ggplot() + p)
173
174
  } else {
175!
    return(p)
176
  }
177
}
1
#' Skeletonize a polygon
2
#'
3
#' This function generates a straight skeleton of a polygon, based on a set of vertices and holes.
4
#' It uses the CGAL library to create the straight skeleton using exact arithmetic,
5
#' and then parses that file into a more manageable format.
6
#'
7
#' @param vertices Default `NULL`. A matrix of x and y coordinates representing the vertices of the polygon in counter-clockwise (CCW) order.
8
#' @param holes Default `list()`. A list of matrices, each representing a hole in the polygon with x and y coordinates in clockwise (CW) order.
9
#' @param debug Default `FALSE`. A logical flag that controls whether debugging information should be printed.
10
#' @param return_raw_ss Default `FALSE`. A logical flag that controls whether the raw straight skeleton should be returned.
11
#' @param merge_nodes_tolerance Default `1e-5`. A numeric value specifying the tolerance level for merging nodes. It should be a value between 0 and 1.
12
#' This value species the size of the grid that the nodes are snapped to determining identical nodes.
13
#' @param progress Default `TRUE`. A logical flag that controls whether a progress bar should be displayed while skeletonizing.
14
#'
15
#' @return If `return_raw_ss` is FALSE, a list with two data frames, 'nodes' and 'links', which represent the nodes and edges of the straight skeleton, respectively.
16
#' If `return_raw_ss` is TRUE, a data frame representing the raw straight skeleton is returned.
17
#' If the polygon is not simple, a warning is issued and NULL is returned.
18
#'
19
#' @export
20
#' @examples
21
#' # Example 1: Simple rectangle polygon with no holes
22
#' vertices1 = matrix(c(0,0, 4,0, 4,3, 0,3, 0,0), ncol = 2, byrow = TRUE)
23
#' skeleton1 = skeletonize(vertices1)
24
#' if(run_docs_raybevel()){
25
#' plot_skeleton(skeleton1)
26
#' }
27
#'
28
#' # Example 2: Triangle polygon with no holes
29
#' vertices2 = matrix(c(0,0, 2,0, 1,2, 0,0), ncol = 2, byrow = TRUE)
30
#' skeleton2 = skeletonize(vertices2)
31
#' if(run_docs_raybevel()) {
32
#' plot_skeleton(skeleton2)
33
#' }
34
#'
35
#' # Example 3: Polygon with a hole
36
#' # Outer polygon
37
#' vertices3 = matrix(c(0,0, 5,0, 5,5, 0,5, 0,0), ncol = 2, byrow = TRUE)
38
#' # Hole inside the polygon
39
#' hole3 = matrix(c(1,1, 4,1, 4,4, 1,4, 1,1), ncol = 2, byrow = TRUE)[5:1,]
40
#' skeleton3 = skeletonize(vertices3, holes = list(hole3))
41
#' if(run_docs_raybevel()) {
42
#' plot_skeleton(skeleton3)
43
#' }
44
#'
45
#' # Example 4: Polygon with multiple holes
46
#' # Outer polygon
47
#' vertices4 = matrix(c(0,0, 7,0, 7,7, 0,7, 0,0), ncol = 2, byrow = TRUE)
48
#' # Holes inside the polygon
49
#' hole4_1 = matrix(c(1,1, 2,1, 2,2, 1,2, 1,1), ncol = 2, byrow = TRUE)[5:1,]
50
#' hole4_2 = matrix(c(5,5, 6,5, 6,6, 5,6, 5,5), ncol = 2, byrow = TRUE)[5:1,]
51
#' skeleton4 = skeletonize(vertices4, holes = list(hole4_1, hole4_2))
52
#' if(run_docs_raybevel()) {
53
#' plot_skeleton(skeleton4)
54
#' }
55
#'
56
#' # Example 5: Using debug and returning raw straight skeleton
57
#' vertices5 = matrix(c(0,0, 3,0, 3,3, 0,3, 0,0), ncol = 2, byrow = TRUE)
58
#' raw_skeleton5 = skeletonize(vertices5, debug = TRUE, return_raw_ss = TRUE)
59
#'
60
#' # Skeletonize and plot an {sf} object
61
#' if(run_docs_raybevel()) {
62
#'   us_states = spData::us_states
63
#'   texas = us_states[us_states$NAME == "Texas",]
64
#'   plot_skeleton(skeletonize(texas))
65
#' }
66
skeletonize = function(vertices, holes = list(), debug = FALSE,
67
                       merge_nodes_tolerance = 1e-5,
68
                       return_raw_ss = FALSE,
69
                       progress = TRUE) {
70144x
  if(inherits(vertices,"data.frame") && !inherits(vertices,"sf")) {
71!
    vertices = as.matrix(vertices)
72
  }
73144x
  stopifnot(merge_nodes_tolerance >= 0 && merge_nodes_tolerance < 1)
74144x
  if(inherits(vertices, "sf")) {
755x
    pb = progress::progress_bar$new(
765x
      format = ":current/:total skeletonizing [:bar] eta: :eta",
775x
      total = nrow(vertices), clear = TRUE, width = 60)
785x
    non_empty_geometry = list()
795x
    cntr = 1
805x
    list_idx = list()
815x
    for(i in seq_len(length(vertices$geometry))) {
82102x
      if(length(vertices$geometry[[i]]) > 0) {
83102x
        non_empty_geometry[[cntr]]  = vertices$geometry[[i]]
84102x
        list_idx[[cntr]] = i
85102x
        cntr = cntr + 1
86
      }
87
    }
885x
    all_coords = lapply(non_empty_geometry, sf::st_coordinates)
895x
    is_multipolygon = unlist(lapply(non_empty_geometry, (function(x) inherits(x,"MULTIPOLYGON"))))
905x
    is_polygon = unlist(lapply(non_empty_geometry, (function(x) inherits(x,"POLYGON"))))
91
925x
    ss_list = list()
935x
    counter = 1
945x
    for(i in seq_len(length(all_coords))) {
95102x
      if(progress) {
96102x
        pb$tick()
97
      }
98102x
      single_row_geometry = all_coords[[i]]
99102x
      if(is_polygon[i]) {
100!
        all_features = split(as.data.frame(single_row_geometry)[,c("X","Y","L1")],
101!
                             list(single_row_geometry[,c("L2")]))
102!
        for(j in seq_len(length(all_features))) {
103!
          single_feature = all_features[[j]]
104!
          exterior_points = single_feature[,"L1"] == 1
105!
          verts = as.matrix(single_feature[exterior_points,c("X","Y")])
106!
          if(all(verts[1,] == verts[nrow(verts),])) {
107!
            verts = verts[-nrow(verts),]
108
          }
109!
          hole_mat = single_feature[!exterior_points,]
110!
          if(nrow(hole_mat) > 0) {
111!
            holes = split(as.data.frame(hole_mat)[,c("X","Y")],
112!
                          hole_mat[,c("L1")])
113
          } else {
114!
            holes = list()
115
          }
116!
          if(!is_simple_polygon(verts)) {
117!
            warning(sprintf("Row %i in `sf` object not simple polygon, skipping",i))
118!
            next
119
          }
120
          #Fix orientations
121!
          if(!is_ccw_polygon(as.matrix(verts))) {
122!
            verts = verts[rev(seq_len(nrow(verts))),]
123
          }
124!
          for(k in seq_len(length(holes))) {
125!
            if(all(holes[[k]][1,] == holes[[k]][nrow(holes[[k]]),])) {
126!
              holes[[k]] = holes[[k]][-nrow(holes[[k]]),]
127
            }
128!
            holes[[k]] = as.matrix(holes[[k]])
129!
            if(!is_simple_polygon(as.matrix(holes[[k]]))) {
130!
              warning(sprintf("Hole in row %i in `sf` object not simple polygon, skipping", i))
131!
              next
132
            }
133!
            if(is_ccw_polygon(holes[[k]])) {
134!
              holes[[k]] = holes[[k]][rev(seq_len(nrow(holes[[k]]))),]
135
            }
136
          }
137
          #Skeletonize
138!
          ss_list[[counter]] = skeletonize(as.matrix(verts), debug = debug,
139!
                                           holes = holes,
140!
                                           return_raw_ss = return_raw_ss,
141!
                                           merge_nodes_tolerance = merge_nodes_tolerance)
142!
          attr(ss_list[[counter]], "original_sf_row_index") = list_idx[[i]]
143!
          counter = counter + 1
144
        }
145102x
      } else if (is_multipolygon[i]) {
146102x
        all_polygons = split(as.data.frame(single_row_geometry)[,c("X", "Y", "L1", "L2")],
147102x
                             list(single_row_geometry[,c("L3")]))
148102x
        for(ii in seq_len(length(all_polygons))) {
149102x
          single_polygon = all_polygons[[ii]]
150102x
          all_features = split(as.data.frame(single_polygon)[,c("X", "Y", "L1")],
151102x
                               list(single_polygon[,c("L2")]))
152102x
          for(j in seq_len(length(all_features))) {
153137x
            single_feature = all_features[[j]]
154137x
            exterior_points = single_feature[,"L1"] == 1
155137x
            verts = as.matrix(single_feature[exterior_points,c("X","Y")])
156137x
            if(all(verts[1,] == verts[nrow(verts),])) {
157137x
              verts = verts[-nrow(verts),]
158
            }
159137x
            hole_mat = single_feature[!exterior_points,]
160137x
            if(nrow(hole_mat) > 0) {
161!
              holes = split(as.data.frame(hole_mat)[,c("X","Y")],
162!
                            hole_mat[,c("L1")])
163
            } else {
164137x
              holes = list()
165
            }
166
            #Fix orientations
167137x
            if(!is_ccw_polygon(verts)) {
168137x
              verts = verts[rev(seq_len(nrow(verts))),]
169
            }
170137x
            vert_hashes = apply(verts,1,digest::digest)
171137x
            cleaned_holes = list()
172137x
            cntr = 1
173137x
            for(k in seq_len(length(holes))) {
174!
              if(!is_simple_polygon(as.matrix(holes[[k]]))) {
175!
                warning(sprintf("Hole in row %i in `sf` object not simple polygon, skipping", i))
176!
                next
177
              }
178!
              if(is_ccw_polygon(holes[[k]])) {
179!
                holes[[k]] = holes[[k]][rev(seq_len(nrow(holes[[k]]))),]
180
              }
181!
              hole_hashes = apply(holes,1,digest::digest)
182!
              if(any(hole_hashes %in% vert_hashes)) {
183!
                warning(sprintf("Hole has shared node with vertex exterior which can cause problems with CGAL's underlying straight skeleton algorithm--skipping hole."))
184!
                next
185
              }
186!
              cleaned_holes[[cntr]] = as.matrix(holes[[k]])
187!
              cntr = cntr + 1
188
            }
189
            #Skeletonize
190137x
            ss_list[[counter]] = skeletonize(as.matrix(verts), debug = debug,
191137x
                                             holes = cleaned_holes,
192137x
                                             return_raw_ss = return_raw_ss,
193137x
                                             merge_nodes_tolerance = merge_nodes_tolerance)
194137x
            attr(ss_list[[counter]], "original_sf_row_index") = list_idx[[i]]
195137x
            counter = counter + 1
196
          }
197
        }
198
      }
199
    }
2005x
    if(length(ss_list) > 1) {
2014x
      class(ss_list) = c("rayskeleton_list", "list")
2024x
      return(ss_list)
203
    } else {
2041x
      return(ss_list[[1]])
205
    }
206
  } else {
207
    #Fix orientations
208139x
    if(all(vertices[1,] == vertices[nrow(vertices),])) {
2091x
      vertices = vertices[-nrow(vertices),]
210
    }
211139x
    if(!is_ccw_polygon(as.matrix(vertices))) {
212!
      vertices = vertices[rev(seq_len(nrow(vertices))),]
213
    }
214139x
    for(k in seq_len(length(holes))) {
2152x
      if(all(holes[[k]][1,] == holes[[k]][nrow(holes[[k]]),])) {
2162x
        holes[[k]] = holes[[k]][-nrow(holes[[k]]),]
217
      }
2182x
      holes[[k]] = as.matrix(holes[[k]])
2192x
      if(!is_simple_polygon(as.matrix(holes[[k]]))) {
220!
        warning(sprintf("Hole in row %i in `sf` object not simple polygon, skipping", i))
221!
        next
222
      }
2232x
      if(is_ccw_polygon(holes[[k]])) {
224!
        holes[[k]] = holes[[k]][rev(seq_len(nrow(holes[[k]]))),]
225
      }
226
    }
227
  }
228139x
  stopifnot(ncol(vertices) == 2)
229139x
  if(all(vertices[1,] == vertices[nrow(vertices),])) {
230!
    vertices = vertices[-nrow(vertices),]
231
  }
232139x
  for(i in seq_len(length(holes))) {
2332x
    hole = as.matrix(holes[[i]])
2342x
    if(all(hole[1,] == hole[nrow(hole),])) {
235!
      holes[[i]] = hole[-nrow(hole),]
236
    } else {
2372x
      holes[[i]] = hole
238
    }
239
  }
240139x
  return_data = skeletonize_rcpp(vertices, holes, 0)
241
242139x
  if(length(return_data) == 0) {
243!
    warning("Polygon is not simple--not computing straight skeleton.")
244!
    return()
245
  }
246139x
  ss = do.call("rbind", return_data$bisectors)
247139x
  colnames(ss) = c("end_x","end_y","start_x","start_y","time","time_start", "id", "id_start")
248139x
  if(return_raw_ss) {
249!
    return(as.data.frame(ss))
250
  }
251
  #De-duplicate half edges
252139x
  ss = ss[ss[,"id_start"] < ss[,"id"] | (ss[,"time"] == 0  & ss[,"time_start"] == 0) ,]
253
  #Re-connect first vertex so everything is CCW
254
  # stopifnot(ss[1:2,"id_start"] == 0)
255
  # ss[1,] = ss[1,c(3,4,1,2,5,6,8,7)]
256139x
  ss = unique(as.data.frame(ss))
257139x
  ss$edge = ss$time == 0 & ss$time_start == 0
258
  # ss = ss[,c(1:8,9)]
259139x
  start_nodes = as.data.frame(ss[,c("id_start", "start_x", "start_y", "time_start")])
260139x
  start_nodes = arrange_base(unique(start_nodes[start_nodes$time_start == 0,]),"id_start")
261139x
  ss = arrange_base(as.data.frame(ss), "time_start", "time")
262139x
  start_ss = ss[,c(8,3:4,6,5)]
263139x
  colnames(start_ss) = c("id","x","y","time","other_time")
264139x
  end_ss = ss[,c(7,1:2,5,6)]
265139x
  colnames(end_ss) = c("id","x","y","time","other_time")
266139x
  nodes = rbind(start_ss,end_ss)
267139x
  nodes$edge = nodes$time == 0 & nodes$other_time == 0
268139x
  rev_nodes = (nodes[nodes$time < nodes$other_time,])
269139x
  nodes = (nodes[nodes$time >= nodes$other_time,])
270139x
  if(any(!rev_nodes$id %in% nodes$id)) {
271!
    cut_nodes = unique(rev_nodes$id[which(!rev_nodes$id %in% nodes$id)])
272!
    new_nodes = rev_nodes[rev_nodes$id %in% cut_nodes,]
273!
    nodes = rbind(nodes,new_nodes)
274
  }
275
276139x
  nodes = unique(nodes[,c(1:4,6)])
277139x
  nodes = arrange_base(nodes, "id")
278139x
  links = ss[,c("id_start", "id", "time","time_start")]
279139x
  colnames(links) = c("source","destination" ,"destination_time","source_time")
280139x
  links = links[,c(1,2,4,3)]
281139x
  links = as.data.frame(links)
282139x
  links$edge = links$source_time == 0 & links$destination_time == 0
283139x
  links = links[,c(1,2,5,3,4)]
284139x
  id_as_factor = as.factor(nodes$id)
285139x
  id_levels = levels(id_as_factor)
286139x
  nodes$id = as.factor(nodes$id)
287139x
  links$source = as.integer(factor(links$source, levels = id_levels))
288139x
  links$destination = as.integer(factor(links$destination, levels = id_levels))
289139x
  nodes$id = as.integer(id_as_factor)
290139x
  edge_links = links[links$edge,]
291139x
  edge_links = edge_links[rev(seq_len(nrow(edge_links))),c(2,1,3,5,4)]
292139x
  colnames(edge_links) = c("source","destination" ,"edge", "source_time","destination_time")
293139x
  links = rbind(edge_links, links[!links$edge,])
294139x
  rownames(nodes) = seq_len(nrow(nodes))
295139x
  rownames(links) = seq_len(nrow(links))
296
297139x
  ss = list(nodes = nodes, links = links)
298139x
  class(ss) = "rayskeleton"
299139x
  for(i in seq_len(length(holes))) {
3002x
    colnames(holes[[i]]) = c("x","y")
301
  }
302139x
  colnames(vertices) = c("x","y")
303139x
  attr(ss,"original_vertices") = vertices
304139x
  attr(ss,"original_holes") = holes
305139x
  if(merge_nodes_tolerance > 0) {
306139x
    ss = discretize_and_merge_nodes(ss, merge_nodes_tolerance)
307
  }
308139x
  ss = remove_reversed_links(ss)
309139x
  return(ss)
310
}
311
1
#' Extrude Sides of Polygon
2
#'
3
#' @keywords internal
4
extrude_sides = function(vertices, holes = list(), bottom = 0, top = 1) {
557x
  vert_list = list()
657x
  idx_list = list()
7
  #Need to ensure all polygons are closed
857x
  close_poly = function(dat) {
9169x
    if(!all(dat[1L,] == dat[nrow(dat),])) {
10169x
      dat[c(seq_len(nrow(dat)), 1L),]
11!
    } else dat
12
  }
1357x
  vertices = close_poly(vertices)
1457x
  holes = lapply(holes, close_poly)
15
1657x
  all_polys = c(list(vertices), holes)
1757x
  n_verts = 0
1857x
  for(j in seq_len(length(all_polys))) {
19169x
    polyv = all_polys[[j]]
20169x
    x = polyv[,1]
21169x
    y = polyv[,2]
22
23169x
    nr = nrow(polyv)-1
24
25169x
    vertices_top = cbind(polyv[-(nr+1),1:2],rep(top,nr))
26169x
    vertices_bottom = cbind(polyv[-(nr+1),1:2],rep(bottom,nr))
27169x
    colnames(vertices_top) = c("x","y","z")
28169x
    colnames(vertices_bottom) = c("x","y","z")
29
30169x
    vert_list[[j]] = rbind(vertices_top,vertices_bottom)
31
32
    # Find which direction polygon is wound by computing signed area,
33
    # assumes non-intersecting polygon (side is a closed polygon).  CW
34
    # outer polygon need to flip sides, as do CCW holes
35
36169x
    i = seq_len(nr)
37169x
    ii = seq_len(nr) + 1L   # i + 1
38169x
    area_s = sum(x[i] * y[ii] - x[ii] * y[i]) / 2
39
40169x
    ccw = area_s >= 0  # treat degenerates as counter-clockwise
41169x
    side_rev = (j == 1L && ccw) || !ccw
42
    #Get matrices to create triangles from polygon
43169x
    idx_mat = matrix(unlist(lapply(seq_len(nr),rep,2)), ncol = 3, nrow=2*nr)
44169x
    tri_idx_mat = matrix(c(0,nr,nr,
45169x
                           0,nr,0), nrow = 2*nr, ncol = 3, byrow=TRUE)
46169x
    vert_idx_mat = matrix(c(0,0,1,
47169x
                            0,1,1), nrow = 2*nr, ncol = 3, byrow=TRUE)
48169x
    end_idx_mat = matrix(0, nrow = 2*nr, ncol = 3, byrow=TRUE)
49169x
    end_idx_mat[seq(2*nr-1,2*nr,by=1),] = c(0,0,0,-nr,-nr,-nr)
50169x
    tri_idx = idx_mat + tri_idx_mat + vert_idx_mat + end_idx_mat
51169x
    if(!side_rev) {
52!
      idx_list[[j]] = tri_idx[,3:1] + n_verts
53
    } else {
54169x
      idx_list[[j]] = tri_idx + n_verts
55
    }
56169x
    n_verts = n_verts + nrow(vert_list[[j]])
57
  }
58
5957x
  v_mat = do.call(rbind,vert_list)
6057x
  i_mat = do.call(rbind,idx_list)
6157x
  edge_mesh = rayvertex::construct_mesh(vertices = as.matrix(v_mat),
6257x
                                        indices = as.matrix(i_mat)-1)
6357x
  return(edge_mesh)
64
}
1
#' Recalculate Ordered IDs
2
#'
3
#' @keywords internal
4
recalculate_ordered_ids = function(skeleton) {
5203x
  nodes = skeleton$nodes
6203x
  links = skeleton$links
7203x
  id_as_factor = as.factor(nodes$id)
8203x
  id_levels = levels(id_as_factor)
9203x
  nodes$id = as.factor(nodes$id)
10203x
  links$source = as.integer(factor(links$source, levels = id_levels))
11203x
  links$destination = as.integer(factor(links$destination, levels = id_levels))
12203x
  nodes$id = as.integer(id_as_factor)
13203x
  skeleton$nodes = nodes
14203x
  skeleton$links = links
15203x
  return(skeleton)
16
}
1
#' Generate Offset Polygon
2
#'
3
#' @keywords internal
4
generate_offset_links_nodes = function(ss, offsets, return_polys = FALSE, progress = FALSE, verbose = FALSE) {
5139x
  links = ss$links
6139x
  nodes = ss$nodes
7139x
  offsets = offsets[which(offsets < max(nodes$time)) ]
8
9139x
  node_maxima_ids = identify_maxima_nodes(ss)
10139x
  nodes$local_maxima = nodes$id %in% node_maxima_ids
11139x
  links$local_maxima_destination = links$destination %in% node_maxima_ids
12139x
  links$local_maxima_source = links$source %in% node_maxima_ids
13
14139x
  max_time = max(links$destination_time)
15139x
  if(all(offsets >= max_time)) {
1619x
    return(list(data.frame(x=numeric(),y=numeric())))
17
  }
18120x
  poly_list = generate_offset_links_nodes_rcpp(links, nodes, offsets = offsets, progress = progress)
19
20120x
  new_links_offset = list()
21120x
  for(ii in seq_along(poly_list)) {
22376x
    if(length(poly_list[[ii]]) > 0) {
23376x
      all_new_nodes = do.call("rbind",poly_list[[ii]])
24376x
      colnames(all_new_nodes) = c("polygon_id", "source", "destination", "new_id",
25376x
                                  "x","y","time","x1","y1","x2","y2", "new_node")
26376x
      if(return_polys) {
2756x
        just_poly = all_new_nodes[,c("polygon_id", "x","y")]
2856x
        names(just_poly) = c("id","x","y")
2956x
        just_poly = split(as.data.frame(just_poly[,-1]), just_poly[,1])
3056x
        return(just_poly)
31
      }
32320x
      new_links_poly = split(as.data.frame(all_new_nodes[,-1,drop=FALSE]), all_new_nodes[,1,drop=FALSE])
33
34320x
      new_links_offset[[ii]] = new_links_poly
35
    }
36
  }
3764x
  if(return_polys) {
38!
    all_new_nodes = do.call("rbind",new_links_offset)
39!
    just_poly = all_new_nodes[,c("polygon_id", "x","y")]
40!
    names(just_poly) = c("id","x","y")
41!
    just_poly = split(as.data.frame(just_poly[,-1]), just_poly[,1])
42!
    return(just_poly)
43
  }
4464x
  print_time(verbose, "Inserting polygon links and nodes")
45
4664x
  return(insert_polygon_links_nodes(ss, new_links_offset))
47
}
48
49
50
#' Insert Polygon Links/Nodes
51
#'
52
#' @keywords internal
53
insert_polygon_links_nodes = function(ss, new_links_all) {
5464x
  links = ss$links
5564x
  nodes = ss$nodes
5664x
  counter = 1
5764x
  poly_counter = 1
5864x
  new_link_list = list()
5964x
  new_link_list_poly = list()
6064x
  new_node_list = list()
6164x
  links_to_remove = list()
6264x
  raw_df = function(list_vals) {
635248x
    structure(list_vals,
645248x
              class = "data.frame",
655248x
              row.names = seq_len(length(list_vals[[1]])))
66
  }
67
  # plot_skeleton(ss, label_ids = TRUE)
6864x
  for(ii in seq_len(length(new_links_all))) {
69320x
    new_links = new_links_all[[ii]]
70320x
    if(length(new_links) == 0) {
71!
      next
72
    }
73320x
    new_nodes_single = do.call("rbind", new_links)[,c(3:6)]
74
    # new_nodes_single = do.call("rbind", new_links)[,c(3:6,12)]
75
    # new_nodes_single = new_nodes_single[new_nodes_single$new_node == 1,1:4, drop = FALSE]
76320x
    colnames(new_nodes_single)[1] = "id"
77320x
    new_nodes_single$edge = FALSE
78320x
    new_node_list[[ii]] = new_nodes_single[order(new_nodes_single$id),]
79320x
    for(i in seq_len(length(new_links))) {
80576x
      single_poly = new_links[[i]]
81576x
      prev_id = 0
82576x
      for(j in seq_len(nrow(single_poly))) {
832816x
        new_id = single_poly$new_id[j]
842816x
        new_time = single_poly$time[j]
852816x
        old_source =  single_poly$source[j]
862816x
        old_destination =  single_poly$destination[j]
872816x
        if(j != nrow(single_poly)) {
882240x
          poly_id = single_poly$new_id[j + 1]
89
        } else {
90576x
          poly_id = single_poly$new_id[1]
91
        }
922816x
        link_remove_idx = which((links$source == old_source &
932816x
                                 links$destination == old_destination) |
942816x
                                (links$destination == old_source &
952816x
                                 links$source == old_destination))
962816x
        stopifnot(length(link_remove_idx) == 1)
972816x
        stopifnot(length(old_source) == 1)
982816x
        stopifnot(length(old_destination) == 1)
992816x
        stopifnot(length(poly_id) == 1)
1002816x
        stopifnot(length(new_time) == 1)
101
1022816x
        old_link = links[link_remove_idx,]
1032816x
        old_source_time = old_link$source_time
1042816x
        old_destination_time = old_link$destination_time
105
1062816x
        if(old_source != new_id) {
1072432x
          links_to_remove[[counter]] = link_remove_idx
108
1092432x
          new_link_list[[counter]] = raw_df(list(source = c(old_source,new_id),
1102432x
                                                 destination = c(new_id,old_destination),
1112432x
                                                 source_time = c(old_source_time, new_time),
1122432x
                                                 destination_time = c(new_time, old_destination_time),
1132432x
                                                 edge = c(FALSE, FALSE),
1142432x
                                                 link_remove = rep(link_remove_idx,2),
1152432x
                                                 old_source_id = rep(old_source,2),
1162432x
                                                 old_dest_id = rep(old_destination,2))) #We will remove this variable before joining
1172432x
          counter = counter + 1
118
        }
119
        # if(prev_id == 0 || prev_id == new_id ) {
1202816x
          new_link_list_poly[[poly_counter]] = raw_df(list(source = new_id,
1212816x
                                                          destination = poly_id,
1222816x
                                                          source_time = new_time,
1232816x
                                                          destination_time = new_time,
1242816x
                                                          edge = FALSE))
1252816x
          poly_counter = poly_counter + 1
126
127
        # } else {
128
        #   new_link_list_poly[[poly_counter]] = data.frame(source = prev_id,
129
        #                                              destination = new_id,
130
        #                                              source_time = new_time,
131
        #                                              destination_time = new_time,
132
        #                                              edge = FALSE)
133
        #   poly_counter = poly_counter + 1
134
        #
135
        #   new_link_list_poly[[poly_counter]] = data.frame(source = new_id,
136
        #                                              destination = poly_id,
137
        #                                              source_time = new_time,
138
        #                                              destination_time = new_time,
139
        #                                              edge = FALSE)
140
        #   poly_counter = poly_counter + 1
141
142
        # }
143
          # prev_id = poly_id
144
        # if(j == nrow(single_poly) && poly_id != single_poly$new_id[1]) {
145
        #   browser()
146
        #   new_link_list_poly[[poly_counter]] = data.frame(source = poly_id,
147
        #                                                   destination = single_poly$new_id[1],
148
        #                                                   source_time = new_time,
149
        #                                                   destination_time = new_time,
150
        #                                                   edge = FALSE)
151
        #   poly_counter = poly_counter + 1
152
        # }
153
      }
154
    }
155
  }
15664x
  new_nodes = do.call("rbind", new_node_list)
15764x
  new_skeleton_links_raw = do.call("rbind",new_link_list)
15864x
  links_to_slice = split(new_skeleton_links_raw,new_skeleton_links_raw[,6])
159
  # browser()
16064x
  new_links = lapply(links_to_slice, process_sliced_links)
16164x
  new_skeleton_links = do.call("rbind",new_links)
16264x
  new_poly_links = do.call("rbind", new_link_list_poly)
16364x
  links = rbind(links[-unlist(links_to_remove),],
16464x
                new_skeleton_links,
16564x
                new_poly_links)
16664x
  nodes_updated = rbind(nodes,new_nodes)
16764x
  rownames(nodes_updated) = NULL
16864x
  new_ss = list(nodes = nodes_updated, links = links)
16964x
  class(new_ss) = "rayskeleton"
17064x
  attr(new_ss, "original_vertices") = attr(ss, "original_vertices")
17164x
  attr(new_ss, "original_holes") = attr(ss, "original_holes")
17264x
  new_ss_no_dupe = remove_node_duplicates(new_ss)
17364x
  return(new_ss_no_dupe)
174
}
175
176
#' Process sliced links
177
#'
178
#' @keywords internal
179
process_sliced_links = function(link_group) {
1801152x
  n_new_nodes = nrow(link_group)/2
1811152x
  new_link_info = link_group[seq(2,nrow(link_group),by=2),]
1821152x
  old_source_time = link_group$source_time[1]
1831152x
  old_dest_time = link_group$destination_time[2]
1841152x
  if(old_source_time < old_dest_time) {
1851152x
    start_node = link_group$old_source_id[1]
1861152x
    end_node = link_group$old_dest_id[1]
1871152x
    prev_time = old_source_time
1881152x
    end_time = old_dest_time
189
  } else {
190!
    end_node = link_group$old_source_id[1]
191!
    start_node = link_group$old_dest_id[1]
192!
    prev_time = old_dest_time
193!
    end_time = old_source_time
194
195
  }
1961152x
  new_links = list()
1971152x
  current_node = start_node
1981152x
  for(k in seq_len(n_new_nodes)) {
1992432x
    new_node = new_link_info$source[k]
2002432x
    new_time = new_link_info$source_time[k]
2012432x
    if(new_time < prev_time) {
202!
      stop(sprintf("New time (%f) is not greater than previous time (%f) ",new_time,prev_time))
203
    }
2042432x
    if(new_time != prev_time) {
2052432x
      new_links[[k]] = data.frame(source = current_node,
2062432x
                                  destination = new_node,
2072432x
                                  source_time = prev_time,
2082432x
                                  destination_time = new_time,
2092432x
                                  edge = FALSE)
210
    }
2112432x
    current_node = new_node
2122432x
    prev_time = new_time
213
  }
2141152x
  new_links[[k+1]] = data.frame(source = current_node,
2151152x
                                destination = end_node,
2161152x
                                source_time = prev_time,
2171152x
                                destination_time = end_time,
2181152x
                                edge = FALSE)
219
2201152x
  return(do.call("rbind",new_links))
221
}
222
223
#' Make incremental nodes
224
#'
225
#' @keywords internal
226
make_incremental_nodes = function(ss) {
22764x
  fac_id = factor(ss$nodes$id)
22864x
  levels_id = levels(factor(ss$nodes$id))
22964x
  ss$nodes$id = as.integer(fac_id)
23064x
  ss$links$source = as.integer(factor(ss$links$source, levels = levels_id))
23164x
  ss$links$destination = as.integer(factor(ss$links$destination, levels = levels_id))
23264x
  return(ss)
233
}
1
#' Generate 2D Bevel Profile for 3D Polygons
2
#'
3
#' @param bevel_type Character `angled`. Type of the bevel, one of the following options:
4
#'   - "circular": Creates a rounded bevel resembling a quarter-circle.
5
#'   - "exp": Creates an exponential curve, starting slow and accelerating.
6
#'   - "bump": Creates a bump-like profile, rising and falling within the coverage.
7
#'   - "step": Generates a step-like bevel with a flat top.
8
#'   - "block": Generates a block-like bevel, jumping straight to the max_height and back to the base.
9
#'   - "angled": Generates a straight angled bevel. You can optionally set the 'angle' parameter for this bevel.
10
#'   - "flat": Generates a flat area.
11
#' @param bevel_start Default `0`. The starting point of the bevel along the curve, ranges between 0 and 1.
12
#' @param bevel_end Default `0.2`. The ending point of the bevel along the curve, ranges between 0 and 1.
13
#' @param max_height Default `1`. The maximum height of the bevel, as measured from the initial height.
14
#' @param angle Default `NULL`. Optional angle parameter in degrees for angular bevels.
15
#' @param curve_points Default `50`. Number of points to plot for curve-based bevels.
16
#' @param reverse Default `FALSE`. If `TRUE`, the curve is reversed vertically.
17
#' @param flip Default `FALSE`. If `TRUE`, the curve is flipped horizontally.
18
#' @param initial_height Default `0`. The initial height from which the bevel starts. The bevel is rescaled to fit within the range from initial_height to max_height.
19
#' @param manual_offsets Default `NULL`, none. This will force the bevel to add a point (interpolating between the two nearest points)
20
#' at the specified offsets. This is useful when you want to add points at specific distances along the curve.
21
#' @param add_end_points Default `TRUE`. Whether to ensure there is a point at zero and a point at one.
22
#' @param step_epsilon Default `1e-5`. The size for the small percentage step when using a step bevel.
23
#' @param set_minimum_zero Default `TRUE`. Whether to offset the lowest point of the bevel so it's at zero.
24
#' @param zero_offset_epsilon Default `1e-5`. Amount to offset the bevel to ensure no self-intersection with the base.
25
#' @param plot_bevel Default `FALSE`. Whether to plot the bevel.
26
#'
27
#' @return List containing 'x' and 'y', which are the coordinates of the 2D bevel profile.
28
#'
29
#' @export
30
#' @examples
31
#' # Generate a single bevel profile and plot it
32
#' coords = generate_bevel("circular", 0.2, 0.8, 0.2, plot_bevel = TRUE)
33
#'
34
#' # Plot all bevel profiles in a grid
35
#' plot_all_bevels = function() {
36
#'   oldpar = par(mfrow = c(4, 3), mai = c(0.2, 0.2, 0.5, 0.2))
37
#'   on.exit(par(oldpar))
38
#'   max_height = c(1,1,1,1)
39
#'   types = rep(c("circular", "exp", "bump", "step", "block", "angled"),2)
40
#'   reverses = c(rep(FALSE,6),rep(TRUE,6))
41
#'   for(i in seq_len(length(types))) {
42
#'     coords = generate_bevel(types[i], 0.2, 0.8, 1, flip = TRUE,
43
#'                             angle = 45, reverse = reverses[i], plot_bevel = TRUE)
44
#'   }
45
#' }
46
#' plot_all_bevels()
47
generate_bevel = function(bevel_type = "angled", bevel_start = 0, bevel_end = 0.2,
48
                          max_height = 1, angle = NULL, curve_points = 50,
49
                          reverse = FALSE, flip = FALSE,
50
                          initial_height = 0, add_end_points = TRUE,
51
                          manual_offsets = NULL,
52
                          step_epsilon = 1e-8,
53
                          plot_bevel = FALSE,
54
                          set_minimum_zero = TRUE,
55
                          zero_offset_epsilon = 1e-5) {
56
  # Check angle constraint if bevel_type is angled
57!
  if(bevel_type == "angled") {
58!
    if(!is.null(angle)) {
59!
      stopifnot(angle < 90 && angle > -90)
60!
      angle = angle*pi/180
61!
      max_height = tan(angle) * (bevel_end - bevel_start)
62
    }
63
  }
64
65
  # Initialize empty vectors for x and y
66!
  x = c()
67!
  y = c()
68
  # Define curve points based on bevel_type
69!
  if(bevel_type == "step") {
70!
    x = c(bevel_start, bevel_start + step_epsilon)
71!
    y = c(0, max_height)
72!
  } else if(bevel_type == "block") {
73!
    x = c(bevel_start, bevel_start + step_epsilon, bevel_end - step_epsilon, bevel_end)
74!
    y = c(0,max_height, max_height, 0)
75!
  } else if(bevel_type == "angled") {
76!
    x = c(bevel_start, bevel_end)
77!
    y = c(0, max_height)
78!
  } else if(bevel_type == "flat") {
79!
    x = c(bevel_start, bevel_end)
80!
    y = c(0, 0)
81
  } else {
82!
    x_curve = seq(bevel_start, bevel_end, length.out = curve_points)
83!
    if(bevel_type == "circular") {
84!
      y_curve = sqrt(1 - ((x_curve - bevel_start) / (bevel_end - bevel_start) - 1)^2)
85!
    } else if(bevel_type == "exp") {
86!
      y_curve = 1 - exp(-5 * (x_curve - bevel_start) / (bevel_end - bevel_start))
87!
    } else if(bevel_type == "bump") {
88!
      y_curve = sqrt(1 - (2 * (x_curve - bevel_start) / (bevel_end - bevel_start) - 1)^2)
89
    } else {
90!
      stop(sprintf("bevel_type `%s` not recognized.", bevel_type))
91
    }
92!
    y_curve = y_curve * max_height
93!
    x = c(x, x_curve)
94!
    y = c(y, y_curve)
95
  }
96!
  if(flip) {
97!
    y = rev(y)
98
  }
99!
  if(add_end_points) {
100!
    if(x[1] != 0) {
101!
      x = c(0,x)
102!
      y = c(y[1],y)
103
    }
104!
    if(x[length(x)] != 1) {
105!
      x = c(x,1)
106!
      last_val = y[length(y)]
107!
      y = c(y,last_val)
108
    }
109
  }
110!
  if(!is.null(manual_offsets)) {
111!
    manual_offsets = manual_offsets[manual_offsets < 1 & manual_offsets > 0]
112!
    for(j in seq_len(length(manual_offsets))) {
113!
      if(any(abs(x-manual_offsets[j]) < 1e-14)) {
114!
        manual_offsets[j] = NA
115
      }
116
    }
117!
    manual_offsets = manual_offsets[!is.na(manual_offsets)]
118!
    if(length(manual_offsets) > 0) {
119!
      max_x = max(x)
120!
      manual_vals = stats::approx(x=x,y=y, xout = manual_offsets)$y
121!
      manual_vals[max_x < manual_offsets] = y[length(y)]
122!
      x = c(x,manual_offsets)
123!
      x_order = order(x)
124!
      x = x[x_order]
125!
      y = c(y,manual_vals)
126!
      y = y[x_order]
127
    }
128
  }
129
  # Reverse the bevel if specified
130!
  if(reverse) {
131!
    y = max_height - y
132
  }
133
  # Adjust heights based on initial_height
134!
  diff_height = y[1]-initial_height
135!
  y = y - diff_height
136
137!
  if(set_minimum_zero && min(y) <= 0) {
138!
    y = y - min(y) + zero_offset_epsilon
139
  }
140
141!
  if(plot_bevel) {
142!
    plot(x, y, type = 'l', axes = FALSE, lwd = 2, xlim = c(min(x)-0.1, max(x)+0.1), ylim = c(min(y)-0.1, max(y)+0.1))
143!
    graphics::box()
144
  }
145
146!
  return(list(x = x, y = y))
147
}
148
149
#' Generate Complex 2D Bevel Profile for 3D Polygons
150
#'
151
#' All arguments are recycled to the length of the longest argument, allowing for the generation of
152
#' complex and repetitive bevel patterns without manual replication of argument values.
153
#'
154
#' @param bevel_type Vector of bevel types. Options are: `"circular"`, `"exp"`, `"bump"`, `"step"`, `"block"`, `"angled"`.
155
#' Note that for the `"step"` type, the transition occurs at `bevel_start`.
156
#' @param bevel_start Numeric vector of values between `0` and `1`.
157
#' Percentage distance in the interior the polygon at which to begin the corresponding `bevel_type`. Note that for the `"step"` type, this is ignored.
158
#' @param bevel_end Numeric vector of values between `0` and `1`.
159
#' Percentage distance in the interior the polygon at which to end the corresponding `bevel_type`.
160
#' @param segment_height Numeric vector. The maximum heights of each bevel, as measured from the initial height at the end of the previous bevel.
161
#' @param angle Default `NULL`. Numeric vector. Optional angle parameter in degrees for angular bevels (overrides values in `max_height`).
162
#' @param curve_points Default `50`. Integer vector of number of points for each curve.
163
#' @param manual_offsets Default `NULL`, none. This will force the bevel to add a point (interpolating between the two nearest points)
164
#' at the specified offsets. This is useful when you want to add points at specific distances along the curve.
165
#' @param add_end_points Default `TRUE`. Whether to ensure there is a point at zero and a point at one.
166
#' @param reverse Default `FALSE`. Whether to reverse each bevel.
167
#' @param flip Default `FALSE`. Whether to reverse each bevel horizontally.
168
#' @param plot_bevel Default `FALSE`. Whether to plot the resulting bevel.
169
#' @param overall_height Default `NA`. Numeric value specifying the overall height of the curve.
170
#' @param set_minimum_zero Default `TRUE`. Whether to offset the lowest point of the bevel so it's at zero.
171
#' @param zero_offset_epsilon Default `1e-5`. Amount to offset the bevel to ensure no self-intersection with the base.
172
#'
173
#' @return List containing 'x' and 'y', which are the coordinates of the complex 2D bevel profile
174
#' @export
175
#' @examples
176
#' # Generate a complex bevel profile and plot it
177
#' complex_coords = generate_complex_bevel(
178
#'   bevel_type  = c("circular", "bump", "step", "block", "angled"),
179
#'   bevel_start = c(0,   0.2, 0.6, 0.7, 0.9),
180
#'   bevel_end   = c(0.2, 0.5, 0.7, 0.8, 1.0),
181
#'   segment_height  = c(0.1, 0.2, 0.2, 0.2, 0.4),
182
#'   angle = 45,
183
#'   curve_points = c(50, 50, 50, 1, 1),
184
#'   reverse = c(FALSE, TRUE, FALSE, FALSE, FALSE),
185
#'   plot_bevel = TRUE
186
#' )
187
#' # Create a step function with reverses to generate a square wave pattern
188
#' complex_coords = generate_complex_bevel(
189
#'   bevel_type  = "step",
190
#'   bevel_start = head(seq(0,1,by=0.05),-1),
191
#'   bevel_end   = 1,
192
#'   segment_height  = 0.1,
193
#'   angle = 45,
194
#'   reverse = c(FALSE, TRUE),
195
#'   plot_bevel = TRUE
196
#' )
197
#' #Generate an increasing sawtooth pattern with angles
198
#' complex_coords = generate_complex_bevel(
199
#'   bevel_type  = "angled",
200
#'   bevel_start = head(seq(0,1,by=0.05),-1),
201
#'   bevel_end   = tail(seq(0,1,by=0.05),-1),
202
#'   segment_height  = 0.1,
203
#'   angle = c(45,30),
204
#'   reverse = c(FALSE, TRUE),
205
#'   plot_bevel = TRUE
206
#' )
207
#' # Create a step function to turn polygons into a ziggurat (note bevel_end is ignored)
208
#' complex_coords = generate_complex_bevel(
209
#'   bevel_type  = "step",
210
#'   bevel_start = head(seq(0,1,by=0.05),-1),
211
#'   bevel_end   = 1,
212
#'   segment_height  = 0.1,
213
#'   reverse = FALSE,
214
#'   plot_bevel = TRUE
215
#' )
216
generate_complex_bevel = function(bevel_type,
217
                                  bevel_start = 0,
218
                                  bevel_end = 1,
219
                                  segment_height = 1,
220
                                  angle = 45,
221
                                  curve_points = 30,
222
                                  reverse = FALSE,
223
                                  flip = FALSE,
224
                                  manual_offsets = NULL,
225
                                  add_end_points = TRUE,
226
                                  plot_bevel = FALSE,
227
                                  overall_height = NA,
228
                                  set_minimum_zero = TRUE,
229
                                  zero_offset_epsilon = 1e-6) {
230!
  completed_vals = data.frame(bevel_type = bevel_type,
231!
                              bevel_start = bevel_start,
232!
                              bevel_end = bevel_end,
233!
                              segment_height = segment_height,
234!
                              angle = angle,
235!
                              curve_points = curve_points,
236!
                              flip = flip,
237!
                              reverse = reverse)
238
  # Sort by bevel_start for sequential generation
239!
  completed_vals = completed_vals[order(completed_vals$bevel_start), ]
240
241
  # Add stop time to step types
242!
  for(i in seq_len(nrow(completed_vals))) {
243!
    if(completed_vals[i,"bevel_type"] == "step") {
244!
      completed_vals[i,"bevel_end"] = completed_vals[i,"bevel_start"] + 1e-5
245
    }
246
  }
247
  # Error if the bevels overlap
248!
  for(i in seq_len(nrow(completed_vals)-1)) {
249!
    if(completed_vals[i,"bevel_end"] > completed_vals[i + 1,"bevel_start"]) {
250!
      stop(sprintf("%ith `bevel_start` (%0.3f) starts before %ith `bevel_end` (%0.3f)",
251!
                   i+i, i, completed_vals[i + 1,"bevel_start"], completed_vals[i,"bevel_end"]))
252
    }
253
  }
254!
  x = c()
255!
  y = c()
256!
  y_prev_end = 0
257
258!
  manual_offsets_bool = rep(FALSE, length(manual_offsets))
259
260!
  for(i in seq_len(nrow(completed_vals))) {
261!
    row = completed_vals[i, ]
262!
    manual_offsets_bool[manual_offsets >= row$bevel_start &
263!
                        manual_offsets <= row$bevel_end] = TRUE
264!
    manual_offset_segment = manual_offsets[manual_offsets >= row$bevel_start &
265!
                                           manual_offsets <= row$bevel_end]
266!
    if(length(manual_offset_segment) == 0) {
267!
      manual_offset_segment = NULL
268
    }
269!
    bevel_segment = generate_bevel(
270!
      bevel_type = row$bevel_type,
271!
      bevel_start = row$bevel_start,
272!
      bevel_end = row$bevel_end,
273!
      max_height = row$segment_height,
274!
      angle = if (!is.null(row$angle)) row$angle else NULL,
275!
      curve_points = row$curve_points,
276!
      reverse = row$reverse,
277!
      flip = row$flip,
278!
      manual_offsets = manual_offset_segment,
279!
      initial_height = y_prev_end,  # Pass the last height of the previous bevel as the initial height
280!
      add_end_points = FALSE,
281!
      set_minimum_zero = FALSE
282
    )
283
284!
    y_prev_end = bevel_segment$y[length(bevel_segment$y)]  # Update y_prev_end for the next iteration
285
286!
    if(i == 1) {
287!
      x = bevel_segment$x
288!
      y = bevel_segment$y
289
    } else {
290!
      x = c(x, bevel_segment$x)
291!
      y = c(y, bevel_segment$y)
292
    }
293
  }
294
295!
  if(add_end_points) {
296!
    if(x[1] != 0) {
297!
      x = c(0,x)
298!
      y = c(y[1],y)
299
    }
300!
    if(x[length(x)] != 1) {
301!
      x = c(x,1)
302!
      y = c(y,y[length(y)])
303
    }
304
  }
305
306!
  duplicated_x = duplicated(x)
307!
  x = x[!duplicated_x]
308!
  y = y[!duplicated_x]
309
310!
  if(any(manual_offsets_bool)) {
311!
    manual_offsets_remaining = manual_offsets[!manual_offsets_bool]
312!
    manual_heights_insert = stats::approx(x=x,y=y, xout = manual_offsets_remaining)$y
313!
    x = c(x,manual_offsets_remaining)
314!
    y = c(y,manual_heights_insert)
315!
    order_x = order(x)
316!
    x = x[order_x]
317!
    y = y[order_x]
318
  }
319
320!
  duplicated_x = duplicated(x)
321!
  x = x[!duplicated_x]
322!
  y = y[!duplicated_x]
323
324
325!
  if(!is.na(overall_height)) {
326!
    stopifnot(is.numeric(overall_height) && length(overall_height) == 1)
327!
    min_val = min(y)
328!
    max_val = max(y)
329!
    y = (y - min_val) / (max_val - min_val) * overall_height + min_val
330
  }
331
332!
  if(set_minimum_zero && min(y) <= 0) {
333!
    range_y = range(y)
334!
    range_y = range_y[2] - range_y[1]
335!
    epsilon = range_y * zero_offset_epsilon
336!
    y = y - min(y) + epsilon
337
  }
338
339!
  if(plot_bevel) {
340!
    plot(x, y, type = 'l', axes = FALSE, lwd = 2, xlim = c(min(x)-0.1, max(x)+0.1), ylim = c(min(y)-0.1, max(y)+0.1))
341!
    graphics::box()
342
  }
343
344!
  return(list(x = x, y = y))
345
}
1
#' Print time
2
#'
3
#' @return Nothing
4
#' @keywords internal
5
init_time = function() {
6320x
  assign("init_time", proc.time()[3], envir = ray_environment)
7320x
  assign("prev_time", proc.time()[3], envir = ray_environment)
8
}
9
10
#' Get time
11
#'
12
#' @return Nothing
13
#' @keywords internal
14
get_time = function(init = TRUE) {
15!
  if(init) {
16!
    get("init_time", envir = ray_environment)
17
  } else {
18!
    get("prev_time", envir = ray_environment)
19
  }
20
}
21
22
#' Print time
23
#'
24
#' @return Nothing
25
#' @keywords internal
26
print_time = function(verbose = FALSE, message_text = "") {
27385x
  if(verbose) {
28!
    time_now = proc.time()[3]
29!
    message(sprintf("%-27s: %0.1f secs (Total: %0.1f secs)",
30!
                    message_text,
31!
                    time_now-get_time(FALSE),
32!
                    time_now-get_time(TRUE)))
33!
    assign("prev_time", time_now, envir = ray_environment)
34
  }
35
}
1
#' Discretize and Merge Nodes
2
#'
3
#' @keywords internal
4
discretize_and_merge_nodes = function(skeleton, tolerance = 1e-5) {
5
  # Calculate bounding box of the nodes
6139x
  x_range = range(skeleton$nodes$x)
7139x
  y_range = range(skeleton$nodes$y)
8139x
  width = x_range[2] - x_range[1]
9139x
  height = y_range[2] - y_range[1]
10
11
  # Snap each point to its nearest grid cell
12139x
  skeleton$nodes$grid_x = round((skeleton$nodes$x - x_range[1]) / width * 1/tolerance)
13139x
  skeleton$nodes$grid_y = round((skeleton$nodes$y - y_range[1]) / height * 1/tolerance)
14
15
  # Merge nodes based on their grid cells
16139x
  skeleton$nodes$grid_id = paste(skeleton$nodes$grid_x, skeleton$nodes$grid_y, sep="-")
17139x
  nodes_to_remove = duplicated(skeleton$nodes$grid_id)
18139x
  nodes_to_keep = which(!nodes_to_remove)
19
20
  # Map all nodes to their corresponding kept node
21139x
  id_map = stats::setNames(nodes_to_keep, skeleton$nodes$id[nodes_to_keep])
22139x
  for(node_id in skeleton$nodes$id) {
2314332x
    grid_id = skeleton$nodes$grid_id[skeleton$nodes$id == node_id]
2414332x
    id_map[as.character(node_id)] = skeleton$nodes$id[skeleton$nodes$grid_id == grid_id][1]
25
  }
26
27
  # Update links to reflect the merged nodes
28139x
  skeleton$links$source = id_map[as.character(skeleton$links$source)]
29139x
  skeleton$links$destination = id_map[as.character(skeleton$links$destination)]
30
31
  # Remove duplicate nodes
32139x
  skeleton$nodes = skeleton$nodes[!nodes_to_remove, ]
33139x
  skeleton$nodes = skeleton$nodes[, c("id", "x", "y", "time", "edge"), drop = FALSE]
34
35
  # Calculate new ids
36139x
  skeleton = recalculate_ordered_ids(skeleton)
37
38
  #Remove self-referencing links
39139x
  skeleton$links = skeleton$links[skeleton$links$source != skeleton$links$destination, ]
40
41
  #Remove duplicate links
42139x
  link_duplicates = duplicated(skeleton$links[, c("source", "destination")])
43139x
  skeleton$links = skeleton$links[!link_duplicates, ]
44
45139x
  return(skeleton)
46
}
1
#' Remove Node Duplicates
2
#'
3
#' @description Replace dup
4
#'
5
#' @param ss
6
#'
7
#' @keywords internal
8
remove_node_duplicates = function(ss) {
964x
  ss$nodes = ss$nodes[!duplicated(ss$nodes),]
10
  #Calculate unique nodes (position/time)
1164x
  row_hashes = apply(ss$nodes[,c(-1,-4)], 1, digest::digest)
1264x
  unique_row_hashes = unique(row_hashes)
1364x
  id_val = rep(0, length(unique_row_hashes))
1464x
  replace_node_list = list()
15
16
  #Find first row index that matches row hash
1764x
  for(i in seq_len(length(unique_row_hashes))) {
183776x
    tmp_id_val = which(unique_row_hashes[i] == row_hashes)
193776x
    id_val[i] = tmp_id_val[1]
203776x
    replace_node_list[[i]] = tmp_id_val[-1]
21
  }
22
  #Copy original skeleton
2364x
  new_ss = ss
24
25
  #Look through all new id values and replace links references to new IDs
2664x
  for(i in seq_len(length(id_val))) {
273776x
    if(length(replace_node_list[[i]]) > 0) {
28
      #Replace link information with de-duplicated nodes
29!
      new_ss$links$source[ss$links$source %in% replace_node_list[[i]] ] = id_val[i]
30!
      new_ss$links$destination[ss$links$destination %in% replace_node_list[[i]] ] = id_val[i]
31
    }
32
  }
3364x
  new_ss$links = new_ss$links[!duplicated(new_ss$links),]
3464x
  new_ss$links = new_ss$links[new_ss$links$source != new_ss$links$destination,]
35
3664x
  new_ss$nodes = new_ss$nodes[!new_ss$nodes$id %in% unlist(replace_node_list),]
3764x
  new_ss_inc = make_incremental_nodes(new_ss)
3864x
  return(new_ss_inc)
39
}
1
#' Plot Offset Polygons
2
#'
3
#' Plot the offset polygons generated by the `generate_offset_polygon` function.
4
#'
5
#' @param offset_polygons Default `NULL`. A `rayskeleton_polygon` or `rayskeleton_polygon_list` object, generated from
6
#' `generate_offset_polygon()`.
7
#' @param color Default `grDevices::heat.colors`.  A color or palette function to generate the color palette for the offset polygons' borders.
8
#' @param xlim Default `NULL`. The x-axis limits as a vector of two values (min, max). If `NULL`, it calculates the limits from the data.
9
#' @param ylim Default `NULL`. The y-axis limits as a vector of two values (min, max). If `NULL`, it calculates the limits from the data.
10
#' @param fill Default `NULL`. A color or palette function to generate the fill palette for the polygons' interiors.
11
#' @param linewidth Default `1`. The linewidth of the polygon.
12
#' @param background Default `"white"`. Background color.
13
#' @param plot_original_polygon Default `TRUE`. Whether to plot the original polygon.
14
#' @param plot_skeleton Default `FALSE`. Whether to plot the straight skeleton.
15
#' @param return_layers Default `FALSE`, plots the figure. If `TRUE`, this will instead
16
#' return a list of the ggplot layers.
17
#' @param ... Additional arguments to pass to `plot_skeleton()` if `plot_skeleton = TRUE`
18
#'
19
#'
20
#' @return A plot showing the offset polygons.
21
#' @export
22
#' @examples
23
#' # Outer polygon
24
#' vertices = matrix(c(0,0, 7,0, 7,7, 0,7, 0,0), ncol = 2, byrow = TRUE)
25
#' # Holes inside the polygon
26
#' hole_1 = matrix(c(1,1, 2,1, 2,2, 1,2, 1,1), ncol = 2, byrow = TRUE)[5:1,]
27
#' hole_2 = matrix(c(5,5, 6,5, 6,6, 5,6, 5,5), ncol = 2, byrow = TRUE)[5:1,]
28
#' skeleton = skeletonize(vertices, holes = list(hole_1, hole_2))
29
#' if(run_docs_raybevel()) {
30
#' plot_skeleton(skeleton)
31
#' }
32
#'
33
#' #Generate three offsets with the skeleton
34
#' if(run_docs_raybevel()) {
35
#' plot_offset_polygon(generate_offset_polygon(skeleton, c(0.25,0.75,1.5,2)), plot_skeleton = TRUE)
36
#' }
37
#' 
38
#' #Generate many offsets
39
#' if(run_docs_raybevel()) {
40
#' plot_offset_polygon(generate_offset_polygon(skeleton, seq(0.05,2.55,by=0.1)))
41
#' }
42
#' 
43
#' #Pass a palette
44
#' if(run_docs_raybevel()) {
45
#' plot_offset_polygon(generate_offset_polygon(skeleton, seq(0.05,2.55,by=0.1)),
46
#'                     color = heat.colors)
47
#' }
48
#' 
49
#' #Pass colors manually (colors in excess of the number of offsets are ignored)
50
#' if(run_docs_raybevel()) {
51
#' plot_offset_polygon(generate_offset_polygon(skeleton, seq(0.05,2.55,by=0.1)),
52
#'                     color = rep(c("red","red","blue","blue"),100))
53
#' }
54
#'
55
#' # Skeletonize and plot an {sf} object
56
#' if(run_docs_raybevel()) {
57
#'   us_states = spData::us_states
58
#'   texas = us_states[us_states$NAME == "Texas",]
59
#'   texas_skeleton = skeletonize(texas)
60
#'   plot_offset_polygon(generate_offset_polygon(texas_skeleton, seq(0, 2.5, by = 0.1)),
61
#'                       color = heat.colors,
62
#'                       linewidth = 1)
63
#' }
64
plot_offset_polygon = function(offset_polygons,
65
                               plot_original_polygon = TRUE,
66
                               fill = NA, color= "dodgerblue", xlim=NULL, ylim=NULL,
67
                               linewidth = 1, background = "white",
68
                               plot_skeleton = FALSE, return_layers = FALSE, ...) {
69
  # Check if ggplot2 package is installed
705x
  if(!(length(find.package("ggplot2", quiet = TRUE)) > 0)) {
71!
    stop("{ggplot2} package required for plot_offset_polygon_ggplot()")
72
  }
73
74
  # Import ggplot2 functions
755x
  ggplot = ggplot2::ggplot
765x
  aes = ggplot2::aes
775x
  geom_polygon = ggplot2::geom_polygon
785x
  theme_void = ggplot2::theme_void
795x
  coord_fixed = ggplot2::coord_fixed
805x
  theme = ggplot2::theme
815x
  element_rect = ggplot2::element_rect
82
835x
  x = y = NULL
84
  # Create an empty ggplot object
85
865x
  p = list()
875x
  if (inherits(offset_polygons, "rayskeleton_polygons")) {
884x
    if(all(is.na(offset_polygons))) {
89!
      stop("No non-NA offset polygons passed.")
90
    }
914x
    max_offsets = max(unlist(lapply(offset_polygons[!is.na(offset_polygons)], length)))
92
93
    # Set color palettes if provided
944x
    n_polygons = max_offsets
954x
    if(is.function(color)) {
96!
      color = color(n_polygons)
974x
    } else if (is.character(color)) {
984x
      if(length(color) == 1) {
994x
        color = rep(color[1], n_polygons)
100
      }
101
    } else {
102!
      color = rep(color[1], n_polygons)
103
    }
104
1054x
    if(is.function(fill)) {
106!
      fill = fill(n_polygons)
1074x
    } else if (is.character(fill)) {
108!
      if(length(fill) == 1) {
109!
        fill = rep(fill[1], n_polygons)
110
      }
111
    } else {
1124x
      fill = rep(fill[1], n_polygons)
113
    }
1144x
    ray_environment$final_polygon = FALSE
1154x
    on.exit({ray_environment$final_polygon = TRUE},
1164x
            add = TRUE)
1174x
    for(ii in seq_len(length(offset_polygons))) {
11871x
      single_skeleton = offset_polygons[[ii]]
11971x
      number_offsets = attr(single_skeleton, "number_offsets")
12071x
      for(j in seq_len(number_offsets)) {
12175x
        single_offset = single_skeleton[[j]]
12275x
        n_polygons = attr(single_offset, "number_polygons")
12375x
        for(i in seq_len(n_polygons)) {
12488x
          if(nrow(single_offset[[i]]) > 0) {
12569x
            poly = single_offset[[i]]
12669x
            colnames(poly) = c("x","y")
12769x
            p[[length(p) + 1]] = geom_polygon(data = data.frame(poly), aes(x = x, y = y),
12869x
                                              fill = fill[j], color = color[j], linewidth = linewidth)
129
          }
130
        }
131
      }
132
    }
1334x
    ray_environment$final_polygon = TRUE
134!
  } else if(!inherits(offset_polygons, "rayskeleton_offset_polygons_collection")) {
135!
    stop(sprintf("`offset_polygons`` must be of class `rayskeleton_polygon` or `rayskeleton_offset_polygons_collection` (object is class `%s`)",
136!
                 class(offset_polygons)))
137
  }
138
1394x
  for(i in seq_len(length(offset_polygons))) {
14071x
    original_vertices = attr(offset_polygons[[i]], "original_vertices")
14171x
    colnames(original_vertices) = c("x","y")
142
    # If skeleton is provided and plot_original_polygon is TRUE, add original polygon and holes to the plot
14371x
    if (plot_original_polygon) {
14471x
      p[[length(p) + 1]] = geom_polygon(data = data.frame(original_vertices),
14571x
                           aes(x = x, y = y), fill = NA, color = "black", linewidth = linewidth)
146
147
      # Plot holes, if they exist
14871x
      original_holes = attr(offset_polygons[[i]], "original_holes")
14971x
      if (!is.null(original_holes)) {
15071x
        for (hole in original_holes) {
151!
          colnames(hole) = c("x","y")
152!
          p[[length(p) + 1]] = geom_polygon(data = data.frame(hole),
153!
                               aes(x = x, y = y), fill = NA, color = "black", linewidth = linewidth)
154
        }
155
      }
156
    }
157
  }
1584x
  if(plot_skeleton) {
159!
    for(i in seq_len(length(offset_polygons))) {
160!
      p[[length(p) + 1]] = plot_skeleton(attr(offset_polygons[[i]], "skeleton"),
161!
                                         return_layers = TRUE,
162
                                         ... )
163
    }
164
  }
165
166
  # Set x and y limits if provided
1674x
  if(ray_environment$final_polygon && !return_layers) {
1684x
    p[[length(p) + 1]] = coord_fixed()
1694x
    p[[length(p) + 1]] = theme_void()
1704x
    p[[length(p) + 1]] = theme(legend.position = "none")
1714x
    if(!is.na(background)) {
1724x
      p[[length(p) + 1]] = theme(plot.background = element_rect(fill = background,
1734x
                                                                color = NA))
174
    }
1754x
    return(ggplot() + p)
176
  } else {
177!
    return(p)
178
  }
179
}
1
#' Generate an offset polygon
2
#'
3
#' This function generates an interior offset polygon from a straight skeleton.
4
#'
5
#' @param skeleton Default `NULL`. A straight skeleton generated from the `skeletonize` function.
6
#' @param offset Default `NULL`. The offset(s) of the polygon.
7
#' @param progress Default `FALSE`. Whether to display a progress bar.
8
#'
9
#' @return A list of data frames, each representing a polygon offset by the specified amount.
10
#'
11
#' @export
12
#' @examples
13
#' # Simple polygon example
14
#' simple_poly = matrix(c(0,0, 3,0, 3,3, 0,3, 0,0), ncol=2, byrow=TRUE)
15
#' skeleton = skeletonize(simple_poly)
16
#' offset_polys = generate_offset_polygon(skeleton, c(0.25, 0.5))
17
#' print(offset_polys)
18
#'
19
#' # Polygon with hole example
20
#' # Outer polygon
21
#' vertices = matrix(c(0,0, 7,0, 7,7, 0,7, 0,0), ncol = 2, byrow = TRUE)
22
#' # Holes inside the polygon
23
#' hole_1 = matrix(c(1,1, 2,1, 2,2, 1,2, 1,1), ncol = 2, byrow = TRUE)[5:1,]
24
#' hole_2 = matrix(c(5,5, 6,5, 6,6, 5,6, 5,5), ncol = 2, byrow = TRUE)[5:1,]
25
#' skeleton = skeletonize(vertices, holes = list(hole_1, hole_2))
26
#' if(run_docs_raybevel()) {
27
#' plot_skeleton(skeleton)
28
#' }
29
#' 
30
#' #Generate three offsets
31
#' if(run_docs_raybevel()) {
32
#' plot_offset_polygon(generate_offset_polygon(skeleton, c(0.25,0.75,1.5,2)))
33
#' }
34
#' 
35
#' #Generate many offsets
36
#' if(run_docs_raybevel()) {
37
#' plot_offset_polygon(generate_offset_polygon(skeleton, seq(0,2.5,by=0.1)+0.05))
38
#' }
39
#' 
40
#' # Skeletonize and plot an {sf} object
41
#' if(run_docs_raybevel()) {
42
#'   us_states = spData::us_states
43
#'   texas = us_states[us_states$NAME == "Texas",]
44
#'   texas_skeleton = skeletonize(texas)
45
#'   plot_offset_polygon(generate_offset_polygon(texas_skeleton, seq(0, 2.5, by = 0.1)),
46
#'                       border = heat.colors,
47
#'                       linewidth = 1)
48
#' }
49
generate_offset_polygon = function(skeleton, offset, progress = FALSE) {
505x
  offset = offset[order(offset)]
515x
  if(inherits(skeleton, "rayskeleton_list")) {
524x
    is_list = TRUE
534x
    max_internal_distance = max(unlist(lapply(skeleton, \(x) max(x$nodes$time))))
54
  } else {
551x
    is_list = FALSE
561x
    max_internal_distance =  max(skeleton$nodes$time)
57
  }
585x
  offset = offset[offset < max_internal_distance]
595x
  if(length(offset) == 0) {
601x
    stop(sprintf("offsets are all greater than maximum internal distance (%f)",max_internal_distance))
61
  }
624x
  poly_list = list()
634x
  if(is_list) {
643x
    for(j in seq_len(length(skeleton))) {
6570x
      poly_list_skeleton = list()
6670x
      for(i in seq_len(length(offset))) {
6774x
        poly_list_skeleton[[i]] = generate_offset_links_nodes(skeleton[[j]], offset[i], return_polys = TRUE,
6874x
                                                              verbose = FALSE, progress = progress)
6974x
        class(poly_list_skeleton[[i]]) = c("rayskeleton_offset_polygons", "list")
7074x
        num_polygons = length(poly_list_skeleton[[i]])
7174x
        attr(poly_list_skeleton[[i]], "number_polygons") = num_polygons
7274x
        offset_len = seq_len(length(num_polygons))
7374x
        names(poly_list_skeleton[[i]]) = sprintf("%s_off%i",offset_len,i)
74
      }
7570x
      class(poly_list_skeleton) = c("rayskeleton_offset_polygons_collection", "list")
7670x
      attr(poly_list_skeleton, "skeleton") = skeleton[[j]]
7770x
      attr(poly_list_skeleton, "number_offsets") = length(offset)
7870x
      attr(poly_list_skeleton, "original_vertices") = attr(skeleton[[j]], "original_vertices")
7970x
      attr(poly_list_skeleton, "original_holes") = attr(skeleton[[j]], "original_holes")
8070x
      poly_list[[j]] = poly_list_skeleton
81
    }
82
  } else {
831x
    poly_list_skeleton = list()
841x
    for(i in seq_len(length(offset))) {
851x
      poly_list_skeleton[[i]] = generate_offset_links_nodes(skeleton, offset[i], return_polys = TRUE,
861x
                                                   verbose = FALSE, progress = progress)
871x
      class(poly_list_skeleton[[i]]) = c("rayskeleton_offset_polygons", "list")
881x
      num_polygons = length(poly_list_skeleton[[i]])
891x
      attr(poly_list_skeleton[[i]], "number_polygons") = num_polygons
901x
      offset_len = seq_len(length(poly_list_skeleton[[i]]))
911x
      names(poly_list_skeleton[[i]]) = sprintf("offset_%f_%i",offset[i],i)
92
    }
931x
    class(poly_list_skeleton) = c("rayskeleton_offset_polygons_collection", "list")
941x
    attr(poly_list_skeleton, "skeleton") = skeleton
951x
    attr(poly_list_skeleton, "number_offsets") = length(offset)
961x
    attr(poly_list_skeleton, "original_vertices") = attr(skeleton, "original_vertices")
971x
    attr(poly_list_skeleton, "original_holes") = attr(skeleton, "original_holes")
981x
    poly_list[[1]] = poly_list_skeleton
99
  }
1004x
  class(poly_list) = c("rayskeleton_polygons", "list")
1014x
  return(poly_list)
102
}
1
#' Identify Local and Global Maxima Nodes
2
#'
3
#' @param straight_skeleton The straight skeleton object.
4
#' @keywords internal
5
#'
6
#' @return Vector containting maxima ids
7
identify_maxima_nodes = function(straight_skeleton) {
8139x
  nodes = straight_skeleton$nodes
9139x
  links = straight_skeleton$links
10
11139x
  local_maxima = list()
12
13139x
  for(i in seq_len(nrow(nodes))) {
149163x
    node_id = nodes[i, 'id']
159163x
    node_time = nodes[i, 'time']
16
17
    # Find neighboring nodes
189163x
    neighbors = c(links[links$source == node_id, 'destination'],
199163x
                  links[links$destination == node_id, 'source'])
20
219163x
    neighbor_times = nodes[nodes$id %in% neighbors, 'time']
22
23
    # Check if the node is a local maximum
249163x
    if(all(node_time >= neighbor_times)) {
25588x
      local_maxima[[i]] = node_id
26
    }
27
  }
28
29139x
  return(unlist(local_maxima))
30
}
1
2
#' Title
3
#'
4
#' @param v1 Vector 1
5
#' @param v2 Vector 2
6
#'
7
#' @return Value
8
#' @keywords internal
9
#'
10
#' @examples
11
#' #None
12
determinant2x2 = function(v1,v2) {
13!
  det(matrix(c(v1,v2), ncol=2,nrow=2))
14
}
15
16
#' Dot Product
17
#'
18
#' @param v1 Vector 1
19
#' @param v2 Vector 2
20
#'
21
#' @return Value
22
#' @keywords internal
23
#'
24
#' @examples
25
#' #None
26
dot = function(v1,v2) {
27!
  sum(v1*v2)
28
}
29
30
#' Dot Product
31
#'
32
#'
33
#' @return Value
34
#' @keywords internal
35
#'
36
#' @examples
37
#' #None
38
unit_vector = function(v) {
39!
  v/sqrt(sum(v*v))
40
}
41
42
43
#' Interpolate Location
44
#'
45
#' @param node_start Length-2 Numeric x/y position
46
#' @param node_end   Length-2 Numeric x/y position
47
#' @param height_start Length-1 Numeric height at start node
48
#' @param height_end   Length-1 Numeric height at end node
49
#' @param height Length-1 Numeric height at which to interpolate
50
#'
51
#' @keywords internal
52
interpolate_location = function(node_start,
53
                                node_end,
54
                                height_start,
55
                                height_end,
56
                                height) {
57!
  if((height_end - height_start) == 0) {
58!
    return(node_end)
59
  }
60!
  if(height == height_end) {
61!
    return(node_end)
62
  }
63!
  if(height == height_start) {
64!
    return(node_start)
65
  }
66!
  t = (height - height_start)/(height_end - height_start)
67!
  return(node_start * (1 - t) + node_end * t)
68
}
1
#' Discretize and Merge Nodes
2
#'
3
#' @keywords internal
4
find_dangling_nodes = function(skeleton) {
5
  # Extract node IDs from links dataframe
6!
  source_nodes = unique(skeleton$links$source)
7!
  destination_nodes = unique(skeleton$links$destination)
8
9
  # Find nodes that don't have any link pointing to them
10!
  nodes_without_incoming_links = setdiff(skeleton$nodes$id, destination_nodes)
11
12
  # Find nodes that don't have any link originating from them
13!
  nodes_without_outgoing_links = setdiff(skeleton$nodes$id, source_nodes)
14
15
  # Combine the two lists and identify unique IDs
16!
  dangling_nodes = unique(c(nodes_without_incoming_links, nodes_without_outgoing_links))
17
18
  # Return the IDs of the dangling nodes
19!
  return(dangling_nodes)
20
}
1
#' Arrange or Reorder Rows of a Data Frame by Columns
2
#'
3
#' This function sorts a data frame based on the provided columns.
4
#'
5
#' @param data A data frame.
6
#' @param ... Column names to determine the sort order.
7
#'
8
#' @return A sorted data frame.
9
#'
10
#' @keywords internal
11
arrange_base = function(data, ...){
12417x
  colnames = as.character(substitute(list(...))[-1])
13417x
  order_args = lapply(colnames, function(col) data[[col]])
14417x
  sorted_indices = do.call(order, order_args)
15417x
  return(data[sorted_indices, ])
16
}
1
#' Extrude Sides of Polygon
2
#'
3
#' @keywords internal
4
swap_yz = function(mesh) {
565x
  for(i in seq_along(mesh$vertices)) {
6171x
    mesh$vertices[[i]] = mesh$vertices[[i]][,c(1,3,2)]
7171x
    mesh$vertices[[i]][,1] = -mesh$vertices[[i]][,1]
8
  }
9
  # for(i in seq_along(mesh$shapes)) {
10
  #   mesh$shapes[[i]]$indices = mesh$shapes[[i]]$indices[,3:1]
11
  #   mesh$shapes[[i]]$norm_indices = mesh$shapes[[i]]$norm_indices[,3:1]
12
  #   mesh$shapes[[i]]$tex_indices = mesh$shapes[[i]]$tex_indices[,3:1]
13
  # }
1465x
  return(mesh)
15
}
1
#' Remove Reversed Links
2
#'
3
#' @keywords internal
4
remove_reversed_links = function(skeleton) {
5
  # Create two new columns: min_id and max_id
6139x
  skeleton$links$min_id = pmin(skeleton$links$source, skeleton$links$destination)
7139x
  skeleton$links$max_id = pmax(skeleton$links$source, skeleton$links$destination)
8
9
  # Identify duplicates based on min_id and max_id
10139x
  dupes = duplicated(skeleton$links[, c("min_id", "max_id")])
11
12
  # Remove the duplicated links
13139x
  skeleton$links = skeleton$links[!dupes, ]
14
15
  # Remove the temporary columns
16139x
  skeleton$links$min_id = NULL
17139x
  skeleton$links$max_id = NULL
18
19139x
  return(skeleton)
20
}
1
ray_environment = new.env(parent = emptyenv())
2
3
.onLoad = function(libname, pkgname) {
4!
  assign("init_time", 0, envir = ray_environment)
5!
  assign("prev_time", 0, envir = ray_environment)
6!
  assign("final_polygon", TRUE, envir = ray_environment)
7
}
1
#include <Rcpp.h>
2
#include <vector>
3
#include <cmath>
4
#include <algorithm>
5
#include <RProgress.h>
6
7
#include "RcppThread.h"
8
#include "math.h"
9
#include <iostream>
10
#include <vector>
11
#include <unordered_set>
12
#include <algorithm>
13
#include <functional>
14
15
using namespace Rcpp;
16
17
// Custom hash function for a vector of integers
187432x
std::size_t vec_hash(const std::vector<int>& vec) {
197432x
  std::size_t seed = vec.size();
2044648x
  for(auto& i : vec) {
2129784x
    seed ^= i + 0x9e3779b9 + (seed << 6) + (seed >> 2);
22
  }
237432x
  return seed;
24
}
25
26
struct Node2 {
27
  int id;
28
  double x;
29
  double y;
30
  double time;
31
  int edge;
32
};
33
34
struct Link2 {
35
  int source;
36
  int destination;
37
  int edge;
38
  double source_time;
39
  double destination_time;
40
  int visited;
41
};
42
43282543x
static std::vector<double> getNodePositionById(const std::vector<Node2>& nodes, int id) {
446564226x
  for(const auto& node : nodes) {
456369608x
    if(node.id == id) {
46866397x
      return {node.x, node.y};
47
    }
48
  }
49-87925x
  return {}; // Empty vector if node ID is not found
50
}
51
52
// Helper function definitions
53
std::vector<double> getNodePositionById(const std::vector<Node2>& nodes, int id);
54
double determinant2x2(const std::vector<double>& v1, const std::vector<double>& v2);
55
double dot(const std::vector<double>& v1, const std::vector<double>& v2);
56
57
// [[Rcpp::export]]
5865x
List convert_ss_to_polygons_rcpp(List ss, int numbercores, bool progress) {
5965x
  if(numbercores == NA_INTEGER || numbercores < 1) {
60!
    numbercores = 1;
61
  }
62
63130x
  List nodesDF = ss["nodes"];
64130x
  List linksDF = ss["links"];
65
66
67
  // Convert nodes to C++ vector of structs
68130x
  IntegerVector node_ids = nodesDF["id"];
69130x
  NumericVector node_x = nodesDF["x"];
70130x
  NumericVector node_y = nodesDF["y"];
71130x
  NumericVector node_time = nodesDF["time"];
7265x
  LogicalVector node_edge = nodesDF["edge"];
73
7465x
  std::vector<Node2> nodes;
753846x
  for(int i = 0; i < static_cast<int>(node_ids.size()); ++i) {
763781x
    Node2 n = {node_ids[i], node_x[i], node_y[i], node_time[i], node_edge[i]};
773781x
    nodes.push_back(n);
78
  }
79
80
  // Convert links to C++ vector of structs
81130x
  IntegerVector link_source = linksDF["source"];
82130x
  IntegerVector link_dest = linksDF["destination"];
83130x
  LogicalVector link_edge = linksDF["edge"];
84130x
  NumericVector link_source_time = linksDF["source_time"];
8565x
  NumericVector link_dest_time = linksDF["destination_time"];
86
8765x
  std::vector<Link2> links;
887497x
  for(int i = 0; i < static_cast<int>(link_source.size()); ++i) {
897432x
    Link2 l = {link_source[i], link_dest[i], link_edge[i], link_source_time[i], link_dest_time[i], false};
907432x
    links.push_back(l);
91
  }
9265x
  RcppThread::ProgressCounter pb(link_source.size(), 1, "Polygonizing: ");
9365x
  std::vector<std::vector<int>> list_all_polygons;
9465x
  list_all_polygons.resize(links.size());
95
  // for(int k = 0; k< links.size(); k++) {
9665x
  RcppThread::parallelFor(static_cast<size_t>(0), links.size(), [&links, &nodes, &list_all_polygons, &pb, &progress] (size_t k) {
977390x
    bool first = true;
987390x
    int first_node = links[k].source;
997392x
    int tmp_source = first_node;
1007392x
    int first_dest = links[k].destination;
1017392x
    int tmp_dest = first_dest;
1027392x
    std::vector<int> single_polygon_indices;
103
104
    while(true) {
10537019x
      if(tmp_source == first_node && tmp_dest == first_dest && !first) {
1067426x
        break;
107
      }
10829593x
      first = false;
109
11029593x
      std::vector<double> node1_position = getNodePositionById(nodes, tmp_source);
11129506x
      std::vector<double> node2_position = getNodePositionById(nodes, tmp_dest);
112
11329503x
      std::vector<double> node1_position_first = getNodePositionById(nodes, first_node);
11429493x
      std::vector<double> node2_position_first = getNodePositionById(nodes, first_dest);
115
116
      // RcppThread::Rcout << first_node << " " << tmp_source << " " << first_dest << " " << tmp_dest << "\n";
117
      // RcppThread::Rcout << node1_position_first[0] << " " << node1_position_first[1] << " " <<
118
      //   node1_position[0] << " " << node1_position[1] << " | " << node2_position_first[0] << " " << node2_position_first[1] << " " <<
119
      //     node2_position[0] << " " << node2_position[1] <<"\n";
120
121
122
      // Calculate the direction vector v1 for the current link
12359126x
      std::vector<double> v1 = {node2_position[0] - node1_position[0], node2_position[1] - node1_position[1]};
124
12529562x
      double best_angle = 180.0;
12629562x
      int best_dest = -1;
12729562x
      int best_source = -1;
12829562x
      double best_len = std::numeric_limits<double>::infinity();
129
130
      // Loop over all candidate next links
1312947309x
      for(const auto& link : links) {
1322878059x
        if((link.destination == tmp_dest && link.source == tmp_source) ||
1332861483x
           (link.source == tmp_dest && link.destination == tmp_source)) {
1342832261x
          continue;
135
        }
136
1372848378x
        if(link.source != tmp_dest && link.destination != tmp_dest) {
1382802580x
          continue;
139
        }
140
141
        int candidate_source, candidate_dest;
14245798x
        if(link.destination == tmp_dest) {
14343486x
          candidate_source = link.destination;
14443486x
          candidate_dest = link.source;
145
        } else {
1462312x
          candidate_source = link.source;
1472312x
          candidate_dest = link.destination;
148
        }
149
150
        // Calculate the direction vector v2 for the candidate link
15145798x
        std::vector<double> cs_position = getNodePositionById(nodes, candidate_source);
15288734x
        std::vector<double> cd_position = getNodePositionById(nodes, candidate_dest);
153179468x
        std::vector<double> v2 = {cd_position[0] - cs_position[0], cd_position[1] - cs_position[1]};
154
155
        // Calculate angle between v1 and v2
15689343x
        double det_val = determinant2x2(v1, v2);
15790102x
        double dot_val = dot(v1, v2);
15890000x
        double angle = std::atan2(det_val, dot_val) * 180.0 / M_PI;
159
160
        // Check if this angle is the smallest so far
16190000x
        double length_v2 = dot(v2, v2);
16290251x
        if((angle < best_angle) || (angle == best_angle && best_len > length_v2)) {
16353450x
          best_angle = angle;
164
16553450x
          best_dest = candidate_dest;
16653450x
          best_source = candidate_source;
16753450x
          best_len = length_v2;
168
        }
169
      }
17039688x
      if(best_source < 0 || best_dest < 0) {
1719978x
        throw std::runtime_error("Didn't find candidate");
172
      }
173
174
      // Update tmp_source and tmp_dest for the next iteration
17529710x
      tmp_source = best_source;
17629710x
      tmp_dest = best_dest;
17729710x
      single_polygon_indices.push_back(best_dest);
178
    }
1797426x
    if(progress) {
180!
      pb++;
181
    }
1827426x
    list_all_polygons[k] = single_polygon_indices;
1837411x
  }, static_cast<size_t>(numbercores));
184
  // }
185
186
  // Here I'm doing the sorting and hashing in C++
18765x
  std::unordered_map<std::size_t, bool> seen_hashes;
18865x
  std::vector<std::vector<int>> unique_polygons;
189
1907562x
  for (const auto& polygon : list_all_polygons) {
1917432x
    std::vector<int> sorted_polygon = polygon;
1927432x
    std::sort(sorted_polygon.begin(), sorted_polygon.end());
1937432x
    std::size_t hash = vec_hash(sorted_polygon);
194
1957432x
    if (seen_hashes.find(hash) == seen_hashes.end()) {
196
      // This is a unique polygon, save it and mark it as seen
1973588x
      unique_polygons.push_back(polygon);
1983588x
      seen_hashes[hash] = true;
199
    }
200
  }
201
20265x
  List all_polygons;
2033653x
  for(int i = 0; i < static_cast<int>(unique_polygons.size()); i++) {
2043588x
    IntegerVector one_polygon;
20517680x
    for(int j = 0; j < static_cast<int>(unique_polygons[i].size()); j++) {
20614092x
      one_polygon.push_back(unique_polygons[i][j]);
207
    }
2083588x
    all_polygons.push_back(one_polygon);
209
  }
210
21165x
  return all_polygons;
212
}
1
#include <Rcpp.h>
2
#include <vector>
3
#include <cmath>
4
#include "math.h"
5
#include "RProgress.h"
6
7
using namespace Rcpp;
8
9
struct Node {
10
  int id;
11
  double x;
12
  double y;
13
  double time;
14
  int edge;
15
  int local_maxima;
16
};
17
18
struct Link {
19
  int source;
20
  int destination;
21
  int edge;
22
  int maxima_source;
23
  int maxima_dest;
24
  int visited;
25
  double source_time;
26
  double destination_time;
27
};
28
29
struct NewNode {
30
  int polygon_id;
31
  int source;
32
  int destination;
33
  int new_id;
34
  double x;
35
  double y;
36
  double time;
37
  double x1;
38
  double y1;
39
  double x2;
40
  double y2;
41
  int new_node;
42
};
43
4497034x
static std::vector<double> getNodePositionById(const std::vector<Node>& nodes, int id) {
457638791x
  for(const auto& node : nodes) {
467541757x
    if(node.id == id) {
47291102x
      return {node.x, node.y};
48
    }
49
  }
50!
  return {}; // Empty vector if node ID is not found
51
}
52
5338314x
double getNodeTimeById(const std::vector<Node>& nodes, int id) {
542938832x
  for(const auto& node : nodes) {
552900518x
    if(node.id == id) {
5638314x
      return node.time;
57
    }
58
  }
59!
  return -1; // Empty vector if node ID is not found
60
}
61
62
// Convert DataFrame to std::vector of Nodes
63120x
std::vector<Node> convertDataFrameToNodes(DataFrame df) {
64120x
  size_t nrows = df.nrow();
65240x
  IntegerVector id = Rcpp::as<IntegerVector>(df["id"]);
66240x
  NumericVector x = Rcpp::as<NumericVector>(df["x"]);
67240x
  NumericVector y = Rcpp::as<NumericVector>(df["y"]);
68240x
  NumericVector time = Rcpp::as<NumericVector>(df["time"]);
69240x
  IntegerVector edge = Rcpp::as<IntegerVector>(df["edge"]);
70240x
  IntegerVector maxima = Rcpp::as<IntegerVector>(df["local_maxima"]);
71
72120x
  std::vector<Node> nodes;
73120x
  nodes.resize(nrows);
749013x
  for (size_t i = 0; i < nrows; ++i) {
758893x
    nodes[i].id = id(i);
768893x
    nodes[i].x = x(i);
778893x
    nodes[i].y = y(i);
788893x
    nodes[i].time = time(i);
798893x
    nodes[i].edge = edge(i);
808893x
    nodes[i].local_maxima = maxima(i);
81
  }
82120x
  return nodes;
83
}
84
855226x
std::vector<double> interpolate_location(const std::vector<double>& node_start,
86
                                         const std::vector<double>& node_end,
87
                                         double height_start,
88
                                         double height_end,
89
                                         double height) {
90
  // Initialize result vector
915226x
  std::vector<double> result(2, 0.0);
92
93
  // Handling edge cases
945226x
  if (height_end - height_start == 0.0) {
95!
    return node_end;
96
  }
975226x
  if (height == height_end) {
98!
    return node_end;
99
  }
1005226x
  if (height == height_start) {
101!
    return node_start;
102
  }
103
104
  // Calculate interpolation factor t
1055226x
  double t = (height - height_start) / (height_end - height_start);
106
107
  // Perform the interpolation
1085226x
  result[0] = node_start[0] * (1 - t) + node_end[0] * t;
1095226x
  result[1] = node_start[1] * (1 - t) + node_end[1] * t;
110
1115226x
  return result;
112
}
113
114
// Convert DataFrame to std::vector of Links
115120x
std::vector<Link> convertDataFrameToLinks(DataFrame df) {
116120x
  size_t nrows = df.nrow();
117240x
  IntegerVector source = Rcpp::as<IntegerVector>(df["source"]);
118240x
  IntegerVector destination = Rcpp::as<IntegerVector>(df["destination"]);
119240x
  LogicalVector edge = Rcpp::as<LogicalVector>(df["edge"]);
120240x
  NumericVector source_time = Rcpp::as<NumericVector>(df["source_time"]);
121240x
  NumericVector destination_time = Rcpp::as<NumericVector>(df["destination_time"]);
122240x
  LogicalVector local_maxima_destination = Rcpp::as<LogicalVector>(df["local_maxima_destination"]);
123240x
  LogicalVector local_maxima_source = Rcpp::as<LogicalVector>(df["local_maxima_source"]);
124
125120x
  std::vector<Link> links;
126120x
  links.resize(nrows);
127
12813620x
  for (size_t i = 0; i < nrows; ++i) {
12913500x
    links[i].source = (int)source(i);
13013500x
    links[i].destination = (int)destination(i);
13113500x
    links[i].edge = (int)edge(i);
13213500x
    links[i].source_time = (double)source_time(i);
13313500x
    links[i].destination_time = (double)destination_time(i);
13413500x
    links[i].maxima_source = (int)local_maxima_source(i);
13513500x
    links[i].maxima_dest = (int)local_maxima_destination(i);
13613500x
    links[i].visited = (int)0;
137
  }
138120x
  return links;
139
}
140
141
// [[Rcpp::export]]
142120x
List generate_offset_links_nodes_rcpp(DataFrame ss_links, DataFrame ss_nodes, NumericVector offsets, bool return_polys = false, bool progress = false) {
143
144120x
  std::vector<Link> links = convertDataFrameToLinks(ss_links);
145120x
  std::vector<Node> nodes = convertDataFrameToNodes(ss_nodes);
146
147120x
  int max_node = -1;
1489013x
  for(size_t ii = 0; ii < (size_t)nodes.size(); ii++) {
1498893x
    max_node = std::max(nodes[ii].id,max_node);
150
  }
151120x
  int new_node_start = max_node + 1;
152
153120x
  List return_data;
154
155
  // Initialize containers for new links and nodes
156120x
  std::vector<Link> newLinks;
157120x
  std::vector<Node> newNodes;
158
159
  // Main loop to iterate over offsets
160240x
  RProgress::RProgress pb("Inserting links: :percent (:eta remaining)");
161120x
  if(progress) {
162!
   pb.set_total(offsets.size());
163!
   pb.tick(0);
164
  }
165496x
  for(size_t ii = 0; ii < (size_t)offsets.size(); ++ii) {
166376x
    if(progress) {
167!
      pb.tick(ii);
168
    }
169376x
    double offset = offsets[ii];
170752x
    std::vector<bool> visited(links.size());
171752x
    std::vector<bool> away_from_offset(links.size());
172376x
    std::vector<bool> equal_to_offset(links.size());
173376x
    std::vector<NewNode> new_node_info;
174
17522580x
    for(size_t jj = 0; jj < links.size(); jj++) {
17622204x
      visited[jj] = (bool)links[jj].edge;
17732513x
      away_from_offset[jj] = (links[jj].source_time < offset && links[jj].destination_time < offset) ||
17832513x
                             (links[jj].source_time > offset && links[jj].destination_time > offset);
17922204x
      equal_to_offset[jj] = links[jj].source_time == offset;
180
    }
181
182376x
    int first_node = -1;
183376x
    int first_dest = -1;
184376x
    int tmp_source = -1;
185376x
    int tmp_dest = -1;
186376x
    int num_polygons = 1;
187376x
    bool first = true;
188376x
    bool any_picked = false;
189376x
    bool new_poly = true;
190
19113482x
    for(size_t jj = 0; jj < links.size(); jj++) {
19213482x
      if(links[jj].maxima_dest && links[jj].destination_time >= offset) {
193376x
        first_node = links[jj].source;
194376x
        first_dest = links[jj].destination;
195376x
        tmp_source = first_node;
196376x
        tmp_dest = first_dest;
197376x
        break;
198
      }
199
    }
200
201
    while(true) {
20219401x
      Rcpp::checkUserInterrupt();
203
      // if(tmp_source == first_node && tmp_dest == first_dest && !first) {
204
      //   break;
205
      // }
20619401x
      std::vector<Link> non_visited_links;
2073234453x
      for(size_t jj = 0; jj < links.size(); ++jj) {
2083215052x
        if(!visited[jj]) {
2091220830x
          non_visited_links.push_back(links[jj]);
210
        }
2113215052x
        if(non_visited_links.size() > links.size()) {
212!
          throw std::runtime_error("Memory corruption");
213
        }
214
      }
21519401x
      std::vector<Link> remaining_links;
21619401x
      if(!first || any_picked) {
21719025x
        if(tmp_source < 0 || tmp_dest < 0) {
218!
          throw std::runtime_error("Bug or malformed input: next node not found");
219
        }
22019025x
        if(tmp_source == first_node && tmp_dest == first_dest) {
2211217x
          new_poly = true;
22254850x
          for(size_t jj = 0; jj < links.size(); ++jj) {
22353633x
            if(!visited[jj] && !away_from_offset[jj] && !links[jj].edge) {
22410561x
              remaining_links.push_back(links[jj]);
225
            }
226
          }
2271217x
          if(remaining_links.size() == 0) {
228244x
            break;
229
          }
230973x
          first_node = remaining_links[0].source;
231973x
          first_dest = remaining_links[0].destination;
232973x
          tmp_source = first_node;
233973x
          tmp_dest = first_dest;
234973x
          num_polygons++;
235
        }
236
      }
237
      // size_t remaining_links_count = std::count_if(visited.begin(), visited.end(), [](bool l) { return !l; });
238
23919157x
      first = false;
240
24119157x
      std::vector<double> node1_position = getNodePositionById(nodes, tmp_source);
24219157x
      std::vector<double> node2_position = getNodePositionById(nodes, tmp_dest);
24319157x
      double node1_time = getNodeTimeById(nodes, tmp_source);
24419157x
      double node2_time = getNodeTimeById(nodes, tmp_dest);
245
2463216828x
      for(size_t jj = 0; jj < links.size(); jj++) {
2473197671x
        if((links[jj].source == tmp_source &&
2486385390x
            links[jj].destination == tmp_dest) ||
2493187719x
           (links[jj].destination == tmp_source &&
25038688x
            links[jj].source == tmp_dest)) {
25119157x
          visited[jj] = true;
252
        }
253
      }
25419157x
      std::vector<double> node_position_new;
25519157x
      if(offset >= node1_time && offset < node2_time) {
2565717x
        if(new_poly) {
257645x
          first_node = tmp_source;
258645x
          first_dest = tmp_dest;
259
        }
260
        int node_val;
2615717x
        bool make_new_node = true;
2625717x
        if(node1_time == offset) {
263491x
          make_new_node = false;
264491x
          node_position_new = node1_position;
265491x
          node_val = tmp_source;
2665226x
        } else if (node2_time == offset) {
267!
          make_new_node = false;
268!
          node_position_new = node2_position;
269!
          node_val = tmp_dest;
270
        } else {
27110452x
          node_position_new = interpolate_location(node1_position,node2_position,
2725226x
                                                   node1_time,node2_time,offset);
2735226x
          node_val = new_node_start;
274
        }
275
276
        NewNode new_node = {num_polygons, tmp_source, tmp_dest, node_val,
27711434x
                            node_position_new[0], node_position_new[1],
27811434x
                            offset, node1_position[0], node1_position[1],
27911434x
                            node2_position[0],node2_position[1],
2805717x
                            make_new_node};
2815717x
        new_node_info.push_back(new_node);
282
2835717x
        if(make_new_node) {
2845226x
          new_node_start++;
285
        }
2865717x
        new_poly = false;
287
      } else {
28813440x
        if(new_poly) {
289751x
          first_node = tmp_source;
290751x
          first_dest = tmp_dest;
291
        }
292
      }
293
294
      // bool all_remaining_at_offset = true;
295
      // for(int jj = 0; jj < non_visited_links.size(); jj++) {
296
      //   if(((non_visited_links[jj].destination_time == offset && non_visited_links[jj].maxima_dest) ||
297
      //      (non_visited_links[jj].source_time == offset && non_visited_links[jj].maxima_source)) &&
298
      //      new_poly) {
299
      //     Rcpp::Rcout << "All remaining offset \n";
300
      //   } else {
301
      //     all_remaining_at_offset = false;
302
      //   }
303
      // }
304
      // if(all_remaining_at_offset) {
305
      //   break;
306
      // }
307
30819157x
      bool is_edge = false;
3092137631x
      for(size_t jj = 0; jj < nodes.size(); jj++) {
3102118474x
        if(nodes[jj].id == tmp_dest) {
31119157x
          is_edge = nodes[jj].edge;
312
        }
313
      }
314
      // Rcpp::Rcout << offset << " " << node1_time << " " << node2_time << " " <<
315
      //   first_node << " " << first_dest << " " << tmp_source << " " << tmp_dest << " " << remaining_links_count << " " <<
316
      //     is_edge << " " << bool((node1_time - offset) == 0) <<  " " << bool((node2_time - offset) == 0) << "\n";
317
      // Rcpp::Rcout << tmp_source << " " << tmp_dest << " " << offset << " " <<
318
      //   remaining_links_count << "\n";
319
      //
32019157x
      if((offset < node1_time && offset >= node2_time) ||
321
          is_edge) {
3225663x
        int new_source = tmp_dest;
3235663x
        int new_dest = tmp_source;
3245663x
        tmp_source = new_source;
3255663x
        tmp_dest = new_dest;
3265663x
        continue;
327
      }
328
329
      // Calculate the direction vector v1 for the current link
33026988x
      std::vector<double> v1 = {node2_position[0] - node1_position[0], node2_position[1] - node1_position[1]};
331
33213494x
      double best_angle = 180.0;
33313494x
      int best_dest = -1;
33413494x
      int best_source = -1;
33513494x
      double best_len = std::numeric_limits<double>::infinity();
33613494x
      any_picked = false;
337
338
      // Loop over all candidate next links
3392376203x
      for(const auto& link : links) {
3402349215x
        if((link.destination == tmp_dest && link.source == tmp_source) ||
3412339263x
           (link.source == tmp_dest && link.destination == tmp_source)) {
3422319855x
          continue;
343
        }
344
3452335721x
        if(link.source != tmp_dest && link.destination != tmp_dest) {
3462304569x
          continue;
347
        }
348
34931152x
        if(link.edge) {
350!
          continue;
351
        }
35231152x
        if(node2_time == offset) {
3531792x
          if(!(tmp_dest == link.source && link.destination_time >= offset) ||
3541024x
             !(tmp_dest == link.destination && link.source_time >= offset)) {
3551792x
            continue;
356
          }
357
        }
358
        // if(node2_time == offset) {
359
        //   if((tmp_dest == link.source && link.destination_time >= offset) ||
360
        //      (tmp_dest == link.destination && link.source_time >= offset)) {
361
        //     continue;
362
        //   }
363
        // }
36429360x
        if(link.destination == tmp_dest && link.maxima_dest && link.destination_time == offset) {
365!
          continue;
366
        }
36729360x
        if(tmp_dest == link.source && link.maxima_source && link.source_time == offset) {
368!
          continue;
369
        }
37029360x
        any_picked = true;
371
372
        int candidate_source, candidate_dest;
37329360x
        if(link.destination == tmp_dest) {
37421670x
          candidate_source = link.destination;
37521670x
          candidate_dest = link.source;
376
        } else {
3777690x
          candidate_source = link.source;
3787690x
          candidate_dest = link.destination;
379
        }
380
381
        // Calculate the direction vector v2 for the candidate link
38229360x
        std::vector<double> cs_position = getNodePositionById(nodes, candidate_source);
38329360x
        std::vector<double> cd_position = getNodePositionById(nodes, candidate_dest);
38458720x
        std::vector<double> v2 = {cd_position[0] - cs_position[0], cd_position[1] - cs_position[1]};
385
386
        // Calculate angle between v1 and v2
38729360x
        double det_val = determinant2x2(v1, v2);
38829360x
        double dot_val = dot(v1, v2);
38929360x
        double angle = std::atan2(det_val, dot_val) * 180.0 / M_PI;
390
391
        // Check if this angle is the smallest so far
39229360x
        double length_v2 = dot(v2, v2);
39329360x
        if((angle < best_angle) || (angle == best_angle && best_len > length_v2)) {
39420566x
          best_angle = angle;
395
39620566x
          best_dest = candidate_dest;
39720566x
          best_source = candidate_source;
39820566x
          best_len = length_v2;
399
        }
400
      }
40113494x
      if(any_picked) {
40212790x
        tmp_source = best_source;
40312790x
        tmp_dest = best_dest;
404
      }
40513494x
      bool all_remaining_at_offset = true;
406910211x
      for(size_t jj = 0; jj < non_visited_links.size(); jj++) {
407905101x
        if(((non_visited_links[jj].destination_time == offset && non_visited_links[jj].maxima_dest) ||
408905101x
           (non_visited_links[jj].source_time == offset && non_visited_links[jj].maxima_source)) &&
409
           new_poly) {
410
          // Rcpp::Rcout << "All remaining offset \n";
411
        } else {
412893581x
          all_remaining_at_offset = false;
413
        }
414
      }
41513494x
      if(all_remaining_at_offset) {
416132x
        break;
417
      }
418
      // if(best_source < 0 || best_dest < 0) {
419
      //   throw std::runtime_error("Didn't find candidate");
420
      // }
421
    }
422376x
    List single_offset_nodes;
4236093x
    for(size_t jj = 0; jj < new_node_info.size(); jj++) {
4245717x
      NewNode& x = new_node_info[jj];
4255717x
      NumericVector node_data = {(double)x.polygon_id,
4265717x
                                 (double)x.source,
4275717x
                                 (double)x.destination,
4285717x
                                 (double)x.new_id,
4295717x
                                 x.x,
4305717x
                                 x.y,
4315717x
                                 x.time,
4325717x
                                 x.x1,
4335717x
                                 x.y1,
4345717x
                                 x.x2,
4355717x
                                 x.y2,
4365717x
                                 (double)x.new_node};
4375717x
      single_offset_nodes.push_back(node_data);
438
    }
439376x
    return_data.push_back(single_offset_nodes);
440
  }
441120x
  return(return_data);
442
}
1
#include "math.h"
2
3
// Helper function to calculate determinant of two 2D vectors
4118640x
double determinant2x2(const std::vector<double>& v1, const std::vector<double>& v2) {
5118640x
  return v1[0] * v2[1] - v1[1] * v2[0];
6
}
7
8
// Helper function to calculate dot product of two 2D vectors
9237643x
double dot(const std::vector<double>& v1, const std::vector<double>& v2) {
10237643x
  return v1[0] * v2[0] + v1[1] * v2[1];
11
}
1
#include <Rcpp.h>
2
using namespace Rcpp;
3
4
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
5
#include <CGAL/Polygon_2.h>
6
#include <CGAL/Polygon_with_holes_2.h>
7
#include <CGAL/Polygon_set_2.h>
8
#include <CGAL/create_straight_skeleton_from_polygon_with_holes_2.h>
9
#include <CGAL/create_offset_polygons_2.h>
10
#include <CGAL/Boolean_set_operations_2/Gps_polygon_validation.h>
11
#include <CGAL/Boolean_set_operations_2.h>
12
#include <CGAL/General_polygon_set_2.h>
13
#include "print.h"
14
#include <vector>
15
#include <cassert>
16
17
18
#define is_inside(os) ((os == CGAL::ON_ORIENTED_BOUNDARY) ? true :  \
19
(os == CGAL::POSITIVE) ? true : false)
20
21
typedef CGAL::Exact_predicates_inexact_constructions_kernel K ;
22
typedef K::Point_2                   Point ;
23
typedef CGAL::Polygon_2<K>           Polygon_2 ;
24
// typedef CGAL::Polygon_set_2<K>       PolygonSet;
25
typedef CGAL::Straight_skeleton_2<K> Ss ;
26
typedef std::shared_ptr<Polygon_2> PolygonPtr ;
27
typedef std::shared_ptr<Ss> SsPtr ;
28
typedef std::vector<PolygonPtr> PolygonPtrVector ;
29
typedef CGAL::Polygon_with_holes_2<K> Polygon_with_holes ;
30
typedef CGAL::Gps_segment_traits_2<K> Traits_2;
31
32
33
typedef typename Ss::Vertex_const_handle     Vertex_const_handle ;
34
typedef typename Ss::Halfedge_const_handle   Halfedge_const_handle ;
35
typedef typename Ss::Halfedge_const_iterator Halfedge_const_iterator ;
36
37
// [[Rcpp::export]]
38278x
bool is_ccw_polygon(NumericMatrix vertices) {
39278x
  Polygon_2 base_poly;
4014874x
  for(int i = 0; i < vertices.rows(); i++) {
4114596x
    base_poly.push_back(Point(vertices(i,0),vertices(i,1)));
42
  }
43278x
  if(base_poly.is_counterclockwise_oriented()) {
44139x
    return(true);
45
  } else {
46139x
    return(false);
47
  }
48
}
49
50
// [[Rcpp::export]]
512x
bool is_simple_polygon(NumericMatrix vertices) {
522x
  Polygon_2 base_poly;
5310x
  for(int i = 0; i < vertices.rows(); i++) {
548x
    base_poly.push_back(Point(vertices(i,0),vertices(i,1)));
55
  }
562x
  if(base_poly.is_simple()) {
572x
    return(true);
58
  } else {
59!
    return(false);
60
  }
61
}
62
63
// [[Rcpp::export]]
64139x
List skeletonize_rcpp(NumericMatrix vertices,
65
                      List holes,
66
                      double offset) {
67139x
  Polygon_2 base_poly;
687437x
  for(int i = 0; i < vertices.rows(); i++) {
69
    // Rcpp::Rcout << "Vert: " << vertices(i,0) << " " << vertices(i,1) << "\n";
70
717298x
    base_poly.push_back(Point(vertices(i,0),vertices(i,1)));
72
  }
73139x
  if(!base_poly.is_counterclockwise_oriented()) {
74!
    throw std::runtime_error("raybevel: Polygon is not CCW oriented.");
75
  }
76139x
  if(!base_poly.is_simple()) {
77!
    throw std::runtime_error("raybevel: Polygon is not simple.");
78
  }
79139x
  Polygon_with_holes poly(base_poly);
80
81141x
  for(int i = 0; i < holes.length(); i++) {
822x
    Polygon_2 new_hole;
832x
    bool all_inside = true;
842x
    NumericMatrix hole = Rcpp::as<NumericMatrix>(holes(i));
8510x
    for(int i = 0; i < hole.rows(); i++) {
868x
      Point tmp_point(hole(i,0),hole(i,1));
878x
      if(!is_inside(base_poly.oriented_side(tmp_point))) {
88!
        all_inside = false;
89!
        break;
90
      }
918x
      new_hole.push_back(tmp_point);
92
    }
932x
    if(all_inside) {
94
      // if(!new_hole.is_clockwise_oriented()) {
95
      //   throw std::runtime_error("rayskeleton: Hole in polygon is not CW oriented.");
96
      // }
97
      // if(!new_hole.is_simple()) {
98
      //   throw std::runtime_error("rayskeleton: Hole in polygon is not simple.");
99
      // }
1002x
      poly.add_hole(new_hole);
101
    }
102
  }
103
  // auto trait = PolygonSet::Traits_2();
104
  // Traits_2 trait_val;
105
  // if(!is_closed_polygon_with_holes(poly, trait_val)) {
106
  //   throw std::runtime_error("rayskeleton: Isn't closed polygon with holes.");
107
  // }
108
  //
109
  // if(!has_valid_orientation_polygon_with_holes(poly, trait_val)) {
110
  //   throw std::runtime_error("rayskeleton: Polygon doesn't have valid orientation.");
111
  // }
112
  // if(!are_holes_and_boundary_pairwise_disjoint(poly, trait_val)) {
113
  //   throw std::runtime_error("rayskeleton: Holes either intersect themselves or intersect with the outer boundary.");
114
  // }
115
116139x
  SsPtr ss;
117
  try {
118139x
    ss = CGAL::create_interior_straight_skeleton_2(poly);
119!
  } catch (...) {
120!
    throw std::runtime_error("unknown cgal error occurred");
121
  };
122
  // double lOffset = offset ;
123
124
  // int contours = 0;
125139x
  int bisectors = 0;
126
127
12843141x
  for (Halfedge_const_iterator i = ss->halfedges_begin(); i != ss->halfedges_end(); ++i ) {
12943002x
    if(!i->is_border()) {
13035696x
      bisectors++;
131
    }
132
  }
133139x
  List bisector_list(bisectors);
134139x
  int bis_cntr = 0;
135
13643141x
  for (Halfedge_const_iterator i = ss->halfedges_begin(); i != ss->halfedges_end(); ++i ) {
13743002x
    if(!i->is_border()) {
138
      NumericVector temp = Rcpp::NumericVector::create(
13935696x
        i->vertex()->point().x(),
14035696x
        i->vertex()->point().y(),
14135696x
        i->opposite()->vertex()->point().x(),
14235696x
        i->opposite()->vertex()->point().y(),
14335696x
        i->vertex()->time(),
14435696x
        i->opposite()->vertex()->time(),
14535696x
        i->vertex()->id(),
14635696x
        i->opposite()->vertex()->id()
147
      );
14835696x
      bisector_list(bis_cntr) = temp;
14935696x
      bis_cntr++;
150
    }
151
  }
152
153139x
  List all_data = List::create(_["bisectors"] = bisector_list);
154139x
  return(all_data);
155
}