|
src/ |
1948 | 1001 | 0 | 1001 | 0.0 | 0.00% |
|
src/ |
306 | 176 | 0 | 176 | 0.0 | 0.00% |
|
src/ |
270 | 151 | 0 | 151 | 0.0 | 0.00% |
|
src/ |
177 | 116 | 0 | 116 | 0.0 | 0.00% |
|
R/ |
212 | 111 | 0 | 111 | 0.0 | 0.00% |
|
src/ |
217 | 69 | 0 | 69 | 0.0 | 0.00% |
|
R/ |
252 | 48 | 0 | 48 | 0.0 | 0.00% |
|
src/ |
74 | 46 | 0 | 46 | 0.0 | 0.00% |
|
R/ |
48 | 40 | 0 | 40 | 0.0 | 0.00% |
|
R/ |
87 | 35 | 0 | 35 | 0.0 | 0.00% |
|
R/ |
52 | 30 | 0 | 30 | 0.0 | 0.00% |
|
src/ |
792 | 16 | 0 | 16 | 0.0 | 0.00% |
|
src/ |
601 | 11 | 0 | 11 | 0.0 | 0.00% |
|
R/ |
32 | 9 | 0 | 9 | 0.0 | 0.00% |
|
src/ |
12 | 7 | 0 | 7 | 0.0 | 0.00% |
|
R/ |
19 | 5 | 0 | 5 | 0.0 | 0.00% |
|
src/ |
12 | 5 | 0 | 5 | 0.0 | 0.00% |
|
R/ |
21 | 3 | 0 | 3 | 0.0 | 0.00% |
|
src/ |
297 | 2 | 0 | 2 | 0.0 | 0.00% |
|
src/ |
162 | 2 | 0 | 2 | 0.0 | 0.00% |
|
R/ |
921 | 537 | 6 | 531 | 3.5 | 1.12% |
|
R/ |
84 | 43 | 1 | 42 | 0.3 | 2.33% |
|
src/ |
105 | 71 | 5 | 66 | 56295.6 | 7.04% |
|
src/ |
2143 | 1424 | 117 | 1307 | 74985.0 | 8.22% |
|
src/ |
1167 | 229 | 21 | 208 | 41894.7 | 9.17% |
|
R/ |
1270 | 459 | 79 | 380 | 0.3 | 17.21% |
|
R/ |
315 | 97 | 25 | 72 | 134.8 | 25.77% |
|
R/ |
504 | 209 | 60 | 149 | 30.9 | 28.71% |
|
src/ |
811 | 378 | 125 | 253 | 65.4 | 33.07% |
|
R/ |
158 | 57 | 20 | 37 | 58.6 | 35.09% |
|
R/ |
95 | 49 | 22 | 27 | 0.4 | 44.90% |
|
R/ |
168 | 71 | 32 | 39 | 1.8 | 45.07% |
|
R/ |
90 | 54 | 25 | 29 | 0.5 | 46.30% |
|
src/ |
80 | 54 | 26 | 28 | 21780.4 | 48.15% |
|
src/ |
398 | 89 | 43 | 46 | 13.3 | 48.31% |
|
R/ |
174 | 35 | 17 | 18 | 2.4 | 48.57% |
|
src/ |
111 | 64 | 34 | 30 | 29.4 | 53.12% |
|
src/ |
1638 | 783 | 444 | 339 | 30259.0 | 56.70% |
|
src/ |
3406 | 1346 | 779 | 567 | 4822.5 | 57.88% |
|
R/ |
77 | 17 | 10 | 7 | 1.2 | 58.82% |
|
R/ |
701 | 390 | 238 | 152 | 3.2 | 61.03% |
|
R/ |
350 | 225 | 140 | 85 | 2.6 | 62.22% |
|
src/ |
243 | 35 | 23 | 12 | 159216.0 | 65.71% |
|
src/ |
55 | 12 | 8 | 4 | 3.3 | 66.67% |
|
R/ |
152 | 84 | 57 | 27 | 3.0 | 67.86% |
|
R/ |
376 | 152 | 108 | 44 | 11.2 | 71.05% |
|
R/ |
50 | 18 | 13 | 5 | 7.7 | 72.22% |
|
src/ |
555 | 30 | 22 | 8 | 3.7 | 73.33% |
|
src/ |
913 | 25 | 19 | 6 | 19936.1 | 76.00% |
|
src/ |
698 | 388 | 302 | 86 | 388.7 | 77.84% |
|
src/ |
181 | 103 | 83 | 20 | 495188.6 | 80.58% |
|
src/ |
1068 | 86 | 70 | 16 | 2036335.7 | 81.40% |
|
src/ |
87 | 28 | 24 | 4 | 7986.8 | 85.71% |
|
R/ |
844 | 557 | 478 | 79 | 1189.8 | 85.82% |
|
src/ |
1140 | 68 | 62 | 6 | 6159112.0 | 91.18% |
|
src/ |
159 | 109 | 102 | 7 | 1382.4 | 93.58% |
|
src/ |
81 | 40 | 38 | 2 | 5394605.6 | 95.00% |
|
R/ |
173 | 105 | 100 | 5 | 2184.4 | 95.24% |
|
R/ |
542 | 353 | 337 | 16 | 127.3 | 95.47% |
|
R/ |
86 | 59 | 57 | 2 | 3.1 | 96.61% |
|
src/ |
79 | 43 | 42 | 1 | 225.1 | 97.67% |
|
R/ |
239 | 144 | 144 | 0 | 20.5 | 100.00% |
|
R/ |
210 | 121 | 121 | 0 | 21.2 | 100.00% |
|
R/ |
199 | 98 | 98 | 0 | 20.1 | 100.00% |
|
R/ |
223 | 76 | 76 | 0 | 43.2 | 100.00% |
|
src/ |
706 | 46 | 46 | 0 | 654110.9 | 100.00% |
|
src/ |
118 | 42 | 42 | 0 | 11.0 | 100.00% |
|
src/ |
152 | 30 | 30 | 0 | 18.3 | 100.00% |
|
R/ |
93 | 25 | 25 | 0 | 158.9 | 100.00% |
|
R/ |
37 | 17 | 17 | 0 | 6.2 | 100.00% |
|
R/ |
82 | 15 | 15 | 0 | 184.6 | 100.00% |
|
src/ |
152 | 2 | 2 | 0 | 1485.0 | 100.00% |
|
src/ |
197 | 2 | 2 | 0 | 5.0 | 100.00% |
| Total | 30247 | 11477 | 4832 | 6645 | 91502.4 | 42.10% |
| 1 | #' Signed polygon area in local coordinates | |
| 2 | #' @keywords internal | |
| 3 | #' @noRd | |
| 4 | polygon_ring_area = function(p) { | |
| 5 | 560x | q = sweep(p, 2, p[1, ]) |
| 6 | 560x | size = max(abs(q)) |
| 7 | 560x | if (!is.finite(size) || size == 0) { |
| 8 | ! | return(0) |
| 9 | } | |
| 10 | 560x | q = q / size |
| 11 | 560x | j = c(seq_len(nrow(q))[-1L], 1L) |
| 12 | 560x | sum(q[, 1] * q[j, 2] - q[j, 1] * q[, 2]) / 2 |
| 13 | } | |
| 14 | ||
| 15 | #' Normalize an extrusion ring without its closing vertex | |
| 16 | #' @keywords internal | |
| 17 | #' @noRd | |
| 18 | polygon_ring = function(p) { | |
| 19 | if ( | |
| 20 | 389x | !is.matrix(p) || |
| 21 | 389x | !is.numeric(p) || |
| 22 | 389x | ncol(p) < 2L || |
| 23 | 389x | nrow(p) < 3L || |
| 24 | 389x | any(!is.finite(p[, 1:2, drop = FALSE])) |
| 25 | ) { | |
| 26 | 4x | stop( |
| 27 | 4x | "Each polygon ring must contain at least three finite x/y vertices.", |
| 28 | 4x | call. = FALSE |
| 29 | ) | |
| 30 | } | |
| 31 | 385x | p = unname(p[, 1:2, drop = FALSE]) |
| 32 | 385x | p = p[ |
| 33 | 385x | c(TRUE, rowSums(p[-1L, , drop = FALSE] != p[-nrow(p), , drop = FALSE]) > 0), |
| 34 | , | |
| 35 | 385x | drop = FALSE |
| 36 | ] | |
| 37 | 385x | if (nrow(p) > 1L && all(p[1, ] == p[nrow(p), ])) { |
| 38 | 50x | p = p[-nrow(p), , drop = FALSE] |
| 39 | } | |
| 40 | 385x | if (nrow(p) < 3L) { |
| 41 | 1x | stop( |
| 42 | 1x | "Each polygon ring needs at least three distinct vertices.", |
| 43 | 1x | call. = FALSE |
| 44 | ) | |
| 45 | } | |
| 46 | # Remove straight, forward-going redundant points from caps and walls alike. | |
| 47 | # A reversal along an edge is invalid, not a removable collinear vertex. | |
| 48 | 384x | repeat { |
| 49 | 388x | n = nrow(p) |
| 50 | 388x | q = sweep(p, 2, p[1, ]) |
| 51 | 388x | size = max(abs(q)) |
| 52 | 388x | if (!is.finite(size) || size == 0) { |
| 53 | ! | break |
| 54 | } | |
| 55 | 388x | q = q / size |
| 56 | 388x | a = q - q[c(n, seq_len(n - 1L)), , drop = FALSE] |
| 57 | 388x | b = q[c(seq_len(n)[-1L], 1L), , drop = FALSE] - q |
| 58 | 388x | straight = a[, 1] * b[, 2] == a[, 2] * b[, 1] |
| 59 | 388x | if (any(straight & rowSums(a * b) < 0)) { |
| 60 | 2x | stop( |
| 61 | 2x | "Polygon rings must not self-intersect or retrace an edge.", |
| 62 | 2x | call. = FALSE |
| 63 | ) | |
| 64 | } | |
| 65 | 386x | remove = straight & rowSums(a * b) > 0 |
| 66 | 386x | if (!any(remove) || sum(!remove) < 3L) { |
| 67 | 382x | break |
| 68 | } | |
| 69 | 4x | p = p[!remove, , drop = FALSE] |
| 70 | } | |
| 71 | 382x | if (polygon_ring_area(p) == 0) { |
| 72 | 1x | stop( |
| 73 | 1x | "Polygon rings must have nonzero area and must not self-intersect.", |
| 74 | 1x | call. = FALSE |
| 75 | ) | |
| 76 | } | |
| 77 | 381x | p |
| 78 | } | |
| 79 | ||
| 80 | #' Point containment for disjoint simple polygon rings | |
| 81 | #' @keywords internal | |
| 82 | #' @noRd | |
| 83 | polygon_contains = function(ring, point) { | |
| 84 | 62x | p = sweep(ring, 2, point) |
| 85 | 62x | j = c(seq_len(nrow(p))[-1L], 1L) |
| 86 | 62x | i = which((p[, 2] > 0) != (p[j, 2] > 0)) |
| 87 | 62x | if (!length(i)) { |
| 88 | 17x | return(FALSE) |
| 89 | } | |
| 90 | 45x | x = p[i, 1] + (p[j[i], 1] - p[i, 1]) * (-p[i, 2] / (p[j[i], 2] - p[i, 2])) |
| 91 | 45x | sum(x > 0) %% 2L == 1L |
| 92 | } | |
| 93 | ||
| 94 | #' Reject crossing or touching extrusion ring edges | |
| 95 | #' @keywords internal | |
| 96 | #' @noRd | |
| 97 | polygon_check_edges = function(rings) { | |
| 98 | 167x | p = do.call(rbind, rings) |
| 99 | 167x | p = sweep(p, 2, p[1, ]) |
| 100 | 167x | size = max(abs(p)) |
| 101 | 167x | if (!is.finite(size) || size == 0) { |
| 102 | ! | stop("Polygon coordinate extent must be finite and nonzero.", call. = FALSE) |
| 103 | } | |
| 104 | 167x | p = p / size |
| 105 | 167x | lengths = vapply(rings, nrow, 0L) |
| 106 | 167x | starts = c(0L, utils::head(cumsum(lengths), -1L)) |
| 107 | 167x | next_id = unlist(Map( |
| 108 | 167x | function(n, start) c(seq_len(n)[-1L], 1L) + start, |
| 109 | 167x | lengths, |
| 110 | 167x | starts |
| 111 | )) | |
| 112 | 167x | q = p[next_id, , drop = FALSE] |
| 113 | 167x | xmin = pmin(p[, 1], q[, 1]) |
| 114 | 167x | xmax = pmax(p[, 1], q[, 1]) |
| 115 | 167x | ymin = pmin(p[, 2], q[, 2]) |
| 116 | 167x | ymax = pmax(p[, 2], q[, 2]) |
| 117 | 167x | cross_sign = function(a, b) { |
| 118 | 20x | left = a[, 1] * b[, 2] |
| 119 | 20x | right = a[, 2] * b[, 1] |
| 120 | 20x | value = left - right |
| 121 | 20x | value[abs(value) <= 8 * .Machine$double.eps * (abs(left) + abs(right))] = 0 |
| 122 | 20x | sign(value) |
| 123 | } | |
| 124 | 167x | active = integer() |
| 125 | 167x | for (i in order(xmin)) { |
| 126 | 816x | active = active[xmax[active] >= xmin[i]] |
| 127 | 816x | candidates = active[ |
| 128 | 816x | ymin[active] <= ymax[i] & |
| 129 | 816x | ymax[active] >= ymin[i] & |
| 130 | 816x | next_id[active] != i & |
| 131 | 816x | active != next_id[i] |
| 132 | ] | |
| 133 | 816x | if (length(candidates)) { |
| 134 | 5x | a = p[candidates, , drop = FALSE] |
| 135 | 5x | b = q[candidates, , drop = FALSE] |
| 136 | 5x | c = matrix(p[i, ], nrow(a), 2L, byrow = TRUE) |
| 137 | 5x | d = matrix(q[i, ], nrow(a), 2L, byrow = TRUE) |
| 138 | if ( | |
| 139 | 5x | any( |
| 140 | 5x | cross_sign(b - a, c - a) * cross_sign(b - a, d - a) <= 0 & |
| 141 | 5x | cross_sign(d - c, a - c) * cross_sign(d - c, b - c) <= 0 |
| 142 | ) | |
| 143 | ) { | |
| 144 | 4x | stop( |
| 145 | 4x | "Polygon rings must not self-intersect, cross, or touch other rings.", |
| 146 | 4x | call. = FALSE |
| 147 | ) | |
| 148 | } | |
| 149 | } | |
| 150 | 812x | active = c(active, i) |
| 151 | } | |
| 152 | 163x | invisible(NULL) |
| 153 | } | |
| 154 | ||
| 155 | #' Validate polygon holes and choose consistent ring winding | |
| 156 | #' @keywords internal | |
| 157 | #' @noRd | |
| 158 | polygon_component = function(rings) { | |
| 159 | 149x | if (!length(rings)) { |
| 160 | 1x | stop("Empty polygons cannot be extruded.", call. = FALSE) |
| 161 | } | |
| 162 | 148x | rings = lapply(rings, polygon_ring) |
| 163 | 148x | polygon_check_edges(rings) |
| 164 | 145x | if (length(rings) > 1L) { |
| 165 | 18x | for (i in 2:length(rings)) { |
| 166 | 24x | if (!polygon_contains(rings[[1]], rings[[i]][1, ])) { |
| 167 | 1x | stop( |
| 168 | 1x | "Every hole must lie strictly inside its outer polygon.", |
| 169 | 1x | call. = FALSE |
| 170 | ) | |
| 171 | } | |
| 172 | 23x | for (j in seq_len(i - 1L)[-1L]) { |
| 173 | if ( | |
| 174 | 6x | polygon_contains(rings[[j]], rings[[i]][1, ]) || |
| 175 | 6x | polygon_contains(rings[[i]], rings[[j]][1, ]) |
| 176 | ) { | |
| 177 | 1x | stop( |
| 178 | 1x | "Polygon holes must not overlap or contain other holes.", |
| 179 | 1x | call. = FALSE |
| 180 | ) | |
| 181 | } | |
| 182 | } | |
| 183 | } | |
| 184 | } | |
| 185 | 143x | for (i in seq_along(rings)) { |
| 186 | 164x | if ((polygon_ring_area(rings[[i]]) > 0) != (i == 1L)) { |
| 187 | 123x | rings[[i]] = rings[[i]][c(1L, nrow(rings[[i]]):2L), , drop = FALSE] |
| 188 | } | |
| 189 | } | |
| 190 | 143x | rings |
| 191 | } | |
| 192 | ||
| 193 | #' Resolve polygon input into components with per-feature heights | |
| 194 | #' @keywords internal | |
| 195 | #' @noRd | |
| 196 | polygon_components = function( | |
| 197 | polygon, | |
| 198 | holes, | |
| 199 | top, | |
| 200 | bottom, | |
| 201 | data_column_top, | |
| 202 | data_column_bottom, | |
| 203 | scale_data | |
| 204 | ) { | |
| 205 | 163x | spatial = inherits(polygon, "SpatialPolygons") |
| 206 | 163x | is_sf = inherits(polygon, "sf") |
| 207 | 163x | if ((spatial || is_sf) && !is.null(holes)) { |
| 208 | ! | warning("`holes` is unused when input is sf or Spatial.", call. = FALSE) |
| 209 | } | |
| 210 | 163x | components = list() |
| 211 | 163x | append = function(rings, high, low) { |
| 212 | 155x | components[[length(components) + 1L]] <<- list( |
| 213 | 155x | rings = rings, |
| 214 | 155x | top = high, |
| 215 | 155x | bottom = low |
| 216 | ) | |
| 217 | } | |
| 218 | 163x | if (is_sf) { |
| 219 | 15x | if (!requireNamespace("sf", quietly = TRUE)) { |
| 220 | ! | stop("The sf package is required for sf input.", call. = FALSE) |
| 221 | } | |
| 222 | 15x | geometry = sf::st_geometry(polygon) |
| 223 | 15x | if (!length(geometry)) { |
| 224 | 1x | stop("Empty polygons cannot be extruded.", call. = FALSE) |
| 225 | } | |
| 226 | 14x | height_column = function(name, fallback, argument) { |
| 227 | 24x | if (is.null(name)) { |
| 228 | 11x | return(rep(fallback, length(geometry))) |
| 229 | } | |
| 230 | 14x | if ( |
| 231 | 13x | !is.character(name) || |
| 232 | 13x | length(name) != 1L || |
| 233 | 13x | is.na(name) || |
| 234 | 13x | !nzchar(name) |
| 235 | ) { | |
| 236 | 1x | stop( |
| 237 | 1x | sprintf("`%s` must be NULL or a single column name.", argument), |
| 238 | 1x | call. = FALSE |
| 239 | ) | |
| 240 | } | |
| 241 | 12x | if (!name %in% names(polygon)) { |
| 242 | 1x | warning( |
| 243 | 1x | sprintf("Was not able to find %s `%s` in sf object.", argument, name), |
| 244 | 1x | call. = FALSE |
| 245 | ) | |
| 246 | 1x | return(rep(fallback, length(geometry))) |
| 247 | } | |
| 248 | 11x | values = polygon[[name]] |
| 249 | 14x | if ( |
| 250 | 11x | !is.numeric(values) || |
| 251 | 11x | !is.null(dim(values)) || |
| 252 | 11x | length(values) != length(geometry) || |
| 253 | 11x | any(!is.finite(values)) || |
| 254 | 11x | any(!is.finite(values * scale_data)) |
| 255 | ) { | |
| 256 | 3x | stop( |
| 257 | 3x | sprintf("`%s` must select a finite numeric height column.", argument), |
| 258 | 3x | call. = FALSE |
| 259 | ) | |
| 260 | } | |
| 261 | 8x | values * scale_data |
| 262 | } | |
| 263 | 14x | high = height_column(data_column_top, top, "data_column_top") |
| 264 | 10x | low = height_column(data_column_bottom, bottom, "data_column_bottom") |
| 265 | 10x | for (i in seq_along(geometry)) { |
| 266 | 17x | g = geometry[[i]] |
| 267 | 17x | if (inherits(g, "POLYGON")) { |
| 268 | 13x | pieces = list(unclass(g)) |
| 269 | 4x | } else if (inherits(g, "MULTIPOLYGON")) { |
| 270 | 3x | pieces = unclass(g) |
| 271 | } else { | |
| 272 | 1x | stop( |
| 273 | 1x | "sf geometry must contain only POLYGON or MULTIPOLYGON features.", |
| 274 | 1x | call. = FALSE |
| 275 | ) | |
| 276 | } | |
| 277 | 16x | if (!length(pieces)) { |
| 278 | 1x | stop("Empty polygons cannot be extruded.", call. = FALSE) |
| 279 | } | |
| 280 | 15x | for (rings in pieces) { |
| 281 | 16x | append(rings, high[i], low[i]) |
| 282 | } | |
| 283 | } | |
| 284 | 148x | } else if (spatial) { |
| 285 | 4x | if (!length(polygon@polygons)) { |
| 286 | ! | stop("Empty polygons cannot be extruded.", call. = FALSE) |
| 287 | } | |
| 288 | 4x | for (feature in polygon@polygons) { |
| 289 | 4x | rings = lapply(feature@Polygons, function(r) polygon_ring(r@coords)) |
| 290 | 4x | hole = vapply(feature@Polygons, function(r) r@hole, TRUE) |
| 291 | 4x | outer = which(!hole) |
| 292 | 4x | if (!length(outer)) { |
| 293 | ! | stop("Spatial polygons require an outer ring.", call. = FALSE) |
| 294 | } | |
| 295 | 4x | polygon_check_edges(rings) |
| 296 | 4x | groups = lapply(outer, function(i) list(rings[[i]])) |
| 297 | 4x | for (i in which(hole)) { |
| 298 | 8x | parents = which(vapply( |
| 299 | 8x | outer, |
| 300 | 8x | function(j) polygon_contains(rings[[j]], rings[[i]][1, ]), |
| 301 | 8x | TRUE |
| 302 | )) | |
| 303 | # The innermost containing exterior owns the hole, independent of ring order. | |
| 304 | 8x | if (!length(parents)) { |
| 305 | ! | stop( |
| 306 | ! | "Every hole must lie strictly inside its outer polygon.", |
| 307 | ! | call. = FALSE |
| 308 | ) | |
| 309 | } | |
| 310 | 8x | depth = vapply( |
| 311 | 8x | parents, |
| 312 | 8x | function(j) { |
| 313 | 9x | sum(vapply( |
| 314 | 9x | outer[parents], |
| 315 | 9x | function(k) { |
| 316 | 11x | polygon_contains(rings[[k]], rings[[outer[j]]][1, ]) |
| 317 | }, | |
| 318 | 9x | TRUE |
| 319 | )) | |
| 320 | }, | |
| 321 | 8x | 0L |
| 322 | ) | |
| 323 | 8x | owner = parents[which.max(depth)] |
| 324 | 8x | groups[[owner]][[length(groups[[owner]]) + 1L]] = rings[[i]] |
| 325 | } | |
| 326 | 4x | for (rings in groups) { |
| 327 | 8x | append(rings, top, bottom) |
| 328 | } | |
| 329 | } | |
| 330 | } else { | |
| 331 | 144x | xy = tryCatch(grDevices::xy.coords(polygon), error = function(e) NULL) |
| 332 | 144x | if (is.null(xy) || !length(xy$x)) { |
| 333 | 2x | stop( |
| 334 | 2x | "`polygon` must specify nonempty finite x/y coordinates.", |
| 335 | 2x | call. = FALSE |
| 336 | ) | |
| 337 | } | |
| 338 | 142x | p = cbind(xy$x, xy$y) |
| 339 | if ( | |
| 340 | 142x | is.null(holes) || |
| 341 | 142x | (is.numeric(holes) && length(holes) == 1L && isTRUE(holes == 0)) |
| 342 | ) { | |
| 343 | 121x | starts = 1L |
| 344 | } else { | |
| 345 | if ( | |
| 346 | 21x | !is.numeric(holes) || |
| 347 | 21x | !length(holes) || |
| 348 | 21x | any(!is.finite(holes)) || |
| 349 | 21x | any(holes != floor(holes)) || |
| 350 | 21x | any(holes < 4L | holes > nrow(p)) || |
| 351 | 21x | any(diff(holes) <= 0) |
| 352 | ) { | |
| 353 | 11x | stop( |
| 354 | 11x | "`holes` must be NULL, zero, or strictly increasing integer start indices from 4 to the vertex count.", |
| 355 | 11x | call. = FALSE |
| 356 | ) | |
| 357 | } | |
| 358 | 10x | starts = c(1L, as.integer(holes)) |
| 359 | } | |
| 360 | 131x | ends = c(starts[-1L] - 1L, nrow(p)) |
| 361 | 131x | append( |
| 362 | 131x | Map(function(a, b) p[seq.int(a, b), , drop = FALSE], starts, ends), |
| 363 | 131x | top, |
| 364 | 131x | bottom |
| 365 | ) | |
| 366 | } | |
| 367 | 143x | components |
| 368 | } | |
| 369 | ||
| 370 | #' Construct a shared-vertex polygon extrusion mesh | |
| 371 | #' @keywords internal | |
| 372 | #' @noRd | |
| 373 | polygon_mesh_data = function( | |
| 374 | polygon, | |
| 375 | plane, | |
| 376 | top, | |
| 377 | bottom, | |
| 378 | holes, | |
| 379 | center, | |
| 380 | flip_horizontal, | |
| 381 | flip_vertical, | |
| 382 | data_column_top, | |
| 383 | data_column_bottom, | |
| 384 | scale_data, | |
| 385 | scale | |
| 386 | ) { | |
| 387 | 193x | for (name in c("top", "bottom", "scale_data")) { |
| 388 | 564x | sweep_scalar(get(name), name) |
| 389 | } | |
| 390 | 178x | for (name in c("center", "flip_horizontal", "flip_vertical")) { |
| 391 | 531x | flag = get(name) |
| 392 | 531x | if (!is.logical(flag) || length(flag) != 1L || is.na(flag)) { |
| 393 | 3x | stop(sprintf("`%s` must be TRUE or FALSE.", name), call. = FALSE) |
| 394 | } | |
| 395 | } | |
| 396 | if ( | |
| 397 | 175x | !is.character(plane) || |
| 398 | 175x | length(plane) != 1L || |
| 399 | 175x | is.na(plane) || |
| 400 | 175x | !tolower(plane) %in% c("xz", "zx", "xy", "yx", "zy", "yz") |
| 401 | ) { | |
| 402 | 4x | stop("`plane` must be one of xz, zx, xy, yx, zy, or yz.", call. = FALSE) |
| 403 | } | |
| 404 | 171x | plane = tolower(plane) |
| 405 | if ( | |
| 406 | 171x | !is.numeric(scale) || |
| 407 | 171x | !length(scale) %in% c(1L, 3L) || |
| 408 | 171x | any(!is.finite(scale)) || |
| 409 | 171x | any(scale == 0) |
| 410 | ) { | |
| 411 | 8x | stop( |
| 412 | 8x | "`scale` must contain one or three finite, nonzero numbers.", |
| 413 | 8x | call. = FALSE |
| 414 | ) | |
| 415 | } | |
| 416 | 163x | scale = rep(scale, length.out = 3L) |
| 417 | 163x | components = polygon_components( |
| 418 | 163x | polygon, |
| 419 | 163x | holes, |
| 420 | 163x | top, |
| 421 | 163x | bottom, |
| 422 | 163x | data_column_top, |
| 423 | 163x | data_column_bottom, |
| 424 | 163x | scale_data |
| 425 | ) | |
| 426 | # Retain the established coordinate convention, including the first-axis mirror. | |
| 427 | 143x | for (i in seq_along(components)) { |
| 428 | 155x | rings = lapply(components[[i]]$rings, function(p) { |
| 429 | 181x | p = polygon_ring(p) |
| 430 | 175x | p[, 1] = p[, 1] * if (flip_horizontal) 1 else -1 |
| 431 | 175x | if (flip_vertical) { |
| 432 | 14x | p[, 2] = -p[, 2] |
| 433 | } | |
| 434 | 175x | p |
| 435 | }) | |
| 436 | 149x | components[[i]]$rings = polygon_component(rings) |
| 437 | } | |
| 438 | 131x | offset = c(0, 0) |
| 439 | 131x | if (center) { |
| 440 | 6x | all_points = do.call( |
| 441 | 6x | rbind, |
| 442 | 6x | lapply(components, function(c) do.call(rbind, c$rings)) |
| 443 | ) | |
| 444 | 6x | offset = apply(all_points, 2, function(x) min(x) / 2 + max(x) / 2) |
| 445 | } | |
| 446 | 131x | permutation = switch( |
| 447 | 131x | plane, |
| 448 | 131x | xz = 1:3, |
| 449 | 131x | zx = c(3, 2, 1), |
| 450 | 131x | xy = c(3, 1, 2), |
| 451 | 131x | yx = c(1, 3, 2), |
| 452 | 131x | zy = c(2, 3, 1), |
| 453 | 131x | yz = c(2, 1, 3) |
| 454 | ) | |
| 455 | 131x | reflected = xor(plane %in% c("zx", "yx", "yz"), prod(sign(scale)) < 0) |
| 456 | 131x | meshes = lapply(components, function(component) { |
| 457 | 143x | rings = component$rings |
| 458 | 143x | p = do.call(rbind, rings) |
| 459 | 143x | n = nrow(p) |
| 460 | 143x | lengths = vapply(rings, nrow, 0L) |
| 461 | 143x | starts = c(0L, utils::head(cumsum(lengths), -1L)) |
| 462 | 143x | local = sweep(p, 2, p[1, ]) |
| 463 | 143x | local = local / max(abs(local)) |
| 464 | 143x | caps = matrix( |
| 465 | 143x | decido::earcut( |
| 466 | 143x | local, |
| 467 | 143x | holes = if (length(starts) > 1L) starts[-1L] + 1L else 0L |
| 468 | ), | |
| 469 | 143x | ncol = 3L, |
| 470 | 143x | byrow = TRUE |
| 471 | ) | |
| 472 | 143x | if (!nrow(caps)) { |
| 473 | ! | stop("Polygon could not be triangulated.", call. = FALSE) |
| 474 | } | |
| 475 | 143x | a = local[caps[, 2], , drop = FALSE] - local[caps[, 1], , drop = FALSE] |
| 476 | 143x | b = local[caps[, 3], , drop = FALSE] - local[caps[, 1], , drop = FALSE] |
| 477 | 143x | area = a[, 1] * b[, 2] - a[, 2] * b[, 1] |
| 478 | 143x | if (any(area == 0)) { |
| 479 | ! | stop("Polygon triangulation produced a degenerate cap.", call. = FALSE) |
| 480 | } | |
| 481 | 143x | caps[area < 0, ] = caps[area < 0, c(1, 3, 2), drop = FALSE] |
| 482 | 143x | next_id = unlist(Map( |
| 483 | 143x | function(n, start) c(seq_len(n)[-1L], 1L) + start, |
| 484 | 143x | lengths, |
| 485 | 143x | starts |
| 486 | )) | |
| 487 | # Earcut can discard collinear vertices. Require the cap boundary to match | |
| 488 | # the wall rings exactly, so no T-junction can silently enter the mesh. | |
| 489 | 143x | edges = rbind(caps[, c(1, 2)], caps[, c(2, 3)], caps[, c(3, 1)]) |
| 490 | 143x | edge_key = function(a, b) paste(pmin(a, b), pmax(a, b)) |
| 491 | 143x | counts = table(edge_key(edges[, 1], edges[, 2])) |
| 492 | 143x | boundary = edge_key(seq_len(n), next_id) |
| 493 | 131x | if ( |
| 494 | 143x | anyNA(counts[boundary]) || |
| 495 | 143x | any(counts[boundary] != 1L) || |
| 496 | 143x | any(counts[!names(counts) %in% boundary] != 2L) |
| 497 | ) { | |
| 498 | ! | stop( |
| 499 | ! | "Polygon triangulation did not preserve a closed cap boundary.", |
| 500 | ! | call. = FALSE |
| 501 | ) | |
| 502 | } | |
| 503 | 143x | p = sweep(p, 2, offset) |
| 504 | 143x | low = min(component$top, component$bottom) |
| 505 | 143x | high = max(component$top, component$bottom) |
| 506 | 143x | vertices = cbind(p[, 1], low, p[, 2]) |
| 507 | 143x | indices = caps |
| 508 | 143x | if (low != high) { |
| 509 | 134x | vertices = rbind(vertices, cbind(p[, 1], high, p[, 2])) |
| 510 | 134x | i = seq_len(n) |
| 511 | 134x | indices = rbind( |
| 512 | 134x | caps, |
| 513 | 134x | caps[, c(1, 3, 2)] + n, |
| 514 | 134x | cbind(i, i + n, next_id + n), |
| 515 | 134x | cbind(i, next_id + n, next_id) |
| 516 | ) | |
| 517 | } | |
| 518 | 143x | vertices = sweep(vertices[, permutation, drop = FALSE], 2, scale, "*") |
| 519 | 143x | if (any(!is.finite(vertices))) { |
| 520 | ! | stop("Scaled polygon vertices must be finite.", call. = FALSE) |
| 521 | } | |
| 522 | 143x | if (anyDuplicated(vertices)) { |
| 523 | 1x | stop( |
| 524 | 1x | "Scaling or centering collapsed distinct polygon vertices.", |
| 525 | 1x | call. = FALSE |
| 526 | ) | |
| 527 | } | |
| 528 | 142x | if (reflected) { |
| 529 | 33x | indices = indices[, c(1, 3, 2), drop = FALSE] |
| 530 | } | |
| 531 | 142x | list(vertices = vertices, indices = indices) |
| 532 | }) | |
| 533 | 130x | counts = vapply(meshes, function(m) nrow(m$vertices), 0L) |
| 534 | 130x | starts = c(0L, utils::head(cumsum(counts), -1L)) |
| 535 | 130x | list( |
| 536 | 130x | vertices = do.call(rbind, lapply(meshes, `[[`, "vertices")), |
| 537 | 130x | indices = do.call( |
| 538 | 130x | rbind, |
| 539 | 130x | Map(function(m, start) m$indices + start - 1L, meshes, starts) |
| 540 | ) | |
| 541 | ) | |
| 542 | } |
| 1 | #' Validate Mesh Data | |
| 2 | #' | |
| 3 | #' This function takes a mesh and validates it. The mesh should be a list with | |
| 4 | #' "shapes", "materials", "vertices", "texcoords", "normals", and "material_hashes" entries. | |
| 5 | #' | |
| 6 | #' @section Shapes: | |
| 7 | #' Each "shapes" entry should be a list with "mesh", "name", and "material" entries. | |
| 8 | #' Each "mesh" entry should have "indices", "tex_indices", "norm_indices", "material_ids", "has_vertex_tex", and "has_vertex_normals". | |
| 9 | #' The indices should not exceed the number of rows in their corresponding vertex/normal/texcoord data. There should be no NA/NaN values in the vertex/normal/texcoord data. | |
| 10 | #' | |
| 11 | #' @section Materials (for rayvertex package only): | |
| 12 | #' Each "materials" entry is expected to be a list with several entries with specific required lengths, as listed below: | |
| 13 | #' | |
| 14 | #' | Attribute | Length | Type | | |
| 15 | #' | :----------------------: | :------: | :---------: | | |
| 16 | #' | diffuse | 3 | Numeric | | |
| 17 | #' | ambient | 3 | Numeric | | |
| 18 | #' | specular | 3 | Numeric | | |
| 19 | #' | transmittance | 3 | Numeric | | |
| 20 | #' | emission | 3 | Numeric | | |
| 21 | #' | shininess | 1 | Numeric | | |
| 22 | #' | ior | 1 | Numeric | | |
| 23 | #' | dissolve | 1 | Numeric | | |
| 24 | #' | illum | 1 | Numeric | | |
| 25 | #' | diffuse_texname | 1 | Character | | |
| 26 | #' | normal_texname | 1 | Character | | |
| 27 | #' | bump_texname | 1 | Character | | |
| 28 | #' | specular_texname | 1 | Character | | |
| 29 | #' | ambient_texname | 1 | Character | | |
| 30 | #' | emissive_texname | 1 | Character | | |
| 31 | #' | diffuse_intensity | 1 | Numeric | | |
| 32 | #' | bump_intensity | 1 | Numeric | | |
| 33 | #' | specular_intensity | 1 | Numeric | | |
| 34 | #' | emission_intensity | 1 | Numeric | | |
| 35 | #' | ambient_intensity | 1 | Numeric | | |
| 36 | #' | culling | 1 | Character | | |
| 37 | #' | type | 1 | Character | | |
| 38 | #' | translucent | 1 | Logical | | |
| 39 | #' | toon_levels | 1 | Numeric | | |
| 40 | #' | toon_outline_width | 1 | Numeric | | |
| 41 | #' | toon_outline_color | 3 | Numeric | | |
| 42 | #' | reflection_intensity | 1 | Numeric | | |
| 43 | #' | reflection_sharpness | 1 | Numeric | | |
| 44 | #' | two_sided | 1 | Logical | | |
| 45 | #' | |
| 46 | #' Note: This materials validation only applies to the rayvertex package. Other renderers might choose to use their own information in the material list. | |
| 47 | #' | |
| 48 | #' @param mesh List. A mesh is a list as described above. | |
| 49 | #' @param validate_materials Default `TRUE`. Whether or not to validate "materials". | |
| 50 | #' @return A mesh. | |
| 51 | #' @export | |
| 52 | #' @examples | |
| 53 | #' # validate a mesh | |
| 54 | #' mesh = validate_mesh(sphere_mesh()) | |
| 55 | validate_mesh = function(mesh, validate_materials = TRUE) { | |
| 56 | 14x | stopifnot(inherits(mesh, "ray_mesh")) |
| 57 | 14x | stopifnot(all( |
| 58 | 14x | names(mesh) %in% |
| 59 | 14x | c("shapes", "materials", "vertices", "texcoords", "normals") |
| 60 | )) | |
| 61 | 14x | stopifnot(length(attr(mesh, "material_hashes")) > 0) |
| 62 | ||
| 63 | # Validate shapes | |
| 64 | 14x | for (i in seq_along(mesh$shapes)) { |
| 65 | 21x | mesh_entry = mesh$shapes[[i]] |
| 66 | 21x | stopifnot(is.list(mesh_entry)) |
| 67 | 21x | stopifnot(all( |
| 68 | 21x | names(mesh_entry) %in% |
| 69 | 21x | c( |
| 70 | 21x | "indices", |
| 71 | 21x | "tex_indices", |
| 72 | 21x | "norm_indices", |
| 73 | 21x | "material_ids", |
| 74 | 21x | "has_vertex_tex", |
| 75 | 21x | "has_vertex_normals" |
| 76 | ) | |
| 77 | )) | |
| 78 | 21x | stopifnot(is.numeric(mesh_entry$indices)) |
| 79 | 21x | stopifnot(is.numeric(mesh_entry$tex_indices)) |
| 80 | 21x | stopifnot(is.numeric(mesh_entry$norm_indices)) |
| 81 | 21x | stopifnot(is.numeric(mesh_entry$material_ids)) |
| 82 | 21x | stopifnot(is.logical(mesh_entry$has_vertex_tex)) |
| 83 | 21x | stopifnot(is.logical(mesh_entry$has_vertex_normals)) |
| 84 | ||
| 85 | # Validate vertex, normal, texcoord indices | |
| 86 | 21x | vertices = mesh$vertices[[i]] |
| 87 | 21x | normals = mesh$normals[[i]] |
| 88 | 21x | texcoords = mesh$texcoords[[i]] |
| 89 | 21x | materials_mesh = mesh$materials[[i]] |
| 90 | ||
| 91 | 21x | stopifnot(is.matrix(vertices)) |
| 92 | 21x | stopifnot(!any(is.na(vertices)), !any(is.nan(vertices))) |
| 93 | ||
| 94 | 21x | if (any(mesh_entry$has_vertex_normals)) { |
| 95 | 18x | stopifnot(is.matrix(normals)) |
| 96 | 18x | stopifnot(!any(is.na(normals)), !any(is.nan(normals))) |
| 97 | } | |
| 98 | 21x | if (any(mesh_entry$has_vertex_tex)) { |
| 99 | 19x | stopifnot(is.matrix(texcoords)) |
| 100 | 19x | stopifnot(!any(is.na(texcoords)), !any(is.nan(texcoords))) |
| 101 | } | |
| 102 | ||
| 103 | 21x | max_vertex_index = nrow(vertices) - 1 |
| 104 | 21x | max_normal_index = nrow(normals) - 1 |
| 105 | 21x | max_texcoord_index = nrow(texcoords) - 1 |
| 106 | 21x | max_materials = length(materials_mesh) - 1 |
| 107 | ||
| 108 | 21x | stopifnot(all(mesh_entry$vertex_index <= max_vertex_index)) |
| 109 | 21x | stopifnot(all(mesh_entry$normal_index <= max_normal_index)) |
| 110 | 21x | stopifnot(all(mesh_entry$texcoord_index <= max_texcoord_index)) |
| 111 | 21x | stopifnot(all(mesh_entry$material_id <= max_materials)) |
| 112 | } | |
| 113 | ||
| 114 | # Validate materials | |
| 115 | 14x | if (validate_materials) { |
| 116 | 14x | for (i in seq_along(mesh$materials)) { |
| 117 | 21x | materials <- mesh$materials[[i]] |
| 118 | 21x | for (j in seq_along(materials)) { |
| 119 | 21x | material <- materials[[j]] |
| 120 | 21x | stopifnot(is.list(material)) |
| 121 | 21x | stopifnot(all( |
| 122 | 21x | names(material) %in% |
| 123 | 21x | c( |
| 124 | 21x | "diffuse", |
| 125 | 21x | "ambient", |
| 126 | 21x | "specular", |
| 127 | 21x | "transmittance", |
| 128 | 21x | "emission", |
| 129 | 21x | "shininess", |
| 130 | 21x | "ior", |
| 131 | 21x | "dissolve", |
| 132 | 21x | "illum", |
| 133 | 21x | "diffuse_texname", |
| 134 | 21x | "normal_texname", |
| 135 | 21x | "specular_texname", |
| 136 | 21x | "ambient_texname", |
| 137 | 21x | "emissive_texname", |
| 138 | 21x | "diffuse_intensity", |
| 139 | 21x | "bump_intensity", |
| 140 | 21x | "bump_texname", |
| 141 | 21x | "specular_intensity", |
| 142 | 21x | "emission_intensity", |
| 143 | 21x | "ambient_intensity", |
| 144 | 21x | "culling", |
| 145 | 21x | "type", |
| 146 | 21x | "translucent", |
| 147 | 21x | "toon_levels", |
| 148 | 21x | "toon_outline_width", |
| 149 | 21x | "toon_outline_color", |
| 150 | 21x | "reflection_intensity", |
| 151 | 21x | "reflection_sharpness", |
| 152 | 21x | "two_sided", |
| 153 | 21x | "sigma" |
| 154 | ) | |
| 155 | )) | |
| 156 | ||
| 157 | # Validate material attributes types and lengths | |
| 158 | 21x | stopifnot(is.numeric(material$diffuse), length(material$diffuse) == 3) |
| 159 | 21x | stopifnot(is.numeric(material$ambient), length(material$ambient) == 3) |
| 160 | 21x | stopifnot(is.numeric(material$specular), length(material$specular) == 3) |
| 161 | 21x | stopifnot( |
| 162 | 21x | is.numeric(material$transmittance), |
| 163 | 21x | length(material$transmittance) == 3 |
| 164 | ) | |
| 165 | 21x | stopifnot(is.numeric(material$emission), length(material$emission) == 3) |
| 166 | 21x | stopifnot( |
| 167 | 21x | is.numeric(material$shininess), |
| 168 | 21x | length(material$shininess) == 1 |
| 169 | ) | |
| 170 | 21x | stopifnot(is.numeric(material$ior), length(material$ior) == 1) |
| 171 | 21x | stopifnot(is.numeric(material$dissolve), length(material$dissolve) == 1) |
| 172 | 21x | stopifnot(is.numeric(material$illum), length(material$illum) == 1) |
| 173 | 21x | stopifnot(is.character(material$diffuse_texname)) |
| 174 | 21x | stopifnot(is.character(material$normal_texname)) |
| 175 | 21x | stopifnot(is.character(material$bump_texname)) |
| 176 | 21x | stopifnot(is.character(material$specular_texname)) |
| 177 | 21x | stopifnot(is.character(material$ambient_texname)) |
| 178 | 21x | stopifnot(is.character(material$emissive_texname)) |
| 179 | 21x | stopifnot( |
| 180 | 21x | is.numeric(material$diffuse_intensity), |
| 181 | 21x | length(material$diffuse_intensity) == 1 |
| 182 | ) | |
| 183 | 21x | stopifnot( |
| 184 | 21x | is.numeric(material$bump_intensity), |
| 185 | 21x | length(material$bump_intensity) == 1 |
| 186 | ) | |
| 187 | 21x | stopifnot( |
| 188 | 21x | is.numeric(material$specular_intensity), |
| 189 | 21x | length(material$specular_intensity) == 1 |
| 190 | ) | |
| 191 | 21x | stopifnot( |
| 192 | 21x | is.numeric(material$emission_intensity), |
| 193 | 21x | length(material$emission_intensity) == 1 |
| 194 | ) | |
| 195 | 21x | stopifnot( |
| 196 | 21x | is.numeric(material$ambient_intensity), |
| 197 | 21x | length(material$ambient_intensity) == 1 |
| 198 | ) | |
| 199 | 21x | stopifnot(is.numeric(material$culling), length(material$culling) == 1) |
| 200 | 21x | stopifnot(is.character(material$type)) |
| 201 | 21x | stopifnot( |
| 202 | 21x | is.logical(material$translucent), |
| 203 | 21x | length(material$translucent) == 1 |
| 204 | ) | |
| 205 | 21x | stopifnot( |
| 206 | 21x | is.numeric(material$toon_levels), |
| 207 | 21x | length(material$toon_levels) == 1 |
| 208 | ) | |
| 209 | 21x | stopifnot( |
| 210 | 21x | is.numeric(material$toon_outline_width), |
| 211 | 21x | length(material$toon_outline_width) == 1 |
| 212 | ) | |
| 213 | 21x | stopifnot( |
| 214 | 21x | is.numeric(material$toon_outline_color), |
| 215 | 21x | length(material$toon_outline_color) == 3 |
| 216 | ) | |
| 217 | 21x | stopifnot( |
| 218 | 21x | is.numeric(material$reflection_intensity), |
| 219 | 21x | length(material$reflection_intensity) == 1 |
| 220 | ) | |
| 221 | 21x | stopifnot( |
| 222 | 21x | is.numeric(material$reflection_sharpness), |
| 223 | 21x | length(material$reflection_sharpness) == 1 |
| 224 | ) | |
| 225 | 21x | stopifnot( |
| 226 | 21x | is.logical(material$two_sided), |
| 227 | 21x | length(material$two_sided) == 1 |
| 228 | ) | |
| 229 | 21x | stopifnot( |
| 230 | 21x | is.numeric(material$sigma), |
| 231 | 21x | length(material$sigma) == 1, |
| 232 | 21x | material$sigma >= 0 && material$sigma <= 90 |
| 233 | ) | |
| 234 | } | |
| 235 | } | |
| 236 | } | |
| 237 | ||
| 238 | 14x | return(mesh) |
| 239 | } |
| 1 | #' Draw a Lathe Profile | |
| 2 | #' | |
| 3 | #' Click on a base R plot to draw a radius/height polygon for [lathe_mesh()]. | |
| 4 | #' After the second click, the preview joins the newest point to the first | |
| 5 | #' point, updating the closing segment after each additional click. | |
| 6 | #' | |
| 7 | #' @param xlim Default `c(0, 1)`. Increasing, finite radius limits for the | |
| 8 | #' drawing area. Both limits must be nonnegative. | |
| 9 | #' @param ylim Default `c(0, 1)`. Increasing, finite height limits for the | |
| 10 | #' drawing area. | |
| 11 | #' @param snap Default `0.02`. Distance from radius zero within which clicks | |
| 12 | #' snap to the axis, expressed as a fraction of the width of `xlim`. Set to | |
| 13 | #' zero to disable snapping. Applies only when `xlim` starts at zero. | |
| 14 | #' | |
| 15 | #' @details | |
| 16 | #' Requires an interactive graphics device that supports [graphics::locator()]. | |
| 17 | #' Left-click to add vertices in boundary order. Click **Undo** above the plot | |
| 18 | #' to remove the most recent vertex and update the preview. Undo can be used | |
| 19 | #' repeatedly, including to clear the drawing; it has no effect when empty. | |
| 20 | #' Finish using the device's | |
| 21 | #' locator termination action: for example, Escape on Quartz, another mouse | |
| 22 | #' button on X11, or Finish in RStudio. The plot uses equal X and Y scales. | |
| 23 | #' Other clicks outside the supplied limits and consecutive duplicate clicks are | |
| 24 | #' ignored. A dashed line marks the automatically supplied closing segment. | |
| 25 | #' | |
| 26 | #' At least three noncollinear vertices are needed to finish a polygon. | |
| 27 | #' Self-intersections and retraced edges are rejected. Redundant collinear | |
| 28 | #' vertices are removed, and the boundary is oriented counterclockwise to | |
| 29 | #' produce outward-facing lathe surfaces. | |
| 30 | #' | |
| 31 | #' For a polygon away from the axis, the first vertex is repeated at the end | |
| 32 | #' so [lathe_mesh()] includes the closing segment. When the polygon meets the | |
| 33 | #' axis, its boundary must touch it at a single vertex or along a single edge. | |
| 34 | #' Axis vertices become the profile endpoints; an edge along the axis is | |
| 35 | #' omitted because it does not sweep out a surface. This keeps radius-zero | |
| 36 | #' vertices out of the profile interior, as required by [lathe_mesh()]. | |
| 37 | #' | |
| 38 | #' @return A numeric matrix with columns `radius` and `height`, ready to pass | |
| 39 | #' as the `profile` argument of [lathe_mesh()]. Returns `NULL` if drawing is | |
| 40 | #' finished with no points remaining. | |
| 41 | #' @seealso [lathe_mesh()] | |
| 42 | #' @export | |
| 43 | #' @examplesIf interactive() | |
| 44 | #' profile = draw_lathe_profile(xlim = c(0, 2), ylim = c(0, 4)) | |
| 45 | #' if (!is.null(profile)) { | |
| 46 | #' mesh = lathe_mesh(profile) | |
| 47 | #' rasterize_scene(mesh, lookfrom = c(6, 5, 8), lookat = c(0, 2, 0)) | |
| 48 | #' } | |
| 49 | draw_lathe_profile = function(xlim = c(0, 1), ylim = c(0, 1), snap = 0.02) { | |
| 50 | 29x | for (name in c("xlim", "ylim")) { |
| 51 | 51x | limits = get(name) |
| 52 | if ( | |
| 53 | 51x | !is.numeric(limits) || |
| 54 | 51x | length(limits) != 2L || |
| 55 | 51x | any(!is.finite(limits)) || |
| 56 | 51x | !is.finite(diff(limits)) || |
| 57 | 51x | diff(limits) <= 0 |
| 58 | ) { | |
| 59 | 14x | stop(sprintf("`%s` must contain two increasing finite limits.", name)) |
| 60 | } | |
| 61 | } | |
| 62 | 15x | if (xlim[1L] < 0) { |
| 63 | 1x | stop("`xlim` must be nonnegative.") |
| 64 | } | |
| 65 | if ( | |
| 66 | 14x | !is.numeric(snap) || |
| 67 | 14x | length(snap) != 1L || |
| 68 | 14x | !is.finite(snap) || |
| 69 | 14x | snap < 0 || |
| 70 | 14x | snap >= 1 |
| 71 | ) { | |
| 72 | 7x | stop( |
| 73 | 7x | "`snap` must be a finite fraction from zero up to, but not including, one." |
| 74 | ) | |
| 75 | } | |
| 76 | 7x | if (!grDevices::dev.interactive(orNone = TRUE)) { |
| 77 | 1x | stop("Drawing a lathe profile requires an interactive graphics device.") |
| 78 | } | |
| 79 | ||
| 80 | 6x | margins = graphics::par("mar") |
| 81 | 6x | on.exit(graphics::par(mar = margins), add = TRUE) |
| 82 | 6x | graphics::par(mar = pmax(margins, c(0, 0, 4.1, 0))) |
| 83 | 6x | profile = matrix(numeric(), ncol = 2L) |
| 84 | 6x | repeat { |
| 85 | 34x | graphics::plot( |
| 86 | 34x | NA_real_, |
| 87 | 34x | NA_real_, |
| 88 | 34x | type = "n", |
| 89 | 34x | xlim = xlim, |
| 90 | 34x | ylim = ylim, |
| 91 | 34x | asp = 1, |
| 92 | 34x | xaxs = "i", |
| 93 | 34x | yaxs = "i", |
| 94 | 34x | xlab = "Radius (x)", |
| 95 | 34x | ylab = "Height (y)", |
| 96 | 34x | sub = "Click to add points; Undo to remove; Esc / right-click / Finish to end" |
| 97 | ) | |
| 98 | 34x | graphics::title(main = "Draw a lathe profile", line = 3) |
| 99 | 34x | graphics::grid() |
| 100 | 34x | graphics::rect(xlim[1L], ylim[1L], xlim[2L], ylim[2L], border = "grey70") |
| 101 | 34x | graphics::abline(v = 0, col = "grey50") |
| 102 | 34x | count = nrow(profile) |
| 103 | 34x | if (count >= 2L) { |
| 104 | 15x | graphics::polygon(profile, col = "lightblue", border = NA) |
| 105 | 15x | graphics::lines(profile, col = "steelblue4", lwd = 2) |
| 106 | 15x | graphics::segments( |
| 107 | 15x | profile[count, 1L], |
| 108 | 15x | profile[count, 2L], |
| 109 | 15x | profile[1L, 1L], |
| 110 | 15x | profile[1L, 2L], |
| 111 | 15x | col = "steelblue4", |
| 112 | 15x | lwd = 2, |
| 113 | 15x | lty = 2 |
| 114 | ) | |
| 115 | } | |
| 116 | 34x | if (count) { |
| 117 | 25x | graphics::points(profile, pch = 19, col = "steelblue4") |
| 118 | 25x | graphics::points(profile[1L, , drop = FALSE], pch = 21, bg = "white") |
| 119 | } | |
| 120 | # Keep the control outside the drawing area, sized to its label. | |
| 121 | 34x | usr = graphics::par("usr") |
| 122 | 34x | undo_x = usr[2L] - |
| 123 | 34x | c(graphics::strwidth("Undo") + 2 * graphics::strwidth("M"), 0) |
| 124 | 34x | undo_y = usr[4L] + c(1, 3) * graphics::strheight("M") |
| 125 | 34x | graphics::rect( |
| 126 | 34x | undo_x[1L], |
| 127 | 34x | undo_y[1L], |
| 128 | 34x | undo_x[2L], |
| 129 | 34x | undo_y[2L], |
| 130 | 9x | col = if (count) "grey95" else "white", |
| 131 | 34x | border = "grey60", |
| 132 | 34x | xpd = NA |
| 133 | ) | |
| 134 | 34x | graphics::text( |
| 135 | 34x | mean(undo_x), |
| 136 | 34x | mean(undo_y), |
| 137 | 34x | "Undo", |
| 138 | 9x | col = if (count) "black" else "grey60", |
| 139 | 34x | xpd = NA |
| 140 | ) | |
| 141 | 34x | point = graphics::locator(1L) |
| 142 | 34x | if (is.null(point)) { |
| 143 | 6x | break |
| 144 | } | |
| 145 | 28x | point = c(point$x, point$y) |
| 146 | 6x | if ( |
| 147 | 28x | all(is.finite(point)) && |
| 148 | 28x | point[1L] >= undo_x[1L] && |
| 149 | 28x | point[1L] <= undo_x[2L] && |
| 150 | 28x | point[2L] >= undo_y[1L] && |
| 151 | 28x | point[2L] <= undo_y[2L] |
| 152 | ) { | |
| 153 | 5x | if (count) { |
| 154 | 3x | profile = profile[-count, , drop = FALSE] |
| 155 | } | |
| 156 | 5x | next |
| 157 | } | |
| 158 | 6x | if ( |
| 159 | 23x | any(!is.finite(point)) || |
| 160 | 23x | point[1L] < xlim[1L] || |
| 161 | 23x | point[1L] > xlim[2L] || |
| 162 | 23x | point[2L] < ylim[1L] || |
| 163 | 23x | point[2L] > ylim[2L] |
| 164 | ) { | |
| 165 | 3x | message("Click inside the drawing limits.") |
| 166 | 3x | next |
| 167 | } | |
| 168 | 20x | if (xlim[1L] == 0 && point[1L] <= snap * diff(xlim)) { |
| 169 | 3x | point[1L] = 0 |
| 170 | } | |
| 171 | 20x | if (count && all(point == profile[count, ])) { |
| 172 | 1x | next |
| 173 | } | |
| 174 | 19x | profile = rbind(profile, point) |
| 175 | } | |
| 176 | 6x | if (!nrow(profile)) { |
| 177 | 2x | return(NULL) |
| 178 | } | |
| 179 | 4x | lathe_profile_polygon(profile) |
| 180 | } | |
| 181 | ||
| 182 | #' Convert a drawn polygon to a lathe profile | |
| 183 | #' @keywords internal | |
| 184 | #' @noRd | |
| 185 | lathe_profile_polygon = function(profile) { | |
| 186 | 17x | profile = polygon_ring(profile) |
| 187 | 15x | polygon_check_edges(list(profile)) |
| 188 | 14x | count = nrow(profile) |
| 189 | 14x | if (polygon_ring_area(profile) < 0) { |
| 190 | 4x | profile = profile[c(1L, count:2L), , drop = FALSE] |
| 191 | } | |
| 192 | 14x | axis = which(profile[, 1L] == 0) |
| 193 | 14x | if (length(axis)) { |
| 194 | 11x | next_id = c(seq_len(count)[-1L], 1L) |
| 195 | 11x | axis_edges = which(profile[, 1L] == 0 & profile[next_id, 1L] == 0) |
| 196 | 11x | if (length(axis) > 2L || (length(axis) == 2L && length(axis_edges) != 1L)) { |
| 197 | 1x | stop( |
| 198 | 1x | "The polygon must meet the axis at a single vertex or along a single edge." |
| 199 | ) | |
| 200 | } | |
| 201 | 10x | start = if (length(axis_edges)) next_id[axis_edges] else axis |
| 202 | 10x | profile = profile[c(start:count, seq_len(start - 1L)), , drop = FALSE] |
| 203 | } | |
| 204 | 13x | if (length(axis) < 2L) { |
| 205 | 4x | profile = rbind(profile, profile[1L, , drop = FALSE]) |
| 206 | } | |
| 207 | 13x | rownames(profile) = NULL |
| 208 | 13x | colnames(profile) = c("radius", "height") |
| 209 | 13x | profile |
| 210 | } |
| 1 | #' Cube 3D Model | |
| 2 | #' | |
| 3 | #' 3D obj model of the letter R | |
| 4 | #' | |
| 5 | #' @param position Default `c(0,0,0)`. Position of the mesh. | |
| 6 | #' @param scale Default `c(1,1,1)`. Scale of the mesh. Can also be a single numeric value scaling all axes uniformly. | |
| 7 | #' @param angle Default `c(0,0,0)`. Angle to rotate the mesh. | |
| 8 | #' @param pivot_point Default `c(0,0,0)`. Point around which to rotate the mesh. | |
| 9 | #' @param order_rotation Default `c(1,2,3)`. Order to rotate the axes. | |
| 10 | #' @param material Default [material_list()] (default values). Specify the material of the object. | |
| 11 | #' | |
| 12 | #' @return List describing the mesh. | |
| 13 | #' @export | |
| 14 | #' | |
| 15 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 16 | #' #Generate a cube | |
| 17 | #' generate_cornell_mesh() |> | |
| 18 | #' add_shape(cube_mesh(position = c(555/2, 100, 555/2), scale = 100)) |> | |
| 19 | #' rasterize_scene(light_info = directional_light(c(0.5,0.5,-1))) | |
| 20 | #' #Generate a blue rotated cube | |
| 21 | #' generate_cornell_mesh() |> | |
| 22 | #' add_shape(cube_mesh(position = c(555/2, 100, 555/2), scale = 100, angle=c(0,45,0), | |
| 23 | #' material = material_list(diffuse="dodgerblue"))) |> | |
| 24 | #' rasterize_scene(light_info = directional_light(c(0.5,0.5,-1))) | |
| 25 | #' #Generate a scaled, blue rotated cube | |
| 26 | #' generate_cornell_mesh() |> | |
| 27 | #' add_shape(cube_mesh(position = c(555/2, 100, 555/2), angle=c(0,45,0), | |
| 28 | #' scale = c(2,0.5,0.8)*100, | |
| 29 | #' material = material_list(diffuse="dodgerblue"))) |> | |
| 30 | #' rasterize_scene(light_info = directional_light(c(0.5,0.5,-1))) | |
| 31 | cube_mesh = function( | |
| 32 | position = c(0, 0, 0), | |
| 33 | scale = c(1, 1, 1), | |
| 34 | angle = c(0, 0, 0), | |
| 35 | pivot_point = c(0, 0, 0), | |
| 36 | order_rotation = c(1, 2, 3), | |
| 37 | material = material_list() | |
| 38 | ) { | |
| 39 | 3x | obj = get("cube", envir = ray_environment) |
| 40 | 3x | obj = set_material(obj, material = material) |
| 41 | 3x | if (any(scale != 1)) { |
| 42 | ! | obj = scale_mesh(obj, scale = scale) |
| 43 | } | |
| 44 | ||
| 45 | 3x | if (any(angle != 0)) { |
| 46 | ! | obj = rotate_mesh( |
| 47 | ! | obj, |
| 48 | ! | angle = angle, |
| 49 | ! | pivot_point = pivot_point, |
| 50 | ! | order_rotation = order_rotation |
| 51 | ) | |
| 52 | } | |
| 53 | 3x | obj = translate_mesh(obj, position) |
| 54 | 3x | obj |
| 55 | } | |
| 56 | ||
| 57 | #' Sphere 3D Model | |
| 58 | #' | |
| 59 | #' @param position Default `c(0,0,0)`. Position of the mesh. | |
| 60 | #' @param scale Default `c(1,1,1)`. Scale of the mesh. Can also be a single numeric value scaling all axes uniformly. | |
| 61 | #' @param angle Default `c(0,0,0)`. Angle to rotate the mesh. | |
| 62 | #' @param pivot_point Default `c(0,0,0)`. Point around which to rotate the mesh. | |
| 63 | #' @param order_rotation Default `c(1,2,3)`. Order to rotate the axes. | |
| 64 | #' @param radius Default `1`. Radius of the sphere. | |
| 65 | #' @param low_poly Default `FALSE`. If `TRUE`, will use a low-poly sphere. | |
| 66 | #' @param normals Default `TRUE`. Whether to include vertex normals. | |
| 67 | #' @param material Default [material_list()] (default values). Specify the material of the object. | |
| 68 | #' | |
| 69 | #' @return List describing the mesh. | |
| 70 | #' @export | |
| 71 | #' | |
| 72 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 73 | #' #Generate a sphere in the Cornell box. | |
| 74 | #' generate_cornell_mesh() |> | |
| 75 | #' add_shape(sphere_mesh(position = c(555/2, 555/2, 555/2), radius = 100)) |> | |
| 76 | #' rasterize_scene(light_info = directional_light(c(0,0.5,-1))) | |
| 77 | #' #Generate a shiny sphere in the Cornell box | |
| 78 | #' generate_cornell_mesh() |> | |
| 79 | #' add_shape(sphere_mesh(position = c(555/2, 100, 555/2), radius = 100, | |
| 80 | #' material = material_list(diffuse = "gold",type="phong"))) |> | |
| 81 | #' rasterize_scene(light_info = directional_light(c(0.5,0.5,-1))) | |
| 82 | #' #Generate an ellipsoid in the Cornell box | |
| 83 | #' generate_cornell_mesh() |> | |
| 84 | #' add_shape(sphere_mesh(position = c(555/2, 210, 555/2), radius = 100, | |
| 85 | #' angle=c(0,30,0), scale = c(0.5,2,0.5), | |
| 86 | #' material = material_list(diffuse = "dodgerblue",type="phong"))) |> | |
| 87 | #' rasterize_scene(light_info = directional_light(c(0.5,0.5,-1))) | |
| 88 | sphere_mesh = function( | |
| 89 | position = c(0, 0, 0), | |
| 90 | scale = c(1, 1, 1), | |
| 91 | angle = c(0, 0, 0), | |
| 92 | pivot_point = c(0, 0, 0), | |
| 93 | order_rotation = c(1, 2, 3), | |
| 94 | radius = 1, | |
| 95 | low_poly = FALSE, | |
| 96 | normals = TRUE, | |
| 97 | material = material_list() | |
| 98 | ) { | |
| 99 | 1x | if (!low_poly) { |
| 100 | 1x | obj = get("sphere", envir = ray_environment) |
| 101 | } else { | |
| 102 | ! | obj = get("low_poly_sphere", envir = ray_environment) |
| 103 | } | |
| 104 | 1x | obj$vertices[[1]] = obj$vertices[[1]] * radius |
| 105 | 1x | if (!normals) { |
| 106 | ! | obj$shapes[[1]]$has_vertex_normals = rep( |
| 107 | ! | FALSE, |
| 108 | ! | length(obj$shapes[[1]]$indices) |
| 109 | ) | |
| 110 | ! | obj$normals[[1]] = matrix(0, nrow = 0, ncol = 3) |
| 111 | } | |
| 112 | 1x | if (any(scale != 1)) { |
| 113 | ! | obj = scale_mesh(obj, scale = scale) |
| 114 | } | |
| 115 | 1x | if (any(angle != 0)) { |
| 116 | ! | obj = rotate_mesh( |
| 117 | ! | obj, |
| 118 | ! | angle = angle, |
| 119 | ! | pivot_point = pivot_point, |
| 120 | ! | order_rotation = order_rotation |
| 121 | ) | |
| 122 | } | |
| 123 | 1x | obj = translate_mesh(obj, position) |
| 124 | 1x | obj = set_material(obj, material = material) |
| 125 | ||
| 126 | 1x | obj |
| 127 | } | |
| 128 | ||
| 129 | #' Cone 3D Model | |
| 130 | #' | |
| 131 | #' @param start Default `c(0, 0, 0)`. Base of the cone, specifying `x`, `y`, `z`. | |
| 132 | #' @param end Default `c(0, 1, 0)`. Tip of the cone, specifying `x`, `y`, `z`. | |
| 133 | #' @param radius Default `1`. Radius of the bottom of the cone. | |
| 134 | #' @param direction Default `NA`. Alternative to `start` and `end`, specify the direction (via | |
| 135 | #' a length-3 vector) of the cone. Cone will be centered at `start`, and the length will be | |
| 136 | #' determined by the magnitude of the direction vector. | |
| 137 | #' @param from_center Default `TRUE`. If orientation specified via `direction`, setting this argument | |
| 138 | #' to `FALSE` will make `start` specify the bottom of the cone, instead of the middle. | |
| 139 | #' @param material Default [material_list()] (default values). Specify the material of the object. | |
| 140 | #' | |
| 141 | #' @return List describing the mesh. | |
| 142 | #' @export | |
| 143 | #' | |
| 144 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 145 | #' #Generate a cone | |
| 146 | #' generate_cornell_mesh() |> | |
| 147 | #' add_shape(cone_mesh(start = c(555/2, 20, 555/2), end = c(555/2, 300, 555/2), | |
| 148 | #' radius = 100)) |> | |
| 149 | #' rasterize_scene(light_info = directional_light(c(0.5,0.5,-1))) | |
| 150 | #' #Generate a blue cone with a wide base | |
| 151 | #' generate_cornell_mesh() |> | |
| 152 | #' add_shape(cone_mesh(start = c(555/2, 20, 555/2), end = c(555/2, 300, 555/2), radius=200, | |
| 153 | #' material = material_list(diffuse="dodgerblue"))) |> | |
| 154 | #' rasterize_scene(light_info = directional_light(c(0.5,0.5,-1))) | |
| 155 | #' #Generate a long, thin cone | |
| 156 | #' generate_cornell_mesh() |> | |
| 157 | #' add_shape(cone_mesh(start = c(555/2, 20, 555/2), end = c(555/2, 400, 555/2), radius=50, | |
| 158 | #' material = material_list(diffuse="dodgerblue"))) |> | |
| 159 | #' rasterize_scene(light_info = directional_light(c(0.5,0.5,-1))) | |
| 160 | cone_mesh = function( | |
| 161 | start = c(0, 0, 0), | |
| 162 | end = c(0, 1, 0), | |
| 163 | radius = 0.5, | |
| 164 | direction = NA, | |
| 165 | from_center = FALSE, | |
| 166 | material = material_list() | |
| 167 | ) { | |
| 168 | ! | obj = get("cone", envir = ray_environment) |
| 169 | ! | obj = set_material(obj, material = material) |
| 170 | ||
| 171 | ! | if (all(!is.na(direction)) && length(direction) == 3) { |
| 172 | ! | if (from_center) { |
| 173 | ! | new_start = start - direction / 2 |
| 174 | ! | new_end = start + direction / 2 |
| 175 | } else { | |
| 176 | ! | new_start = start |
| 177 | ! | new_end = start + direction |
| 178 | } | |
| 179 | ! | start = new_start |
| 180 | ! | end = new_end |
| 181 | } | |
| 182 | ! | x = (start[1] + end[1]) / 2 |
| 183 | ! | y = (start[2] + end[2]) / 2 |
| 184 | ! | z = (start[3] + end[3]) / 2 |
| 185 | ! | order_rotation = c(3, 2, 1) |
| 186 | ! | phi = atan2(as.numeric(end[1] - start[1]), as.numeric(end[3] - start[3])) / |
| 187 | ! | pi * |
| 188 | ! | 180 + |
| 189 | ! | 90 |
| 190 | ||
| 191 | ! | length_xy = sqrt((end[1] - start[1])^2 + (end[3] - start[3])^2) |
| 192 | ! | if (end[1] == start[1] && end[3] == start[3]) { |
| 193 | ! | if (start[2] - end[2] > 0) { |
| 194 | ! | theta = 180 |
| 195 | } else { | |
| 196 | ! | theta = 0 |
| 197 | } | |
| 198 | } else { | |
| 199 | ! | theta = atan2(as.numeric(-length_xy), as.numeric(end[2] - start[2])) / |
| 200 | ! | pi * |
| 201 | ! | 180 |
| 202 | } | |
| 203 | ! | fulllength = sqrt(sum((end - start)^2)) |
| 204 | ! | angle = c(0, -phi, theta) |
| 205 | ||
| 206 | ! | obj = scale_mesh(obj, scale = c(radius / 0.5, fulllength, radius / 0.5)) |
| 207 | ||
| 208 | ! | obj = rotate_mesh(obj, angle = angle, order_rotation = order_rotation) |
| 209 | ! | obj = translate_mesh(obj, c(x, y, z)) |
| 210 | ! | obj |
| 211 | } | |
| 212 | ||
| 213 | #' Arrow 3D Model | |
| 214 | #' | |
| 215 | #' @param start Default `c(0, 0, 0)`. Base of the arrow, specifying `x`, `y`, `z`. | |
| 216 | #' @param end Default `c(0, 1, 0)`. Tip of the arrow, specifying `x`, `y`, `z`. | |
| 217 | #' @param radius_top Default `0.5`. Radius of the top of the arrow. | |
| 218 | #' @param radius_tail Default `0.2`. Radius of the tail of the arrow. | |
| 219 | #' @param tail_proportion Default `0.5`. Proportion of the arrow that is the tail. | |
| 220 | #' @param direction Default `NA`. Alternative to `start` and `end`, specify the direction (via | |
| 221 | #' a length-3 vector) of the arrow. Arrow will be centered at `start`, and the length will be | |
| 222 | #' determined by the magnitude of the direction vector. | |
| 223 | #' @param from_center Default `TRUE`. If orientation specified via `direction`, setting this argument | |
| 224 | #' to `FALSE` will make `start` specify the bottom of the cone, instead of the middle. | |
| 225 | #' @param material Default [material_list()] (default values). Specify the material of the object. | |
| 226 | #' | |
| 227 | #' @return List describing the mesh. | |
| 228 | #' @export | |
| 229 | #' | |
| 230 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 231 | #' #Generate an arrow | |
| 232 | #' generate_cornell_mesh() |> | |
| 233 | #' add_shape(arrow_mesh(start = c(555/2, 20, 555/2), end = c(555/2, 300, 555/2), radius_tail=50, | |
| 234 | #' radius_top = 100, | |
| 235 | #' material = material_list(diffuse="dodgerblue"))) |> | |
| 236 | #' rasterize_scene(light_info = directional_light(c(0.5,0.5,-1))) | |
| 237 | #' #Generate a blue arrow with a wide tail | |
| 238 | #' generate_cornell_mesh() |> | |
| 239 | #' add_shape(arrow_mesh(start = c(555/2, 20, 555/2), end = c(555/2, 300, 555/2), radius_tail=100, | |
| 240 | #' radius_top = 150, | |
| 241 | #' material = material_list(diffuse="dodgerblue"))) |> | |
| 242 | #' rasterize_scene(light_info = directional_light(c(0.5,0.5,-1))) | |
| 243 | #' #Generate a long, thin arrow and change the proportions | |
| 244 | #' generate_cornell_mesh() |> | |
| 245 | #' add_shape(arrow_mesh(start = c(555/2, 20, 555/2), end = c(555/2, 400, 555/2), radius_top=30, | |
| 246 | #' radius_tail = 10, tail_proportion = 0.8, | |
| 247 | #' material = material_list(diffuse="dodgerblue"))) |> | |
| 248 | #' rasterize_scene(light_info = directional_light(c(0.5,0.5,-1))) | |
| 249 | #' #Change the start and end points | |
| 250 | #' generate_cornell_mesh() |> | |
| 251 | #' add_shape(arrow_mesh(start = c(500, 20, 555/2), end = c(50, 500, 555/2), radius_top=30, | |
| 252 | #' radius_tail = 10, tail_proportion = 0.8, | |
| 253 | #' material = material_list(diffuse="dodgerblue"))) |> | |
| 254 | #' add_shape(arrow_mesh(start = c(500, 500, 500), end = c(50, 50, 50), radius_top=30, | |
| 255 | #' radius_tail = 10, tail_proportion = 0.8, | |
| 256 | #' material = material_list(diffuse="red"))) |> | |
| 257 | #' add_shape(arrow_mesh(start = c(555/2, 50, 500), end = c(555/2, 50, 50), radius_top=30, | |
| 258 | #' radius_tail = 10, tail_proportion = 0.8, | |
| 259 | #' material = material_list(diffuse="green"))) |> | |
| 260 | #' rasterize_scene(light_info = directional_light(c(0.5,0.5,-1))) | |
| 261 | arrow_mesh = function( | |
| 262 | start = c(0, 0, 0), | |
| 263 | end = c(0, 1, 0), | |
| 264 | radius_top = 0.5, | |
| 265 | radius_tail = 0.25, | |
| 266 | tail_proportion = 0.5, | |
| 267 | direction = NA, | |
| 268 | from_center = TRUE, | |
| 269 | material = material_list() | |
| 270 | ) { | |
| 271 | ! | stopifnot(tail_proportion > 0 && tail_proportion < 1) |
| 272 | ||
| 273 | ! | if (all(!is.na(direction)) && length(direction) == 3) { |
| 274 | ! | if (from_center) { |
| 275 | ! | new_start = start - direction / 2 |
| 276 | ! | new_end = start + direction / 2 |
| 277 | } else { | |
| 278 | ! | new_start = start |
| 279 | ! | new_end = start + direction |
| 280 | } | |
| 281 | ! | start = new_start |
| 282 | ! | end = new_end |
| 283 | } | |
| 284 | ! | x = (start[1] + end[1]) / 2 |
| 285 | ! | y = (start[2] + end[2]) / 2 |
| 286 | ! | z = (start[3] + end[3]) / 2 |
| 287 | ! | order_rotation = c(3, 2, 1) |
| 288 | ! | phi = atan2(as.numeric(end[1] - start[1]), as.numeric(end[3] - start[3])) / |
| 289 | ! | pi * |
| 290 | ! | 180 + |
| 291 | ! | 90 |
| 292 | ||
| 293 | ! | length_xy = sqrt((end[1] - start[1])^2 + (end[3] - start[3])^2) |
| 294 | ! | if (end[1] == start[1] && end[3] == start[3]) { |
| 295 | ! | if (start[2] - end[2] > 0) { |
| 296 | ! | theta = 180 |
| 297 | } else { | |
| 298 | ! | theta = 0 |
| 299 | } | |
| 300 | } else { | |
| 301 | ! | theta = atan2(as.numeric(-length_xy), as.numeric(end[2] - start[2])) / |
| 302 | ! | pi * |
| 303 | ! | 180 |
| 304 | } | |
| 305 | ! | fulllength = sqrt(sum((end - start)^2)) |
| 306 | ! | angle = c(0, -phi, theta) |
| 307 | ||
| 308 | ! | obj = get("arrow", envir = ray_environment) |
| 309 | ! | obj = set_material(obj, material = material) |
| 310 | ||
| 311 | ! | obj$vertices[[1]][c(1:32, 66:97), c(1, 3)] = obj$vertices[[1]][ |
| 312 | ! | c(1:32, 66:97), |
| 313 | ! | c(1, 3) |
| 314 | ] * | |
| 315 | ! | radius_tail / |
| 316 | ! | 0.25 |
| 317 | ! | obj$vertices[[1]][34:65, c(1, 3)] = obj$vertices[[1]][34:65, c(1, 3)] * |
| 318 | ! | radius_top / |
| 319 | ! | 0.5 |
| 320 | ||
| 321 | #Proportions | |
| 322 | ! | obj$vertices[[1]][33, 2] = (1 - 0.5) * fulllength |
| 323 | ! | obj$vertices[[1]][c(1:32, 34:65), 2] = (tail_proportion - 0.5) * fulllength |
| 324 | ! | obj$vertices[[1]][66:97, 2] = (-0.5 * fulllength) |
| 325 | ||
| 326 | ! | obj = rotate_mesh(obj, angle = angle, order_rotation = order_rotation) |
| 327 | ! | obj = translate_mesh(obj, c(x, y, z)) |
| 328 | ! | obj |
| 329 | } | |
| 330 | ||
| 331 | #' Cylinder 3D Model | |
| 332 | #' | |
| 333 | #' @param position Default `c(0,0,0)`. Position of the mesh. | |
| 334 | #' @param angle Default `c(0,0,0)`. Angle to rotate the mesh. | |
| 335 | #' @param pivot_point Default `c(0,0,0)`. Point around which to rotate the mesh. | |
| 336 | #' @param order_rotation Default `c(1,2,3)`. Order to rotate the axes. | |
| 337 | #' @param radius Default `0.5`. Radius of the cylinder. | |
| 338 | #' @param length Default `1`. Length of the cylinder. | |
| 339 | #' @param material Default [material_list()] (default values). Specify the material of the object. | |
| 340 | #' | |
| 341 | #' | |
| 342 | #' @return List describing the mesh. | |
| 343 | #' @export | |
| 344 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 345 | #' #Generate a cylinder | |
| 346 | #' generate_cornell_mesh() |> | |
| 347 | #' add_shape(cylinder_mesh(position=c(555/2,150,555/2), | |
| 348 | #' radius = 50, length=300, material = material_list(diffuse="purple"))) |> | |
| 349 | #' rasterize_scene(light_info = directional_light(c(0.5,0.5,-1))) | |
| 350 | #' #Generate a wide, thin disk | |
| 351 | #' generate_cornell_mesh() |> | |
| 352 | #' add_shape(cylinder_mesh(position=c(555/2,20,555/2), | |
| 353 | #' radius = 200, length=5, material = material_list(diffuse="purple"))) |> | |
| 354 | #' rasterize_scene(light_info = directional_light(c(0.5,0.5,-1))) | |
| 355 | #' #Generate a narrow cylinder | |
| 356 | #' generate_cornell_mesh() |> | |
| 357 | #' add_shape(cylinder_mesh(position=c(555/2,555/2,555/2),angle=c(45,-45,0), | |
| 358 | #' radius = 10, length=500, material = material_list(diffuse="purple"))) |> | |
| 359 | #' rasterize_scene(light_info = directional_light(c(0.5,0.5,-1))) | |
| 360 | cylinder_mesh = function( | |
| 361 | position = c(0, 0, 0), | |
| 362 | radius = 0.5, | |
| 363 | length = 1, | |
| 364 | angle = c(0, 0, 0), | |
| 365 | pivot_point = c(0, 0, 0), | |
| 366 | order_rotation = c(1, 2, 3), | |
| 367 | material = material_list() | |
| 368 | ) { | |
| 369 | ! | obj = get("cylinder", envir = ray_environment) |
| 370 | ! | obj = set_material(obj, material = material) |
| 371 | ! | obj = scale_mesh(obj, scale = c(radius, length, radius)) |
| 372 | ||
| 373 | ! | if (any(angle != 0)) { |
| 374 | ! | obj = rotate_mesh( |
| 375 | ! | obj, |
| 376 | ! | angle = angle, |
| 377 | ! | pivot_point = pivot_point, |
| 378 | ! | order_rotation = order_rotation |
| 379 | ) | |
| 380 | } | |
| 381 | ! | obj = translate_mesh(obj, position) |
| 382 | ||
| 383 | ! | obj |
| 384 | } | |
| 385 | ||
| 386 | #' Segment 3D Model | |
| 387 | #' | |
| 388 | #' @param start Default `c(0, 0, 0)`. Base of the segment, specifying `x`, `y`, `z`. | |
| 389 | #' @param end Default `c(0, 1, 0)`. End of the segment, specifying `x`, `y`, `z`. | |
| 390 | #' @param radius Default `0.5`. Radius of the cylinder. | |
| 391 | #' @param direction Default `NA`. Alternative to `start` and `end`, specify the direction (via | |
| 392 | #' a length-3 vector) of the arrow. Arrow will be centered at `start`, and the length will be | |
| 393 | #' determined by the magnitude of the direction vector. | |
| 394 | #' @param from_center Default `TRUE`. If orientation specified via `direction`, setting this argument | |
| 395 | #' to `FALSE` will make `start` specify the bottom of the cone, instead of the middle. | |
| 396 | #' @param square Default `FALSE`. If `TRUE`, will use a square instead of a circle for the cylinder. | |
| 397 | #' @param material Default [material_list()] (default values). Specify the material of the object. | |
| 398 | #' | |
| 399 | #' @return List describing the mesh. | |
| 400 | #' @export | |
| 401 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 402 | #' #Generate a segment in the cornell box. | |
| 403 | #' generate_cornell_mesh() |> | |
| 404 | #' add_shape(segment_mesh(start = c(100, 100, 100), end = c(455, 455, 455), radius = 50)) |> | |
| 405 | #' rasterize_scene(light_info = directional_light(c(0,0.5,-1))) | |
| 406 | #' # Draw a line graph representing a normal distribution, but with metal: | |
| 407 | #' xvals = seq(-3, 3, length.out = 30) | |
| 408 | #' yvals = dnorm(xvals) | |
| 409 | #' | |
| 410 | #' scene_list = list() | |
| 411 | #' for(i in 1:(length(xvals) - 1)) { | |
| 412 | #' scene_list = add_shape(scene_list, | |
| 413 | #' segment_mesh(start = c(555/2 + xvals[i] * 80, yvals[i] * 800, 555/2), | |
| 414 | #' end = c(555/2 + xvals[i + 1] * 80, yvals[i + 1] * 800, 555/2), | |
| 415 | #' radius = 10, | |
| 416 | #' material = material_list(diffuse="purple", type="phong"))) | |
| 417 | #' } | |
| 418 | #' | |
| 419 | #' generate_cornell_mesh() |> | |
| 420 | #' add_shape(scene_list) |> | |
| 421 | #' rasterize_scene(light_info = directional_light(c(0,0.5,-1))) | |
| 422 | #' #Draw the outline of a cube: | |
| 423 | #' | |
| 424 | #' cube_outline = segment_mesh(start = c(100, 100, 100), end = c(100, 100, 455), radius = 10) |> | |
| 425 | #' add_shape(segment_mesh(start = c(100, 100, 100), end = c(100, 455, 100), radius = 10)) |> | |
| 426 | #' add_shape(segment_mesh(start = c(100, 100, 100), end = c(455, 100, 100), radius = 10)) |> | |
| 427 | #' add_shape(segment_mesh(start = c(100, 100, 455), end = c(100, 455, 455), radius = 10)) |> | |
| 428 | #' add_shape(segment_mesh(start = c(100, 100, 455), end = c(455, 100, 455), radius = 10)) |> | |
| 429 | #' add_shape(segment_mesh(start = c(100, 455, 455), end = c(100, 455, 100), radius = 10)) |> | |
| 430 | #' add_shape(segment_mesh(start = c(100, 455, 455), end = c(455, 455, 455), radius = 10)) |> | |
| 431 | #' add_shape(segment_mesh(start = c(455, 455, 100), end = c(455, 100, 100), radius = 10)) |> | |
| 432 | #' add_shape(segment_mesh(start = c(455, 455, 100), end = c(455, 455, 455), radius = 10)) |> | |
| 433 | #' add_shape(segment_mesh(start = c(455, 100, 100), end = c(455, 100, 455), radius = 10)) |> | |
| 434 | #' add_shape(segment_mesh(start = c(455, 100, 455), end = c(455, 455, 455), radius = 10)) |> | |
| 435 | #' add_shape(segment_mesh(start = c(100, 455, 100), end = c(455, 455, 100), radius = 10)) | |
| 436 | #' | |
| 437 | #' generate_cornell_mesh() |> | |
| 438 | #' add_shape(set_material(cube_outline,diffuse="dodgerblue",type="phong")) |> | |
| 439 | #' rasterize_scene(light_info = directional_light(c(0,0.5,-1))) | |
| 440 | #' #Shrink and rotate the cube | |
| 441 | #' generate_cornell_mesh() |> | |
| 442 | #' add_shape( | |
| 443 | #' scale_mesh(rotate_mesh(set_material(cube_outline,diffuse="dodgerblue",type="phong"), | |
| 444 | #' angle=c(45,45,45), pivot_point=c(555/2,555/2,555/2)),0.5, | |
| 445 | #' center=c(555/2,555/2,555/2))) |> | |
| 446 | #' rasterize_scene(light_info = directional_light(c(0,0.5,-1))) | |
| 447 | segment_mesh = function( | |
| 448 | start = c(0, -1, 0), | |
| 449 | end = c(0, 1, 0), | |
| 450 | radius = 0.5, | |
| 451 | direction = NA, | |
| 452 | from_center = TRUE, | |
| 453 | square = FALSE, | |
| 454 | material = material_list() | |
| 455 | ) { | |
| 456 | ! | if (all(!is.na(direction)) && length(direction) == 3) { |
| 457 | ! | if (from_center) { |
| 458 | ! | new_start = start - direction / 2 |
| 459 | ! | new_end = start + direction / 2 |
| 460 | } else { | |
| 461 | ! | new_start = start |
| 462 | ! | new_end = start + direction |
| 463 | } | |
| 464 | ! | start = new_start |
| 465 | ! | end = new_end |
| 466 | } | |
| 467 | ! | x = (start[1] + end[1]) / 2 |
| 468 | ! | y = (start[2] + end[2]) / 2 |
| 469 | ! | z = (start[3] + end[3]) / 2 |
| 470 | ! | order_rotation = c(3, 2, 1) |
| 471 | ! | phi = atan2(as.numeric(end[1] - start[1]), as.numeric(end[3] - start[3])) / |
| 472 | ! | pi * |
| 473 | ! | 180 + |
| 474 | ! | 90 |
| 475 | ||
| 476 | ! | length_xy = sqrt((end[1] - start[1])^2 + (end[3] - start[3])^2) |
| 477 | ! | if (end[1] == start[1] && end[3] == start[3]) { |
| 478 | ! | if (start[2] - end[2] > 0) { |
| 479 | ! | theta = 180 |
| 480 | } else { | |
| 481 | ! | theta = 0 |
| 482 | } | |
| 483 | } else { | |
| 484 | ! | theta = atan2(as.numeric(-length_xy), as.numeric((end[2] - start[2]))) / |
| 485 | ! | pi * |
| 486 | ! | 180 |
| 487 | } | |
| 488 | ! | fulllength = sqrt(sum((end - start)^2)) |
| 489 | ! | angle = c(0, -phi, theta) |
| 490 | ||
| 491 | ! | if (!square) { |
| 492 | ! | obj = cylinder_mesh( |
| 493 | ! | angle = angle, |
| 494 | ! | order_rotation = order_rotation, |
| 495 | ! | radius = radius, |
| 496 | ! | length = fulllength, |
| 497 | ! | material = material |
| 498 | ) | |
| 499 | } else { | |
| 500 | ! | obj = cube_mesh( |
| 501 | ! | angle = angle, |
| 502 | ! | order_rotation = order_rotation, |
| 503 | ! | scale = c(radius * 2, fulllength, radius * 2), |
| 504 | ! | material = material |
| 505 | ) | |
| 506 | } | |
| 507 | ! | obj = translate_mesh(obj, c(x, y, z)) |
| 508 | ! | obj |
| 509 | } | |
| 510 | ||
| 511 | #' XY Rectangle 3D Model | |
| 512 | #' | |
| 513 | #' @param position Default `c(0,0,0)`. Position of the mesh. | |
| 514 | #' @param scale Default `c(1,1,1)`. Scale of the mesh. Can also be a single numeric value scaling all axes uniformly. | |
| 515 | #' @param angle Default `c(0,0,0)`. Angle to rotate the mesh. | |
| 516 | #' @param pivot_point Default `c(0,0,0)`. Point around which to rotate the mesh. | |
| 517 | #' @param order_rotation Default `c(1,2,3)`. Order to rotate the axes. | |
| 518 | #' @param material Default [material_list()] (default values). Specify the material of the object. | |
| 519 | #' | |
| 520 | #' @return List describing the mesh. | |
| 521 | #' @export | |
| 522 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 523 | #' generate_cornell_mesh() |> | |
| 524 | #' add_shape(xy_rect_mesh(position = c(555/2, 100, 555/2), scale=200, | |
| 525 | #' material = material_list(diffuse = "purple"),angle=c(0,180,0))) |> | |
| 526 | #' rasterize_scene(light_info = directional_light(c(0,0.5,-1))) | |
| 527 | #' #Rotate the plane and scale | |
| 528 | #' generate_cornell_mesh() |> | |
| 529 | #' add_shape(xy_rect_mesh(position = c(555/2, 100, 555/2), scale=c(200,100,1), angle=c(0,180,0), | |
| 530 | #' material = material_list(diffuse = "purple"))) |> | |
| 531 | #' rasterize_scene(light_info = directional_light(c(0,0.5,-1))) | |
| 532 | xy_rect_mesh = function( | |
| 533 | position = c(0, 0, 0), | |
| 534 | scale = c(1, 1, 1), | |
| 535 | angle = c(0, 0, 0), | |
| 536 | pivot_point = c(0, 0, 0), | |
| 537 | order_rotation = c(1, 2, 3), | |
| 538 | material = material_list() | |
| 539 | ) { | |
| 540 | 2x | obj = get("xy_plane", envir = ray_environment) |
| 541 | 2x | obj = set_material(obj, material = material) |
| 542 | ||
| 543 | 2x | if (any(scale != 1)) { |
| 544 | 2x | obj = scale_mesh(obj, scale = scale) |
| 545 | } | |
| 546 | 2x | if (any(angle != 0)) { |
| 547 | ! | obj = rotate_mesh( |
| 548 | ! | obj, |
| 549 | ! | angle = angle, |
| 550 | ! | pivot_point = pivot_point, |
| 551 | ! | order_rotation = order_rotation |
| 552 | ) | |
| 553 | } | |
| 554 | 2x | obj = translate_mesh(obj, position) |
| 555 | 2x | obj |
| 556 | } | |
| 557 | ||
| 558 | #' XZ Rectangle 3D Model | |
| 559 | #' | |
| 560 | #' @param position Default `c(0,0,0)`. Position of the mesh. | |
| 561 | #' @param scale Default `c(1,1,1)`. Scale of the mesh. Can also be a single numeric value scaling all axes uniformly. | |
| 562 | #' @param angle Default `c(0,0,0)`. Angle to rotate the mesh. | |
| 563 | #' @param pivot_point Default `c(0,0,0)`. Point around which to rotate the mesh. | |
| 564 | #' @param order_rotation Default `c(1,2,3)`. Order to rotate the axes. | |
| 565 | #' @param material Default [material_list()] (default values). Specify the material of the object. | |
| 566 | #' | |
| 567 | #' @return List describing the mesh. | |
| 568 | #' @export | |
| 569 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 570 | #' generate_cornell_mesh() |> | |
| 571 | #' add_shape(xz_rect_mesh(position = c(555/2, 100, 555/2), scale=200, | |
| 572 | #' material = material_list(diffuse = "purple"))) |> | |
| 573 | #' rasterize_scene(light_info = directional_light(c(0,0.5,-1))) | |
| 574 | #' #Rotate the plane and scale | |
| 575 | #' generate_cornell_mesh() |> | |
| 576 | #' add_shape(xz_rect_mesh(position = c(555/2, 100, 555/2), scale=c(200,1,100), angle=c(0,30,0), | |
| 577 | #' material = material_list(diffuse = "purple"))) |> | |
| 578 | #' rasterize_scene(light_info = directional_light(c(0,0.5,-1))) | |
| 579 | xz_rect_mesh = function( | |
| 580 | position = c(0, 0, 0), | |
| 581 | scale = c(1, 1, 1), | |
| 582 | angle = c(0, 0, 0), | |
| 583 | pivot_point = c(0, 0, 0), | |
| 584 | order_rotation = c(1, 2, 3), | |
| 585 | material = material_list() | |
| 586 | ) { | |
| 587 | ! | obj = get("xz_plane", envir = ray_environment) |
| 588 | ! | if (any(scale != 1)) { |
| 589 | ! | obj = scale_mesh(obj, scale = scale) |
| 590 | } | |
| 591 | ! | if (any(angle != 0)) { |
| 592 | ! | obj = rotate_mesh( |
| 593 | ! | obj, |
| 594 | ! | angle = angle, |
| 595 | ! | pivot_point = pivot_point, |
| 596 | ! | order_rotation = order_rotation |
| 597 | ) | |
| 598 | } | |
| 599 | ! | obj = translate_mesh(obj, position) |
| 600 | ! | obj = set_material(obj, material = material) |
| 601 | ! | obj |
| 602 | } | |
| 603 | ||
| 604 | #' YZ Rectangle 3D Model | |
| 605 | #' | |
| 606 | #' @param position Default `c(0,0,0)`. Position of the mesh. | |
| 607 | #' @param scale Default `c(1,1,1)`. Scale of the mesh. Can also be a single numeric value scaling all axes uniformly. | |
| 608 | #' @param angle Default `c(0,0,0)`. Angle to rotate the mesh. | |
| 609 | #' @param pivot_point Default `c(0,0,0)`. Point around which to rotate the mesh. | |
| 610 | #' @param order_rotation Default `c(1,2,3)`. Order to rotate the axes. | |
| 611 | #' @param material Default [material_list()] (default values). Specify the material of the object. | |
| 612 | #' | |
| 613 | #' @return List describing the mesh. | |
| 614 | #' @export | |
| 615 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 616 | #' generate_cornell_mesh() |> | |
| 617 | #' add_shape(yz_rect_mesh(position = c(555/2, 100, 555/2), scale=c(200,1,200), angle=c(0,0,0), | |
| 618 | #' material = material_list(diffuse = "purple"))) |> | |
| 619 | #' rasterize_scene(light_info = directional_light(c(0,0.5,-1))) | |
| 620 | #' #Rotate and scale | |
| 621 | #' generate_cornell_mesh() |> | |
| 622 | #' add_shape(yz_rect_mesh(position = c(555/2, 100, 555/2), scale=c(300,1,200), angle=c(0,45,0), | |
| 623 | #' material = material_list(diffuse = "purple"))) |> | |
| 624 | #' rasterize_scene(light_info = directional_light(c(0,0.5,-1))) | |
| 625 | yz_rect_mesh = function( | |
| 626 | position = c(0, 0, 0), | |
| 627 | scale = c(1, 1, 1), | |
| 628 | angle = c(0, 0, 0), | |
| 629 | pivot_point = c(0, 0, 0), | |
| 630 | order_rotation = c(1, 2, 3), | |
| 631 | material = material_list() | |
| 632 | ) { | |
| 633 | ! | obj = get("yz_plane", envir = ray_environment) |
| 634 | ||
| 635 | ! | if (any(scale != 1)) { |
| 636 | ! | obj = scale_mesh(obj, scale = scale) |
| 637 | } | |
| 638 | ! | if (any(angle != 0)) { |
| 639 | ! | obj = rotate_mesh( |
| 640 | ! | obj, |
| 641 | ! | angle = angle, |
| 642 | ! | pivot_point = pivot_point, |
| 643 | ! | order_rotation = order_rotation |
| 644 | ) | |
| 645 | } | |
| 646 | ! | obj = translate_mesh(obj, position) |
| 647 | ! | obj = set_material(obj, material = material) |
| 648 | ! | obj |
| 649 | } | |
| 650 | ||
| 651 | #' Cornell Box 3D Model | |
| 652 | #' | |
| 653 | #' @param leftcolor Default `#1f7326` (green). | |
| 654 | #' @param rightcolor Default `#a60d0d` (red). | |
| 655 | #' @param roomcolor Default `#bababa` (light grey). | |
| 656 | #' @param ceiling Default `TRUE`. Whether to render the ceiling. | |
| 657 | #' @param light Default `TRUE`. Whether to render a point light near the ceiling. | |
| 658 | #'@return List describing the mesh. | |
| 659 | #'@export | |
| 660 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 661 | #' #Generate and render the default Cornell box and add an object. | |
| 662 | #' generate_cornell_mesh() |> | |
| 663 | #' rasterize_scene() | |
| 664 | #' #Add an object to the scene | |
| 665 | #' generate_cornell_mesh() |> | |
| 666 | #' add_shape(obj_mesh(r_obj(),position=c(555/2,555/2,555/2),scale=300,angle=c(0,180,0))) |> | |
| 667 | #' rasterize_scene() | |
| 668 | #' #Turn off the ceiling so the default directional light reaches inside the box | |
| 669 | #' generate_cornell_mesh(ceiling=FALSE) |> | |
| 670 | #' add_shape(obj_mesh(r_obj(),position=c(555/2,555/2,555/2),scale=300,angle=c(0,180,0))) |> | |
| 671 | #' rasterize_scene() | |
| 672 | #' #Adjust the light to the front | |
| 673 | #' generate_cornell_mesh(ceiling=FALSE) |> | |
| 674 | #' add_shape(obj_mesh(r_obj(),position=c(555/2,555/2,555/2),scale=300,angle=c(0,180,0))) |> | |
| 675 | #' rasterize_scene(light_info = directional_light(direction=c(0,1,-1))) | |
| 676 | #' #Change the color palette | |
| 677 | #' generate_cornell_mesh(ceiling=FALSE,leftcolor="purple", rightcolor="yellow") |> | |
| 678 | #' add_shape(obj_mesh(r_obj(),position=c(555/2,555/2,555/2),scale=300,angle=c(0,180,0))) |> | |
| 679 | #' rasterize_scene(light_info = directional_light(direction=c(0,1,-1))) | |
| 680 | generate_cornell_mesh = function( | |
| 681 | leftcolor = "#1f7326", | |
| 682 | rightcolor = "#a60d0d", | |
| 683 | roomcolor = "#bababa", | |
| 684 | ceiling = TRUE, | |
| 685 | light = TRUE | |
| 686 | ) { | |
| 687 | ! | ambient_intensity = 0.25 |
| 688 | ! | if (ceiling) { |
| 689 | ! | scene = set_material( |
| 690 | ! | cube_mesh( |
| 691 | ! | position = c(555 + 5, 555 / 2, 555 / 2), |
| 692 | ! | scale = c(10, 555, 555) |
| 693 | ), | |
| 694 | ! | diffuse = leftcolor, |
| 695 | ! | ambient = leftcolor, |
| 696 | ! | ambient_intensity = ambient_intensity |
| 697 | ) |> | |
| 698 | ! | add_shape(set_material( |
| 699 | ! | cube_mesh( |
| 700 | ! | position = c(-5, 555 / 2, 555 / 2), |
| 701 | ! | angle = c(0, 180, 0), |
| 702 | ! | scale = c(10, 555, 555) |
| 703 | ), | |
| 704 | ! | diffuse = rightcolor, |
| 705 | ! | ambient = rightcolor, |
| 706 | ! | ambient_intensity = ambient_intensity |
| 707 | )) |> | |
| 708 | ! | add_shape(set_material( |
| 709 | ! | cube_mesh( |
| 710 | ! | position = c(555 / 2, 555 + 5, 555 / 2), |
| 711 | ! | scale = c(575, 10, 555) |
| 712 | ), | |
| 713 | ! | diffuse = roomcolor, |
| 714 | ! | ambient = roomcolor, |
| 715 | ! | ambient_intensity = ambient_intensity |
| 716 | )) |> | |
| 717 | ! | add_shape(set_material( |
| 718 | ! | cube_mesh(position = c(555 / 2, -5, 555 / 2), scale = c(575, 10, 555)), |
| 719 | ! | diffuse = roomcolor, |
| 720 | ! | ambient = roomcolor, |
| 721 | ! | ambient_intensity = ambient_intensity |
| 722 | )) |> | |
| 723 | ! | add_shape(set_material( |
| 724 | ! | cube_mesh( |
| 725 | ! | position = c(555 / 2, 555 / 2 - 5, 555 + 5), |
| 726 | ! | scale = c(575, 565, 10) |
| 727 | ), | |
| 728 | ! | diffuse = roomcolor, |
| 729 | ! | ambient = roomcolor, |
| 730 | ! | ambient_intensity = ambient_intensity |
| 731 | )) | |
| 732 | } else { | |
| 733 | ! | scene = set_material( |
| 734 | ! | cube_mesh( |
| 735 | ! | position = c(555 + 5, 555 / 2, 555 / 2), |
| 736 | ! | scale = c(10, 555, 555) |
| 737 | ), | |
| 738 | ! | diffuse = leftcolor, |
| 739 | ! | ambient = leftcolor, |
| 740 | ! | ambient_intensity = ambient_intensity |
| 741 | ) |> | |
| 742 | ! | add_shape(set_material( |
| 743 | ! | cube_mesh( |
| 744 | ! | position = c(-5, 555 / 2, 555 / 2), |
| 745 | ! | angle = c(0, 180, 0), |
| 746 | ! | scale = c(10, 555, 555) |
| 747 | ), | |
| 748 | ! | diffuse = rightcolor, |
| 749 | ! | ambient = rightcolor, |
| 750 | ! | ambient_intensity = ambient_intensity |
| 751 | )) |> | |
| 752 | ! | add_shape(set_material( |
| 753 | ! | cube_mesh(position = c(555 / 2, -5, 555 / 2), scale = c(575, 10, 555)), |
| 754 | ! | diffuse = roomcolor, |
| 755 | ! | ambient = roomcolor, |
| 756 | ! | ambient_intensity = ambient_intensity |
| 757 | )) |> | |
| 758 | ! | add_shape(set_material( |
| 759 | ! | cube_mesh( |
| 760 | ! | position = c(555 / 2, 555 / 2 - 5, 555 + 5), |
| 761 | ! | scale = c(575, 565, 10) |
| 762 | ), | |
| 763 | ! | diffuse = roomcolor, |
| 764 | ! | ambient = roomcolor, |
| 765 | ! | ambient_intensity = ambient_intensity |
| 766 | )) | |
| 767 | } | |
| 768 | ! | attr(scene, "cornell") = TRUE |
| 769 | ! | attr(scene, "cornell_light") = light |
| 770 | ! | scene |
| 771 | } | |
| 772 | ||
| 773 | #' OBJ Mesh 3D Model | |
| 774 | #' | |
| 775 | #' @param filename OBJ filename. | |
| 776 | #' @param position Default `c(0,0,0)`. Position of the mesh. | |
| 777 | #' @param scale Default `c(1,1,1)`. Scale of the mesh. Can also be a single numeric value scaling all axes uniformly. | |
| 778 | #' @param angle Default `c(0,0,0)`. Angle to rotate the mesh. | |
| 779 | #' @param pivot_point Default `c(0,0,0)`. Point around which to rotate the mesh. | |
| 780 | #' @param order_rotation Default `c(1,2,3)`. Order to rotate the axes. | |
| 781 | #' @param center Default `FALSE`. Whether to center the mesh. | |
| 782 | #' @param materialspath Default `NULL`. Path to the MTL file, if different from the OBJ file. | |
| 783 | #' @param material Default `NULL`, read from the MTL file. If not `NULL`, this accepts the output | |
| 784 | #' from the [material_list()] function to specify the material. | |
| 785 | #'@return List describing the mesh. | |
| 786 | #'@export | |
| 787 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 788 | #' #Read in the provided 3D R mesh | |
| 789 | #' generate_cornell_mesh(ceiling=FALSE) |> | |
| 790 | #' add_shape(obj_mesh(r_obj(),position=c(555/2,555/2,555/2),scale=400,angle=c(0,180,0))) |> | |
| 791 | #' rasterize_scene(light_info = directional_light(direction=c(0.2,0.5,-1))) | |
| 792 | obj_mesh = function( | |
| 793 | filename, | |
| 794 | position = c(0, 0, 0), | |
| 795 | scale = c(1, 1, 1), | |
| 796 | angle = c(0, 0, 0), | |
| 797 | pivot_point = c(0, 0, 0), | |
| 798 | order_rotation = c(1, 2, 3), | |
| 799 | materialspath = NULL, | |
| 800 | center = FALSE, | |
| 801 | material = NULL | |
| 802 | ) { | |
| 803 | 4x | if (!file.exists(filename) || dir.exists(filename)) { |
| 804 | ! | stop(sprintf("OBJ `%s` not found or not an OBJ file", filename)) |
| 805 | } | |
| 806 | 4x | obj_loaded = read_obj(filename, materialspath) |
| 807 | ||
| 808 | 4x | if (any(scale != 1)) { |
| 809 | ! | obj_loaded = scale_mesh(obj_loaded, scale = scale) |
| 810 | } | |
| 811 | 4x | if (length(obj_loaded$materials[[1]]) == 0 && is.null(material)) { |
| 812 | ! | material = material_list() |
| 813 | } | |
| 814 | 4x | if (!is.null(material)) { |
| 815 | ! | obj_loaded = set_material(obj_loaded, material = material) |
| 816 | } | |
| 817 | 4x | if (center) { |
| 818 | ! | obj_loaded = center_mesh(obj_loaded) |
| 819 | } | |
| 820 | 4x | if (any(angle != 0)) { |
| 821 | ! | obj_loaded = rotate_mesh( |
| 822 | ! | obj_loaded, |
| 823 | ! | angle = angle, |
| 824 | ! | pivot_point = pivot_point, |
| 825 | ! | order_rotation = order_rotation |
| 826 | ) | |
| 827 | } | |
| 828 | ||
| 829 | 4x | obj_loaded = translate_mesh(obj_loaded, position) |
| 830 | 4x | obj_loaded |
| 831 | } | |
| 832 | ||
| 833 | #' Torus 3D Model | |
| 834 | #' | |
| 835 | #' @param position Default `c(0,0,0)`. Position of the mesh. | |
| 836 | #' @param scale Default `c(1,1,1)`. Scale of the mesh. Can also be a single numeric value scaling all axes uniformly. | |
| 837 | #' @param angle Default `c(0,0,0)`. Angle to rotate the mesh. | |
| 838 | #' @param pivot_point Default `c(0,0,0)`. Point around which to rotate the mesh. | |
| 839 | #' @param order_rotation Default `c(1,2,3)`. Order to rotate the axes. | |
| 840 | #' @param radius Default `0.5`. The radius of the torus. | |
| 841 | #' @param ring_radius Default `0.2`. The radius of the ring. | |
| 842 | #' @param sides Default `36`. The number of faces around the ring when triangulating the torus. | |
| 843 | #' @param rings Default `36`. The number of faces around the torus. | |
| 844 | #' @param material Default [material_list()] (default values). Specify the material of the object. | |
| 845 | #' | |
| 846 | #'@return List describing the mesh. | |
| 847 | #'@export | |
| 848 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 849 | #'#Plot a group of tori in the cornell box | |
| 850 | #'generate_cornell_mesh(ceiling = FALSE) |> | |
| 851 | #' add_shape(torus_mesh(position=c(555/2,555/3,555/2), angle=c(20,0,45), | |
| 852 | #' radius=120, ring_radius = 40, | |
| 853 | #' material = material_list(diffuse="dodgerblue4",type="phong", | |
| 854 | #' ambient="dodgerblue4",ambient_intensity=0.2))) |> | |
| 855 | #' add_shape(torus_mesh(position=c(400,400,555/2), angle=c(20,200,45),radius=80, ring_radius = 30, | |
| 856 | #' material=material_list(diffuse="orange",type="phong", | |
| 857 | #' ambient="orange",ambient_intensity=0.2))) |> | |
| 858 | #' add_shape(torus_mesh(position=c(150,450,555/2), angle=c(60,180,0),radius=40, ring_radius = 20, | |
| 859 | #' material=material_list(diffuse="red",type="phong"))) |> | |
| 860 | #' rasterize_scene(light_info = directional_light(c(0,1,-2))) | |
| 861 | torus_mesh = function( | |
| 862 | position = c(0, 0, 0), | |
| 863 | scale = c(1, 1, 1), | |
| 864 | angle = c(0, 0, 0), | |
| 865 | pivot_point = c(0, 0, 0), | |
| 866 | order_rotation = c(1, 2, 3), | |
| 867 | radius = 0.5, | |
| 868 | ring_radius = 0.2, | |
| 869 | sides = 36, | |
| 870 | rings = 36, | |
| 871 | material = material_list() | |
| 872 | ) { | |
| 873 | ! | num_vertices_row = sides + 1 |
| 874 | ! | num_vertices_col = rings + 1 |
| 875 | ! | numVertices = num_vertices_row * num_vertices_col |
| 876 | ! | theta = 0.0 |
| 877 | ! | phi = 0.0 |
| 878 | ||
| 879 | ! | vertical_stride = pi * 2.0 / rings |
| 880 | ! | horizontal_stride = pi * 2.0 / sides |
| 881 | ||
| 882 | ! | counter = 1 |
| 883 | ! | vertices = list() |
| 884 | ! | for (v_iter in seq_len(num_vertices_col) - 1) { |
| 885 | ! | theta = vertical_stride * v_iter |
| 886 | ! | for (h_iter in seq_len(num_vertices_row) - 1) { |
| 887 | ! | phi = horizontal_stride * h_iter |
| 888 | ||
| 889 | ! | x = cos(theta) * (radius + ring_radius * cos(phi)) |
| 890 | ! | y = sin(theta) * (radius + ring_radius * cos(phi)) |
| 891 | ! | z = ring_radius * sin(phi) |
| 892 | ||
| 893 | ! | vertices[[counter]] = matrix(c(x, z, y), ncol = 3) |
| 894 | ! | counter = counter + 1 |
| 895 | } | |
| 896 | } | |
| 897 | ||
| 898 | ! | counter = 1 |
| 899 | ! | normals = list() |
| 900 | ! | for (v_iter in seq_len(num_vertices_col) - 1) { |
| 901 | ! | theta = vertical_stride * v_iter |
| 902 | ! | for (h_iter in seq_len(num_vertices_row) - 1) { |
| 903 | ! | phi = horizontal_stride * h_iter |
| 904 | ||
| 905 | ! | x = cos(theta) * (ring_radius * cos(phi)) |
| 906 | ! | y = sin(theta) * (ring_radius * cos(phi)) |
| 907 | ! | z = ring_radius * sin(phi) |
| 908 | ||
| 909 | ! | normals[[counter]] = matrix(c(x, z, y), ncol = 3) |
| 910 | ! | counter = counter + 1 |
| 911 | } | |
| 912 | } | |
| 913 | ||
| 914 | ! | indices = list() |
| 915 | ! | counter = 1 |
| 916 | ! | for (v_iter in seq_len(rings) - 1) { |
| 917 | ! | for (h_iter in seq_len(sides) - 1) { |
| 918 | ! | lt = (h_iter + v_iter * (num_vertices_row)) |
| 919 | ! | rt = (h_iter + 1) + v_iter * (num_vertices_row) |
| 920 | ! | lb = (h_iter + (v_iter + 1) * (num_vertices_row)) |
| 921 | ! | rb = (h_iter + 1) + (v_iter + 1) * (num_vertices_row) |
| 922 | ! | indices[[counter]] = matrix(c(lt, rt, lb), ncol = 3) |
| 923 | ! | counter = counter + 1 |
| 924 | ! | indices[[counter]] = matrix(c(rt, rb, lb), ncol = 3) |
| 925 | ! | counter = counter + 1 |
| 926 | } | |
| 927 | } | |
| 928 | ! | indices = do.call(rbind, indices) |
| 929 | ! | normals = do.call(rbind, normals) |
| 930 | ! | normalized_normals = t(apply(normals, 1, normalize)) |
| 931 | ! | obj = construct_mesh( |
| 932 | ! | vertices = do.call(rbind, vertices), |
| 933 | ! | indices = indices, |
| 934 | ! | normals = normalized_normals, |
| 935 | ! | norm_indices = indices, |
| 936 | ! | material = material |
| 937 | ) | |
| 938 | ||
| 939 | ! | if (any(scale != 1)) { |
| 940 | ! | obj = scale_mesh(obj, scale = scale) |
| 941 | } | |
| 942 | ! | if (material$type == "toon" || material$type == "toon_phong") { |
| 943 | ! | obj2 = torus_mesh( |
| 944 | ! | position = c(0, 0, 0), |
| 945 | ! | scale = scale, |
| 946 | ! | radius = radius, |
| 947 | ! | ring_radius = ring_radius + material[[1]]$toon_outline_width / 2, |
| 948 | ! | sides = sides, |
| 949 | ! | rings = rings, |
| 950 | ! | material = material_list( |
| 951 | ! | diffuse = material[[1]]$toon_outline_color, |
| 952 | ! | type = "color", |
| 953 | ! | culling = "front" |
| 954 | ) | |
| 955 | ) | |
| 956 | ! | obj = add_shape(obj, obj2) |
| 957 | } | |
| 958 | ! | if (any(angle != 0)) { |
| 959 | ! | obj = rotate_mesh( |
| 960 | ! | obj, |
| 961 | ! | angle = angle, |
| 962 | ! | pivot_point = pivot_point, |
| 963 | ! | order_rotation = order_rotation |
| 964 | ) | |
| 965 | } | |
| 966 | ! | obj = translate_mesh(obj, position) |
| 967 | ! | obj |
| 968 | } | |
| 969 | ||
| 970 | #' Mesh3d 3D Model | |
| 971 | #' | |
| 972 | #' @param mesh Mesh3d object. | |
| 973 | #' @param center Default `FALSE`. Whether to center the mesh. | |
| 974 | #' @param position Default `c(0,0,0)`. Position of the mesh. | |
| 975 | #' @param scale Default `c(1,1,1)`. Scale of the mesh. Can also be a single numeric value scaling all axes uniformly. | |
| 976 | #' @param angle Default `c(0,0,0)`. Angle to rotate the mesh. | |
| 977 | #' @param pivot_point Default `c(0,0,0)`. Point around which to rotate the mesh. | |
| 978 | #' @param order_rotation Default `c(1,2,3)`. Order to rotate the axes. | |
| 979 | #' @param materialspath Default `NULL`. Path to the MTL file, if different from the OBJ file. | |
| 980 | #' @param material Default `NULL`, read from the MTL file. If not `NULL`, this accepts the output | |
| 981 | #' from the [material_list()] function to specify the material. | |
| 982 | #'@return List describing the mesh. | |
| 983 | #'@export | |
| 984 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 985 | #' # Read in a mesh3d object and rasterize it | |
| 986 | #' library(Rvcg) | |
| 987 | #' data(humface) | |
| 988 | #' | |
| 989 | #' mesh3d_mesh(humface,position = c(0,-0.3,0),scale = 1/70, | |
| 990 | #' material=material_list(diffuse="dodgerblue4", type="phong", shininess=20, | |
| 991 | #' ambient = "dodgerblue4", ambient_intensity=0.3)) |> | |
| 992 | #' rasterize_scene(lookat = c(0,0.5,1), light_info = directional_light(c(1,0.5,1))) | |
| 993 | #' | |
| 994 | #' # Subdivide the mesh for a smoother appearance | |
| 995 | #' mesh3d_mesh(humface,position = c(0,-0.3,0),scale = 1/70, | |
| 996 | #' material=material_list(diffuse="dodgerblue4", type="phong", shininess=20, | |
| 997 | #' ambient = "dodgerblue4", ambient_intensity=0.3)) |> | |
| 998 | #' subdivide_mesh() |> | |
| 999 | #' rasterize_scene(lookat = c(0,0.5,1), light_info = directional_light(c(1,0.5,1))) | |
| 1000 | mesh3d_mesh = function( | |
| 1001 | mesh, | |
| 1002 | center = FALSE, | |
| 1003 | position = c(0, 0, 0), | |
| 1004 | scale = c(1, 1, 1), | |
| 1005 | angle = c(0, 0, 0), | |
| 1006 | pivot_point = c(0, 0, 0), | |
| 1007 | order_rotation = c(1, 2, 3), | |
| 1008 | materialspath = NULL, | |
| 1009 | material = material_list() | |
| 1010 | ) { | |
| 1011 | 1x | mat_vals = mesh$material |
| 1012 | 1x | if (!is.null(mesh$texcoords)) { |
| 1013 | ! | texcoords = t(mesh$texcoords) |
| 1014 | ! | tex_indices = t(mesh$it) - 1 |
| 1015 | } else { | |
| 1016 | 1x | texcoords = NULL |
| 1017 | 1x | tex_indices = NULL |
| 1018 | } | |
| 1019 | 1x | if (!is.null(mat_vals)) { |
| 1020 | ! | if (!is.null(mat_vals$color)) { |
| 1021 | ! | diffuse_val = mat_vals$color |
| 1022 | } else { | |
| 1023 | ! | diffuse_val = material[[1]]$diffuse |
| 1024 | } | |
| 1025 | ! | if (!is.null(mat_vals$alpha)) { |
| 1026 | ! | dissolve_val = mat_vals$alpha |
| 1027 | } else { | |
| 1028 | ! | dissolve_val = material[[1]]$dissolve |
| 1029 | } | |
| 1030 | ! | if (!is.null(mat_vals$ambient)) { |
| 1031 | ! | ambient_val = mat_vals$ambient |
| 1032 | } else { | |
| 1033 | ! | ambient_val = material[[1]]$ambient |
| 1034 | } | |
| 1035 | ! | if (!is.null(mat_vals$shininess)) { |
| 1036 | ! | exponent_val = mat_vals$shininess |
| 1037 | } else { | |
| 1038 | ! | exponent_val = material[[1]]$shininess |
| 1039 | } | |
| 1040 | ! | mesh = construct_mesh( |
| 1041 | ! | vertices = t(mesh$vb)[, 1:3], |
| 1042 | ! | indices = t(mesh$it) - 1, |
| 1043 | ! | texcoords = texcoords, |
| 1044 | ! | tex_indices = tex_indices, |
| 1045 | ! | material = material_list( |
| 1046 | ! | diffuse = diffuse_val, |
| 1047 | ! | dissolve = dissolve_val, |
| 1048 | ! | ambient = ambient_val, |
| 1049 | ! | shininess = exponent_val |
| 1050 | ) | |
| 1051 | ) | |
| 1052 | } else { | |
| 1053 | 1x | mesh = construct_mesh( |
| 1054 | 1x | vertices = t(mesh$vb)[, 1:3], |
| 1055 | 1x | indices = t(mesh$it) - 1, |
| 1056 | 1x | tex_indices = tex_indices, |
| 1057 | 1x | texcoords = texcoords, |
| 1058 | 1x | material = material |
| 1059 | ) | |
| 1060 | } | |
| 1061 | ||
| 1062 | 1x | if (any(scale != 1)) { |
| 1063 | ! | mesh = scale_mesh(mesh, scale = scale) |
| 1064 | } | |
| 1065 | 1x | if (center) { |
| 1066 | 1x | mesh = center_mesh(mesh) |
| 1067 | } | |
| 1068 | 1x | if (any(angle != 0)) { |
| 1069 | ! | mesh = rotate_mesh( |
| 1070 | ! | mesh, |
| 1071 | ! | angle = angle, |
| 1072 | ! | pivot_point = pivot_point, |
| 1073 | ! | order_rotation = order_rotation |
| 1074 | ) | |
| 1075 | } | |
| 1076 | 1x | mesh = translate_mesh(mesh, position) |
| 1077 | 1x | mesh |
| 1078 | } | |
| 1079 | ||
| 1080 | #' Text Object | |
| 1081 | #' | |
| 1082 | #' @param label Text string. | |
| 1083 | #' @param position Default `c(0,0,0)`. Position of the mesh. | |
| 1084 | #' @param text_height Default `1`. Height of the text. | |
| 1085 | #' @param font Default `"sans"`. A character string specifying the font family (e.g., `"Arial"`, `"Times"`, `"Helvetica"`). | |
| 1086 | #' @param font_color Default `"black"`. The font color. | |
| 1087 | #' @param font_lineheight Default `12`. The lineheight for strings with newlines. | |
| 1088 | #' @param font_size Default `100`. The size of the font. Note that this does not control the size of the text, just the resolution | |
| 1089 | #' as rendered in the texture. | |
| 1090 | #' @param background_color Default `"white"`. The background color. | |
| 1091 | #' @param background_alpha Default `0`. The background opacity. `1` is fully opaque. | |
| 1092 | #' @param orientation Default `xy`. Orientation of the plane. Other options are `yz` and `xz`. | |
| 1093 | #' @param scale Default `c(1,1,1)`. Scale of the mesh. Can also be a single numeric value scaling all axes uniformly. | |
| 1094 | #' @param angle Default `c(0,0,0)`. Angle to rotate the mesh. | |
| 1095 | #' @param pivot_point Default `c(0,0,0)`. Point around which to rotate the mesh. | |
| 1096 | #' @param order_rotation Default `c(1,2,3)`. Order to rotate the axes. | |
| 1097 | #' @param color Default `NULL`. Deprecated alias for `font_color`; retained for compatibility. | |
| 1098 | #' @importFrom grDevices col2rgb | |
| 1099 | #' | |
| 1100 | #' @return List describing the mesh. | |
| 1101 | #' @export | |
| 1102 | #' | |
| 1103 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 1104 | #' #Generate a label in the Cornell box. | |
| 1105 | #' generate_cornell_mesh() |> | |
| 1106 | #' add_shape(text3d_mesh(label="Cornell Box", position=c(555/2,555/2,555/2),angle=c(0,180,0), | |
| 1107 | #' text_height=120)) |> | |
| 1108 | #' rasterize_scene(light_info = directional_light(c(0.1,0.4,-1))) | |
| 1109 | #' #Change the orientation | |
| 1110 | #' generate_cornell_mesh() |> | |
| 1111 | #' add_shape(text3d_mesh(label="YZ Plane", position=c(540,555/2,555/2),text_height=180, | |
| 1112 | #' orientation = "yz",angle=c(0,180,0))) |> | |
| 1113 | #' add_shape(text3d_mesh(label="XY Plane", position=c(555/2,555/2,540),text_height=180, | |
| 1114 | #' orientation = "xy", angle=c(0,180,0))) |> | |
| 1115 | #' add_shape(text3d_mesh(label="XZ Plane", position=c(555/2,15,555/2),text_height=180, | |
| 1116 | #' orientation = "xz", angle=c(0,180,0))) |> | |
| 1117 | #' rasterize_scene(light_info = directional_light(c(0.1,0.4,-1))) | |
| 1118 | #' #Add an label in front of a sphere and change the font | |
| 1119 | #' generate_cornell_mesh() |> | |
| 1120 | #' add_shape(text3d_mesh(label="Cornell Box", position=c(555/2,555/2,555/2),text_height=180, | |
| 1121 | #' font = "Serif", font_color="orange", | |
| 1122 | #' angle=c(0,180,0))) |> | |
| 1123 | #' add_shape(text3d_mesh(label="Sphere", position=c(555/2,130,100),text_height=100, | |
| 1124 | #' font = "sans", | |
| 1125 | #' font_color="lightblue",angle=c(0,180,40))) |> | |
| 1126 | #' add_shape(sphere_mesh(radius=100,position=c(555/2,100,555/2), | |
| 1127 | #' material=material_list(diffuse="purple",type="phong"))) |> | |
| 1128 | #' rasterize_scene(light_info = directional_light(c(0.1,0.4,-1))) | |
| 1129 | #' #A room full of b's | |
| 1130 | #' set.seed(1) | |
| 1131 | #' bee_scene = list() | |
| 1132 | #' for(i in 1:100) { | |
| 1133 | #' bee_scene = add_shape(bee_scene, text3d_mesh("B", position=c(20+runif(3)*525), | |
| 1134 | #' font_color="yellow", text_height = 100, | |
| 1135 | #' angle=c(0,180,0))) | |
| 1136 | #' } | |
| 1137 | #' generate_cornell_mesh() |> | |
| 1138 | #' add_shape(bee_scene) |> | |
| 1139 | #' rasterize_scene(light=directional_light(c(0,1,-1))) | |
| 1140 | #' | |
| 1141 | #' #A room full of bees | |
| 1142 | #' bee_scene = list() | |
| 1143 | #' set.seed(1) | |
| 1144 | #' for(i in 1:100) { | |
| 1145 | #' bee_scene = add_shape(bee_scene, text3d_mesh("\U1F41D", position=c(20+runif(3)*525), | |
| 1146 | #' font_color="yellow", text_height = 100, | |
| 1147 | #' angle=c(0,180,0))) | |
| 1148 | #' } | |
| 1149 | #' generate_cornell_mesh() |> | |
| 1150 | #' add_shape(bee_scene) |> | |
| 1151 | #' rasterize_scene(light=directional_light(c(0,1,-1))) | |
| 1152 | text3d_mesh = function( | |
| 1153 | label, | |
| 1154 | position = c(0, 0, 0), | |
| 1155 | text_height = 1, | |
| 1156 | orientation = "xy", | |
| 1157 | font_color = "black", | |
| 1158 | font_size = 100, | |
| 1159 | font = "sans", | |
| 1160 | font_lineheight = 12, | |
| 1161 | background_color = "white", | |
| 1162 | background_alpha = 0, | |
| 1163 | angle = c(0, 0, 0), | |
| 1164 | pivot_point = c(0, 0, 0), | |
| 1165 | order_rotation = c(1, 2, 3), | |
| 1166 | scale = c(1, 1, 1), | |
| 1167 | color = NULL | |
| 1168 | ) { | |
| 1169 | 2x | if (!is.null(color) && missing(font_color)) { |
| 1170 | 1x | font_color = color |
| 1171 | } | |
| 1172 | 2x | labelfile = tempfile(fileext = ".png") |
| 1173 | 2x | text_image = suppressWarnings(rayimage::render_text_image( |
| 1174 | 2x | label, |
| 1175 | 2x | font = font, |
| 1176 | 2x | size = font_size, |
| 1177 | 2x | color = font_color, |
| 1178 | 2x | just = "left", |
| 1179 | 2x | lineheight = font_lineheight, |
| 1180 | 2x | background_color = background_color, |
| 1181 | 2x | background_alpha = background_alpha, |
| 1182 | 2x | filename = labelfile |
| 1183 | )) | |
| 1184 | 2x | height_val_raw = nrow(text_image) |
| 1185 | 2x | width_val_raw = ncol(text_image) |
| 1186 | 2x | ratio = text_height / height_val_raw |
| 1187 | 2x | width_val = width_val_raw * ratio |
| 1188 | 2x | if (orientation == "xy" || orientation == "yx") { |
| 1189 | 2x | mesh = xy_rect_mesh( |
| 1190 | 2x | position = position, |
| 1191 | 2x | angle = angle, |
| 1192 | 2x | pivot_point = pivot_point, |
| 1193 | 2x | order_rotation = order_rotation, |
| 1194 | 2x | scale = c(width_val, text_height, 1) |
| 1195 | ) | |
| 1196 | ! | } else if (orientation == "yz" || orientation == "zy") { |
| 1197 | ! | mesh = yz_rect_mesh( |
| 1198 | ! | position = position, |
| 1199 | ! | angle = angle, |
| 1200 | ! | pivot_point = pivot_point, |
| 1201 | ! | order_rotation = order_rotation, |
| 1202 | ! | scale = c(1, text_height, width_val) |
| 1203 | ) | |
| 1204 | ! | } else if (orientation == "xz" || orientation == "zx") { |
| 1205 | ! | mesh = xz_rect_mesh( |
| 1206 | ! | position = position, |
| 1207 | ! | angle = angle, |
| 1208 | ! | pivot_point = pivot_point, |
| 1209 | ! | order_rotation = order_rotation, |
| 1210 | ! | scale = c(width_val, 1, text_height) |
| 1211 | ) | |
| 1212 | } else { | |
| 1213 | ! | stop("Orientation ", orientation, " not recognized") |
| 1214 | } | |
| 1215 | 2x | mesh = set_material( |
| 1216 | 2x | mesh, |
| 1217 | 2x | material = material_list( |
| 1218 | 2x | texture_location = labelfile, |
| 1219 | 2x | type = "color", |
| 1220 | 2x | culling = "none" |
| 1221 | ) | |
| 1222 | ) | |
| 1223 | 2x | return(mesh) |
| 1224 | } | |
| 1225 | ||
| 1226 | #' PLY Mesh 3D Model | |
| 1227 | #' | |
| 1228 | #' @param filename PLY filename. | |
| 1229 | #' @param center Default `FALSE`. Whether to center the mesh. | |
| 1230 | #' @param position Default `c(0,0,0)`. Position of the mesh. | |
| 1231 | #' @param scale Default `c(1,1,1)`. Scale of the mesh. Can also be a single numeric value scaling all axes uniformly. | |
| 1232 | #' @param angle Default `c(0,0,0)`. Angle to rotate the mesh. | |
| 1233 | #' @param pivot_point Default `c(0,0,0)`. Point around which to rotate the mesh. | |
| 1234 | #' @param order_rotation Default `c(1,2,3)`. Order to rotate the axes. | |
| 1235 | #' @param material Default [material_list()] (default values). Specify the material of the object. | |
| 1236 | #'@return List describing the mesh. | |
| 1237 | #'@export | |
| 1238 | #'@examples | |
| 1239 | #'#See the documentation for [obj_mesh()]--no example PLY models are included with this package, | |
| 1240 | #'#but the process of loading a model is the same (but no materials are included in PLY files). | |
| 1241 | ply_mesh = function( | |
| 1242 | filename, | |
| 1243 | center = FALSE, | |
| 1244 | position = c(0, 0, 0), | |
| 1245 | scale = c(1, 1, 1), | |
| 1246 | angle = c(0, 0, 0), | |
| 1247 | pivot_point = c(0, 0, 0), | |
| 1248 | order_rotation = c(1, 2, 3), | |
| 1249 | material = material_list() | |
| 1250 | ) { | |
| 1251 | ! | ply_loaded = read_ply(filename) |
| 1252 | ! | if (any(scale != 1)) { |
| 1253 | ! | ply_loaded = scale_mesh(ply_loaded, scale = scale) |
| 1254 | } | |
| 1255 | ! | ply_loaded = set_material(ply_loaded, material = material) |
| 1256 | ! | if (center) { |
| 1257 | ! | ply_loaded = center_mesh(ply_loaded) |
| 1258 | } | |
| 1259 | ! | if (any(angle != 0)) { |
| 1260 | ! | ply_loaded = rotate_mesh( |
| 1261 | ! | ply_loaded, |
| 1262 | ! | angle = angle, |
| 1263 | ! | pivot_point = pivot_point, |
| 1264 | ! | order_rotation = order_rotation |
| 1265 | ) | |
| 1266 | } | |
| 1267 | ||
| 1268 | ! | ply_loaded = translate_mesh(ply_loaded, position) |
| 1269 | ! | ply_loaded |
| 1270 | } |
| 1 | #' Convert Color | |
| 2 | #' | |
| 3 | #' @param color The color to convert. Can be either a hexadecimal code, or a numeric rgb | |
| 4 | #' vector listing three intensities between `0` and `1`. | |
| 5 | #' | |
| 6 | #' @return Color vector | |
| 7 | #' @keywords internal | |
| 8 | convert_color = function(color, as_hex = FALSE) { | |
| 9 | 995x | if (inherits(color, "character")) { |
| 10 | 186x | color = as.vector(grDevices::col2rgb(color)) / 255 |
| 11 | } | |
| 12 | 995x | if (as_hex) { |
| 13 | ! | paste0( |
| 14 | "#", | |
| 15 | ! | paste0( |
| 16 | ! | format(as.hexmode(round(color * 255, 0)), width = 2), |
| 17 | ! | collapse = "" |
| 18 | ), | |
| 19 | ! | collapse = "" |
| 20 | ) | |
| 21 | } else { | |
| 22 | 995x | color |
| 23 | } | |
| 24 | } | |
| 25 | ||
| 26 | #' Rescale | |
| 27 | #' | |
| 28 | #' @param vals Values | |
| 29 | #' @param to to vales | |
| 30 | #' | |
| 31 | #' @return Color vector | |
| 32 | #' @keywords internal | |
| 33 | rescale = function(vals, to = c(0, 1)) { | |
| 34 | 7x | stopifnot(length(to) == 2) |
| 35 | ||
| 36 | 7x | finite = is.finite(vals) |
| 37 | 7x | if (!any(finite)) { |
| 38 | 1x | return(vals) |
| 39 | } | |
| 40 | ||
| 41 | 6x | range_vals = range(vals[finite], na.rm = TRUE) |
| 42 | 6x | if (diff(range_vals) == 0) { |
| 43 | 1x | vals[finite] = mean(to) |
| 44 | 1x | return(vals) |
| 45 | } | |
| 46 | ||
| 47 | 5x | vals[finite] = (vals[finite] - range_vals[1]) / |
| 48 | 5x | diff(range_vals) * |
| 49 | 5x | diff(to) + |
| 50 | 5x | to[1] |
| 51 | 5x | vals |
| 52 | } | |
| 53 | ||
| 54 | #' Check Filename | |
| 55 | #' | |
| 56 | #' @param file Filename to be checked | |
| 57 | #' @return Flipped matrix | |
| 58 | #' @keywords internal | |
| 59 | get_file_type = function(file) { | |
| 60 | ! | if (is.character(file)) { |
| 61 | ! | if (tools::file_ext(file) == "png") { |
| 62 | ! | imagetype = "png" |
| 63 | } else { | |
| 64 | ! | imagetype = "jpg" |
| 65 | } | |
| 66 | ! | } else if (length(dim(file)) == 3) { |
| 67 | ! | imagetype = "array" |
| 68 | ! | } else if (length(dim(file)) == 2) { |
| 69 | ! | imagetype = "matrix" |
| 70 | } else { | |
| 71 | ! | stop("`", file, "` not recognized class (png, jpeg, array, matrix).") |
| 72 | } | |
| 73 | } | |
| 74 | ||
| 75 | #' Flip Left-Right | |
| 76 | #' | |
| 77 | #' @param x Matrix | |
| 78 | #' | |
| 79 | #' @return Flipped matrix | |
| 80 | #' @keywords internal | |
| 81 | fliplr = function(x) { | |
| 82 | ! | if (length(dim(x)) == 2) { |
| 83 | ! | x[, ncol(x):1] |
| 84 | } else { | |
| 85 | ! | x[, ncol(x):1, ] |
| 86 | } | |
| 87 | } | |
| 88 | ||
| 89 | ||
| 90 | #' Flip Up-Down | |
| 91 | #' | |
| 92 | #' @param x Matrix | |
| 93 | #' | |
| 94 | #' @return Flipped matrix | |
| 95 | #' @keywords internal | |
| 96 | flipud = function(x) { | |
| 97 | ! | if (length(dim(x)) == 2) { |
| 98 | ! | x[nrow(x):1, ] |
| 99 | } else { | |
| 100 | ! | x[nrow(x):1, , ] |
| 101 | } | |
| 102 | } | |
| 103 | ||
| 104 | #' Print time | |
| 105 | #' | |
| 106 | #' @return Nothing | |
| 107 | #' @keywords internal | |
| 108 | init_time = function() { | |
| 109 | 6x | assign("init_time", proc.time()[3], envir = ray_environment) |
| 110 | 6x | assign("prev_time", proc.time()[3], envir = ray_environment) |
| 111 | } | |
| 112 | ||
| 113 | #' Get time | |
| 114 | #' | |
| 115 | #' @return Nothing | |
| 116 | #' @keywords internal | |
| 117 | get_time = function(init = TRUE) { | |
| 118 | ! | if (init) { |
| 119 | ! | get("init_time", envir = ray_environment) |
| 120 | } else { | |
| 121 | ! | get("prev_time", envir = ray_environment) |
| 122 | } | |
| 123 | } | |
| 124 | ||
| 125 | #' Print time | |
| 126 | #' | |
| 127 | #' @return Nothing | |
| 128 | #' @keywords internal | |
| 129 | print_time = function(verbose = FALSE, message_text = "") { | |
| 130 | 99x | if (verbose) { |
| 131 | ! | time_now = proc.time()[3] |
| 132 | ! | message(sprintf( |
| 133 | ! | "%-27s: %0.1f secs (Total: %0.1f secs)", |
| 134 | ! | message_text, |
| 135 | ! | time_now - get_time(FALSE), |
| 136 | ! | time_now - get_time(TRUE) |
| 137 | )) | |
| 138 | ! | assign("prev_time", time_now, envir = ray_environment) |
| 139 | } | |
| 140 | } | |
| 141 | ||
| 142 | #' Verify Vertex Shader | |
| 143 | #' | |
| 144 | #' @return bool | |
| 145 | #' | |
| 146 | #' @keywords internal | |
| 147 | verify_vertex_shader = function(vertex_shader) { | |
| 148 | ! | verify_matrix = matrix(1:18, ncol = 3, nrow = 6) |
| 149 | ! | processed_matrix = t(apply(verify_matrix, 1, vertex_shader)) |
| 150 | ||
| 151 | ! | if (ncol(processed_matrix) != 3) { |
| 152 | ! | return(FALSE) |
| 153 | } | |
| 154 | ! | if (nrow(processed_matrix) != 6) { |
| 155 | ! | return(FALSE) |
| 156 | } | |
| 157 | ! | return(TRUE) |
| 158 | } |
| 1 | #' Validate a scalar sweep argument | |
| 2 | #' @keywords internal | |
| 3 | #' @noRd | |
| 4 | sweep_scalar = function(x, name, lower = -Inf, upper = Inf, integer = FALSE) { | |
| 5 | if ( | |
| 6 | 1069x | !is.numeric(x) || |
| 7 | 1069x | length(x) != 1L || |
| 8 | 1069x | !is.finite(x) || |
| 9 | 1069x | x < lower || |
| 10 | 1069x | x > upper || |
| 11 | 1069x | (integer && x != floor(x)) |
| 12 | ) { | |
| 13 | 21x | stop( |
| 14 | 21x | sprintf( |
| 15 | 21x | "`%s` must be a finite %s in [%s, %s].", |
| 16 | 21x | name, |
| 17 | 5x | if (integer) "integer" else "number", |
| 18 | 21x | lower, |
| 19 | 21x | upper |
| 20 | ), | |
| 21 | 21x | call. = FALSE |
| 22 | ) | |
| 23 | } | |
| 24 | 1048x | x |
| 25 | } | |
| 26 | ||
| 27 | #' Normalize a sweep profile | |
| 28 | #' @keywords internal | |
| 29 | #' @noRd | |
| 30 | sweep_profile = function(polygon, name, added = 0) { | |
| 31 | 66x | p = tryCatch(grDevices::xy.coords(polygon), error = function(e) NULL) |
| 32 | 66x | if (is.null(p)) { |
| 33 | ! | stop( |
| 34 | ! | sprintf("`%s` must specify numeric x/y coordinates.", name), |
| 35 | ! | call. = FALSE |
| 36 | ) | |
| 37 | } | |
| 38 | 66x | p = cbind(p$x, p$y) |
| 39 | 66x | if (nrow(p) < 3L || any(!is.finite(p))) { |
| 40 | ! | stop( |
| 41 | ! | sprintf("`%s` must have at least three finite vertices.", name), |
| 42 | ! | call. = FALSE |
| 43 | ) | |
| 44 | } | |
| 45 | 66x | if (all(p[1, ] == p[nrow(p), ])) { |
| 46 | 2x | p = p[-nrow(p), , drop = FALSE] |
| 47 | } | |
| 48 | 66x | next_i = c(seq_len(nrow(p))[-1L], 1L) |
| 49 | 66x | lengths = sqrt(rowSums((p[next_i, , drop = FALSE] - p)^2)) |
| 50 | 66x | centered = sweep(p, 2, colMeans(p)) |
| 51 | 66x | area = sum( |
| 52 | 66x | centered[, 1] * centered[next_i, 2] - centered[next_i, 1] * centered[, 2] |
| 53 | ) | |
| 54 | if ( | |
| 55 | 66x | nrow(p) < 3L || |
| 56 | 66x | any(lengths == 0) || |
| 57 | 66x | !is.finite(area) || |
| 58 | 66x | abs(area) <= .Machine$double.eps * sum(lengths)^2 |
| 59 | ) { | |
| 60 | 1x | stop( |
| 61 | 1x | sprintf( |
| 62 | 1x | "`%s` must have nonzero area and distinct consecutive vertices.", |
| 63 | 1x | name |
| 64 | ), | |
| 65 | 1x | call. = FALSE |
| 66 | ) | |
| 67 | } | |
| 68 | # Preserve the first vertex so reversing winding preserves correspondence. | |
| 69 | 65x | if (area > 0) { |
| 70 | 1x | p = p[c(1L, nrow(p):2L), , drop = FALSE] |
| 71 | } | |
| 72 | 65x | if (added > 0) { |
| 73 | 1x | next_i = c(seq_len(nrow(p))[-1L], 1L) |
| 74 | 1x | p = do.call( |
| 75 | 1x | rbind, |
| 76 | 1x | lapply(seq_len(nrow(p)), function(i) { |
| 77 | 5x | t = (0:added) / (added + 1) |
| 78 | 5x | (1 - t) %o% p[i, ] + t %o% p[next_i[i], ] |
| 79 | }) | |
| 80 | ) | |
| 81 | } | |
| 82 | 65x | unname(p) |
| 83 | } | |
| 84 | ||
| 85 | #' Prepare sweep control points | |
| 86 | #' @keywords internal | |
| 87 | #' @noRd | |
| 88 | sweep_controls = function( | |
| 89 | points, | |
| 90 | closed, | |
| 91 | closed_smooth, | |
| 92 | straight, | |
| 93 | precomputed | |
| 94 | ) { | |
| 95 | 63x | if (precomputed) { |
| 96 | if ( | |
| 97 | 3x | !is.list(points) || |
| 98 | 3x | !length(points) || |
| 99 | 3x | any(vapply( |
| 100 | 3x | points, |
| 101 | 3x | function(p) { |
| 102 | 3x | !is.matrix(p) || |
| 103 | 3x | !is.numeric(p) || |
| 104 | 3x | !identical(dim(p), c(4L, 3L)) || |
| 105 | 3x | any(!is.finite(p)) |
| 106 | }, | |
| 107 | 3x | TRUE |
| 108 | )) | |
| 109 | ) { | |
| 110 | 1x | stop( |
| 111 | 1x | "Precomputed `points` must be a list of finite numeric 4-by-3 matrices.", |
| 112 | 1x | call. = FALSE |
| 113 | ) | |
| 114 | } | |
| 115 | 2x | cps = points |
| 116 | 2x | if (length(cps) > 1L) { |
| 117 | ! | for (i in seq_len(length(cps) - 1L)) { |
| 118 | if ( | |
| 119 | ! | !isTRUE(all.equal( |
| 120 | ! | cps[[i]][4, ], |
| 121 | ! | cps[[i + 1L]][1, ], |
| 122 | ! | check.attributes = FALSE |
| 123 | )) | |
| 124 | ) { | |
| 125 | ! | stop( |
| 126 | ! | "Precomputed Bezier segments must meet at their endpoints.", |
| 127 | ! | call. = FALSE |
| 128 | ) | |
| 129 | } | |
| 130 | } | |
| 131 | } | |
| 132 | if ( | |
| 133 | 2x | closed && |
| 134 | 2x | !isTRUE(all.equal( |
| 135 | 2x | cps[[1]][1, ], |
| 136 | 2x | cps[[length(cps)]][4, ], |
| 137 | 2x | check.attributes = FALSE |
| 138 | )) | |
| 139 | ) { | |
| 140 | ! | stop( |
| 141 | ! | "Precomputed closed paths must return to their starting point.", |
| 142 | ! | call. = FALSE |
| 143 | ) | |
| 144 | } | |
| 145 | } else { | |
| 146 | 60x | if (is.data.frame(points)) { |
| 147 | ! | points = as.matrix(points) |
| 148 | } | |
| 149 | 60x | if (is.list(points)) { |
| 150 | if ( | |
| 151 | ! | !length(points) || |
| 152 | ! | any(vapply( |
| 153 | ! | points, |
| 154 | ! | function(p) !is.numeric(p) || length(p) != 3L, |
| 155 | ! | TRUE |
| 156 | )) | |
| 157 | ) { | |
| 158 | ! | stop( |
| 159 | ! | "`points` must contain numeric length-three vectors.", |
| 160 | ! | call. = FALSE |
| 161 | ) | |
| 162 | } | |
| 163 | ! | points = do.call(rbind, points) |
| 164 | } | |
| 165 | if ( | |
| 166 | 60x | !is.matrix(points) || |
| 167 | 60x | !is.numeric(points) || |
| 168 | 60x | ncol(points) != 3L || |
| 169 | 60x | nrow(points) < 2L || |
| 170 | 60x | any(!is.finite(points)) |
| 171 | ) { | |
| 172 | 1x | stop( |
| 173 | 1x | "`points` must specify at least two finite three-dimensional points.", |
| 174 | 1x | call. = FALSE |
| 175 | ) | |
| 176 | } | |
| 177 | if ( | |
| 178 | 59x | closed && nrow(points) > 2L && all(points[1, ] == points[nrow(points), ]) |
| 179 | ) { | |
| 180 | ! | points = points[-nrow(points), , drop = FALSE] |
| 181 | } | |
| 182 | 59x | closed = closed && nrow(points) > 2L |
| 183 | if ( | |
| 184 | 59x | any( |
| 185 | 59x | rowSums( |
| 186 | 59x | (points[-1, , drop = FALSE] - points[-nrow(points), , drop = FALSE])^2 |
| 187 | ) == | |
| 188 | 59x | 0 |
| 189 | ) | |
| 190 | ) { | |
| 191 | 1x | stop("Consecutive path points must be distinct.", call. = FALSE) |
| 192 | } | |
| 193 | 58x | n = nrow(points) |
| 194 | 58x | if (closed && closed_smooth && !straight) { |
| 195 | # Periodic cubic interpolation: matching positions, first and second derivatives. | |
| 196 | 12x | previous = c(n, seq_len(n - 1L)) |
| 197 | 12x | following = c(2:n, 1L) |
| 198 | 12x | system = diag(4, n) |
| 199 | 12x | system[cbind(seq_len(n), previous)] = system[cbind( |
| 200 | 12x | seq_len(n), |
| 201 | 12x | previous |
| 202 | )] + | |
| 203 | 12x | 1 |
| 204 | 12x | system[cbind(seq_len(n), following)] = system[cbind( |
| 205 | 12x | seq_len(n), |
| 206 | 12x | following |
| 207 | )] + | |
| 208 | 12x | 1 |
| 209 | 12x | derivatives = solve( |
| 210 | 12x | system, |
| 211 | 12x | 3 * (points[following, ] - points[previous, ]) |
| 212 | ) | |
| 213 | 12x | cps = lapply(seq_len(n), function(i) { |
| 214 | 60x | rbind( |
| 215 | 60x | points[i, ], |
| 216 | 60x | points[i, ] + derivatives[i, ] / 3, |
| 217 | 60x | points[following[i], ] - derivatives[following[i], ] / 3, |
| 218 | 60x | points[following[i], ] |
| 219 | ) | |
| 220 | }) | |
| 221 | 46x | } else if (straight) { |
| 222 | 1x | if (closed) { |
| 223 | ! | points = rbind(points, points[1, ]) |
| 224 | } | |
| 225 | 1x | cps = sweep_control_points_straight(points) |
| 226 | } else { | |
| 227 | 45x | cps = sweep_control_points(points) |
| 228 | 45x | if (closed) { |
| 229 | 3x | first = cps[[1]] |
| 230 | 3x | last = cps[[length(cps)]] |
| 231 | 3x | cps[[length(cps) + 1L]] = rbind( |
| 232 | 3x | last[4, ], |
| 233 | 3x | 2 * last[4, ] - last[3, ], |
| 234 | 3x | 2 * first[1, ] - first[2, ], |
| 235 | 3x | first[1, ] |
| 236 | ) | |
| 237 | } | |
| 238 | } | |
| 239 | } | |
| 240 | 60x | list(cps = cps, closed = closed) |
| 241 | } | |
| 242 | ||
| 243 | #' Evaluate a sweep curve and tangent | |
| 244 | #' @keywords internal | |
| 245 | #' @noRd | |
| 246 | sweep_curve = function(cps, t, closed) { | |
| 247 | 11777x | s = min(1, max(0, t)) * length(cps) |
| 248 | 11777x | index = min(length(cps), floor(s) + 1L) |
| 249 | 11777x | local = s - index + 1 |
| 250 | 11777x | point = sweep_bezier(cps[[index]], local) |
| 251 | 11777x | tangent = sweep_bezier_deriv(cps[[index]], local) |
| 252 | 11777x | unit = function(x) { |
| 253 | 12257x | len = sqrt(sum(x^2)) |
| 254 | 12257x | if (!is.finite(len) || len == 0) { |
| 255 | ! | stop( |
| 256 | ! | "The path has a zero or nonfinite tangent (a cusp or stationary point).", |
| 257 | ! | call. = FALSE |
| 258 | ) | |
| 259 | } | |
| 260 | 12257x | x / len |
| 261 | } | |
| 262 | 11777x | tangent = unit(tangent) |
| 263 | # At polyline joints, use the tangent bisector. For smooth curves this is unchanged. | |
| 264 | 11777x | if (abs(s - round(s)) < 1e-12 && (s > 0 && s < length(cps) || closed)) { |
| 265 | 160x | before = if (s == 0) length(cps) else as.integer(round(s)) |
| 266 | 160x | after = if (s == length(cps)) 1L else as.integer(round(s)) + 1L |
| 267 | 160x | tangent = unit( |
| 268 | 160x | unit(sweep_bezier_deriv(cps[[before]], 1)) + |
| 269 | 160x | unit(sweep_bezier_deriv(cps[[after]], 0)) |
| 270 | ) | |
| 271 | } | |
| 272 | 11777x | list(point = point, tangent = tangent) |
| 273 | } | |
| 274 | ||
| 275 | #' Adaptive arc-length table for a sweep | |
| 276 | #' @keywords internal | |
| 277 | #' @noRd | |
| 278 | sweep_arc_table = function(cps, tolerance) { | |
| 279 | 48x | size = sum(vapply( |
| 280 | 48x | cps, |
| 281 | 48x | function(p) sum(sqrt(rowSums((p[-1, ] - p[-4, ])^2))), |
| 282 | 48x | 0.0 |
| 283 | )) | |
| 284 | 48x | if (!is.finite(size) || size == 0) { |
| 285 | ! | stop("The path must have finite nonzero length.", call. = FALSE) |
| 286 | } | |
| 287 | 48x | samples = list(c(0, cps[[1]][1, ])) |
| 288 | 48x | append_segment = function(p, a, b, depth = 0L) { |
| 289 | 20417x | chord = p[4, ] - p[1, ] |
| 290 | 20417x | error = max( |
| 291 | 20417x | sqrt(sum((p[2, ] - p[1, ] - chord / 3)^2)), |
| 292 | 20417x | sqrt(sum((p[3, ] - p[1, ] - 2 * chord / 3)^2)) |
| 293 | ) | |
| 294 | 20417x | if (depth >= 4L && error <= tolerance * size) { |
| 295 | 10266x | samples[[length(samples) + 1L]] <<- c(b, p[4, ]) |
| 296 | 10266x | return(invisible(NULL)) |
| 297 | } | |
| 298 | 10151x | if (depth >= 20L) { |
| 299 | ! | stop("Arc-length tolerance is too small for this path.", call. = FALSE) |
| 300 | } | |
| 301 | 10151x | a01 = (p[1, ] + p[2, ]) / 2 |
| 302 | 10151x | a12 = (p[2, ] + p[3, ]) / 2 |
| 303 | 10151x | a23 = (p[3, ] + p[4, ]) / 2 |
| 304 | 10151x | b01 = (a01 + a12) / 2 |
| 305 | 10151x | b12 = (a12 + a23) / 2 |
| 306 | 10151x | middle = (b01 + b12) / 2 |
| 307 | 10151x | mid_t = (a + b) / 2 |
| 308 | 10151x | append_segment(rbind(p[1, ], a01, b01, middle), a, mid_t, depth + 1L) |
| 309 | 10151x | append_segment(rbind(middle, b12, a23, p[4, ]), mid_t, b, depth + 1L) |
| 310 | } | |
| 311 | 48x | for (i in seq_along(cps)) { |
| 312 | 115x | append_segment(cps[[i]], (i - 1) / length(cps), i / length(cps)) |
| 313 | } | |
| 314 | 48x | samples = do.call(rbind, samples) |
| 315 | 48x | distance = sqrt(rowSums( |
| 316 | 48x | (samples[-1, 2:4, drop = FALSE] - |
| 317 | 48x | samples[-nrow(samples), 2:4, drop = FALSE])^2 |
| 318 | )) | |
| 319 | 48x | if (any(!is.finite(distance)) || any(distance == 0)) { |
| 320 | ! | stop( |
| 321 | ! | "The path contains a zero-length sampled segment; remove repeated points or cusps.", |
| 322 | ! | call. = FALSE |
| 323 | ) | |
| 324 | } | |
| 325 | 48x | list(t = samples[, 1], distance = c(0, cumsum(distance)) / sum(distance)) |
| 326 | } | |
| 327 | ||
| 328 | #' Transport a sweep frame by double reflection | |
| 329 | #' @keywords internal | |
| 330 | #' @noRd | |
| 331 | sweep_transport = function(normal, from, to) { | |
| 332 | 11713x | delta = to$point - from$point |
| 333 | 11713x | length2 = sum(delta^2) |
| 334 | 11713x | if (length2 == 0) { |
| 335 | 106x | result = normal |
| 336 | } else { | |
| 337 | 11607x | reflected = normal - 2 * sum(delta * normal) / length2 * delta |
| 338 | 11607x | reflected_tangent = from$tangent - |
| 339 | 11607x | 2 * sum(delta * from$tangent) / length2 * delta |
| 340 | 11607x | correction = to$tangent - reflected_tangent |
| 341 | 11607x | correction2 = sum(correction^2) |
| 342 | 11607x | result = if (correction2 < 1e-24) { |
| 343 | ! | reflected |
| 344 | } else { | |
| 345 | 11607x | reflected - 2 * sum(correction * reflected) / correction2 * correction |
| 346 | } | |
| 347 | } | |
| 348 | 11713x | result = result - sum(result * to$tangent) * to$tangent |
| 349 | 11713x | len = sqrt(sum(result^2)) |
| 350 | 11713x | if (!is.finite(len) || len < 1e-12) { |
| 351 | ! | stop("Cannot transport a frame through a path cusp.", call. = FALSE) |
| 352 | } | |
| 353 | 11713x | result / len |
| 354 | } | |
| 355 | ||
| 356 | #' Construct sweep width interpolation | |
| 357 | #' @keywords internal | |
| 358 | #' @noRd | |
| 359 | sweep_width = function(width, width_end, ease) { | |
| 360 | 54x | if (is.numeric(width) && is.null(dim(width))) { |
| 361 | 53x | if (length(width) == 1L) { |
| 362 | 53x | if (length(width_end) == 1L && is.na(width_end)) { |
| 363 | 49x | width_end = width |
| 364 | } | |
| 365 | 53x | width = c(width, width_end) |
| 366 | } | |
| 367 | 53x | width = list(x = seq(0, 1, length.out = length(width)), y = width) |
| 368 | } | |
| 369 | 54x | values = tryCatch(grDevices::xy.coords(width), error = function(e) NULL) |
| 370 | if ( | |
| 371 | 54x | is.null(values) || |
| 372 | 54x | length(values$x) < 2L || |
| 373 | 54x | any(!is.finite(c(values$x, values$y))) || |
| 374 | 54x | any(values$y < 0) || |
| 375 | 54x | any(values$x < 0 | values$x > 1) || |
| 376 | 54x | any(diff(values$x) <= 0) |
| 377 | ) { | |
| 378 | 2x | stop( |
| 379 | 2x | "`width` must give nonnegative finite widths at strictly increasing positions in [0, 1].", |
| 380 | 2x | call. = FALSE |
| 381 | ) | |
| 382 | } | |
| 383 | 52x | if (values$x[1] > 0) { |
| 384 | ! | values$x = c(0, values$x) |
| 385 | ! | values$y = c(values$y[1], values$y) |
| 386 | } | |
| 387 | 52x | if (utils::tail(values$x, 1) < 1) { |
| 388 | ! | values$x = c(values$x, 1) |
| 389 | ! | values$y = c(values$y, utils::tail(values$y, 1)) |
| 390 | } | |
| 391 | 52x | if (ease == "spline") { |
| 392 | 52x | return(stats::splinefun(values$x, values$y, method = "monoH.FC")) |
| 393 | } | |
| 394 | ! | function(u) { |
| 395 | ! | i = pmin( |
| 396 | ! | length(values$x) - 1L, |
| 397 | ! | findInterval(u, values$x, all.inside = TRUE) |
| 398 | ) | |
| 399 | ! | t = (u - values$x[i]) / (values$x[i + 1L] - values$x[i]) |
| 400 | ! | t = switch( |
| 401 | ! | ease, |
| 402 | ! | linear = t, |
| 403 | ! | quad = sweep_quad_in_out(t), |
| 404 | ! | cubic = sweep_cubic_in_out(t), |
| 405 | ! | exp = (sweep_exp_in_out(t) - sweep_exp_in_out(0)) / |
| 406 | ! | (sweep_exp_in_out(1) - sweep_exp_in_out(0)) |
| 407 | ) | |
| 408 | ! | (1 - t) * values$y[i] + t * values$y[i + 1L] |
| 409 | } | |
| 410 | } | |
| 411 | ||
| 412 | #' Build indexed sweep geometry without scene or material state | |
| 413 | #' @keywords internal | |
| 414 | #' @noRd | |
| 415 | sweep_mesh_data = function( | |
| 416 | points, | |
| 417 | polygon = NA, | |
| 418 | polygon_end = NA, | |
| 419 | breaks = NA, | |
| 420 | closed = FALSE, | |
| 421 | closed_smooth = TRUE, | |
| 422 | polygon_add_points = 0, | |
| 423 | twists = 0, | |
| 424 | texture_repeats = 1, | |
| 425 | straight = FALSE, | |
| 426 | precomputed_control_points = FALSE, | |
| 427 | width = 1, | |
| 428 | width_end = NA, | |
| 429 | width_ease = "spline", | |
| 430 | smooth_normals = FALSE, | |
| 431 | u_min = 0, | |
| 432 | u_max = 1, | |
| 433 | linear_step = FALSE, | |
| 434 | end_caps = c(TRUE, TRUE), | |
| 435 | initial_normal = NULL, | |
| 436 | smooth_angle = 180, | |
| 437 | arc_tolerance = 1e-5 | |
| 438 | ) { | |
| 439 | 65x | for (name in c( |
| 440 | 65x | "closed", |
| 441 | 65x | "closed_smooth", |
| 442 | 65x | "straight", |
| 443 | 65x | "precomputed_control_points", |
| 444 | 65x | "smooth_normals", |
| 445 | 65x | "linear_step" |
| 446 | )) { | |
| 447 | 390x | value = get(name) |
| 448 | 390x | if (!is.logical(value) || length(value) != 1L || is.na(value)) { |
| 449 | ! | stop(sprintf("`%s` must be TRUE or FALSE.", name), call. = FALSE) |
| 450 | } | |
| 451 | } | |
| 452 | 65x | if (!is.logical(end_caps) || length(end_caps) != 2L || anyNA(end_caps)) { |
| 453 | 1x | stop("`end_caps` must contain two logical values.", call. = FALSE) |
| 454 | } | |
| 455 | 64x | sweep_scalar(polygon_add_points, "polygon_add_points", 0, 10000, TRUE) |
| 456 | 64x | sweep_scalar(twists, "twists") |
| 457 | 64x | sweep_scalar(texture_repeats, "texture_repeats", 0) |
| 458 | 64x | sweep_scalar(u_min, "u_min", 0) |
| 459 | 64x | sweep_scalar(u_max, "u_max", 0) |
| 460 | 63x | sweep_scalar(smooth_angle, "smooth_angle", 0, 180) |
| 461 | 63x | sweep_scalar(arc_tolerance, "arc_tolerance", .Machine$double.eps, 1) |
| 462 | 63x | width_ease = match.arg( |
| 463 | 63x | width_ease, |
| 464 | 63x | c("spline", "linear", "quad", "cubic", "exp") |
| 465 | ) | |
| 466 | 63x | missing_profile = function(x) { |
| 467 | 125x | is.null(x) || (is.atomic(x) && length(x) == 1L && is.na(x)) |
| 468 | } | |
| 469 | 63x | if (missing_profile(polygon)) { |
| 470 | 38x | theta = 2 * pi * (0:29) / 30 |
| 471 | 38x | polygon = cbind(sin(theta), cos(theta)) / 2 |
| 472 | } | |
| 473 | 63x | p = sweep_profile(polygon, "polygon", polygon_add_points) |
| 474 | 62x | q = if (missing_profile(polygon_end)) { |
| 475 | 59x | p |
| 476 | } else { | |
| 477 | 3x | sweep_profile(polygon_end, "polygon_end", polygon_add_points) |
| 478 | } | |
| 479 | 62x | if (nrow(p) != nrow(q)) { |
| 480 | ! | stop( |
| 481 | ! | "`polygon` and `polygon_end` must have the same number of vertices after closing duplicates are removed.", |
| 482 | ! | call. = FALSE |
| 483 | ) | |
| 484 | } | |
| 485 | 62x | controls = sweep_controls( |
| 486 | 62x | points, |
| 487 | 62x | closed, |
| 488 | 62x | closed_smooth, |
| 489 | 62x | straight, |
| 490 | 62x | precomputed_control_points |
| 491 | ) | |
| 492 | 59x | cps = controls$cps |
| 493 | 59x | closed = controls$closed |
| 494 | 59x | if (is.atomic(breaks) && length(breaks) == 1L && is.na(breaks)) { |
| 495 | 15x | breaks = 20L * length(cps) |
| 496 | } | |
| 497 | 59x | sweep_scalar(breaks, "breaks", 2, .Machine$integer.max, TRUE) |
| 498 | 54x | width_at = sweep_width(width, width_end, width_ease) |
| 499 | 52x | if (!closed && (u_min > 1 || u_max > 1 || u_max < u_min)) { |
| 500 | 1x | stop("Open paths require 0 <= u_min <= u_max <= 1.", call. = FALSE) |
| 501 | } | |
| 502 | 51x | if (u_min == u_max) { |
| 503 | 2x | return(list()) |
| 504 | } | |
| 505 | 49x | span = u_max - u_min |
| 506 | 49x | full = closed && span >= 1 |
| 507 | 49x | if (closed) { |
| 508 | 14x | if (span < 0) { |
| 509 | ! | span = span %% 1 |
| 510 | } | |
| 511 | 14x | u_min = u_min %% 1 |
| 512 | 14x | if (full) { |
| 513 | 13x | u_min = 0 |
| 514 | 13x | span = 1 |
| 515 | 13x | end_caps = c(FALSE, FALSE) |
| 516 | } | |
| 517 | 14x | u_max = u_min + span |
| 518 | } | |
| 519 | 49x | if (span == 0) { |
| 520 | ! | return(list()) |
| 521 | } | |
| 522 | 49x | if (full && breaks < 4) { |
| 523 | 1x | stop( |
| 524 | 1x | "Full closed sweeps require at least four `breaks` (three distinct rings).", |
| 525 | 1x | call. = FALSE |
| 526 | ) | |
| 527 | } | |
| 528 | 48x | intervals = if (u_max > 1) { |
| 529 | 1x | list(c(u_min, 1), c(0, u_max - 1)) |
| 530 | } else { | |
| 531 | 47x | list(c(u_min, u_max)) |
| 532 | } | |
| 533 | 48x | arc = sweep_arc_table(cps, arc_tolerance) |
| 534 | 48x | curve_samples = lapply(arc$t, function(t) sweep_curve(cps, t, closed)) |
| 535 | 48x | first = curve_samples[[1]] |
| 536 | 48x | if (is.null(initial_normal)) { |
| 537 | 46x | second = sweep_bezier_2nd_deriv(cps[[1]], 0) |
| 538 | 46x | normal = cross_prod(first$tangent, second) |
| 539 | 46x | if (sqrt(sum(normal^2)) < 1e-10 * max(1, sqrt(sum(second^2)))) { |
| 540 | 36x | normal = diag(3)[, which.min(abs(first$tangent))] |
| 541 | } | |
| 542 | } else { | |
| 543 | if ( | |
| 544 | 2x | !is.numeric(initial_normal) || |
| 545 | 2x | length(initial_normal) != 3L || |
| 546 | 2x | any(!is.finite(initial_normal)) |
| 547 | ) { | |
| 548 | ! | stop("`initial_normal` must be a finite three-vector.", call. = FALSE) |
| 549 | } | |
| 550 | 2x | normal = initial_normal |
| 551 | } | |
| 552 | 48x | normal = normal - sum(normal * first$tangent) * first$tangent |
| 553 | 48x | if (sqrt(sum(normal^2)) < 1e-12) { |
| 554 | 1x | stop( |
| 555 | 1x | "`initial_normal` must not be zero or parallel to the initial tangent.", |
| 556 | 1x | call. = FALSE |
| 557 | ) | |
| 558 | } | |
| 559 | 47x | frame_normals = vector("list", length(curve_samples)) |
| 560 | 47x | frame_normals[[1]] = normal / sqrt(sum(normal^2)) |
| 561 | 47x | for (i in seq_len(length(curve_samples) - 1L)) { |
| 562 | 10250x | frame_normals[[i + 1L]] = sweep_transport( |
| 563 | 10250x | frame_normals[[i]], |
| 564 | 10250x | curve_samples[[i]], |
| 565 | 10250x | curve_samples[[i + 1L]] |
| 566 | ) | |
| 567 | } | |
| 568 | 47x | correction = 0 |
| 569 | 47x | if (closed) { |
| 570 | 13x | last = tail(frame_normals, 1)[[1]] |
| 571 | 13x | correction = atan2( |
| 572 | 13x | sum(first$tangent * cross_prod(last, frame_normals[[1]])), |
| 573 | 13x | sum(last * frame_normals[[1]]) |
| 574 | ) | |
| 575 | } | |
| 576 | 47x | parameter_at = if (linear_step) { |
| 577 | 1x | stats::approxfun(arc$distance, arc$t, rule = 2) |
| 578 | } else { | |
| 579 | 46x | function(u) u |
| 580 | } | |
| 581 | 47x | distance_at = stats::approxfun(arc$t, arc$distance, rule = 2) |
| 582 | 47x | ring_at = function(u) { |
| 583 | 1463x | t = parameter_at(u) |
| 584 | 1463x | i = findInterval(t, arc$t, all.inside = TRUE) |
| 585 | 1463x | curve = sweep_curve(cps, t, closed) |
| 586 | 1463x | s = sweep_transport(frame_normals[[i]], curve_samples[[i]], curve) |
| 587 | # Rotate around the tangent using a signed closure correction. | |
| 588 | 1463x | angle = correction * distance_at(t) |
| 589 | 1463x | s = cos(angle) * s + sin(angle) * cross_prod(curve$tangent, s) |
| 590 | 1463x | r = cross_prod(s, curve$tangent) |
| 591 | 1463x | angle = u * twists * 2 * pi |
| 592 | 1463x | rotation = matrix( |
| 593 | 1463x | c(cos(angle), -sin(angle), sin(angle), cos(angle)), |
| 594 | 1463x | 2, |
| 595 | 1463x | 2, |
| 596 | 1463x | byrow = TRUE |
| 597 | ) | |
| 598 | 1463x | profile = ((1 - u) * p + u * q) %*% t(rotation) |
| 599 | 1463x | basis = cbind(s, r) |
| 600 | 1463x | offsets = profile %*% t(basis) |
| 601 | 1463x | list( |
| 602 | 1463x | vertices = sweep(offsets * width_at(u), 2, curve$point, "+"), |
| 603 | 1463x | offsets = offsets, |
| 604 | 1463x | profile = profile, |
| 605 | 1463x | tangent = curve$tangent, |
| 606 | 1463x | width = width_at(u) |
| 607 | ) | |
| 608 | } | |
| 609 | 47x | seam_map = NULL |
| 610 | 47x | if (closed && (full || length(intervals) == 2L)) { |
| 611 | 13x | a = ring_at(0)$vertices |
| 612 | 13x | b = ring_at(1)$vertices |
| 613 | 13x | tolerance = 1e-8 * max(1, max(abs(a)), max(abs(b))) |
| 614 | 13x | for (shift in 0:(nrow(p) - 1L)) { |
| 615 | 53x | candidate = (seq_len(nrow(p)) + shift - 1L) %% nrow(p) + 1L |
| 616 | 53x | if (max(abs(a[candidate, ] - b)) < tolerance) { |
| 617 | 11x | seam_map = candidate |
| 618 | 11x | break |
| 619 | } | |
| 620 | } | |
| 621 | 13x | if (is.null(seam_map)) { |
| 622 | 2x | stop( |
| 623 | 2x | "Closed sweep profiles do not meet: widths and profiles must match at the seam, and twists must respect the profile's rotational symmetry.", |
| 624 | 2x | call. = FALSE |
| 625 | ) | |
| 626 | } | |
| 627 | } | |
| 628 | 45x | grid = seq(0, 1, length.out = breaks) |
| 629 | # Include polyline corners, even when the requested sample grid misses them. | |
| 630 | 45x | if (straight) { |
| 631 | 1x | knots = seq(0, 1, length.out = length(cps) + 1L) |
| 632 | 1x | grid = sort(unique(c( |
| 633 | 1x | grid, |
| 634 | 1x | if (linear_step) distance_at(knots) else knots |
| 635 | ))) | |
| 636 | } | |
| 637 | 45x | result = list() |
| 638 | 45x | for (part in seq_along(intervals)) { |
| 639 | 46x | interval = intervals[[part]] |
| 640 | 46x | samples = sort(unique(c( |
| 641 | 46x | interval, |
| 642 | 46x | grid[grid > interval[1] & grid < interval[2]] |
| 643 | ))) | |
| 644 | 46x | rings = lapply(samples, ring_at) |
| 645 | 46x | if (!is.null(seam_map) && tail(samples, 1) == 1) { |
| 646 | 11x | rings[[length(rings)]]$vertices = ring_at(0)$vertices[ |
| 647 | 11x | seam_map, |
| 648 | , | |
| 649 | 11x | drop = FALSE |
| 650 | ] | |
| 651 | } | |
| 652 | 46x | caps = c( |
| 653 | 46x | part == 1L && end_caps[1], |
| 654 | 46x | part == length(intervals) && end_caps[2] |
| 655 | ) | |
| 656 | 46x | result[[part]] = sweep_assemble( |
| 657 | 46x | rings, |
| 658 | 46x | samples, |
| 659 | 46x | ring_at, |
| 660 | 46x | smooth_normals, |
| 661 | 46x | smooth_angle, |
| 662 | 46x | texture_repeats, |
| 663 | 46x | caps, |
| 664 | 46x | if (full) seam_map else NULL, |
| 665 | 46x | seam_map |
| 666 | ) | |
| 667 | } | |
| 668 | 45x | result |
| 669 | } | |
| 670 | ||
| 671 | #' Assemble indexed sweep rings and caps | |
| 672 | #' @keywords internal | |
| 673 | #' @noRd | |
| 674 | sweep_assemble = function( | |
| 675 | rings, | |
| 676 | samples, | |
| 677 | ring_at, | |
| 678 | smooth, | |
| 679 | smooth_angle, | |
| 680 | texture_repeats, | |
| 681 | caps, | |
| 682 | join_map, | |
| 683 | periodic_map | |
| 684 | ) { | |
| 685 | 46x | n = nrow(rings[[1]]$vertices) |
| 686 | 46x | nr = length(rings) |
| 687 | 46x | next_i = c(2:n, 1L) |
| 688 | 46x | previous = c(n, seq_len(n - 1L)) |
| 689 | 46x | vertices = texcoords = normals = vector("list", nr) |
| 690 | 46x | indices = vector("list", nr) |
| 691 | 46x | offset = 0L |
| 692 | 46x | for (i in seq_len(nr)) { |
| 693 | 888x | ring = rings[[i]] |
| 694 | 888x | if (i == nr && !is.null(join_map)) { |
| 695 | 10x | indices[[i]] = indices[[1]][ |
| 696 | 10x | if (length(indices[[1]]) == 1L) 1L else join_map |
| 697 | ] | |
| 698 | 10x | vertices[[i]] = matrix(numeric(), ncol = 3) |
| 699 | } else { | |
| 700 | 878x | vertices[[i]] = if (ring$width == 0) { |
| 701 | 46x | ring$vertices[1, , drop = FALSE] |
| 702 | } else { | |
| 703 | 832x | ring$vertices |
| 704 | } | |
| 705 | 878x | indices[[i]] = offset + seq_len(nrow(vertices[[i]])) |
| 706 | 878x | offset = offset + nrow(vertices[[i]]) |
| 707 | } | |
| 708 | 888x | lengths = sqrt(rowSums((ring$profile[next_i, ] - ring$profile)^2)) |
| 709 | 888x | if (any(lengths == 0)) { |
| 710 | ! | stop( |
| 711 | ! | "Interpolated profiles must have distinct consecutive vertices.", |
| 712 | ! | call. = FALSE |
| 713 | ) | |
| 714 | } | |
| 715 | 888x | texcoords[[i]] = cbind( |
| 716 | 888x | c(0, cumsum(lengths)) / sum(lengths), |
| 717 | 888x | samples[i] * texture_repeats |
| 718 | ) | |
| 719 | 888x | if (smooth) { |
| 720 | 269x | h = 1e-5 |
| 721 | 269x | lo = max(0, samples[i] - h) |
| 722 | 269x | hi = min(1, samples[i] + h) |
| 723 | 269x | a = ring_at(lo)$vertices |
| 724 | 269x | b = ring_at(hi)$vertices |
| 725 | 269x | if (!is.null(periodic_map) && samples[i] == 0) { |
| 726 | ! | a = ring_at(1 - h)$vertices[order(periodic_map), ] |
| 727 | ! | lo = -h |
| 728 | } | |
| 729 | 269x | if (!is.null(periodic_map) && samples[i] == 1) { |
| 730 | ! | b = ring_at(h)$vertices[periodic_map, ] |
| 731 | ! | hi = 1 + h |
| 732 | } | |
| 733 | 269x | longitudinal = (b - a) / (hi - lo) |
| 734 | 269x | incoming = ring$offsets - ring$offsets[previous, ] |
| 735 | 269x | outgoing = ring$offsets[next_i, ] - ring$offsets |
| 736 | 269x | unit_rows = function(x) { |
| 737 | 1334x | sizes = sqrt(rowSums(x^2)) |
| 738 | 1334x | if (any(!is.finite(sizes)) || any(sizes == 0)) { |
| 739 | ! | stop( |
| 740 | ! | "Cannot compute normals at a degenerate sweep surface.", |
| 741 | ! | call. = FALSE |
| 742 | ) | |
| 743 | } | |
| 744 | 1334x | x / sizes |
| 745 | } | |
| 746 | 269x | incoming = unit_rows(incoming) |
| 747 | 269x | outgoing = unit_rows(outgoing) |
| 748 | 269x | cross_rows = function(a, b) { |
| 749 | 538x | cbind( |
| 750 | 538x | a[, 2] * b[, 3] - a[, 3] * b[, 2], |
| 751 | 538x | a[, 3] * b[, 1] - a[, 1] * b[, 3], |
| 752 | 538x | a[, 1] * b[, 2] - a[, 2] * b[, 1] |
| 753 | ) | |
| 754 | } | |
| 755 | 269x | ni = unit_rows(cross_rows(incoming, longitudinal)) |
| 756 | 269x | no = unit_rows(cross_rows(outgoing, longitudinal)) |
| 757 | 269x | blend = rowSums(incoming * outgoing) >= cospi(smooth_angle / 180) - 1e-12 |
| 758 | 269x | if (any(blend)) { |
| 759 | 258x | averaged = unit_rows( |
| 760 | 258x | ni[blend, , drop = FALSE] + no[blend, , drop = FALSE] |
| 761 | ) | |
| 762 | 258x | ni[blend, ] = no[blend, ] = averaged |
| 763 | } | |
| 764 | 269x | normals[[i]] = rbind(ni, no) |
| 765 | } | |
| 766 | } | |
| 767 | 46x | faces = texture_faces = normal_faces = list() |
| 768 | 46x | for (i in seq_len(nr - 1L)) { |
| 769 | 842x | lower = indices[[i]] |
| 770 | 842x | upper = indices[[i + 1L]] |
| 771 | 842x | lu = (i - 1L) * (n + 1L) + seq_len(n) |
| 772 | 842x | uu = i * (n + 1L) + seq_len(n) |
| 773 | 842x | ln = (i - 1L) * (2L * n) |
| 774 | 842x | un = i * (2L * n) |
| 775 | 842x | if (length(lower) == 1L && length(upper) == 1L) { |
| 776 | 42x | next |
| 777 | } | |
| 778 | 800x | if (length(lower) == 1L) { |
| 779 | 1x | f = cbind(lower, upper[next_i], upper) |
| 780 | 1x | tf = cbind(lu, uu + 1L, uu) |
| 781 | 1x | nf = cbind(ln + n + seq_len(n), un + next_i, un + n + seq_len(n)) |
| 782 | 799x | } else if (length(upper) == 1L) { |
| 783 | ! | f = cbind(lower, lower[next_i], upper) |
| 784 | ! | tf = cbind(lu, lu + 1L, uu) |
| 785 | ! | nf = cbind(ln + n + seq_len(n), ln + next_i, un + n + seq_len(n)) |
| 786 | } else { | |
| 787 | 799x | f = rbind( |
| 788 | 799x | cbind(lower, lower[next_i], upper), |
| 789 | 799x | cbind(upper, lower[next_i], upper[next_i]) |
| 790 | ) | |
| 791 | 799x | tf = rbind(cbind(lu, lu + 1L, uu), cbind(uu, lu + 1L, uu + 1L)) |
| 792 | 799x | nf = rbind( |
| 793 | 799x | cbind(ln + n + seq_len(n), ln + next_i, un + n + seq_len(n)), |
| 794 | 799x | cbind(un + n + seq_len(n), ln + next_i, un + next_i) |
| 795 | ) | |
| 796 | } | |
| 797 | 800x | faces[[length(faces) + 1L]] = f |
| 798 | 800x | texture_faces[[length(texture_faces) + 1L]] = tf |
| 799 | 800x | normal_faces[[length(normal_faces) + 1L]] = nf |
| 800 | } | |
| 801 | 46x | surface = NULL |
| 802 | 46x | if (length(faces)) { |
| 803 | 43x | surface = list( |
| 804 | 43x | vertices = unname(do.call(rbind, vertices)), |
| 805 | 43x | indices = do.call(rbind, faces) - 1L, |
| 806 | 43x | texcoords = do.call(rbind, texcoords), |
| 807 | 43x | tex_indices = do.call(rbind, texture_faces) - 1L |
| 808 | ) | |
| 809 | 43x | if (smooth) { |
| 810 | 15x | surface$normals = do.call(rbind, normals) |
| 811 | 15x | surface$norm_indices = do.call(rbind, normal_faces) - 1L |
| 812 | } | |
| 813 | } | |
| 814 | 46x | cap_meshes = list() |
| 815 | 46x | for (end in which(caps)) { |
| 816 | 68x | ring = rings[[if (end == 1L) 1L else nr]] |
| 817 | 68x | if (ring$width == 0) { |
| 818 | 7x | next |
| 819 | } | |
| 820 | 61x | triangles = matrix(decido::earcut(ring$profile), ncol = 3L, byrow = TRUE) |
| 821 | 61x | if (nrow(triangles) != n - 2L) { |
| 822 | ! | stop( |
| 823 | ! | "Cannot triangulate sweep cap: the profile must be a simple polygon without holes.", |
| 824 | ! | call. = FALSE |
| 825 | ) | |
| 826 | } | |
| 827 | 61x | desired = ring$tangent * if (end == 1L) -1 else 1 |
| 828 | 61x | v = ring$vertices[triangles[1, ], ] |
| 829 | 61x | if (sum(cross_prod(v[2, ] - v[1, ], v[3, ] - v[1, ]) * desired) < 0) { |
| 830 | 31x | triangles = triangles[, c(1, 3, 2)] |
| 831 | } | |
| 832 | 61x | uv = sweep(ring$profile, 2, apply(ring$profile, 2, min)) |
| 833 | 61x | uv = sweep(uv, 2, apply(uv, 2, max), "/") |
| 834 | 61x | cap_meshes[[length(cap_meshes) + 1L]] = list( |
| 835 | 61x | vertices = ring$vertices, |
| 836 | 61x | indices = triangles - 1L, |
| 837 | 61x | normals = matrix(desired, nrow = 1L), |
| 838 | 61x | norm_indices = matrix(0L, nrow(triangles), 3L), |
| 839 | 61x | texcoords = uv, |
| 840 | 61x | tex_indices = triangles - 1L |
| 841 | ) | |
| 842 | } | |
| 843 | 46x | list(surface = surface, caps = cap_meshes) |
| 844 | } |
| 1 | #' Define the ray_shape class | |
| 2 | #' | |
| 3 | #' @param ... Objects to be included in the ray_shape. | |
| 4 | #' @return A new ray_shape object. | |
| 5 | #' @keywords internal | |
| 6 | ray_shape = function(...) { | |
| 7 | 168x | vctrs::new_vctr(list(...), class = c("ray_shape", "list")) |
| 8 | } | |
| 9 | ||
| 10 | #' Define the ray_shape_list class | |
| 11 | #' | |
| 12 | #' @param ... Objects to be included in the ray_shape_list. | |
| 13 | #' @return A new ray_shape_list object. | |
| 14 | #' @keywords internal | |
| 15 | ray_shape_list = function(...) { | |
| 16 | ! | vctrs::new_vctr(..., class = c("ray_shape_list", "list")) |
| 17 | } | |
| 18 | ||
| 19 | ||
| 20 | #' Abbreviate the ptype of ray_shape | |
| 21 | #' | |
| 22 | #' @param x A ray_shape object. | |
| 23 | #' @param ... Additional arguments (unused). | |
| 24 | #' @return A character vector with the abbreviation "ray_shp". | |
| 25 | #' @keywords internal | |
| 26 | vec_ptype_abbr.ray_shape = function(x, ...) { | |
| 27 | ! | "ray_shp" |
| 28 | } | |
| 29 | ||
| 30 | ||
| 31 | #' Abbreviate the ptype of ray_shape_list | |
| 32 | #' | |
| 33 | #' @param x A ray_shape_list object. | |
| 34 | #' @param ... Additional arguments (unused). | |
| 35 | #' @return A character vector with the abbreviation "ray_shp". | |
| 36 | #' @keywords internal | |
| 37 | vec_ptype_abbr.ray_shape_list = function(x, ...) { | |
| 38 | ! | "ray_shp" |
| 39 | } | |
| 40 | ||
| 41 | #' Format ray_shape for pillar | |
| 42 | #' | |
| 43 | #' @param x A ray_shape object. | |
| 44 | #' @return A formatted character vector. | |
| 45 | #' @keywords internal | |
| 46 | format_pillar_shp = function(x) { | |
| 47 | ! | format_shp = function(x) { |
| 48 | ! | n_tris = nrow(x$indices) |
| 49 | ! | has_tex = if (all(x$has_vertex_tex)) { |
| 50 | ! | cli::col_green("UV") |
| 51 | ! | } else if (any(x$has_vertex_tex)) { |
| 52 | ! | cli::col_yellow("UV") |
| 53 | } else { | |
| 54 | ! | pillar::style_subtle("UV") |
| 55 | } | |
| 56 | ! | has_norm = if (all(x$has_vertex_normals)) { |
| 57 | ! | cli::col_green("N") |
| 58 | ! | } else if (any(x$has_vertex_normals)) { |
| 59 | ! | cli::col_yellow("N") |
| 60 | } else { | |
| 61 | ! | pillar::style_subtle("N") |
| 62 | } | |
| 63 | ! | n_mat = length(unique(x$material_ids)) |
| 64 | ||
| 65 | ! | output_shp = (sprintf( |
| 66 | ! | "T:%s%s%s%s%s%sM:%s", |
| 67 | ! | cli::col_cyan(n_tris), |
| 68 | ! | pillar::style_subtle("|"), |
| 69 | ! | has_tex, |
| 70 | ! | pillar::style_subtle("|"), |
| 71 | ! | has_norm, |
| 72 | ! | pillar::style_subtle("|"), |
| 73 | ! | cli::col_cyan(n_mat) |
| 74 | )) | |
| 75 | ! | sprintf( |
| 76 | ! | "%s%s%s", |
| 77 | ! | pillar::style_subtle("<"), |
| 78 | ! | paste0(output_shp, collapse = ""), |
| 79 | ! | pillar::style_subtle(">") |
| 80 | ) | |
| 81 | } | |
| 82 | ! | vapply(x, format_shp, character(1)) |
| 83 | } | |
| 84 | ||
| 85 | #' Pillar shaft for ray_shape_list | |
| 86 | #' | |
| 87 | #' @param x A ray_shape_list object. | |
| 88 | #' @param ... Additional arguments (unused). | |
| 89 | #' @return A pillar shaft object. | |
| 90 | #' @keywords internal | |
| 91 | pillar_shaft.ray_shape_list = function(x, ...) { | |
| 92 | ! | pillar::new_pillar_shaft_simple( |
| 93 | ! | format_pillar_shp(x), |
| 94 | ! | align = "right", |
| 95 | ! | width = 20 |
| 96 | ) | |
| 97 | } | |
| 98 | ||
| 99 | #' Pillar shaft for ray_shape | |
| 100 | #' | |
| 101 | #' @param x A ray_shape object. | |
| 102 | #' @param ... Additional arguments (unused). | |
| 103 | #' @return A pillar shaft object. | |
| 104 | #' @keywords internal | |
| 105 | pillar_shaft.ray_shape = function(x, ...) { | |
| 106 | ! | pillar::new_pillar_shaft_simple( |
| 107 | ! | format_pillar_shp(x), |
| 108 | ! | align = "right", |
| 109 | ! | width = 20 |
| 110 | ) | |
| 111 | } | |
| 112 | ||
| 113 | #' Print method for ray_shape | |
| 114 | #' | |
| 115 | #' @param x A ray_shape object. | |
| 116 | #' @param ... Additional arguments (unused). | |
| 117 | #' @keywords internal | |
| 118 | #' @export | |
| 119 | print.ray_shape = function(x, ...) { | |
| 120 | ! | print_shape = function(x, ...) { |
| 121 | # Print indices | |
| 122 | ! | if (length(x$indices) > 0) { |
| 123 | ! | cat(sprintf( |
| 124 | ! | "$ %s : int [%dx3] %s ...\n", |
| 125 | ! | pillar::style_subtle("indices"), |
| 126 | ! | nrow(x$indices), |
| 127 | ! | cli::col_cyan(paste(t(utils::head(x$indices, 5)), collapse = " ")) |
| 128 | )) | |
| 129 | } else { | |
| 130 | ! | cat(sprintf( |
| 131 | ! | "$ %s : %s\n", |
| 132 | ! | "indices", |
| 133 | ! | pillar::style_subtle("int(0)") |
| 134 | )) | |
| 135 | } | |
| 136 | ||
| 137 | # Print tex_indices | |
| 138 | ! | if (length(x$tex_indices) > 0) { |
| 139 | ! | cat(sprintf( |
| 140 | ! | "$ %s : int [%dx3] %s ...\n", |
| 141 | ! | pillar::style_subtle("tex_indices"), |
| 142 | ! | nrow(x$tex_indices), |
| 143 | ! | cli::col_cyan(paste(utils::head(x$tex_indices, 5), collapse = " ")) |
| 144 | )) | |
| 145 | } else { | |
| 146 | ! | cat(sprintf( |
| 147 | ! | "$ %s : %s\n", |
| 148 | ! | "tex_indices", |
| 149 | ! | pillar::style_subtle("int(0)") |
| 150 | )) | |
| 151 | } | |
| 152 | ||
| 153 | # Print norm_indices | |
| 154 | ! | if (length(x$norm_indices) > 0) { |
| 155 | ! | cat(sprintf( |
| 156 | ! | "$ %s : int [%dx3] %s ...\n", |
| 157 | ! | pillar::style_subtle("norm_indices"), |
| 158 | ! | nrow(x$norm_indices), |
| 159 | ! | cli::col_cyan(paste(utils::head(x$norm_indices, 5), collapse = " ")) |
| 160 | )) | |
| 161 | } else { | |
| 162 | ! | cat(sprintf( |
| 163 | ! | "$ %s : %s\n", |
| 164 | ! | "norm_indices", |
| 165 | ! | pillar::style_subtle("int(0)") |
| 166 | )) | |
| 167 | } | |
| 168 | ||
| 169 | # Print material_ids | |
| 170 | ! | cat(sprintf( |
| 171 | ! | "$ %s : int [%d] %s ...\n", |
| 172 | ! | pillar::style_subtle("material_ids"), |
| 173 | ! | length(x$material_ids), |
| 174 | ! | cli::col_cyan(paste(utils::head(x$material_ids, 5), collapse = " ")) |
| 175 | )) | |
| 176 | ||
| 177 | # Print has_vertex_tex | |
| 178 | ! | cat(sprintf( |
| 179 | ! | "$ %s : logi [%d] %s ...\n", |
| 180 | ! | pillar::style_subtle("has_vertex_tex"), |
| 181 | ! | length(x$has_vertex_tex), |
| 182 | ! | cli::col_cyan(paste(utils::head(x$has_vertex_tex, 5), collapse = " ")) |
| 183 | )) | |
| 184 | ||
| 185 | # Print has_vertex_normals | |
| 186 | ! | cat(sprintf( |
| 187 | ! | "$ %s: logi [%d] %s ...\n", |
| 188 | ! | pillar::style_subtle("has_vertex_normals"), |
| 189 | ! | length(x$has_vertex_normals), |
| 190 | ! | cli::col_cyan(paste(utils::head(x$has_vertex_normals, 5), collapse = " ")) |
| 191 | )) | |
| 192 | } | |
| 193 | ! | for (i in seq_along(x)) { |
| 194 | ! | cat(sprintf(pillar::style_subtle("[[%i]] ray_shape"), i), sep = "\n") |
| 195 | ! | print_shape(x[[1]]) |
| 196 | } | |
| 197 | } | |
| 198 | ||
| 199 | #' Define the ray_vertex_data class | |
| 200 | #' | |
| 201 | #' @param data A matrix with 2 or 3 columns representing vertex data. | |
| 202 | #' @return A new ray_vertex_data object. | |
| 203 | #' @keywords internal | |
| 204 | ray_vertex_data = function(data = NA) { | |
| 205 | 508x | stopifnot(is.matrix(data)) |
| 206 | 508x | stopifnot(ncol(data) == 3 || ncol(data) == 2) |
| 207 | ||
| 208 | 508x | vctrs::new_vctr(list(data), class = "ray_vertex_data") |
| 209 | } | |
| 210 | ||
| 211 | #' Print method for ray_vertex_data | |
| 212 | #' | |
| 213 | #' @param x A ray_vertex_data object. | |
| 214 | #' @param ... Additional arguments (unused). | |
| 215 | #' @keywords internal | |
| 216 | #' @export | |
| 217 | print.ray_vertex_data = function(x, ...) { | |
| 218 | ! | print_data = function(x, ...) { |
| 219 | ! | ncols = ncol(x) |
| 220 | ! | nrows = nrow(x) |
| 221 | ! | cat(sprintf( |
| 222 | ! | "%s%s%s%s%s%s", |
| 223 | ! | pillar::style_subtle("<"), |
| 224 | ! | cli::col_cyan(nrows), |
| 225 | ! | pillar::style_subtle("x"), |
| 226 | ! | cli::col_cyan(ncols), |
| 227 | ! | cli::col_cyan(" matrix"), |
| 228 | ! | pillar::style_subtle(">\n") |
| 229 | )) | |
| 230 | ! | print(utils::head(x, 5)) |
| 231 | ! | if (nrows > 5) { |
| 232 | ! | cat(pillar::style_subtle(sprintf( |
| 233 | ! | "[%s,] %i more rows \n", |
| 234 | ! | cli::symbol$ellipsis, |
| 235 | ! | nrows - 5 |
| 236 | ))) | |
| 237 | } | |
| 238 | } | |
| 239 | ! | for (i in seq_along(x)) { |
| 240 | ! | cat(sprintf(pillar::style_subtle("[[%i]]"), i), sep = "\n") |
| 241 | ! | print_data(x[[i]]) |
| 242 | } | |
| 243 | } | |
| 244 | ||
| 245 | #' Convert RGB to ANSI Color | |
| 246 | #' | |
| 247 | #' @param color Length=3 numeric vector. | |
| 248 | #' | |
| 249 | #' @return ANSI color code as a string. | |
| 250 | #' @keywords internal | |
| 251 | convert_rgb_to_ansi = function(color) { | |
| 252 | # Get the number of supported ANSI colors | |
| 253 | ! | num_colors = cli::num_ansi_colors() |
| 254 | ||
| 255 | # Convert RGB from [0, 1] to [0, 255] | |
| 256 | ! | r = as.integer(color[1] * 255) |
| 257 | ! | g = as.integer(color[2] * 255) |
| 258 | ! | b = as.integer(color[3] * 255) |
| 259 | ||
| 260 | # Define a function to convert RGB to ANSI 256 colors | |
| 261 | ! | rgb_to_ansi256_bg = function(r, g, b) { |
| 262 | ! | if (r == g && g == b) { |
| 263 | ! | if (r < 8) return(16) |
| 264 | ! | if (r > 248) return(231) |
| 265 | ! | return(as.integer((r - 8) / 247 * 24) + 232) |
| 266 | } | |
| 267 | ! | return( |
| 268 | ! | 16 + |
| 269 | ! | 36 * as.integer(r / 255 * 5) + |
| 270 | ! | 6 * as.integer(g / 255 * 5) + |
| 271 | ! | as.integer(b / 255 * 5) |
| 272 | ) | |
| 273 | } | |
| 274 | ||
| 275 | # Define a function to convert RGB to ANSI 16 colors | |
| 276 | ! | rgb_to_ansi16_bg = function(r, g, b) { |
| 277 | ! | if (r < 128 && g < 128 && b < 128) return(40) # Black |
| 278 | ! | if (r > 128 && g < 128 && b < 128) return(41) # Red |
| 279 | ! | if (r < 128 && g > 128 && b < 128) return(42) # Green |
| 280 | ! | if (r > 128 && g > 128 && b < 128) return(43) # Yellow |
| 281 | ! | if (r < 128 && g < 128 && b > 128) return(44) # Blue |
| 282 | ! | if (r > 128 && g < 128 && b > 128) return(45) # Magenta |
| 283 | ! | if (r < 128 && g > 128 && b > 128) return(46) # Cyan |
| 284 | ! | if (r > 192 && g > 192 && b > 192) return(47) # White |
| 285 | ! | return(47) # Default to white for other cases |
| 286 | } | |
| 287 | ||
| 288 | # Select conversion function based on the number of supported colors | |
| 289 | ! | if (num_colors >= 16777216) { |
| 290 | # True color (24-bit) support | |
| 291 | ! | ansi_code = paste0("\033[48;2;", r, ";", g, ";", b, "m") |
| 292 | ! | } else if (num_colors >= 256) { |
| 293 | # 256 colors support | |
| 294 | ! | ansi_code = paste0("\033[48;5;", rgb_to_ansi256_bg(r, g, b), "m") |
| 295 | ! | } else if (num_colors >= 16) { |
| 296 | # 16 colors support | |
| 297 | ! | ansi_code = paste0("\033[", rgb_to_ansi16_bg(r, g, b), "m") |
| 298 | } else { | |
| 299 | # Fallback to black if only 8 colors are supported | |
| 300 | ! | ansi_code = "\033[40m" |
| 301 | } | |
| 302 | ||
| 303 | ! | return(ansi_code) |
| 304 | } | |
| 305 | ||
| 306 | ||
| 307 | #' Print out the color | |
| 308 | #' | |
| 309 | #' @return none | |
| 310 | #' @keywords internal | |
| 311 | cat_color = function( | |
| 312 | color, | |
| 313 | var_name, | |
| 314 | default = NA, | |
| 315 | intensity = 1, | |
| 316 | spacer = "" | |
| 317 | ) { | |
| 318 | ! | print_col = FALSE |
| 319 | ! | if (any(is.na(default))) { |
| 320 | ! | print_col = TRUE |
| 321 | } else { | |
| 322 | ! | print_col = any(color != default) |
| 323 | } | |
| 324 | ! | if (print_col) { |
| 325 | ! | colbg = sprintf( |
| 326 | ! | "%s %s", |
| 327 | ! | convert_rgb_to_ansi(convert_color(color)), |
| 328 | ! | "\033[0m" |
| 329 | ) | |
| 330 | ! | intensity_str = "" |
| 331 | ! | if (intensity != 1) { |
| 332 | ! | intensity_str = sprintf( |
| 333 | ! | "%s %0.1f", |
| 334 | ! | pillar::style_subtle("| intensity:"), |
| 335 | ! | intensity |
| 336 | ) | |
| 337 | } | |
| 338 | ! | cat(sprintf( |
| 339 | ! | "%s%s %s %s %s %s\n", |
| 340 | ! | spacer, |
| 341 | ! | pillar::style_subtle(cli::symbol$bullet), |
| 342 | ! | pillar::style_subtle(sprintf("%s:", var_name)), |
| 343 | ! | convert_color(color, as_hex = TRUE), |
| 344 | ! | colbg, |
| 345 | ! | intensity_str |
| 346 | )) | |
| 347 | } | |
| 348 | } | |
| 349 | ||
| 350 | #' @keywords internal | |
| 351 | #' @export | |
| 352 | print.rayvertex_material = function(x, spacer = "", id = 0, ...) { | |
| 353 | ! | if (spacer != "") { |
| 354 | ! | cat( |
| 355 | ! | pillar::style_subtle(sprintf( |
| 356 | ! | "%s Material ID: %i ", |
| 357 | ! | cli::symbol$bullet, |
| 358 | ! | id |
| 359 | )), | |
| 360 | ! | sep = "\n" |
| 361 | ) | |
| 362 | } else { | |
| 363 | ! | cat( |
| 364 | ! | pillar::style_subtle(sprintf( |
| 365 | ! | "%s rayvertex_material", |
| 366 | ! | cli::symbol$bullet |
| 367 | )), | |
| 368 | ! | sep = "\n" |
| 369 | ) | |
| 370 | } | |
| 371 | ! | print_single_mat = function(x, i = 0) { |
| 372 | # cat(pillar::style_subtle(sprintf("[[%i]]", i)),sep="\n") | |
| 373 | ! | bullet = pillar::style_subtle(cli::symbol$bullet) |
| 374 | ! | cat( |
| 375 | ! | sprintf( |
| 376 | ! | "%s%s %s %s", |
| 377 | ! | spacer, |
| 378 | ! | bullet, |
| 379 | ! | pillar::style_subtle("type:"), |
| 380 | ! | x$type |
| 381 | ), | |
| 382 | ! | sep = "\n" |
| 383 | ) | |
| 384 | ! | cat_color(x$diffuse, "diffuse", NA, x$diffuse_intensity, spacer = spacer) |
| 385 | ! | cat_color( |
| 386 | ! | x$ambient, |
| 387 | ! | "ambient", |
| 388 | ! | c(0, 0, 0), |
| 389 | ! | x$ambient_intensity, |
| 390 | ! | spacer = spacer |
| 391 | ) | |
| 392 | ! | cat_color( |
| 393 | ! | x$specular, |
| 394 | ! | "specular", |
| 395 | ! | c(1, 1, 1), |
| 396 | ! | x$specular_intensity, |
| 397 | ! | spacer = spacer |
| 398 | ) | |
| 399 | ! | cat_color(x$transmittance, "transmittance", c(0, 0, 0), spacer = spacer) |
| 400 | ! | cat_color( |
| 401 | ! | x$emission, |
| 402 | ! | "emission", |
| 403 | ! | c(0, 0, 0), |
| 404 | ! | x$emission_intensity, |
| 405 | ! | spacer = spacer |
| 406 | ) | |
| 407 | ! | if (x$shininess != 50) { |
| 408 | ! | cat( |
| 409 | ! | sprintf( |
| 410 | ! | "%s%s %s %i", |
| 411 | ! | spacer, |
| 412 | ! | bullet, |
| 413 | ! | pillar::style_subtle("shininess:"), |
| 414 | ! | x$shininess |
| 415 | ), | |
| 416 | ! | sep = "\n" |
| 417 | ) | |
| 418 | } | |
| 419 | ! | if (x$ior != 1) { |
| 420 | ! | cat( |
| 421 | ! | sprintf( |
| 422 | ! | "%s%s %s %0.2f", |
| 423 | ! | spacer, |
| 424 | ! | bullet, |
| 425 | ! | pillar::style_subtle("ior:"), |
| 426 | ! | x$ior |
| 427 | ), | |
| 428 | ! | sep = "\n" |
| 429 | ) | |
| 430 | } | |
| 431 | ! | if (x$dissolve != 1) { |
| 432 | ! | cat( |
| 433 | ! | sprintf( |
| 434 | ! | "%s%s %s %0.2f", |
| 435 | ! | spacer, |
| 436 | ! | bullet, |
| 437 | ! | pillar::style_subtle("dissolve:"), |
| 438 | ! | x$dissolve |
| 439 | ), | |
| 440 | ! | sep = "\n" |
| 441 | ) | |
| 442 | } | |
| 443 | ! | if (x$illum != 1) { |
| 444 | ! | cat( |
| 445 | ! | sprintf( |
| 446 | ! | "%s%s %s %i", |
| 447 | ! | spacer, |
| 448 | ! | bullet, |
| 449 | ! | pillar::style_subtle("illum:"), |
| 450 | ! | x$illum |
| 451 | ), | |
| 452 | ! | sep = "\n" |
| 453 | ) | |
| 454 | } | |
| 455 | ! | if (x$sigma != 0) { |
| 456 | ! | cat( |
| 457 | ! | sprintf( |
| 458 | ! | "%s%s %s %i", |
| 459 | ! | spacer, |
| 460 | ! | bullet, |
| 461 | ! | pillar::style_subtle("sigma:"), |
| 462 | ! | x$sigma |
| 463 | ), | |
| 464 | ! | sep = "\n" |
| 465 | ) | |
| 466 | } | |
| 467 | ||
| 468 | ! | if (x$diffuse_texname != "") { |
| 469 | ! | if (file.exists(x$diffuse_texname)) { |
| 470 | ! | fileexists_str = sprintf( |
| 471 | ! | "%s %s %s", |
| 472 | ! | pillar::style_subtle("|"), |
| 473 | ! | cli::col_green(cli::symbol$tick), |
| 474 | ! | "File exists!" |
| 475 | ) | |
| 476 | } else { | |
| 477 | ! | fileexists_str = sprintf( |
| 478 | ! | "%s %s %s", |
| 479 | ! | pillar::style_subtle("|"), |
| 480 | ! | cli::col_red(cli::symbol$cross), |
| 481 | ! | "File not found" |
| 482 | ) | |
| 483 | } | |
| 484 | ! | cat( |
| 485 | ! | sprintf( |
| 486 | ! | "%s%s %s %s %s", |
| 487 | ! | spacer, |
| 488 | ! | bullet, |
| 489 | ! | pillar::style_subtle("diffuse_texname:"), |
| 490 | ! | x$diffuse_texname, |
| 491 | ! | fileexists_str |
| 492 | ), | |
| 493 | ! | sep = "\n" |
| 494 | ) | |
| 495 | } | |
| 496 | ! | if (x$ambient_texname != "") { |
| 497 | ! | if (file.exists(x$ambient_texname)) { |
| 498 | ! | fileexists_str = sprintf( |
| 499 | ! | "%s %s %s", |
| 500 | ! | pillar::style_subtle("|"), |
| 501 | ! | cli::col_green(cli::symbol$tick), |
| 502 | ! | "File exists!" |
| 503 | ) | |
| 504 | } else { | |
| 505 | ! | fileexists_str = sprintf( |
| 506 | ! | "%s %s %s", |
| 507 | ! | pillar::style_subtle("|"), |
| 508 | ! | cli::col_red(cli::symbol$cross), |
| 509 | ! | "File not found" |
| 510 | ) | |
| 511 | } | |
| 512 | ! | cat( |
| 513 | ! | sprintf( |
| 514 | ! | "%s%s %s %s %s", |
| 515 | ! | spacer, |
| 516 | ! | bullet, |
| 517 | ! | pillar::style_subtle("ambient_texname:"), |
| 518 | ! | x$ambient_texname, |
| 519 | ! | fileexists_str |
| 520 | ), | |
| 521 | ! | sep = "\n" |
| 522 | ) | |
| 523 | } | |
| 524 | ! | if (x$specular_texname != "") { |
| 525 | ! | if (file.exists(x$specular_texname)) { |
| 526 | ! | fileexists_str = sprintf( |
| 527 | ! | "%s %s %s", |
| 528 | ! | pillar::style_subtle("|"), |
| 529 | ! | cli::col_green(cli::symbol$tick), |
| 530 | ! | "File exists!" |
| 531 | ) | |
| 532 | } else { | |
| 533 | ! | fileexists_str = sprintf( |
| 534 | ! | "%s %s %s", |
| 535 | ! | pillar::style_subtle("|"), |
| 536 | ! | cli::col_red(cli::symbol$cross), |
| 537 | ! | "File not found" |
| 538 | ) | |
| 539 | } | |
| 540 | ! | cat( |
| 541 | ! | sprintf( |
| 542 | ! | "%s%s %s %s %s", |
| 543 | ! | spacer, |
| 544 | ! | bullet, |
| 545 | ! | pillar::style_subtle("specular_texname:"), |
| 546 | ! | x$specular_texname, |
| 547 | ! | fileexists_str |
| 548 | ), | |
| 549 | ! | sep = "\n" |
| 550 | ) | |
| 551 | } | |
| 552 | ! | if (x$emissive_texname != "") { |
| 553 | ! | if (file.exists(x$emissive_texname)) { |
| 554 | ! | fileexists_str = sprintf( |
| 555 | ! | "%s %s %s", |
| 556 | ! | pillar::style_subtle("|"), |
| 557 | ! | cli::col_green(cli::symbol$tick), |
| 558 | ! | "File exists!" |
| 559 | ) | |
| 560 | } else { | |
| 561 | ! | fileexists_str = sprintf( |
| 562 | ! | "%s %s %s", |
| 563 | ! | pillar::style_subtle("|"), |
| 564 | ! | cli::col_red(cli::symbol$cross), |
| 565 | ! | "File not found" |
| 566 | ) | |
| 567 | } | |
| 568 | ! | cat( |
| 569 | ! | sprintf( |
| 570 | ! | "%s%s %s %s %s", |
| 571 | ! | spacer, |
| 572 | ! | bullet, |
| 573 | ! | pillar::style_subtle("emissive_texname:"), |
| 574 | ! | x$emissive_texname, |
| 575 | ! | fileexists_str |
| 576 | ), | |
| 577 | ! | sep = "\n" |
| 578 | ) | |
| 579 | } | |
| 580 | ! | if (x$bump_texname != "") { |
| 581 | ! | if (file.exists(x$bump_texname)) { |
| 582 | ! | fileexists_str = sprintf( |
| 583 | ! | "%s %s %s", |
| 584 | ! | pillar::style_subtle("|"), |
| 585 | ! | cli::col_green(cli::symbol$tick), |
| 586 | ! | "File exists!" |
| 587 | ) | |
| 588 | } else { | |
| 589 | ! | fileexists_str = sprintf( |
| 590 | ! | "%s %s %s", |
| 591 | ! | pillar::style_subtle("|"), |
| 592 | ! | cli::col_red(cli::symbol$cross), |
| 593 | ! | "File not found" |
| 594 | ) | |
| 595 | } | |
| 596 | ! | bump_int_str = "" |
| 597 | ! | if (x$bump_intensity != 1) { |
| 598 | ! | bump_int_str = sprintf( |
| 599 | ! | "%s intensity: %0.1f", |
| 600 | ! | pillar::style_subtle("|"), |
| 601 | ! | x$bump_intensity |
| 602 | ) | |
| 603 | } | |
| 604 | ! | cat( |
| 605 | ! | sprintf( |
| 606 | ! | "%s%s %s %s %s %s", |
| 607 | ! | spacer, |
| 608 | ! | bullet, |
| 609 | ! | pillar::style_subtle("bump_texname:"), |
| 610 | ! | x$bump_texname, |
| 611 | ! | fileexists_str, |
| 612 | ! | bump_int_str |
| 613 | ), | |
| 614 | ! | sep = "\n" |
| 615 | ) | |
| 616 | } | |
| 617 | ! | if (x$normal_texname != "") { |
| 618 | ! | if (file.exists(x$normal_texname)) { |
| 619 | ! | fileexists_str = sprintf( |
| 620 | ! | "%s %s %s", |
| 621 | ! | pillar::style_subtle("|"), |
| 622 | ! | cli::col_green(cli::symbol$tick), |
| 623 | ! | "File exists!" |
| 624 | ) | |
| 625 | } else { | |
| 626 | ! | fileexists_str = sprintf( |
| 627 | ! | "%s %s %s", |
| 628 | ! | pillar::style_subtle("|"), |
| 629 | ! | cli::col_red(cli::symbol$cross), |
| 630 | ! | "File not found" |
| 631 | ) | |
| 632 | } | |
| 633 | ! | cat( |
| 634 | ! | sprintf( |
| 635 | ! | "%s%s %s %s %s", |
| 636 | ! | spacer, |
| 637 | ! | bullet, |
| 638 | ! | pillar::style_subtle("normal_texname:"), |
| 639 | ! | x$normal_texname, |
| 640 | ! | fileexists_str |
| 641 | ), | |
| 642 | ! | sep = "\n" |
| 643 | ) | |
| 644 | } | |
| 645 | ||
| 646 | ! | if (x$culling != 1) { |
| 647 | ! | cat( |
| 648 | ! | sprintf( |
| 649 | ! | "%s%s %s %i", |
| 650 | ! | spacer, |
| 651 | ! | bullet, |
| 652 | ! | pillar::style_subtle("culling:"), |
| 653 | ! | x$culling |
| 654 | ), | |
| 655 | ! | sep = "\n" |
| 656 | ) | |
| 657 | } | |
| 658 | ! | if (x$dissolve < 1 || any(x$transmittance > 0)) { |
| 659 | ! | cat( |
| 660 | ! | sprintf( |
| 661 | ! | "%s%s %s %s", |
| 662 | ! | spacer, |
| 663 | ! | bullet, |
| 664 | ! | pillar::style_subtle("translucent:"), |
| 665 | ! | ifelse(x$translucent, "TRUE", "FALSE") |
| 666 | ), | |
| 667 | ! | sep = "\n" |
| 668 | ) | |
| 669 | } | |
| 670 | ! | if (x$two_sided) { |
| 671 | ! | cat( |
| 672 | ! | sprintf( |
| 673 | ! | "%s%s %s %s", |
| 674 | ! | spacer, |
| 675 | ! | bullet, |
| 676 | ! | pillar::style_subtle("two_sided:"), |
| 677 | ! | "TRUE" |
| 678 | ), | |
| 679 | ! | sep = "\n" |
| 680 | ) | |
| 681 | } | |
| 682 | ! | if (x$type == "toon") { |
| 683 | ! | cat( |
| 684 | ! | sprintf( |
| 685 | ! | "%s%s %s %s", |
| 686 | ! | pillar::style_subtle("toon_levels:"), |
| 687 | ! | x$toon_levels |
| 688 | ), | |
| 689 | ! | sep = "\n" |
| 690 | ) | |
| 691 | ! | cat( |
| 692 | ! | sprintf( |
| 693 | ! | "%s%s %s %0.2f", |
| 694 | ! | pillar::style_subtle("toon_outline_width:"), |
| 695 | ! | x$toon_outline_width |
| 696 | ), | |
| 697 | ! | sep = "\n" |
| 698 | ) | |
| 699 | ! | cat_color(x$toon_outline_color, "toon_outline_color", NA) |
| 700 | } | |
| 701 | ! | if (x$reflection_intensity > 0) { |
| 702 | ! | cat( |
| 703 | ! | sprintf( |
| 704 | ! | "%s%s %s %0.2f %s %s %0.2f", |
| 705 | ! | spacer, |
| 706 | ! | bullet, |
| 707 | ! | pillar::style_subtle("reflection_intensity:"), |
| 708 | ! | x$reflection_intensity, |
| 709 | ! | pillar::style_subtle("|"), |
| 710 | ! | pillar::style_subtle("reflection_sharpness:"), |
| 711 | ! | x$reflection_sharpness |
| 712 | ), | |
| 713 | ! | sep = "\n" |
| 714 | ) | |
| 715 | } | |
| 716 | } | |
| 717 | ! | print_single_mat(x) |
| 718 | } | |
| 719 | ||
| 720 | #' @keywords internal | |
| 721 | vec_ptype_abbr.ray_vertex_data = function(x, ...) { | |
| 722 | ! | "ray_dat" |
| 723 | } | |
| 724 | ||
| 725 | #' @keywords internal | |
| 726 | format_pillar_data = function(x) { | |
| 727 | ! | format_data = function(x1) { |
| 728 | ! | if (is.null(x1[1]) || any(is.na(x1))) { |
| 729 | ! | return(sprintf( |
| 730 | ! | "%s%s%s", |
| 731 | ! | pillar::style_subtle("<"), |
| 732 | ! | pillar::style_subtle("none"), |
| 733 | ! | pillar::style_subtle(">") |
| 734 | )) | |
| 735 | } | |
| 736 | ! | n_rows = nrow(x1) |
| 737 | ! | dimval = ncol(x1) |
| 738 | ! | if (n_rows != 0) { |
| 739 | ! | sprintf( |
| 740 | ! | "%s%s%s%s%s", |
| 741 | ! | pillar::style_subtle("<"), |
| 742 | ! | cli::col_cyan(n_rows), |
| 743 | ! | pillar::style_subtle("x"), |
| 744 | ! | cli::col_cyan(dimval), |
| 745 | ! | pillar::style_subtle(">") |
| 746 | ) | |
| 747 | } else { | |
| 748 | ! | sprintf( |
| 749 | ! | "%s%s%s", |
| 750 | ! | pillar::style_subtle("<"), |
| 751 | ! | pillar::style_subtle("none"), |
| 752 | ! | pillar::style_subtle(">") |
| 753 | ) | |
| 754 | } | |
| 755 | } | |
| 756 | ! | vapply(x, format_data, character(1)) |
| 757 | } | |
| 758 | ||
| 759 | #' @keywords internal | |
| 760 | pillar_shaft.ray_vertex_data = function(x, ...) { | |
| 761 | ! | pillar::new_pillar_shaft_simple( |
| 762 | ! | format_pillar_data(x), |
| 763 | ! | align = "right", |
| 764 | ! | width = 10 |
| 765 | ) | |
| 766 | } | |
| 767 | ||
| 768 | # Define the ray_vertices class | |
| 769 | rayvertex_material = function(...) { | |
| 770 | 169x | vctrs::new_vctr(..., class = "rayvertex_material") |
| 771 | } | |
| 772 | ||
| 773 | #' @keywords internal | |
| 774 | vec_ptype_abbr.rayvertex_material = function(x, ...) { | |
| 775 | "ray_mat" | |
| 776 | } | |
| 777 | ||
| 778 | # Define the ray_vertices class | |
| 779 | rayvertex_material_list = function(...) { | |
| 780 | ! | vctrs::new_vctr(..., class = "rayvertex_material_list") |
| 781 | } | |
| 782 | ||
| 783 | #' @keywords internal | |
| 784 | vec_ptype_abbr.rayvertex_material = function(x, ...) { | |
| 785 | ! | "ray_mat" |
| 786 | } | |
| 787 | ||
| 788 | #' @keywords internal | |
| 789 | vec_ptype_abbr.rayvertex_material_list = function(x, ...) { | |
| 790 | ! | "ray_mat" |
| 791 | } | |
| 792 | ||
| 793 | #' @keywords internal | |
| 794 | format_pillar_matlist = function(x) { | |
| 795 | ! | format_matlist = function(x1) { |
| 796 | # if(is.null(x1[[1]]) || is.na(x1[[1]])) { | |
| 797 | # if(is.null(x1) || is.na(x1)) { | |
| 798 | # return(sprintf("%s%s%s", | |
| 799 | # pillar::style_subtle("<"), | |
| 800 | # cli::col_red("none"), | |
| 801 | # pillar::style_subtle(">"))) | |
| 802 | # } | |
| 803 | ! | n_mats = length(x1) |
| 804 | ! | if (n_mats == 1) { |
| 805 | ! | return(sprintf( |
| 806 | ! | "%s%s%s", |
| 807 | ! | pillar::style_subtle("<"), |
| 808 | ! | cli::col_green((x1[[1]][["type"]])), |
| 809 | ! | pillar::style_subtle(">") |
| 810 | )) | |
| 811 | } | |
| 812 | ! | if (n_mats > 0) { |
| 813 | ! | return(sprintf( |
| 814 | ! | "%s%s%s", |
| 815 | ! | pillar::style_subtle("<"), |
| 816 | ! | cli::col_cyan(sprintf("%sx", as.character(n_mats))), |
| 817 | ! | pillar::style_subtle(">") |
| 818 | )) | |
| 819 | } else { | |
| 820 | ! | return(sprintf( |
| 821 | ! | "%s%s%s", |
| 822 | ! | pillar::style_subtle("<"), |
| 823 | ! | cli::col_red("none"), |
| 824 | ! | pillar::style_subtle(">") |
| 825 | )) | |
| 826 | } | |
| 827 | } | |
| 828 | ! | vapply(x, format_matlist, character(1)) |
| 829 | } | |
| 830 | ||
| 831 | #' @keywords internal | |
| 832 | #' @export | |
| 833 | print.rayvertex_material_list = function(x, ...) { | |
| 834 | ! | format_pillar_matlist(x) |
| 835 | } | |
| 836 | ||
| 837 | #' @keywords internal | |
| 838 | pillar_shaft.rayvertex_material_list = function(x, ...) { | |
| 839 | ! | pillar::new_pillar_shaft_simple( |
| 840 | ! | format_pillar_matlist(x), |
| 841 | ! | align = "right", |
| 842 | ! | width = 8 |
| 843 | ) | |
| 844 | } | |
| 845 | ||
| 846 | #' @keywords internal | |
| 847 | pillar_shaft.rayvertex_material = function(x, ...) { | |
| 848 | ! | pillar::new_pillar_shaft_simple( |
| 849 | ! | format_pillar_matlist(x), |
| 850 | ! | align = "right", |
| 851 | ! | width = 8 |
| 852 | ) | |
| 853 | } | |
| 854 | ||
| 855 | ||
| 856 | #'@title Constructor for ray_mesh | |
| 857 | #' | |
| 858 | #'@return ray | |
| 859 | #'@keywords internal | |
| 860 | ray_mesh = function(...) { | |
| 861 | 4x | structure(..., class = c("ray_mesh", "tbl", "list")) |
| 862 | } | |
| 863 | ||
| 864 | #' @keywords internal | |
| 865 | tbl_sum.print_raymesh_df <- function(x, ...) { | |
| 866 | } | |
| 867 | ||
| 868 | #' @keywords internal | |
| 869 | #' @export | |
| 870 | print.ray_mesh = function(x, ...) { | |
| 871 | # Count total objects and lights | |
| 872 | ! | total_meshes = length(x$shapes) |
| 873 | ! | total_unique_materials = length(unique(attr(x, "material_hashes"))) |
| 874 | ! | x$materials = rayvertex_material_list(x$material) |
| 875 | # x$shapes = ray_shape_list(x$shapes) | |
| 876 | ||
| 877 | # Count each type of object | |
| 878 | ! | bbox_x = get_mesh_bbox(x) |
| 879 | # Calculate bounding box | |
| 880 | ! | bbxmin = c(bbox_x[1, , drop = TRUE]) |
| 881 | ! | bbxmax = c(bbox_x[2, , drop = TRUE]) |
| 882 | ||
| 883 | # Construct the print output | |
| 884 | ! | line1 = sprintf( |
| 885 | ! | "Summary - %s: %s | %s: %s", |
| 886 | ! | cli::col_blue("Meshes"), |
| 887 | ! | cli::col_cyan(as.character(total_meshes)), |
| 888 | ! | cli::col_blue("Unique Materials"), |
| 889 | ! | cli::col_cyan(as.character(total_unique_materials)) |
| 890 | ) | |
| 891 | ! | min_bbox = sprintf("c(%0.2f, %0.2f, %0.2f)", bbxmin[1], bbxmin[2], bbxmin[3]) |
| 892 | ! | max_bbox = sprintf("c(%0.2f, %0.2f, %0.2f)", bbxmax[1], bbxmax[2], bbxmax[3]) |
| 893 | ! | bbox_text = sprintf( |
| 894 | ! | "XYZ Bounds - %s: %s | %s: %s", |
| 895 | ! | cli::col_blue("Min"), |
| 896 | ! | cli::col_cyan(min_bbox), |
| 897 | ! | cli::col_blue("Max"), |
| 898 | ! | cli::col_cyan(max_bbox) |
| 899 | ) | |
| 900 | # | |
| 901 | ! | cli_output = function() { |
| 902 | ! | cli::cli_rule(left = "Scene Description") |
| 903 | ! | bullets = cli::format_bullets_raw(c( |
| 904 | ! | "*" = line1, |
| 905 | ! | "i" = bbox_text |
| 906 | )) | |
| 907 | ! | cat(paste0(bullets, "\n"), sep = "") |
| 908 | } | |
| 909 | # | |
| 910 | ! | cli_output() |
| 911 | ! | if (length(find.package("tibble", quiet = TRUE)) > 0) { |
| 912 | ! | withr::local_options( |
| 913 | ! | list(pillar.advice = TRUE, pillar.print_max = 3, pillar.width = 50), |
| 914 | ! | code = { |
| 915 | ! | print_tbl = tibble::as_tibble(x) |
| 916 | ! | class(print_tbl) = c("print_raymesh_df", class(print_tbl)) |
| 917 | ! | print(print_tbl, ...) |
| 918 | } | |
| 919 | ) | |
| 920 | } | |
| 921 | } |
| 1 | #'@title Rasterize Scene | |
| 2 | #' | |
| 3 | #'@description Render a 3D scene with meshes, lights, and lines using a software rasterizer. | |
| 4 | #' | |
| 5 | #'@param scene The scene object. | |
| 6 | #'@param filename Default `NULL`. Filename to save the image. If `NULL`, the image will be plotted. | |
| 7 | #'@param width Default `400`. Width of the rendered image. | |
| 8 | #'@param height Default `400`. Width of the rendered image. | |
| 9 | #'@param line_info Default `NULL`. Matrix of line segments to add to the scene. Number of rows must be a multiple of 2. | |
| 10 | #'@param alpha_line Default `1`. Line transparency. | |
| 11 | #'@param parallel Default `TRUE`. Whether to use parallel processing. | |
| 12 | #'@param plot Default `is.na(filename)`. Whether to plot the image. | |
| 13 | #'@param fov Default `20`. Width of the rendered image. | |
| 14 | #'@param lookfrom Default `c(0,0,10)`. Camera location. | |
| 15 | #'@param lookat Default `NULL`. Camera focal position, defaults to the center of the model. | |
| 16 | #'@param fsaa Default `2`. Full screen anti-aliasing multiplier. Must be positive integer, higher numbers | |
| 17 | #'will improve anti-aliasing quality but will vastly increase memory usage. | |
| 18 | #'@param camera_up Default `c(0,1,0)`. Camera up vector. | |
| 19 | #'@param light_info Default [directional_light()]. Description of scene lights, generated with the [point_light()] and | |
| 20 | #'[directional_light()] functions. | |
| 21 | #'@param type Default `diffuse`. Shader type. Other options: `vertex` (Gouraud shading), `phong`, and `color` (no lighting). | |
| 22 | #'@param color Default `darkred`. Color of model if no material file present (or for faces using the default material). | |
| 23 | #'@param background Default `white`. Background color. | |
| 24 | #'@param tangent_space_normals Default `TRUE`. | |
| 25 | #'@param shadow_map Default `FALSE`. | |
| 26 | #'@param shadow_map_bias Default `0.005`. | |
| 27 | #'@param shadow_map_intensity Default `0.5`. | |
| 28 | #'@param shadow_map_dims Default `NULL`. | |
| 29 | #'@param ssao Default `FALSE`. Whether to add screen-space ambient occlusion (SSAO) to the render. | |
| 30 | #'@param ssao_intensity Default `10`. Intensity of the shadow map. | |
| 31 | #'@param ssao_radius Default `0.1`. Radius to use when calculating the SSAO term. | |
| 32 | #'@param tonemap Default `"raw"`. See [rayimage::render_tonemap()] for more details. | |
| 33 | #'@param debug Default `"none"`. | |
| 34 | #'@param near_plane Default `0.1`. | |
| 35 | #'@param far_plane Default `100`. | |
| 36 | #'@param shader Default `"default"`. | |
| 37 | #'@param block_size Default `4`. | |
| 38 | #'@param shape Default `NULL`. The shape to render in the OBJ mesh. | |
| 39 | #'@param line_offset Default `0.0001`. Amount to offset lines towards camera to prevent z-fighting. | |
| 40 | #'@param ortho_dimensions Default `c(1,1)`. Width and height of the orthographic camera. Will only be used if `fov = 0`. | |
| 41 | #'@param bloom Default `FALSE`. Whether to apply bloom to the image. If `TRUE`, | |
| 42 | #' this performs a convolution of the HDR image of the scene with a sharp, long-tailed | |
| 43 | #' exponential kernel, which does not visibly affect dimly pixels, but does result in emitters light | |
| 44 | #' slightly bleeding into adjacent pixels. | |
| 45 | #'@param antialias_lines Default `TRUE`. Whether to anti-alias lines in the scene. | |
| 46 | #'@param environment_map Default `""`. Image file to use as a texture for all reflective and refractive | |
| 47 | #'materials in the scene, along with the background. | |
| 48 | #'@param background_sharpness Default `1.0`. A number greater than zero but less than one indicating the sharpness | |
| 49 | #'of the background image. | |
| 50 | #'@param verbose Default `FALSE`. Prints out timing information. | |
| 51 | #'@param vertex_transform Default `NULL`. A function that transforms the vertex locations, based on their location. | |
| 52 | #'Function should takes a length-3 numeric vector and returns another length-3 numeric vector as the output. | |
| 53 | #'@param validate_scene Default `TRUE`. Whether to validate the scene input. | |
| 54 | #'@param transparent_background Default `FALSE`. Whether the background of the render should be transparent. | |
| 55 | #' | |
| 56 | #'@return Rasterized image. | |
| 57 | #'@export | |
| 58 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 59 | #'#Let's load the cube OBJ file included with the package | |
| 60 | #' | |
| 61 | #'rasterize_scene(cube_mesh(),lookfrom=c(2,4,10), | |
| 62 | #' light_info = directional_light(direction=c(0.5,1,0.7))) | |
| 63 | #'#Flatten the cube, translate downwards, and set to grey | |
| 64 | #'base_model = cube_mesh() |> | |
| 65 | #' scale_mesh(scale=c(5,0.2,5)) |> | |
| 66 | #' translate_mesh(c(0,-0.1,0)) |> | |
| 67 | #' set_material(diffuse="grey80") | |
| 68 | #' | |
| 69 | #'rasterize_scene(base_model, lookfrom=c(2,4,10), | |
| 70 | #' light_info = directional_light(direction=c(0.5,1,0.7))) | |
| 71 | #'#load the R OBJ file, scale it down, color it blue, and add it to the grey base | |
| 72 | #'r_model = obj_mesh(r_obj(simple_r = TRUE)) |> | |
| 73 | #' scale_mesh(scale=0.5) |> | |
| 74 | #' set_material(diffuse="dodgerblue") |> | |
| 75 | #' add_shape(base_model) | |
| 76 | #' | |
| 77 | #'rasterize_scene(r_model, lookfrom=c(2,4,10), | |
| 78 | #' light_info = directional_light(direction=c(0.5,1,0.7))) | |
| 79 | #'#Zoom in and reduce the shadow mapping intensity | |
| 80 | #'rasterize_scene(r_model, lookfrom=c(2,4,10), fov=10,shadow_map = TRUE, shadow_map_intensity=0.3, | |
| 81 | #' light_info = directional_light(direction=c(0.5,1,0.7))) | |
| 82 | #'#Include the resolution (4x) of the shadow map for less pixellation around the edges | |
| 83 | #'#Also decrease the shadow_map_bias slightly to remove the "peter panning" floating shadow effect | |
| 84 | #'rasterize_scene(r_model, lookfrom=c(2,4,10), fov=10, | |
| 85 | #' shadow_map_dims=4, | |
| 86 | #' light_info = directional_light(direction=c(0.5,1,0.7))) | |
| 87 | #'#Add some more directional lights and change their color | |
| 88 | #' lights = directional_light(c(0.7,1.1,-0.9),color = "orange",intensity = 1) |> | |
| 89 | #' add_light(directional_light(c(0.7,1,1),color = "dodgerblue",intensity = 1)) |> | |
| 90 | #' add_light(directional_light(c(2,4,10),color = "white",intensity = 0.5)) | |
| 91 | #'rasterize_scene(r_model, lookfrom=c(2,4,10), fov=10, | |
| 92 | #' light_info = lights) | |
| 93 | #'#Add some point lights | |
| 94 | #'lights_p = lights |> | |
| 95 | #' add_light(point_light(position=c(-1,1,0),color="red", intensity=2)) |> | |
| 96 | #' add_light(point_light(position=c(1,1,0),color="purple", intensity=2)) | |
| 97 | #'rasterize_scene(r_model, lookfrom=c(2,4,10), fov=10, | |
| 98 | #' light_info = lights_p) | |
| 99 | #'#change the camera position | |
| 100 | #'rasterize_scene(r_model, lookfrom=c(-2,2,-10), fov=10, | |
| 101 | #' light_info = lights_p) | |
| 102 | #' | |
| 103 | #'#Add a spiral of lines around the model by generating a matrix of line segments | |
| 104 | #' t = seq(0,8*pi,length.out=361) | |
| 105 | #' line_mat = matrix(nrow=0,ncol=9) | |
| 106 | #' | |
| 107 | #' for(i in 1:360) { | |
| 108 | #' line_mat = add_lines(line_mat, | |
| 109 | #' generate_line(start = c(0.5*sin(t[i]), t[i]/(8*pi), 0.5*cos(t[i])), | |
| 110 | #' end = c(0.5*sin(t[i+1]), t[i+1]/(8*pi), 0.5*cos(t[i+1])))) | |
| 111 | #' } | |
| 112 | #' | |
| 113 | #'rasterize_scene(r_model, lookfrom=c(2,4,10), fov=10, line_info = line_mat, | |
| 114 | #' light_info = lights) | |
| 115 | rasterize_scene = function( | |
| 116 | scene, | |
| 117 | filename = NA, | |
| 118 | width = 800, | |
| 119 | height = 800, | |
| 120 | line_info = NULL, | |
| 121 | alpha_line = 1.0, | |
| 122 | parallel = TRUE, | |
| 123 | plot = is.na(filename), | |
| 124 | fov = 20, | |
| 125 | lookfrom = c(0, 0, 10), | |
| 126 | lookat = NULL, | |
| 127 | camera_up = c(0, 1, 0), | |
| 128 | fsaa = 2, | |
| 129 | light_info = directional_light(), | |
| 130 | color = "red", | |
| 131 | type = "diffuse", | |
| 132 | background = "black", | |
| 133 | tangent_space_normals = TRUE, | |
| 134 | shadow_map = TRUE, | |
| 135 | shadow_map_bias = 0.003, | |
| 136 | shadow_map_intensity = 0, | |
| 137 | shadow_map_dims = NULL, | |
| 138 | ssao = FALSE, | |
| 139 | ssao_intensity = 10, | |
| 140 | ssao_radius = 0.1, | |
| 141 | tonemap = "raw", | |
| 142 | debug = "none", | |
| 143 | near_plane = 0.1, | |
| 144 | far_plane = 100, | |
| 145 | shader = "default", | |
| 146 | block_size = 4, | |
| 147 | shape = NULL, | |
| 148 | line_offset = 0.00001, | |
| 149 | ortho_dimensions = c(1, 1), | |
| 150 | bloom = FALSE, | |
| 151 | antialias_lines = TRUE, | |
| 152 | environment_map = "", | |
| 153 | background_sharpness = 1.0, | |
| 154 | verbose = FALSE, | |
| 155 | vertex_transform = NULL, | |
| 156 | validate_scene = TRUE, | |
| 157 | transparent_background = FALSE | |
| 158 | ) { | |
| 159 | 6x | init_time() |
| 160 | 6x | if (!is.null(attr(scene, "cornell"))) { |
| 161 | ! | corn_message = "Setting default values for Cornell box: " |
| 162 | ! | missing_corn = FALSE |
| 163 | ! | if (missing(lookfrom)) { |
| 164 | ! | lookfrom = c(278, 278, -800) |
| 165 | ! | corn_message = paste0(corn_message, "lookfrom `c(278,278,-800)` ") |
| 166 | ! | missing_corn = TRUE |
| 167 | } | |
| 168 | ! | if (missing(lookat)) { |
| 169 | ! | lookat = c(278, 278, 0) |
| 170 | ! | corn_message = paste0(corn_message, "lookat `c(278,278,0)` ") |
| 171 | ! | missing_corn = TRUE |
| 172 | } | |
| 173 | ! | if (missing(fov)) { |
| 174 | ! | fov = 40 |
| 175 | ! | corn_message = paste0(corn_message, "fov `40` ") |
| 176 | ! | missing_corn = TRUE |
| 177 | } | |
| 178 | ! | if (fov == 0 && missing(ortho_dimensions)) { |
| 179 | ! | ortho_dimensions = c(580, 580) |
| 180 | ! | corn_message = paste0(corn_message, "ortho_dimensions `c(580, 580)` ") |
| 181 | ! | missing_corn = TRUE |
| 182 | } | |
| 183 | ! | corn_message = paste0(corn_message, ".") |
| 184 | ! | if (missing_corn) { |
| 185 | ! | message(corn_message) |
| 186 | } | |
| 187 | ! | if (attr(scene, "cornell_light")) { |
| 188 | ! | light_info = add_light( |
| 189 | ! | light_info, |
| 190 | ! | point_light( |
| 191 | ! | c(555 / 2, 450, 555 / 2), |
| 192 | ! | falloff_quad = 0.0, |
| 193 | ! | constant = 0.0002, |
| 194 | ! | falloff = 0.005 |
| 195 | ) | |
| 196 | ) | |
| 197 | } | |
| 198 | } | |
| 199 | 6x | print_time(verbose, "Validating Mesh") |
| 200 | 6x | if (validate_scene) { |
| 201 | 6x | validate_mesh(scene) |
| 202 | } | |
| 203 | #Get the scene down to one vertex/texcoord/normal matrix, and adjust indices to match | |
| 204 | 6x | print_time(verbose, "Pre-processing scene") |
| 205 | 6x | scene = merge_scene(scene, flatten_materials = TRUE) |
| 206 | #Remove duplicate materials | |
| 207 | 6x | print_time(verbose, "Pre-processed scene") |
| 208 | 6x | obj = remove_duplicate_materials(scene) |
| 209 | 6x | print_time(verbose, "Removed duplicate materials") |
| 210 | ||
| 211 | 6x | fsaa = as.integer(fsaa) |
| 212 | 6x | if (fsaa > 1) { |
| 213 | 1x | for (i in seq_len(length(obj$materials))) { |
| 214 | 1x | obj$materials[[i]]$toon_outline_width = |
| 215 | 1x | obj$materials[[i]]$toon_outline_width * fsaa |
| 216 | } | |
| 217 | 1x | width = width * fsaa |
| 218 | 1x | height = height * fsaa |
| 219 | } | |
| 220 | ||
| 221 | 6x | max_indices = 0 |
| 222 | 6x | has_norms = rep(FALSE, length(obj$shapes)) |
| 223 | 6x | has_tex = rep(FALSE, length(obj$shapes)) |
| 224 | 6x | has_vertex_tex = list() |
| 225 | 6x | has_vertex_normals = list() |
| 226 | ||
| 227 | 6x | if (length(ortho_dimensions) != 2) { |
| 228 | ! | stop("ortho_dimensions must be length-2 numeric vector") |
| 229 | } | |
| 230 | #lights | |
| 231 | 6x | if (!is.null(light_info)) { |
| 232 | 5x | if (ncol(light_info) != 10) { |
| 233 | ! | stop("light_info must have 10 cols") |
| 234 | } | |
| 235 | 5x | lightinfo = light_info |
| 236 | } else { | |
| 237 | 1x | lightinfo = matrix(nrow = 0, ncol = 10) |
| 238 | } | |
| 239 | ||
| 240 | 6x | if (is.null(line_info)) { |
| 241 | 6x | line_info = matrix(nrow = 0, ncol = 0) |
| 242 | } | |
| 243 | ||
| 244 | 6x | bounds = c(Inf, Inf, Inf, -Inf, -Inf, -Inf) |
| 245 | 6x | for (i in seq_len(length(obj$shapes))) { |
| 246 | 6x | has_vertex_tex[[i]] = obj$shapes[[i]]$has_vertex_tex |
| 247 | 6x | has_vertex_normals[[i]] = obj$shapes[[i]]$has_vertex_normals |
| 248 | ||
| 249 | 6x | max_indices = max(c(max_indices, nrow(obj$shapes[[i]]$indices))) |
| 250 | 6x | has_norms[i] = nrow(obj$shapes[[i]]$indices) == |
| 251 | 6x | nrow(obj$shapes[[i]]$norm_indices) |
| 252 | 6x | has_tex[i] = nrow(obj$shapes[[i]]$indices) == |
| 253 | 6x | nrow(obj$shapes[[i]]$tex_indices) && |
| 254 | 6x | all(obj$shapes[[i]]$tex_indices != -1) |
| 255 | } | |
| 256 | 6x | print_time(verbose, "Processed scene bounds") |
| 257 | ||
| 258 | 6x | has_vertex_tex = unlist(has_vertex_tex) |
| 259 | 6x | has_vertex_normals = unlist(has_vertex_normals) |
| 260 | ||
| 261 | 6x | use_default_material = FALSE |
| 262 | 6x | if (length(obj$materials) > 0) { |
| 263 | 6x | has_texture = rep(FALSE, length(obj$materials)) |
| 264 | 6x | has_ambient_texture = rep(FALSE, length(obj$materials)) |
| 265 | 6x | has_bump_texture = rep(FALSE, length(obj$materials)) |
| 266 | 6x | has_normal_texture = rep(FALSE, length(obj$materials)) |
| 267 | 6x | has_specular_texture = rep(FALSE, length(obj$materials)) |
| 268 | 6x | has_emissive_texture = rep(FALSE, length(obj$materials)) |
| 269 | } else { | |
| 270 | ! | use_default_material = TRUE |
| 271 | ! | has_texture = FALSE |
| 272 | ! | has_bump_texture = FALSE |
| 273 | ! | has_ambient_texture = FALSE |
| 274 | ! | has_normal_texture = FALSE |
| 275 | ! | has_specular_texture = FALSE |
| 276 | ! | has_emissive_texture = FALSE |
| 277 | } | |
| 278 | 6x | for (i in seq_len(length(obj$materials))) { |
| 279 | if ( | |
| 280 | 7x | !is.null(obj$materials[[i]]$diffuse_texname) && |
| 281 | 7x | obj$materials[[i]]$diffuse_texname != "" |
| 282 | ) { | |
| 283 | 1x | has_texture[i] = TRUE |
| 284 | 1x | obj$materials[[i]]$diffuse_texname = path.expand( |
| 285 | 1x | obj$materials[[i]]$diffuse_texname |
| 286 | ) | |
| 287 | } | |
| 288 | if ( | |
| 289 | 7x | !is.null(obj$materials[[i]]$bump_texname) && |
| 290 | 7x | obj$materials[[i]]$bump_texname != "" |
| 291 | ) { | |
| 292 | ! | has_bump_texture[i] = TRUE |
| 293 | ! | obj$materials[[i]]$bump_texname = path.expand( |
| 294 | ! | obj$materials[[i]]$bump_texname |
| 295 | ) | |
| 296 | } | |
| 297 | if ( | |
| 298 | 7x | !is.null(obj$materials[[i]]$ambient_texname) && |
| 299 | 7x | obj$materials[[i]]$ambient_texname != "" |
| 300 | ) { | |
| 301 | ! | has_ambient_texture[i] = TRUE |
| 302 | ! | obj$materials[[i]]$ambient_texname = path.expand( |
| 303 | ! | obj$materials[[i]]$ambient_texname |
| 304 | ) | |
| 305 | } | |
| 306 | if ( | |
| 307 | 7x | !is.null(obj$materials[[i]]$specular_texname) && |
| 308 | 7x | obj$materials[[i]]$specular_texname != "" |
| 309 | ) { | |
| 310 | ! | has_specular_texture[i] = TRUE |
| 311 | ! | obj$materials[[i]]$specular_texname = path.expand( |
| 312 | ! | obj$materials[[i]]$specular_texname |
| 313 | ) | |
| 314 | } | |
| 315 | if ( | |
| 316 | 7x | !is.null(obj$materials[[i]]$normal_texname) && |
| 317 | 7x | obj$materials[[i]]$normal_texname != "" |
| 318 | ) { | |
| 319 | ! | has_normal_texture[i] = TRUE |
| 320 | ||
| 321 | ! | obj$materials[[i]]$normal_texname = path.expand( |
| 322 | ! | obj$materials[[i]]$normal_texname |
| 323 | ) | |
| 324 | } | |
| 325 | if ( | |
| 326 | 7x | !is.null(obj$materials[[i]]$emissive_texname) && |
| 327 | 7x | obj$materials[[i]]$emissive_texname != "" |
| 328 | ) { | |
| 329 | ! | has_emissive_texture[i] = TRUE |
| 330 | ||
| 331 | ! | obj$materials[[i]]$emissive_texname = path.expand( |
| 332 | ! | obj$materials[[i]]$emissive_texname |
| 333 | ) | |
| 334 | } | |
| 335 | } | |
| 336 | 6x | print_time(verbose, "Processed texture filenames") |
| 337 | ||
| 338 | 6x | numbercores = getOption( |
| 339 | 6x | "cores", |
| 340 | 6x | default = getOption("Ncpus", default = parallel::detectCores()) |
| 341 | ) | |
| 342 | 6x | if (identical(Sys.getenv("_R_CHECK_LIMIT_CORES_"), "TRUE")) { |
| 343 | ! | numbercores = min(as.integer(numbercores), 2L) |
| 344 | } | |
| 345 | 6x | if (!parallel) { |
| 346 | 6x | numbercores = 1L |
| 347 | } | |
| 348 | ||
| 349 | 6x | color = convert_color(color) |
| 350 | 6x | bg_color = convert_color(background) |
| 351 | ||
| 352 | 6x | typevals = rep(2, max(c(length(obj$materials), 1))) |
| 353 | 6x | if (!use_default_material) { |
| 354 | 6x | for (i in seq_len(length(obj$materials))) { |
| 355 | 7x | typeval = switch( |
| 356 | 7x | obj$materials[[i]]$type, |
| 357 | 7x | "vertex" = 1, |
| 358 | 7x | "diffuse" = 2, |
| 359 | 7x | "phong" = 3, |
| 360 | 7x | "color" = 8, |
| 361 | 7x | "toon" = 9, |
| 362 | 7x | "toon_phong" = 10, |
| 363 | 7x | 1 |
| 364 | ) | |
| 365 | 7x | if (typeval < 8) { |
| 366 | 6x | if (has_normal_texture[i]) { |
| 367 | ! | if (typeval == 2) { |
| 368 | ! | if (!tangent_space_normals) { |
| 369 | ! | typevals[i] = 4 |
| 370 | } else { | |
| 371 | ! | typevals[i] = 5 |
| 372 | } | |
| 373 | ! | } else if (typeval == 3) { |
| 374 | ! | if (!tangent_space_normals) { |
| 375 | ! | typevals[i] = 6 |
| 376 | } else { | |
| 377 | ! | typevals[i] = 7 |
| 378 | } | |
| 379 | } | |
| 380 | } else { | |
| 381 | 6x | typevals[i] = typeval |
| 382 | } | |
| 383 | } else { | |
| 384 | 1x | typevals[i] = typeval |
| 385 | } | |
| 386 | } | |
| 387 | } | |
| 388 | 6x | has_reflection_map = rep(FALSE, length(obj$materials)) |
| 389 | 6x | has_refraction = rep(FALSE, length(obj$materials)) |
| 390 | ||
| 391 | 6x | for (i in seq_len(length(obj$materials))) { |
| 392 | 7x | obj$materials[[i]]$culling = switch( |
| 393 | 7x | obj$materials[[i]]$culling, |
| 394 | 7x | "back" = 1, |
| 395 | 7x | "front" = 2, |
| 396 | 7x | "none" = 3, |
| 397 | 7x | 1 |
| 398 | ) | |
| 399 | if ( | |
| 400 | 7x | environment_map != "" && |
| 401 | 7x | obj$materials[[i]]$reflection_intensity > 0 && |
| 402 | 7x | file.exists(environment_map) && |
| 403 | 7x | !dir.exists(environment_map) |
| 404 | ) { | |
| 405 | ! | has_reflection_map[i] = TRUE |
| 406 | } | |
| 407 | if ( | |
| 408 | 7x | environment_map != "" && |
| 409 | 7x | obj$materials[[i]]$ior != 1 && |
| 410 | 7x | file.exists(environment_map) && |
| 411 | 7x | !dir.exists(environment_map) |
| 412 | ) { | |
| 413 | ! | has_refraction[i] = TRUE |
| 414 | } | |
| 415 | } | |
| 416 | 6x | environment_map_hdr = FALSE |
| 417 | 6x | has_environment_map = FALSE |
| 418 | 6x | if (environment_map != "") { |
| 419 | ! | has_environment_map = TRUE |
| 420 | ! | environment_map = path.expand(environment_map) |
| 421 | ! | if (tools::file_ext(environment_map) == "hdr") { |
| 422 | ! | environment_map_hdr = TRUE |
| 423 | } | |
| 424 | } | |
| 425 | ||
| 426 | 6x | if (is.null(shadow_map_dims)) { |
| 427 | 6x | shadow_map_dims = c(width, height) |
| 428 | } else { | |
| 429 | if ( | |
| 430 | ! | length(shadow_map_dims) == 1 && |
| 431 | ! | is.numeric(shadow_map_dims) && |
| 432 | ! | shadow_map_dims > 0 |
| 433 | ) { | |
| 434 | ! | shadow_map_dims = c(width, height) * shadow_map_dims |
| 435 | ! | } else if (length(shadow_map_dims) != 2) { |
| 436 | ! | stop("shadow_map_dims must be vector of length 2") |
| 437 | } | |
| 438 | } | |
| 439 | ||
| 440 | 6x | is_dir_light = rep(TRUE, nrow(lightinfo)) |
| 441 | 6x | for (i in seq_len(nrow(lightinfo))) { |
| 442 | 5x | if (any(lightinfo[i, 7:9] != 0)) { |
| 443 | ! | is_dir_light[i] = FALSE |
| 444 | } | |
| 445 | } | |
| 446 | 6x | if (!is.null(vertex_transform) && is.function(vertex_transform)) { |
| 447 | ! | if (verify_vertex_shader(vertex_transform)) { |
| 448 | ! | obj$vertices = t(apply(obj$vertices, 1, vertex_transform)) |
| 449 | ! | if (any(is.na(obj$vertices)) || any(is.infinite(obj$vertices))) { |
| 450 | ! | stop( |
| 451 | ! | "vertex_transform transformed a vertex to either NA or infinity--transformed vertices should be finite values." |
| 452 | ) | |
| 453 | } | |
| 454 | } else { | |
| 455 | ! | warning( |
| 456 | ! | "vertex_transform function does not return correct output, not applying" |
| 457 | ) | |
| 458 | } | |
| 459 | } | |
| 460 | 6x | tempboundsmin = apply(obj$vertices, 2, min) |
| 461 | 6x | tempboundsmax = apply(obj$vertices, 2, max) |
| 462 | 6x | bounds[1:3] = c( |
| 463 | 6x | min(c(bounds[1], tempboundsmin[1])), |
| 464 | 6x | min(c(bounds[2], tempboundsmin[2])), |
| 465 | 6x | min(c(bounds[3], tempboundsmin[3])) |
| 466 | ) | |
| 467 | 6x | bounds[4:6] = c( |
| 468 | 6x | max(c(bounds[4], tempboundsmax[1])), |
| 469 | 6x | max(c(bounds[5], tempboundsmax[2])), |
| 470 | 6x | max(c(bounds[6], tempboundsmax[3])) |
| 471 | ) | |
| 472 | ||
| 473 | 6x | if (is.null(lookat)) { |
| 474 | 1x | lookat = (bounds[1:3] + bounds[4:6]) / 2 |
| 475 | 1x | message(sprintf( |
| 476 | 1x | "Setting `lookat` to: c(%0.2f, %0.2f, %0.2f)", |
| 477 | 1x | lookat[1], |
| 478 | 1x | lookat[2], |
| 479 | 1x | lookat[3] |
| 480 | )) | |
| 481 | } | |
| 482 | 6x | print_time(verbose, "Processed materials") |
| 483 | 6x | imagelist = rasterize( |
| 484 | 6x | obj, |
| 485 | 6x | lightinfo, |
| 486 | 6x | line_mat = line_info, |
| 487 | 6x | nx = width, |
| 488 | 6x | ny = height, |
| 489 | 6x | model_color = color, |
| 490 | 6x | lookfrom = lookfrom, |
| 491 | 6x | lookat = lookat, |
| 492 | 6x | fov = fov, |
| 493 | 6x | typevals = typevals, |
| 494 | 6x | has_shadow_map = shadow_map, |
| 495 | 6x | calc_ambient = ssao, |
| 496 | 6x | tbn = tangent_space_normals, |
| 497 | 6x | ambient_radius = ssao_radius, |
| 498 | 6x | shadow_map_bias = shadow_map_bias, |
| 499 | 6x | numbercores = numbercores, |
| 500 | 6x | max_indices = max_indices, |
| 501 | 6x | has_normals_vec = has_norms, |
| 502 | 6x | has_tex_vec = has_tex, #This just determines whether to include tex indices |
| 503 | 6x | has_texture, |
| 504 | 6x | has_ambient_texture, |
| 505 | 6x | has_bump_texture, |
| 506 | 6x | has_normal_texture, |
| 507 | 6x | has_specular_texture, |
| 508 | 6x | has_emissive_texture, |
| 509 | 6x | block_size = block_size, |
| 510 | 6x | use_default_material = use_default_material, |
| 511 | 6x | near_plane, |
| 512 | 6x | far_plane, |
| 513 | 6x | shadow_map_intensity, |
| 514 | 6x | bounds, |
| 515 | 6x | shadow_map_dims, |
| 516 | 6x | camera_up, |
| 517 | 6x | alpha_line, |
| 518 | 6x | line_offset, |
| 519 | 6x | ortho_dimensions, |
| 520 | 6x | is_dir_light, |
| 521 | 6x | antialias_lines, |
| 522 | 6x | has_vertex_tex, |
| 523 | 6x | has_vertex_normals, |
| 524 | 6x | has_reflection_map, |
| 525 | 6x | environment_map, |
| 526 | 6x | background_sharpness, |
| 527 | 6x | has_refraction, |
| 528 | 6x | environment_map_hdr, |
| 529 | 6x | has_environment_map, |
| 530 | 6x | bg_color, |
| 531 | 6x | transparent_background, |
| 532 | 6x | verbose |
| 533 | ) | |
| 534 | 6x | print_time(verbose, "Rasterized image") |
| 535 | ||
| 536 | 6x | if (ssao) { |
| 537 | ! | imagelist$amb = (imagelist$amb)^ssao_intensity |
| 538 | ! | imagelist$r = imagelist$r * imagelist$amb |
| 539 | ! | imagelist$g = imagelist$g * imagelist$amb |
| 540 | ! | imagelist$b = imagelist$b * imagelist$amb |
| 541 | } | |
| 542 | 6x | if (debug == "normals") { |
| 543 | ! | norm_array = array(0, dim = c(dim(imagelist$r)[1:2], 3)) |
| 544 | ! | norm_array[,, 1] = (imagelist$normalx + 1) / 2 |
| 545 | ! | norm_array[,, 2] = (imagelist$normaly + 1) / 2 |
| 546 | ! | norm_array[,, 3] = (imagelist$normalz + 1) / 2 |
| 547 | ! | norm_array = rayimage::render_reorient( |
| 548 | ! | norm_array, |
| 549 | ! | transpose = TRUE, |
| 550 | ! | flipx = TRUE |
| 551 | ) | |
| 552 | ! | if (is.na(filename)) { |
| 553 | ! | if (plot) { |
| 554 | ! | rayimage::plot_image(norm_array) |
| 555 | } | |
| 556 | } else { | |
| 557 | ! | rayimage::ray_write_image( |
| 558 | ! | norm_array, |
| 559 | ! | filename = filename, |
| 560 | ! | write_linear = TRUE |
| 561 | ) | |
| 562 | } | |
| 563 | ! | return(invisible(norm_array)) |
| 564 | } | |
| 565 | 6x | if (debug == "depth") { |
| 566 | ! | depth_array = array(0, dim = c(dim(imagelist$r)[1:2], 3)) |
| 567 | ! | depth_array[,, 1] = (imagelist$linear_depth) |
| 568 | ! | depth_array[,, 2] = (imagelist$linear_depth) |
| 569 | ! | depth_array[,, 3] = (imagelist$linear_depth) |
| 570 | ! | depth_array[is.infinite(depth_array)] = 1 |
| 571 | ! | scale_factor = max(depth_array, na.rm = TRUE) - |
| 572 | ! | min(depth_array, na.rm = TRUE) |
| 573 | ! | depth_array = (depth_array - min(depth_array)) / scale_factor |
| 574 | ! | if (is.na(filename)) { |
| 575 | ! | depth_array = rayimage::render_reorient( |
| 576 | ! | depth_array, |
| 577 | ! | transpose = TRUE, |
| 578 | ! | flipx = TRUE |
| 579 | ) | |
| 580 | ! | if (plot) { |
| 581 | ! | rayimage::plot_image(depth_array) |
| 582 | } | |
| 583 | } else { | |
| 584 | ! | rayimage::ray_write_image( |
| 585 | ! | depth_array, |
| 586 | ! | filename = filename, |
| 587 | ! | write_linear = TRUE |
| 588 | ) | |
| 589 | } | |
| 590 | ! | return(invisible(depth_array)) |
| 591 | } | |
| 592 | 6x | if (debug == "raw_depth") { |
| 593 | ! | return(imagelist$linear_depth) |
| 594 | } | |
| 595 | 6x | if (debug == "position") { |
| 596 | 1x | pos_array = array(0, dim = c(dim(imagelist$r)[1:2], 3)) |
| 597 | 1x | imagelist$positionx = rescale(imagelist$positionx, to = c(0, 1)) |
| 598 | 1x | imagelist$positiony = rescale(imagelist$positiony, to = c(0, 1)) |
| 599 | 1x | imagelist$positionz = rescale(imagelist$positionz, to = c(0, 1)) |
| 600 | ||
| 601 | 1x | pos_array[,, 1] = (imagelist$positionx) |
| 602 | 1x | pos_array[,, 2] = (imagelist$positiony) |
| 603 | 1x | pos_array[,, 3] = (imagelist$positionz) |
| 604 | 1x | pos_array = rayimage::render_reorient( |
| 605 | 1x | pos_array, |
| 606 | 1x | transpose = TRUE, |
| 607 | 1x | flipx = TRUE |
| 608 | ) | |
| 609 | 1x | pos_array[is.infinite(pos_array)] = 1 |
| 610 | 1x | if (is.na(filename)) { |
| 611 | 1x | if (plot) { |
| 612 | ! | rayimage::plot_image(pos_array) |
| 613 | } | |
| 614 | } else { | |
| 615 | ! | rayimage::ray_write_image( |
| 616 | ! | pos_array, |
| 617 | ! | filename = filename, |
| 618 | ! | write_linear = TRUE |
| 619 | ) | |
| 620 | } | |
| 621 | 1x | return(invisible(pos_array)) |
| 622 | } | |
| 623 | 5x | if (debug == "uv") { |
| 624 | ! | uv_array = array(0, dim = c(dim(imagelist$r)[1:2], 3)) |
| 625 | ! | uv_array[,, 1] = (imagelist$uvx) |
| 626 | ! | uv_array[,, 2] = (imagelist$uvy) |
| 627 | ! | uv_array[,, 3] = (imagelist$uvz) |
| 628 | ! | uv_array = rayimage::render_reorient( |
| 629 | ! | uv_array, |
| 630 | ! | transpose = TRUE, |
| 631 | ! | flipx = TRUE |
| 632 | ) | |
| 633 | ! | if (is.na(filename)) { |
| 634 | ! | if (plot) { |
| 635 | ! | rayimage::plot_image(uv_array) |
| 636 | } | |
| 637 | } else { | |
| 638 | ! | rayimage::ray_write_image( |
| 639 | ! | uv_array, |
| 640 | ! | filename = filename, |
| 641 | ! | write_linear = TRUE |
| 642 | ) | |
| 643 | } | |
| 644 | ! | return(invisible(uv_array)) |
| 645 | } | |
| 646 | 5x | if (environment_map == "") { |
| 647 | 5x | imagelist$r[imagelist$depth == 1] = bg_color[1] |
| 648 | 5x | imagelist$g[imagelist$depth == 1] = bg_color[2] |
| 649 | 5x | imagelist$b[imagelist$depth == 1] = bg_color[3] |
| 650 | } | |
| 651 | ||
| 652 | 5x | final_image = array(0, dim = c(dim(imagelist$r)[1:2], 4)) |
| 653 | 5x | final_image[,, 1] = imagelist$r |
| 654 | 5x | final_image[,, 2] = imagelist$g |
| 655 | 5x | final_image[,, 3] = imagelist$b |
| 656 | 5x | final_image[,, 4] = imagelist$a |
| 657 | ||
| 658 | 5x | final_image = rayimage::ray_read_image( |
| 659 | 5x | final_image, |
| 660 | 5x | assume_colorspace = rayimage::CS_SRGB, |
| 661 | 5x | assume_white = "D65", |
| 662 | 5x | source_linear = FALSE |
| 663 | ) |> | |
| 664 | 5x | rayimage::render_reorient( |
| 665 | 5x | transpose = TRUE, |
| 666 | 5x | flipx = TRUE |
| 667 | ) | |
| 668 | 5x | if (tonemap != "raw") { |
| 669 | ! | final_image = rayimage::render_tonemap(final_image, method = tonemap) |
| 670 | } | |
| 671 | 5x | if (bloom) { |
| 672 | ! | final_image = rayimage::render_convolution(final_image, min_value = 1) |
| 673 | ! | print_time(verbose, "Rendered bloom") |
| 674 | } | |
| 675 | 5x | if (fsaa > 1) { |
| 676 | 1x | final_image = rayimage::render_resized( |
| 677 | 1x | final_image, |
| 678 | 1x | mag = 1 / fsaa, |
| 679 | 1x | method = "mitchell" |
| 680 | ) | |
| 681 | 1x | print_time(verbose, "Applied FSAA") |
| 682 | } | |
| 683 | 5x | final_image = rayimage::render_clamp(final_image) |
| 684 | ||
| 685 | # Image is aleady linear | |
| 686 | 5x | if (is.na(filename)) { |
| 687 | 5x | if (plot) { |
| 688 | ! | rayimage::plot_image(final_image) |
| 689 | } | |
| 690 | } else { | |
| 691 | ! | rayimage::ray_write_image( |
| 692 | ! | final_image, |
| 693 | ! | filename = filename |
| 694 | ) | |
| 695 | } | |
| 696 | 5x | if (debug == "all") { |
| 697 | ! | return(imagelist) |
| 698 | } | |
| 699 | 5x | print_time(verbose, "Display/save image") |
| 700 | 5x | return(invisible(final_image)) |
| 701 | } |
| 1 | # fmt: skip file | |
| 2 | ||
| 3 | #'@title Set Material | |
| 4 | #' | |
| 5 | #'@description Set the material(s) of the mesh. | |
| 6 | #' | |
| 7 | #'@param mesh The target mesh. | |
| 8 | #'@param material Default `NULL`. You can pass the output of [material_list()] | |
| 9 | #' to specify the material, or use the following individual settings. | |
| 10 | #'@param id Default `1`. Either a number specifying the material to change, or a character vector | |
| 11 | #'matching the material name. | |
| 12 | #'@param diffuse Default `c(0.5,0.5,0.5)`. The diffuse color. | |
| 13 | #'@param ambient Default `c(0,0,0)`. The ambient color. | |
| 14 | #'@param specular Default `c(1,1,1)`. The specular color. | |
| 15 | #'@param transmittance Default `c(0,0,0)`. The transmittance. | |
| 16 | #'@param emission Default `c(0,0,0)`. The emissive color. | |
| 17 | #'@param shininess Default `50.0`. The shininess exponent. | |
| 18 | #'@param ior Default `1.0`. The index of refraction. If this is not equal to `1.0`, the material will be refractive. | |
| 19 | #'@param dissolve Default `1.0`. The transparency. | |
| 20 | #'@param illum Default `1.0`. The illumination. | |
| 21 | #'@param texture_location Default `""`. The diffuse texture location. | |
| 22 | #'@param normal_texture_location Default `""`. The normal texture location. | |
| 23 | #'@param bump_texture_location Default `""`. The bump texture location. | |
| 24 | #'@param specular_texture_location Default `""`. The specular texture location. | |
| 25 | #'@param ambient_texture_location Default `""`. The ambient texture location. | |
| 26 | #'@param emissive_texture_location Default `""`. The emissive texture location. | |
| 27 | #'@param diffuse_intensity Default `1`. The diffuse intensity. | |
| 28 | #'@param bump_intensity Default `1`. The bump intensity. | |
| 29 | #'@param specular_intensity Default `1`. The specular intensity. | |
| 30 | #'@param emission_intensity Default `1`. The emission intensity. | |
| 31 | #'@param ambient_intensity Default `1`. The ambient intensity. | |
| 32 | #'@param culling Default `"back"`. The culling type. Options are `back`, `front`, and `none`. | |
| 33 | #'@param type Default `"diffuse"`. The shader type. Options include `diffuse`,`phong`,`vertex`, and `color`. | |
| 34 | #'@param translucent Default `TRUE`. Whether light should transmit through a semi-transparent material. | |
| 35 | #'@param toon_levels Default `5`. Number of color breaks in the toon shader. | |
| 36 | #'@param toon_outline_width Default `3`. Number of pixels of toon outline. | |
| 37 | #'@param toon_outline_color Default `black`. Toon outline color. | |
| 38 | #'@param reflection_intensity Default `0.0`. Intensity of the reflection of the environment map, if present. This will be ignored if the material is refractive. | |
| 39 | #'@param reflection_sharpness Default `1.0`. Sharpness of the reflection, where lower values have blurrier reflections. Must be greater than zero and less than one. | |
| 40 | #'@param two_sided Default `NULL`. Whether diffuse materials should be two sided (normal is taken as the absolute value of the dot product of the light direction and the normal). | |
| 41 | #'@param sigma Default `0`. Oren-Nayar angle. | |
| 42 | #' | |
| 43 | #'@return Shape with new material | |
| 44 | #'@export | |
| 45 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 46 | #'#Set the material of an object | |
| 47 | #'generate_cornell_mesh() |> | |
| 48 | #' add_shape(set_material(sphere_mesh(position=c(400,555/2,555/2),radius=40), | |
| 49 | #' diffuse="purple", type="phong")) |> | |
| 50 | #' add_shape(set_material(sphere_mesh(position=c(555/2,220,555/2),radius=40), | |
| 51 | #' dissolve=0.2,culling="none",diffuse="red")) |> | |
| 52 | #' add_shape(set_material(sphere_mesh(position=c(155,300,555/2),radius=60), | |
| 53 | #' material = material_list(diffuse="gold", type="phong", | |
| 54 | #' ambient="gold", ambient_intensity=0.4))) |> | |
| 55 | #' rasterize_scene(light_info=directional_light(direction=c(0.1,0.6,-1))) | |
| 56 | set_material = function(mesh, material = NULL, id = NULL, | |
| 57 | diffuse = c(0.5,0.5,0.5), | |
| 58 | ambient = c(0,0,0), | |
| 59 | specular = c(1,1,1), | |
| 60 | transmittance = c(0,0,0), | |
| 61 | emission = c(0,0,0), | |
| 62 | shininess = 50.0, | |
| 63 | ior = 1.0, | |
| 64 | dissolve = 1.0, | |
| 65 | illum = 1.0, | |
| 66 | texture_location = "", | |
| 67 | normal_texture_location = "", | |
| 68 | bump_texture_location = "", | |
| 69 | specular_texture_location = "", | |
| 70 | ambient_texture_location = "", | |
| 71 | emissive_texture_location = "", | |
| 72 | diffuse_intensity = 1, | |
| 73 | bump_intensity = 1, | |
| 74 | specular_intensity = 1, | |
| 75 | emission_intensity = 1, | |
| 76 | ambient_intensity = 1, | |
| 77 | culling = "back", | |
| 78 | type = "diffuse", | |
| 79 | translucent = TRUE, | |
| 80 | toon_levels = 5, | |
| 81 | toon_outline_width = 3, | |
| 82 | toon_outline_color = "black", | |
| 83 | reflection_intensity = 0.0, | |
| 84 | reflection_sharpness = 0.0, | |
| 85 | two_sided = FALSE, | |
| 86 | sigma = 0) { | |
| 87 | 8x | culling = switch(culling, "back" = 1, "front" = 2, "none" = 3, 1) |
| 88 | 8x | if(is.null(material)) { |
| 89 | ! | material = list() |
| 90 | ! | material$diffuse = convert_color(diffuse) |
| 91 | ! | material$ambient = convert_color(ambient) |
| 92 | ! | material$specular = convert_color(specular) |
| 93 | ! | material$transmittance = convert_color(transmittance) |
| 94 | ! | material$emission = convert_color(emission) |
| 95 | ! | material$shininess = shininess |
| 96 | ! | material$ior = ior |
| 97 | ! | material$dissolve = dissolve |
| 98 | ! | material$illum = illum |
| 99 | ! | material$diffuse_texname = texture_location |
| 100 | ! | material$normal_texname = normal_texture_location |
| 101 | ! | material$bump_texname = bump_texture_location |
| 102 | ! | material$specular_texname = specular_texture_location |
| 103 | ! | material$ambient_texname = ambient_texture_location |
| 104 | ! | material$emissive_texname = emissive_texture_location |
| 105 | ! | material$diffuse_intensity = diffuse_intensity |
| 106 | ! | material$bump_intensity = bump_intensity |
| 107 | ||
| 108 | ! | material$specular_intensity = specular_intensity |
| 109 | ! | material$emission_intensity = emission_intensity |
| 110 | ! | material$ambient_intensity = ambient_intensity |
| 111 | ! | material$culling = culling |
| 112 | ! | material$type = type |
| 113 | ! | material$translucent = translucent |
| 114 | ! | material$toon_levels = toon_levels |
| 115 | ! | material$toon_outline_width = toon_outline_width |
| 116 | ! | material$toon_outline_color = convert_color(toon_outline_color) |
| 117 | ! | material$reflection_intensity = reflection_intensity |
| 118 | ! | material$reflection_sharpness = reflection_sharpness |
| 119 | ! | material$two_sided = two_sided |
| 120 | ! | material$sigma = sigma |
| 121 | ||
| 122 | ! | material = rayvertex_material(material) |
| 123 | } | |
| 124 | 8x | material_hash = digest::digest(material) |
| 125 | #Check if any materials exist | |
| 126 | 8x | if(length(mesh$materials) > 0 && |
| 127 | 8x | !is.null(mesh$materials[[1]]) && |
| 128 | 8x | length(mesh$materials[[1]]) > 0) { |
| 129 | 2x | if(is.null(id)) { |
| 130 | #Replace all materials with single material | |
| 131 | 2x | mesh$materials = vector(mode = "list", length = length(mesh$shapes)) |
| 132 | 2x | for(i in seq_len(length(mesh$shapes))) { |
| 133 | 2x | mesh$materials[[i]] = list() |
| 134 | 2x | mesh$materials[[i]][[1]] = material |
| 135 | } | |
| 136 | 2x | attr(mesh, "material_hashes") = rep(material_hash, length(mesh$shapes)) |
| 137 | 2x | for(i in seq_len(length(mesh$shapes))) { |
| 138 | 2x | mesh$shapes[[i]]$material_ids = rep(0L,nrow(mesh$shapes[[i]]$indices)) |
| 139 | } | |
| 140 | } else { | |
| 141 | ! | mesh$materials[[id]] = list() |
| 142 | ! | mesh$materials[[id]][[1]] = material |
| 143 | ! | mesh$shapes[[id]]$material_ids = rep(0L,nrow(mesh$shapes[[id]]$indices)) |
| 144 | ! | attr(mesh, "material_hashes")[id] = material_hash |
| 145 | } | |
| 146 | } else { | |
| 147 | 6x | n_shapes = length(mesh$shapes) |
| 148 | 6x | for(i in seq_len(n_shapes)) { |
| 149 | 6x | mesh$materials = vector(mode = "list", length = n_shapes) |
| 150 | 6x | mesh$shapes[[i]]$material_ids = rep(0L,nrow(mesh$shapes[[i]]$indices)) |
| 151 | 6x | mesh$materials[[i]][[1]] = material |
| 152 | } | |
| 153 | 6x | attr(mesh, "material_hashes") = rep(material_hash, n_shapes) |
| 154 | } | |
| 155 | # class(mesh) = c("ray_mesh", "list") | |
| 156 | 8x | return(mesh) |
| 157 | } | |
| 158 | ||
| 159 | ||
| 160 | #'@title Change Material | |
| 161 | #' | |
| 162 | #'@description Change individual material properties, leaving others alone. | |
| 163 | #' | |
| 164 | #'@param mesh Mesh to change. | |
| 165 | #'@param id Default `NULL`. Either a number specifying the material to change, or a character vector | |
| 166 | #'matching the material name. | |
| 167 | #'@param sub_id Default `1`. A number specifying which material to change (within an id). | |
| 168 | #'@param diffuse Default `NULL`. The diffuse color. | |
| 169 | #'@param ambient Default `NULL`. The ambient color. | |
| 170 | #'@param specular Default `NULL`. The specular color. | |
| 171 | #'@param transmittance Default `NULL`. The transmittance | |
| 172 | #'@param emission Default `NULL`. The emissive color. | |
| 173 | #'@param shininess Default `NULL`. The shininess exponent. | |
| 174 | #'@param ior Default `NULL`. The index of refraction. If this is not equal to `1.0`, the material will be refractive. | |
| 175 | #'@param dissolve Default `NULL`. The transparency. | |
| 176 | #'@param illum Default `NULL`. The illumination. | |
| 177 | #'@param texture_location Default `NULL`. The diffuse texture location. | |
| 178 | #'@param normal_texture_location Default `NULL`. The normal texture location. | |
| 179 | #'@param bump_texture_location Default `NULL`. The bump texture location. | |
| 180 | #'@param specular_texture_location Default `NULL`. The specular texture location. | |
| 181 | #'@param ambient_texture_location Default `NULL`. The ambient texture location. | |
| 182 | #'@param emissive_texture_location Default `NULL`. The emissive texture location. | |
| 183 | #'@param diffuse_intensity Default `NULL`. The diffuse intensity. | |
| 184 | #'@param bump_intensity Default `NULL`. The bump intensity. | |
| 185 | #'@param specular_intensity Default `NULL`. The specular intensity. | |
| 186 | #'@param emission_intensity Default `NULL`. The emission intensity. | |
| 187 | #'@param ambient_intensity Default `NULL`. The ambient intensity. | |
| 188 | #'@param culling Default `NULL`. The culling type. Options are `back`, `front`, and `none`. | |
| 189 | #'@param type Default `NULL`. The shader type. Options include `diffuse`,`phong`,`vertex`, and `color`. | |
| 190 | #'@param translucent Default `NULL`. Whether light should transmit through a semi-transparent material. | |
| 191 | #'@param toon_levels Default `NULL`. Number of color breaks in the toon shader. | |
| 192 | #'@param toon_outline_width Default `NULL`. Number of pixels of toon outline. | |
| 193 | #'@param toon_outline_color Default `NULL`. Toon outline color. | |
| 194 | #'@param reflection_intensity Default `NULL`. Intensity of the reflection of the environment map, if present. This will be ignored if the material is refractive. | |
| 195 | #'@param reflection_sharpness Default `NULL`. Sharpness of the reflection, where lower values have blurrier reflections. Must be greater than zero and less than one. | |
| 196 | #'@param two_sided Default `NULL`. Whether diffuse materials should be two sided (normal is taken as the absolute value of the dot product of the light direction and the normal). | |
| 197 | #'@param sigma Default `0`. Oren-Nayar angle. | |
| 198 | #' | |
| 199 | #'@return Shape with new material settings | |
| 200 | #'@export | |
| 201 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 202 | #'p_sphere = sphere_mesh(position=c(555/2,555/2,555/2), | |
| 203 | #' radius=40,material=material_list(diffuse="purple")) | |
| 204 | #'generate_cornell_mesh() |> | |
| 205 | #' add_shape(translate_mesh(p_sphere,c(0,-100,0))) |> | |
| 206 | #' add_shape(change_material(translate_mesh(p_sphere,c(200,-100,0)),diffuse="red")) |> | |
| 207 | #' add_shape(change_material(translate_mesh(p_sphere,c(100,-100,0)),dissolve=0.5)) |> | |
| 208 | #' add_shape(change_material(translate_mesh(p_sphere,c(-100,-100,0)),type="phong")) |> | |
| 209 | #' add_shape(change_material(translate_mesh(p_sphere,c(-200,-100,0)),type="phong",shininess=30)) |> | |
| 210 | #' rasterize_scene(light_info=directional_light(direction=c(0.1,0.6,-1))) | |
| 211 | #' | |
| 212 | #'#Change several shapes at once | |
| 213 | #'p_sphere |> | |
| 214 | #' add_shape(change_material(translate_mesh(p_sphere,c(200,0,0)),diffuse="red")) |> | |
| 215 | #' add_shape(change_material(translate_mesh(p_sphere,c(100,0,0)),dissolve=0.5)) |> | |
| 216 | #' add_shape(change_material(translate_mesh(p_sphere,c(-100,0,0)),type="phong")) |> | |
| 217 | #' add_shape(change_material(translate_mesh(p_sphere,c(-200,0,0)),type="phong",shininess=30)) |> | |
| 218 | #' change_material(diffuse = "red") |> | |
| 219 | #' add_shape(generate_cornell_mesh()) |> | |
| 220 | #' rasterize_scene(light_info=directional_light(direction=c(0.1,0.6,-1))) | |
| 221 | change_material = function(mesh, id = NULL, sub_id = 1, | |
| 222 | diffuse = NULL, | |
| 223 | ambient = NULL, | |
| 224 | specular = NULL, | |
| 225 | transmittance = NULL, | |
| 226 | emission = NULL, | |
| 227 | shininess = NULL, | |
| 228 | ior = NULL, | |
| 229 | dissolve = NULL, | |
| 230 | illum = NULL, | |
| 231 | texture_location = NULL, | |
| 232 | normal_texture_location = NULL, | |
| 233 | bump_texture_location = NULL, | |
| 234 | specular_texture_location = NULL, | |
| 235 | ambient_texture_location = NULL, | |
| 236 | emissive_texture_location = NULL, | |
| 237 | diffuse_intensity = NULL, | |
| 238 | bump_intensity = NULL, | |
| 239 | specular_intensity = NULL, | |
| 240 | emission_intensity = NULL, | |
| 241 | ambient_intensity = NULL, | |
| 242 | culling = NULL, | |
| 243 | type = NULL, | |
| 244 | translucent = NULL, | |
| 245 | toon_levels = NULL, | |
| 246 | toon_outline_width = NULL, | |
| 247 | toon_outline_color = NULL, | |
| 248 | reflection_intensity = NULL, | |
| 249 | reflection_sharpness = NULL, | |
| 250 | two_sided = NULL, | |
| 251 | sigma = NULL) { | |
| 252 | ! | if(!is.null(culling)) { |
| 253 | ! | culling = switch(culling, "back" = 1, "front" = 2, "none" = 3, 1) |
| 254 | } | |
| 255 | ||
| 256 | ! | if(!is.null(mesh$materials) && length(mesh$materials) > 0) { |
| 257 | ! | if(is.null(id)) { |
| 258 | ! | for(j in seq_len(length(mesh$materials))) { |
| 259 | ! | for(i in seq_len(length(mesh$materials[[j]]))) { |
| 260 | ! | if(!is.null(ambient)) mesh$materials[[j]][[i]]$ambient = convert_color(ambient) |
| 261 | ! | if(!is.null(diffuse)) mesh$materials[[j]][[i]]$diffuse = convert_color(diffuse) |
| 262 | ! | if(!is.null(specular)) mesh$materials[[j]][[i]]$specular = convert_color(specular) |
| 263 | ! | if(!is.null(transmittance)) mesh$materials[[j]][[i]]$transmittance = convert_color(transmittance) |
| 264 | ! | if(!is.null(emission)) mesh$materials[[j]][[i]]$emission = convert_color(emission) |
| 265 | ! | if(!is.null(shininess)) mesh$materials[[j]][[i]]$shininess = shininess |
| 266 | ! | if(!is.null(ior)) mesh$materials[[j]][[i]]$ior = ior |
| 267 | ! | if(!is.null(dissolve)) mesh$materials[[j]][[i]]$dissolve = dissolve |
| 268 | ! | if(!is.null(illum)) mesh$materials[[j]][[i]]$illum = illum |
| 269 | ! | if(!is.null(ambient_texture_location)) mesh$materials[[j]][[i]]$ambient_texname = ambient_texture_location |
| 270 | ! | if(!is.null(texture_location)) mesh$materials[[j]][[i]]$diffuse_texname = texture_location |
| 271 | ! | if(!is.null(bump_texture_location)) mesh$materials[[j]][[i]]$bump_texname = bump_texture_location |
| 272 | ! | if(!is.null(emissive_texture_location)) mesh$materials[[j]][[i]]$emissive_texname = emissive_texture_location |
| 273 | ! | if(!is.null(specular_texture_location)) mesh$materials[[j]][[i]]$specular_texname = specular_texture_location |
| 274 | ! | if(!is.null(normal_texture_location)) mesh$materials[[j]][[i]]$normal_texname = normal_texture_location |
| 275 | ! | if(!is.null(diffuse_intensity)) mesh$materials[[j]][[i]]$diffuse_intensity = diffuse_intensity |
| 276 | ! | if(!is.null(bump_intensity)) mesh$materials[[j]][[i]]$bump_intensity = bump_intensity |
| 277 | ! | if(!is.null(specular_intensity)) mesh$materials[[j]][[i]]$specular_intensity = specular_intensity |
| 278 | ! | if(!is.null(emission_intensity)) mesh$materials[[j]][[i]]$emission_intensity = emission_intensity |
| 279 | ! | if(!is.null(ambient_intensity)) mesh$materials[[j]][[i]]$ambient_intensity = ambient_intensity |
| 280 | ! | if(!is.null(culling)) mesh$materials[[j]][[i]]$culling = culling |
| 281 | ! | if(!is.null(type)) mesh$materials[[j]][[i]]$type = type |
| 282 | ! | if(!is.null(translucent)) mesh$materials[[j]][[i]]$translucent = translucent |
| 283 | ! | if(!is.null(toon_levels)) mesh$materials[[j]][[i]]$toon_levels = toon_levels |
| 284 | ! | if(!is.null(toon_outline_width)) mesh$materials[[j]][[i]]$toon_outline_width = toon_outline_width |
| 285 | ! | if(!is.null(toon_outline_color)) mesh$materials[[j]][[i]]$toon_outline_color = convert_color(toon_outline_color) |
| 286 | ! | if(!is.null(reflection_intensity)) mesh$materials[[j]][[i]]$reflection_intensity = reflection_intensity |
| 287 | ! | if(!is.null(reflection_sharpness)) mesh$materials[[j]][[i]]$reflection_sharpness = reflection_sharpness |
| 288 | ! | if(!is.null(two_sided)) mesh$materials[[j]][[i]]$two_sided = two_sided |
| 289 | ! | if(!is.null(sigma)) mesh$materials[[j]][[i]]$sigma = sigma |
| 290 | ||
| 291 | } | |
| 292 | } | |
| 293 | } else { | |
| 294 | ! | if(is.numeric(id)) { |
| 295 | ! | if(!is.null(ambient)) mesh$materials[[id]][[sub_id]]$ambient = convert_color(ambient) |
| 296 | ! | if(!is.null(diffuse)) mesh$materials[[id]][[sub_id]]$diffuse = convert_color(diffuse) |
| 297 | ! | if(!is.null(specular)) mesh$materials[[id]][[sub_id]]$specular = convert_color(specular) |
| 298 | ! | if(!is.null(transmittance)) mesh$materials[[id]][[sub_id]]$transmittance = convert_color(transmittance) |
| 299 | ! | if(!is.null(emission)) mesh$materials[[id]][[sub_id]]$emission = convert_color(emission) |
| 300 | ! | if(!is.null(shininess)) mesh$materials[[id]][[sub_id]]$shininess = shininess |
| 301 | ! | if(!is.null(ior)) mesh$materials[[id]][[sub_id]]$ior = ior |
| 302 | ! | if(!is.null(dissolve)) mesh$materials[[id]][[sub_id]]$dissolve = dissolve |
| 303 | ! | if(!is.null(illum)) mesh$materials[[id]][[sub_id]]$illum = illum |
| 304 | ! | if(!is.null(ambient_texture_location)) mesh$materials[[id]][[sub_id]]$ambient_texname = ambient_texture_location |
| 305 | ! | if(!is.null(texture_location)) mesh$materials[[id]][[sub_id]]$diffuse_texname = texture_location |
| 306 | ! | if(!is.null(bump_texture_location)) mesh$materials[[id]][[sub_id]]$bump_texname = bump_texture_location |
| 307 | ! | if(!is.null(emissive_texture_location)) mesh$materials[[id]][[sub_id]]$emissive_texname = emissive_texture_location |
| 308 | ! | if(!is.null(specular_texture_location)) mesh$materials[[id]][[sub_id]]$specular_texname = specular_texture_location |
| 309 | ! | if(!is.null(normal_texture_location)) mesh$materials[[id]][[sub_id]]$normal_texname = normal_texture_location |
| 310 | ! | if(!is.null(diffuse_intensity)) mesh$materials[[id]][[sub_id]]$diffuse_intensity = diffuse_intensity |
| 311 | ! | if(!is.null(bump_intensity)) mesh$materials[[id]][[sub_id]]$bump_intensity = bump_intensity |
| 312 | ! | if(!is.null(specular_intensity)) mesh$materials[[id]][[sub_id]]$specular_intensity = specular_intensity |
| 313 | ! | if(!is.null(emission_intensity)) mesh$materials[[id]][[sub_id]]$emission_intensity = emission_intensity |
| 314 | ! | if(!is.null(ambient_intensity)) mesh$materials[[id]][[sub_id]]$ambient_intensity = ambient_intensity |
| 315 | ! | if(!is.null(culling)) mesh$materials[[id]][[sub_id]]$culling = culling |
| 316 | ! | if(!is.null(type)) mesh$materials[[id]][[sub_id]]$type = type |
| 317 | ! | if(!is.null(translucent)) mesh$materials[[id]][[sub_id]]$translucent = translucent |
| 318 | ! | if(!is.null(toon_levels)) mesh$materials[[id]][[sub_id]]$toon_levels = toon_levels |
| 319 | ! | if(!is.null(toon_outline_width)) mesh$materials[[id]][[sub_id]]$toon_outline_width = toon_outline_width |
| 320 | ! | if(!is.null(toon_outline_color)) mesh$materials[[id]][[sub_id]]$toon_outline_color = convert_color(toon_outline_color) |
| 321 | ! | if(!is.null(reflection_intensity)) mesh$materials[[id]][[sub_id]]$reflection_intensity = reflection_intensity |
| 322 | ! | if(!is.null(reflection_sharpness)) mesh$materials[[id]][[sub_id]]$reflection_sharpness = reflection_sharpness |
| 323 | ! | if(!is.null(two_sided)) mesh$materials[[id]][[sub_id]]$two_sided = two_sided |
| 324 | ! | if(!is.null(sigma)) mesh$materials[[id]][[sub_id]]$sigma = sigma |
| 325 | ||
| 326 | } | |
| 327 | ! | if(is.character(id)) { |
| 328 | ! | for(i in seq_len(length(mesh$materials))) { |
| 329 | ! | if(names(mesh$materials)[i] == id) { |
| 330 | ! | if(!is.null(ambient)) mesh$materials[[i]][[sub_id]]$ambient = convert_color(ambient) |
| 331 | ! | if(!is.null(diffuse)) mesh$materials[[i]][[sub_id]]$diffuse = convert_color(diffuse) |
| 332 | ! | if(!is.null(specular)) mesh$materials[[i]][[sub_id]]$specular = convert_color(specular) |
| 333 | ! | if(!is.null(transmittance)) mesh$materials[[i]][[sub_id]]$transmittance = convert_color(transmittance) |
| 334 | ! | if(!is.null(emission)) mesh$materials[[i]][[sub_id]]$emission = convert_color(emission) |
| 335 | ! | if(!is.null(shininess)) mesh$materials[[i]][[sub_id]]$shininess = shininess |
| 336 | ! | if(!is.null(ior)) mesh$materials[[i]][[sub_id]]$ior = ior |
| 337 | ! | if(!is.null(dissolve)) mesh$materials[[i]][[sub_id]]$dissolve = dissolve |
| 338 | ! | if(!is.null(illum)) mesh$materials[[i]][[sub_id]]$illum = illum |
| 339 | ! | if(!is.null(ambient_texture_location)) mesh$materials[[i]][[sub_id]]$ambient_texname = ambient_texture_location |
| 340 | ! | if(!is.null(texture_location)) mesh$materials[[i]][[sub_id]]$diffuse_texname = texture_location |
| 341 | ! | if(!is.null(bump_texture_location)) mesh$materials[[i]][[sub_id]]$bump_texname = bump_texture_location |
| 342 | ! | if(!is.null(emissive_texture_location)) mesh$materials[[i]][[sub_id]]$emissive_texname = emissive_texture_location |
| 343 | ! | if(!is.null(specular_texture_location)) mesh$materials[[i]][[sub_id]]$specular_texname = specular_texture_location |
| 344 | ! | if(!is.null(normal_texture_location)) mesh$materials[[i]][[sub_id]]$normal_texname = normal_texture_location |
| 345 | ! | if(!is.null(diffuse_intensity)) mesh$materials[[i]][[sub_id]]$diffuse_intensity = diffuse_intensity |
| 346 | ! | if(!is.null(bump_intensity)) mesh$materials[[i]][[sub_id]]$bump_intensity = bump_intensity |
| 347 | ! | if(!is.null(specular_intensity)) mesh$materials[[i]][[sub_id]]$specular_intensity = specular_intensity |
| 348 | ! | if(!is.null(emission_intensity)) mesh$materials[[i]][[sub_id]]$emission_intensity = emission_intensity |
| 349 | ! | if(!is.null(ambient_intensity)) mesh$materials[[i]][[sub_id]]$ambient_intensity = ambient_intensity |
| 350 | ! | if(!is.null(culling)) mesh$materials[[i]][[sub_id]]$culling = culling |
| 351 | ! | if(!is.null(type)) mesh$materials[[i]][[sub_id]]$type = type |
| 352 | ! | if(!is.null(translucent)) mesh$materials[[i]][[sub_id]]$translucent = translucent |
| 353 | ! | if(!is.null(toon_levels)) mesh$materials[[i]][[sub_id]]$toon_levels = toon_levels |
| 354 | ! | if(!is.null(toon_outline_width)) mesh$materials[[i]][[sub_id]]$toon_outline_width = toon_outline_width |
| 355 | ! | if(!is.null(toon_outline_color)) mesh$materials[[i]][[sub_id]]$toon_outline_color = convert_color(toon_outline_color) |
| 356 | ! | if(!is.null(reflection_intensity)) mesh$materials[[i]][[sub_id]]$reflection_intensity = reflection_intensity |
| 357 | ! | if(!is.null(reflection_sharpness)) mesh$materials[[i]][[sub_id]]$reflection_sharpness = reflection_sharpness |
| 358 | ! | if(!is.null(two_sided)) mesh$materials[[i]][[sub_id]]$two_sided = two_sided |
| 359 | ! | if(!is.null(sigma)) mesh$materials[[i]][[sub_id]]$sigma = sigma |
| 360 | ||
| 361 | } | |
| 362 | } | |
| 363 | } | |
| 364 | } | |
| 365 | ! | counter = 0 |
| 366 | ! | for(i in seq_len(length(mesh$materials))) { |
| 367 | ! | for(j in seq_len(length(mesh$materials[[i]]))) { |
| 368 | ! | counter = counter + 1 |
| 369 | } | |
| 370 | } | |
| 371 | ! | attr(mesh, "material_hashes") = vector("character", length = counter) |
| 372 | ! | counter = 1 |
| 373 | ! | for(i in seq_len(length(mesh$materials))) { |
| 374 | ! | for(j in seq_len(length(mesh$materials[[i]]))) { |
| 375 | ! | attr(mesh, "material_hashes")[counter] = digest::digest(mesh$materials[[i]][[j]]) |
| 376 | ! | counter = counter + 1 |
| 377 | } | |
| 378 | } | |
| 379 | } else { | |
| 380 | ! | stop("No materials detected") |
| 381 | } | |
| 382 | ! | class(mesh) = c("ray_mesh", "list") |
| 383 | ||
| 384 | ! | return(mesh) |
| 385 | } | |
| 386 | ||
| 387 | #'@title Material List | |
| 388 | #' | |
| 389 | #'@description Generate a material properties list. | |
| 390 | #' | |
| 391 | #'@param diffuse Default `c(0.5,0.5,0.5)`. The diffuse color. | |
| 392 | #'@param ambient Default `c(0,0,0)`. The ambient color. | |
| 393 | #'@param specular Default `c(1,1,1)`. The specular color. | |
| 394 | #'@param transmittance Default `c(0,0,0)`. The transmittance | |
| 395 | #'@param emission Default `c(0,0,0)`. The emissive color. | |
| 396 | #'@param shininess Default `50.0`. The shininess exponent. | |
| 397 | #'@param ior Default `1.0`. The index of refraction. If this is not equal to `1.0`, the material will be refractive. | |
| 398 | #'@param dissolve Default `1.0`. The transparency. | |
| 399 | #'@param illum Default `1.0`. The illumination. | |
| 400 | #'@param texture_location Default `""`. The diffuse texture location. | |
| 401 | #'@param normal_texture_location Default `""`. The normal texture location. | |
| 402 | #'@param bump_texture_location Default `""`. The bump texture location. | |
| 403 | #'@param specular_texture_location Default `""`. The specular texture location. | |
| 404 | #'@param ambient_texture_location Default `""`. The ambient texture location. | |
| 405 | #'@param emissive_texture_location Default `""`. The emissive texture location. | |
| 406 | #'@param diffuse_intensity Default `1`. The diffuse intensity. | |
| 407 | #'@param bump_intensity Default `1`. The bump intensity. | |
| 408 | #'@param specular_intensity Default `1`. The specular intensity. | |
| 409 | #'@param emission_intensity Default `1`. The emission intensity. | |
| 410 | #'@param ambient_intensity Default `1`. The ambient intensity. | |
| 411 | #'@param culling Default `"back"`. The culling type. Options are `back`, `front`, and `none`. | |
| 412 | #'@param type Default `"diffuse"`. The shader type. Options include `diffuse`,`phong`,`vertex`, and `color`. | |
| 413 | #'@param translucent Default `FALSE`. Whether light should transmit through a semi-transparent material. | |
| 414 | #'@param toon_levels Default `5`. Number of color breaks in the toon shader. | |
| 415 | #'@param toon_outline_width Default `3`. Number of pixels of toon outline. | |
| 416 | #'@param toon_outline_color Default `black`. Toon outline color. | |
| 417 | #'@param reflection_intensity Default `0.0`. Intensity of the reflection of the environment map, if present. This will be ignored if the material is refractive. | |
| 418 | #'@param reflection_sharpness Default `1.0`. Sharpness of the reflection, where lower values have blurrier reflections. Must be greater than zero and less than one. | |
| 419 | #'@param two_sided Default `FALSE`. Whether diffuse materials should be two sided (normal is taken as the absolute value of the dot product of the light direction and the normal). | |
| 420 | #'@param sigma Default `0`. Oren-Nayar angle. | |
| 421 | #' | |
| 422 | #'@return List of material properties. | |
| 423 | #'@export | |
| 424 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 425 | #'mat_prop = material_list(diffuse="purple", type="phong", shininess = 20, | |
| 426 | #' ambient="purple", ambient_intensity=0.3, | |
| 427 | #' specular = "red", specular_intensity=2) | |
| 428 | #' | |
| 429 | #'p_sphere = sphere_mesh(position=c(555/2,555/2,555/2), | |
| 430 | #' radius=40,material=mat_prop) | |
| 431 | #' | |
| 432 | #'rasterize_scene(p_sphere, light_info=directional_light(direction=c(0.1,0.6,-1))) | |
| 433 | material_list = function(diffuse = c(0.8,0.8,0.8), | |
| 434 | ambient = c(0,0,0), | |
| 435 | specular = c(1,1,1), | |
| 436 | transmittance = c(0,0,0), | |
| 437 | emission = c(0,0,0), | |
| 438 | shininess = 50.0, | |
| 439 | ior = 1.0, | |
| 440 | dissolve = 1.0, | |
| 441 | illum = 1.0, | |
| 442 | texture_location = "", | |
| 443 | normal_texture_location = "", | |
| 444 | bump_texture_location = "", | |
| 445 | specular_texture_location = "", | |
| 446 | ambient_texture_location = "", | |
| 447 | emissive_texture_location = "", | |
| 448 | diffuse_intensity = 1, | |
| 449 | bump_intensity = 1, | |
| 450 | specular_intensity = 1, | |
| 451 | emission_intensity = 1, | |
| 452 | ambient_intensity = 1, | |
| 453 | culling = "back", | |
| 454 | type = "diffuse", | |
| 455 | translucent = TRUE, | |
| 456 | toon_levels = 5, | |
| 457 | toon_outline_width = 3, | |
| 458 | toon_outline_color = "black", | |
| 459 | reflection_intensity = 0.0, | |
| 460 | reflection_sharpness = 1.0, | |
| 461 | two_sided = FALSE, | |
| 462 | sigma = 0) { | |
| 463 | 163x | culling = switch(culling, "back" = 1, "front" = 2, "none" = 3, 1) |
| 464 | 163x | material_props = |
| 465 | 163x | list(diffuse = convert_color(diffuse) , |
| 466 | 163x | ambient = convert_color(ambient) , |
| 467 | 163x | specular = convert_color(specular) , |
| 468 | 163x | transmittance = convert_color(transmittance) , |
| 469 | 163x | emission = convert_color(emission) , |
| 470 | 163x | shininess = shininess , |
| 471 | 163x | ior = ior , |
| 472 | 163x | dissolve = dissolve , |
| 473 | 163x | illum = illum , |
| 474 | 163x | ambient_texname = ambient_texture_location , |
| 475 | 163x | diffuse_texname = texture_location , |
| 476 | 163x | bump_texname = bump_texture_location, |
| 477 | 163x | emissive_texname = emissive_texture_location , |
| 478 | 163x | specular_texname = specular_texture_location , |
| 479 | 163x | normal_texname = normal_texture_location , |
| 480 | 163x | diffuse_intensity = diffuse_intensity , |
| 481 | 163x | bump_intensity = bump_intensity, |
| 482 | 163x | specular_intensity = specular_intensity , |
| 483 | 163x | emission_intensity = emission_intensity , |
| 484 | 163x | ambient_intensity = ambient_intensity , |
| 485 | 163x | culling = culling , |
| 486 | 163x | type = type , |
| 487 | 163x | translucent = translucent , |
| 488 | 163x | toon_levels = toon_levels , |
| 489 | 163x | toon_outline_width = toon_outline_width , |
| 490 | 163x | toon_outline_color = convert_color(toon_outline_color) , |
| 491 | 163x | reflection_intensity = reflection_intensity , |
| 492 | 163x | reflection_sharpness = reflection_sharpness, |
| 493 | 163x | two_sided = two_sided, |
| 494 | 163x | sigma = sigma) |
| 495 | 163x | stopifnot(length(material_props$diffuse) == 3) |
| 496 | 163x | stopifnot(length(material_props$ambient) == 3) |
| 497 | 163x | stopifnot(length(material_props$specular) == 3) |
| 498 | 163x | stopifnot(length(material_props$transmittance) == 3) |
| 499 | 163x | stopifnot(length(material_props$emission) == 3) |
| 500 | 163x | stopifnot(length(material_props$toon_outline_color) == 3) |
| 501 | ||
| 502 | ||
| 503 | 163x | return(rayvertex_material(material_props)) |
| 504 | } |
| 1 | ray_environment = new.env(parent = emptyenv()) | |
| 2 | ||
| 3 | .onLoad = function(libname, pkgname) { | |
| 4 | ! | options("ray_loading" = TRUE) |
| 5 | ! | on.exit(options("ray_loading" = NULL)) |
| 6 | ! | assign("arrow", read_obj(system.file("extdata", "arrow.txt", package="rayvertex")), envir = ray_environment) |
| 7 | ! | assign("cone", read_obj(system.file("extdata", "cone.txt", package="rayvertex")), envir = ray_environment) |
| 8 | ! | assign("cube", read_obj(system.file("extdata", "cube.txt", package="rayvertex")), envir = ray_environment) |
| 9 | ! | assign("cylinder", read_obj(system.file("extdata", "cylinder.txt", package="rayvertex")), envir = ray_environment) |
| 10 | ! | assign("disk", read_obj(system.file("extdata", "disk.txt", package="rayvertex")), envir = ray_environment) |
| 11 | ! | assign("low_poly_sphere", read_obj(system.file("extdata", "low_poly_sphere.txt", package="rayvertex")), envir = ray_environment) |
| 12 | ! | assign("r_obj", read_obj(system.file("extdata", "r_obj.txt", package="rayvertex")), envir = ray_environment) |
| 13 | ! | assign("sphere", read_obj(system.file("extdata", "sphere.txt", package="rayvertex")), envir = ray_environment) |
| 14 | ! | assign("xy_plane", read_obj(system.file("extdata", "xy_plane.txt", package="rayvertex")), envir = ray_environment) |
| 15 | ! | assign("xz_plane", read_obj(system.file("extdata", "xz_plane.txt", package="rayvertex")), envir = ray_environment) |
| 16 | ! | assign("yz_plane", read_obj(system.file("extdata", "yz_plane.txt", package="rayvertex")), envir = ray_environment) |
| 17 | ! | assign("init_time", 0, envir = ray_environment) |
| 18 | ! | assign("prev_time", 0, envir = ray_environment) |
| 19 | ! | assign("pkg_loaded", TRUE, envir = ray_environment) |
| 20 | ||
| 21 | #Register methods | |
| 22 | ! | register_s3_method("rayvertex", "print", "ray_mesh") |
| 23 | ! | register_s3_method("rayvertex", "print", "rayvertex_material") |
| 24 | ! | register_s3_method("rayvertex", "print", "rayvertex_material_list") |
| 25 | ! | register_s3_method("rayvertex", "print", "ray_shape") |
| 26 | ||
| 27 | ! | register_s3_method("pillar", "tbl_sum", "print_raymesh_df") |
| 28 | ||
| 29 | # register_s3_method("rayrender", "print", "ray_material") | |
| 30 | # register_s3_method("rayrender", "format", "ray_material") | |
| 31 | # register_s3_method("pillar", "pillar_shaft", "ray_material") | |
| 32 | # register_s3_method("vctrs", "vec_ptype_abbr", "ray_material") | |
| 33 | ||
| 34 | # register_s3_method("rayrender", "print", "ray_transform") | |
| 35 | # register_s3_method("rayrender", "format", "ray_transform") | |
| 36 | # register_s3_method("pillar", "pillar_shaft", "rayvertex_material") | |
| 37 | # register_s3_method("vctrs", "vec_ptype_abbr", "rayvertex_material") | |
| 38 | ||
| 39 | # register_s3_method("pillar", "pillar_shaft", "rayvertex_material") | |
| 40 | # register_s3_method("vctrs", "vec_ptype_abbr", "rayvertex_material") | |
| 41 | ||
| 42 | ! | register_s3_method("pillar", "pillar_shaft", "rayvertex_material_list") |
| 43 | ! | register_s3_method("vctrs", "vec_ptype_abbr", "rayvertex_material_list") |
| 44 | ! | register_s3_method("pillar", "pillar_shaft", "rayvertex_material") |
| 45 | ||
| 46 | ! | register_s3_method("vctrs", "vec_ptype_abbr", "rayvertex_material") |
| 47 | ||
| 48 | # register_s3_method("rayrender", "print", "ray_animated_transform") | |
| 49 | # register_s3_method("rayrender", "format", "ray_animated_transform") | |
| 50 | ! | register_s3_method("pillar", "pillar_shaft", "ray_vertex_data") |
| 51 | ! | register_s3_method("vctrs", "vec_ptype_abbr", "ray_vertex_data") |
| 52 | ||
| 53 | # register_s3_method("rayrender", "print", "ray_shape_info") | |
| 54 | # register_s3_method("rayrender", "format", "ray_shape_info") | |
| 55 | ! | register_s3_method("pillar", "pillar_shaft", "ray_shape") |
| 56 | ! | register_s3_method("vctrs", "vec_ptype_abbr", "ray_shape") |
| 57 | ||
| 58 | ! | register_s3_method("pillar", "pillar_shaft", "ray_shape_list") |
| 59 | ! | register_s3_method("vctrs", "vec_ptype_abbr", "ray_shape_list") |
| 60 | } | |
| 61 | ||
| 62 | register_s3_method <- function(pkg, generic, class, fun = NULL) { | |
| 63 | ! | stopifnot(is.character(pkg), length(pkg) == 1) |
| 64 | ! | stopifnot(is.character(generic), length(generic) == 1) |
| 65 | ! | stopifnot(is.character(class), length(class) == 1) |
| 66 | ||
| 67 | ! | if (is.null(fun)) { |
| 68 | ! | fun <- get(paste0(generic, ".", class), envir = parent.frame()) |
| 69 | } else { | |
| 70 | ! | stopifnot(is.function(fun)) |
| 71 | } | |
| 72 | ||
| 73 | ! | if (pkg %in% loadedNamespaces()) { |
| 74 | ! | registerS3method(generic, class, fun, envir = asNamespace(pkg)) |
| 75 | } | |
| 76 | ||
| 77 | # Always register hook in case package is later unloaded & reloaded | |
| 78 | ! | setHook( |
| 79 | ! | packageEvent(pkg, "onLoad"), |
| 80 | ! | function(...) { |
| 81 | 14x | registerS3method(generic, class, fun, envir = asNamespace(pkg)) |
| 82 | } | |
| 83 | ) | |
| 84 | } |
| 1 | #' @title Write the scene to an OBJ file | |
| 2 | #' | |
| 3 | #' @description Writes the current scene to a Wavefront OBJ file, with or without materials | |
| 4 | #' | |
| 5 | #' @param scene A rayvertex scene. | |
| 6 | #' @param filename The filename for the OBJ file. | |
| 7 | #' @param materials Default `TRUE`. Whether to write an MTL file to specify the materials for the OBJ. | |
| 8 | #' @param fileext Default `".obj"`. The file extension to add to the filename. | |
| 9 | #' | |
| 10 | #' @return None | |
| 11 | #' @export | |
| 12 | #' | |
| 13 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 14 | #' tmpfile = tempfile(fileext = ".obj") | |
| 15 | #' write_scene_to_obj(generate_cornell_mesh(), tmpfile) | |
| 16 | write_scene_to_obj = function( | |
| 17 | scene, | |
| 18 | filename, | |
| 19 | materials = TRUE, | |
| 20 | fileext = ".obj" | |
| 21 | ) { | |
| 22 | 3x | if (!inherits(scene, "ray_mesh")) { |
| 23 | ! | stop("`scene` must be of class `ray_mesh`") |
| 24 | } | |
| 25 | 3x | filename = sprintf("%s%s", tools::file_path_sans_ext(filename), fileext) |
| 26 | 3x | mtl_file = sprintf("%s.mtl", tools::file_path_sans_ext(filename)) |
| 27 | 3x | con = file(filename, open = "w") |
| 28 | 3x | on.exit(close(con), add = TRUE) |
| 29 | 3x | writeLines("# OBJ created with rayvertex", con = con) |
| 30 | 3x | if (materials) { |
| 31 | 3x | con_mtl = file(mtl_file, open = "w") |
| 32 | 3x | on.exit(close(con_mtl), add = TRUE) |
| 33 | 3x | write_materials(con_mtl, scene$materials) |
| 34 | 3x | writeLines(sprintf("mtllib %s", basename(mtl_file)), con = con) |
| 35 | } | |
| 36 | 3x | write_verts(con, scene$vertices) |
| 37 | 3x | write_tex(con, scene$texcoor) |
| 38 | 3x | write_norm(con, scene$normals) |
| 39 | 3x | n_verts = unlist(lapply(scene$vertices, nrow)) |
| 40 | 3x | n_normals = unlist(lapply(scene$normals, nrow)) |
| 41 | 3x | n_texcoords = unlist(lapply(scene$texcoords, nrow)) |
| 42 | #Get max of mats in each | |
| 43 | 3x | get_max_material = function(shape) { |
| 44 | 5x | max(shape$material_ids, na.rm = TRUE) + 1 |
| 45 | } | |
| 46 | 3x | n_mats = unlist(lapply(scene$shapes, get_max_material)) |
| 47 | 3x | write_shapes( |
| 48 | 3x | con, |
| 49 | 3x | scene$shapes, |
| 50 | 3x | n_verts, |
| 51 | 3x | n_normals, |
| 52 | 3x | n_texcoords, |
| 53 | 3x | n_mats, |
| 54 | 3x | materials = materials |
| 55 | ) | |
| 56 | } | |
| 57 | ||
| 58 | #Write functions | |
| 59 | write_verts = function(con, verts) { | |
| 60 | 3x | n_verts = length(verts) |
| 61 | 3x | for (i in seq_len(n_verts)) { |
| 62 | 5x | writeLines( |
| 63 | 5x | sprintf("v %f %f %f", verts[[i]][, 1], verts[[i]][, 2], verts[[i]][, 3]), |
| 64 | 5x | con = con |
| 65 | ) | |
| 66 | } | |
| 67 | } | |
| 68 | ||
| 69 | write_tex = function(con, tex) { | |
| 70 | 3x | n_tex = length(tex) |
| 71 | 3x | for (i in seq_len(n_tex)) { |
| 72 | 5x | if (nrow(tex[[i]] > 0)) { |
| 73 | 4x | writeLines(sprintf("vt %f %f", tex[[i]][, 1], tex[[i]][, 2]), con = con) |
| 74 | } | |
| 75 | } | |
| 76 | } | |
| 77 | ||
| 78 | write_norm = function(con, norm) { | |
| 79 | 3x | n_norm = length(norm) |
| 80 | 3x | for (i in seq_len(n_norm)) { |
| 81 | 5x | if (nrow(norm[[i]] > 0)) { |
| 82 | 4x | writeLines( |
| 83 | 4x | sprintf("vn %f %f %f", norm[[i]][, 1], norm[[i]][, 2], norm[[i]][, 3]), |
| 84 | 4x | con = con |
| 85 | ) | |
| 86 | } | |
| 87 | } | |
| 88 | } | |
| 89 | ||
| 90 | write_shapes = function( | |
| 91 | con, | |
| 92 | shapes, | |
| 93 | n_verts, | |
| 94 | n_normals, | |
| 95 | n_texcoords, | |
| 96 | n_mats, | |
| 97 | materials = FALSE | |
| 98 | ) { | |
| 99 | if ( | |
| 100 | 3x | length(unique(c( |
| 101 | 3x | length(shapes), |
| 102 | 3x | length(n_verts), |
| 103 | 3x | length(n_normals), |
| 104 | 3x | length(n_texcoords) |
| 105 | ))) != | |
| 106 | 3x | 1 |
| 107 | ) { | |
| 108 | ! | stop("All inputs must be same length") |
| 109 | } | |
| 110 | 3x | vert_offset = cumsum(c(1, n_verts)) |
| 111 | 3x | norm_offset = cumsum(c(1, n_normals)) |
| 112 | 3x | tex_offset = cumsum(c(1, n_texcoords)) |
| 113 | 3x | mat_offset = cumsum(c(0, n_mats)) |
| 114 | 3x | prev_mat = 0 |
| 115 | 3x | for (i in seq_len(length(shapes))) { |
| 116 | 5x | single_material = length(unique(shapes[[i]]$material_ids)) == 1L |
| 117 | 5x | single_tex = length(unique(shapes[[i]]$has_vertex_tex)) == 1L |
| 118 | 5x | single_norm = length(unique(shapes[[i]]$has_vertex_normals)) == 1L |
| 119 | 5x | single_mat = length(unique(shapes[[i]]$material_ids)) == 1L |
| 120 | 5x | voff = vert_offset[i] |
| 121 | 5x | noff = norm_offset[i] |
| 122 | 5x | toff = tex_offset[i] |
| 123 | 5x | prev_mat = 0 |
| 124 | if ( | |
| 125 | 5x | single_material && single_tex && single_norm && (single_mat || !materials) |
| 126 | ) { | |
| 127 | 5x | has_tex = shapes[[i]]$has_vertex_tex[1] |
| 128 | 5x | has_norm = shapes[[i]]$has_vertex_normals[1] |
| 129 | 5x | if (materials) { |
| 130 | 5x | new_mat = shapes[[i]]$material_ids[1] + mat_offset[i] |
| 131 | } else { | |
| 132 | ! | new_mat = prev_mat |
| 133 | } | |
| 134 | 5x | if ((i == 1 || prev_mat != new_mat) && materials) { |
| 135 | 5x | writeLines(sprintf("usemtl mat%i", new_mat + 1), con = con) |
| 136 | 5x | prev_mat = new_mat |
| 137 | } | |
| 138 | 5x | if (!has_tex && !has_norm) { |
| 139 | 1x | face_lines = paste( |
| 140 | 1x | "f", |
| 141 | 1x | apply(shapes[[i]]$indices + voff, 1, paste, collapse = " ") |
| 142 | ) | |
| 143 | 4x | } else if (has_tex && has_norm) { |
| 144 | 4x | firstvert = sprintf( |
| 145 | 4x | "%i/%i/%i", |
| 146 | 4x | shapes[[i]]$indices[, 1] + voff, |
| 147 | 4x | shapes[[i]]$tex_indices[, 1] + toff, |
| 148 | 4x | shapes[[i]]$norm_indices[, 1] + noff |
| 149 | ) | |
| 150 | 4x | secondvert = sprintf( |
| 151 | 4x | "%i/%i/%i", |
| 152 | 4x | shapes[[i]]$indices[, 2] + voff, |
| 153 | 4x | shapes[[i]]$tex_indices[, 2] + toff, |
| 154 | 4x | shapes[[i]]$norm_indices[, 2] + noff |
| 155 | ) | |
| 156 | 4x | thirdvert = sprintf( |
| 157 | 4x | "%i/%i/%i", |
| 158 | 4x | shapes[[i]]$indices[, 3] + voff, |
| 159 | 4x | shapes[[i]]$tex_indices[, 3] + toff, |
| 160 | 4x | shapes[[i]]$norm_indices[, 3] + noff |
| 161 | ) | |
| 162 | 4x | face_lines = paste("f", firstvert, secondvert, thirdvert, sep = " ") |
| 163 | ! | } else if (has_tex && !has_norm) { |
| 164 | ! | firstvert = sprintf( |
| 165 | ! | "%i/%i", |
| 166 | ! | shapes[[i]]$indices[, 1] + voff, |
| 167 | ! | shapes[[i]]$tex_indices[, 1] + toff |
| 168 | ) | |
| 169 | ! | secondvert = sprintf( |
| 170 | ! | "%i/%i", |
| 171 | ! | shapes[[i]]$indices[, 2] + voff, |
| 172 | ! | shapes[[i]]$tex_indices[, 2] + toff |
| 173 | ) | |
| 174 | ! | thirdvert = sprintf( |
| 175 | ! | "%i/%i", |
| 176 | ! | shapes[[i]]$indices[, 3] + voff, |
| 177 | ! | shapes[[i]]$tex_indices[, 3] + toff |
| 178 | ) | |
| 179 | ! | face_lines = paste("f", firstvert, secondvert, thirdvert, sep = " ") |
| 180 | ! | } else if (!has_tex && has_norm) { |
| 181 | ! | firstvert = sprintf( |
| 182 | ! | "%i//%i", |
| 183 | ! | shapes[[i]]$indices[, 1] + voff, |
| 184 | ! | shapes[[i]]$norm_indices[, 1] + noff |
| 185 | ) | |
| 186 | ! | secondvert = sprintf( |
| 187 | ! | "%i//%i", |
| 188 | ! | shapes[[i]]$indices[, 2] + voff, |
| 189 | ! | shapes[[i]]$norm_indices[, 2] + noff |
| 190 | ) | |
| 191 | ! | thirdvert = sprintf( |
| 192 | ! | "%i//%i", |
| 193 | ! | shapes[[i]]$indices[, 3] + voff, |
| 194 | ! | shapes[[i]]$norm_indices[, 3] + noff |
| 195 | ) | |
| 196 | ! | face_lines = paste("f", firstvert, secondvert, thirdvert, sep = " ") |
| 197 | } | |
| 198 | 5x | writeLines(face_lines, con = con) |
| 199 | } else { | |
| 200 | ! | n_idx = nrow(shapes[[i]]$indices) |
| 201 | ! | output_list = vector(mode = "list") |
| 202 | ! | counter = 1 |
| 203 | ! | for (j in seq_len(n_idx)) { |
| 204 | ! | has_tex = shapes[[i]]$has_vertex_tex[j] |
| 205 | ! | has_norm = shapes[[i]]$has_vertex_normals[j] |
| 206 | ! | new_mat = shapes[[i]]$material_ids[j] + mat_offset[i] |
| 207 | ! | if ((i == 1 || prev_mat != new_mat) && materials) { |
| 208 | ! | output_list[[counter]] = sprintf("usemtl mat%i", new_mat + 1) |
| 209 | ! | prev_mat = new_mat |
| 210 | ! | counter = counter + 1 |
| 211 | } | |
| 212 | ! | if (!has_tex && !has_norm) { |
| 213 | ! | output_list[[counter]] = paste( |
| 214 | ! | "f", |
| 215 | ! | apply(shapes[[i]]$indices[j, ] + voff, 1, paste, collapse = " ") |
| 216 | ) | |
| 217 | ! | } else if (has_tex && has_norm) { |
| 218 | ! | output_list[[counter]] = paste( |
| 219 | ! | "f", |
| 220 | ! | paste0( |
| 221 | ! | shapes[[i]]$indices[j, ] + voff, |
| 222 | "/", | |
| 223 | ! | shapes[[i]]$tex_indices[j, ] + toff, |
| 224 | "/", | |
| 225 | ! | shapes[[i]]$norm_indices[j, ] + noff, |
| 226 | ! | collapse = " " |
| 227 | ) | |
| 228 | ) | |
| 229 | ! | } else if (has_tex && !has_norm) { |
| 230 | ! | output_list[[counter]] = paste( |
| 231 | ! | "f", |
| 232 | ! | paste0( |
| 233 | ! | shapes[[i]]$indices[j, ] + voff, |
| 234 | "/", | |
| 235 | ! | shapes[[i]]$tex_indices[j, ] + toff, |
| 236 | ! | collapse = " " |
| 237 | ) | |
| 238 | ) | |
| 239 | ! | } else if (!has_tex && has_norm) { |
| 240 | ! | output_list[[counter]] = paste( |
| 241 | ! | "f", |
| 242 | ! | paste0( |
| 243 | ! | shapes[[i]]$indices[j, ] + voff, |
| 244 | "//", | |
| 245 | ! | shapes[[i]]$norm_indices[j, ] + noff, |
| 246 | ! | collapse = " " |
| 247 | ) | |
| 248 | ) | |
| 249 | } | |
| 250 | ! | counter = counter + 1 |
| 251 | } | |
| 252 | ! | face_lines = unlist(output_list) |
| 253 | ! | writeLines(face_lines, con = con) |
| 254 | } | |
| 255 | } | |
| 256 | } | |
| 257 | ||
| 258 | paste_digit = function(num, digits = 4) { | |
| 259 | 20x | sprintf(paste0("%0.", digits, "f", collapse = ""), num) |
| 260 | } | |
| 261 | ||
| 262 | write_materials = function(con, materials) { | |
| 263 | 3x | n_mats = length(materials) |
| 264 | 3x | for (i in seq_len(n_mats)) { |
| 265 | 5x | tmp_mat = materials[[i]][[1]] |
| 266 | 5x | writeLines(sprintf("newmtl mat%i", i), con) |
| 267 | 5x | if (tmp_mat$diffuse_intensity > 0) { |
| 268 | 5x | writeLines( |
| 269 | 5x | sprintf( |
| 270 | 5x | "Kd %s", |
| 271 | 5x | paste( |
| 272 | 5x | paste_digit(tmp_mat$diffuse * tmp_mat$diffuse_intensity), |
| 273 | 5x | collapse = " " |
| 274 | ) | |
| 275 | ), | |
| 276 | 5x | con |
| 277 | ) | |
| 278 | } | |
| 279 | 5x | if (tmp_mat$ambient_intensity > 0) { |
| 280 | 5x | writeLines( |
| 281 | 5x | sprintf( |
| 282 | 5x | "Ka %s", |
| 283 | 5x | paste( |
| 284 | 5x | paste_digit(tmp_mat$ambient * tmp_mat$ambient_intensity), |
| 285 | 5x | collapse = " " |
| 286 | ) | |
| 287 | ), | |
| 288 | 5x | con |
| 289 | ) | |
| 290 | } | |
| 291 | 5x | if (tmp_mat$specular_intensity > 0) { |
| 292 | 5x | writeLines( |
| 293 | 5x | sprintf( |
| 294 | 5x | "Ks %s", |
| 295 | 5x | paste( |
| 296 | 5x | paste_digit(tmp_mat$specular * tmp_mat$specular_intensity), |
| 297 | 5x | collapse = " " |
| 298 | ) | |
| 299 | ), | |
| 300 | 5x | con |
| 301 | ) | |
| 302 | } | |
| 303 | 5x | writeLines( |
| 304 | 5x | sprintf( |
| 305 | 5x | "Tf %s", |
| 306 | 5x | paste(paste_digit(tmp_mat$transmittance), collapse = " ") |
| 307 | ), | |
| 308 | 5x | con |
| 309 | ) | |
| 310 | 5x | if (any(tmp_mat$emission > 0)) { |
| 311 | ! | writeLines( |
| 312 | ! | sprintf( |
| 313 | ! | "Ke %s", |
| 314 | ! | paste( |
| 315 | ! | paste_digit(tmp_mat$emission * tmp_mat$emission_intensity), |
| 316 | ! | collapse = " " |
| 317 | ) | |
| 318 | ), | |
| 319 | ! | con |
| 320 | ) | |
| 321 | } | |
| 322 | 5x | writeLines(sprintf("Ns %f", tmp_mat$shininess), con) |
| 323 | 5x | writeLines(sprintf("illum %i", tmp_mat$illum), con) |
| 324 | 5x | if (tmp_mat$dissolve < 1) { |
| 325 | ! | writeLines(sprintf("d %f", tmp_mat$dissolve), con) |
| 326 | } | |
| 327 | 5x | if (tmp_mat$reflection_sharpness > 0) { |
| 328 | 5x | writeLines(sprintf("sharpness %i", tmp_mat$reflection_sharpness), con) |
| 329 | } | |
| 330 | 5x | if (tmp_mat$ior != 1) { |
| 331 | ! | writeLines(sprintf("Ni %f", tmp_mat$ior), con) |
| 332 | } | |
| 333 | 5x | if (nchar(tmp_mat$diffuse_texname) > 0) { |
| 334 | ! | writeLines(sprintf("map_Kd %s", tmp_mat$diffuse_texname), con) |
| 335 | } | |
| 336 | 5x | if (nchar(tmp_mat$ambient_texname) > 0) { |
| 337 | ! | writeLines(sprintf("map_Ka %s", tmp_mat$ambient_texname), con) |
| 338 | } | |
| 339 | 5x | if (nchar(tmp_mat$emissive_texname) > 0) { |
| 340 | ! | writeLines(sprintf("map_Ke %s", tmp_mat$emissive_texname), con) |
| 341 | } | |
| 342 | 5x | if (nchar(tmp_mat$specular_texname) > 0) { |
| 343 | ! | writeLines(sprintf("map_Ks %s", tmp_mat$specular_texname), con) |
| 344 | } | |
| 345 | 5x | if (nchar(tmp_mat$normal_texname) > 0) { |
| 346 | ! | writeLines(sprintf("norm %s", tmp_mat$normal_texname), con) |
| 347 | } | |
| 348 | 5x | writeLines("\n", con) |
| 349 | } | |
| 350 | } |
| 1 | #' Surface of Revolution Mesh | |
| 2 | #' | |
| 3 | #' Revolve a radius/height profile around the Y axis to create a triangle mesh. | |
| 4 | #' | |
| 5 | #' @param profile Numeric matrix or data frame with two columns: nonnegative | |
| 6 | #' radius and Y coordinate. Rows trace the surface in order. Use a bottom-to-top | |
| 7 | #' profile for outward-facing sides; for a hollow vessel, continue over the rim | |
| 8 | #' and down the inside. Reversing the profile reverses the surface orientation. | |
| 9 | #' @param segments Default `128`. Integer number of segments around the axis, | |
| 10 | #' at least 3. | |
| 11 | #' @param smooth Default `TRUE`. Whether to include smooth vertex normals. | |
| 12 | #' Set to `FALSE` for flat triangle shading. | |
| 13 | #' @param position Default `c(0, 0, 0)`. Position of the mesh. | |
| 14 | #' @param scale Default `c(1, 1, 1)`. Scale of the mesh. A single number scales | |
| 15 | #' all axes uniformly. | |
| 16 | #' @param angle Default `c(0, 0, 0)`. Rotation angles in degrees. | |
| 17 | #' @param pivot_point Default `c(0, 0, 0)`. Point around which to rotate the mesh. | |
| 18 | #' @param order_rotation Default `c(1, 2, 3)`. Order to rotate the axes. | |
| 19 | #' @param material Default `material_list()`. Material of the mesh. | |
| 20 | #' | |
| 21 | #' @details | |
| 22 | #' Positive-radius endpoints leave open rings. To close an end, include a | |
| 23 | #' zero-radius endpoint in the profile. Each axis endpoint uses a single vertex, | |
| 24 | #' and the angular seam shares vertices, so a simple profile with both endpoints | |
| 25 | #' on the axis produces a watertight mesh without degenerate cap triangles. | |
| 26 | #' Axis points are only allowed at the endpoints. Consecutive duplicate points | |
| 27 | #' and immediate reversals are rejected; other self-intersections are not checked. | |
| 28 | #' The first and last profile rows are not automatically joined. | |
| 29 | #' | |
| 30 | #' Smooth normals average adjacent unit profile tangents. Axis endpoint normals | |
| 31 | #' point along the axis. Texture coordinates use angle for U and normalized | |
| 32 | #' distance along the profile for V. Separate texture indices allow U to wrap | |
| 33 | #' from 1 to 0 without duplicating geometry at the seam. | |
| 34 | #' | |
| 35 | #' @return A `ray_mesh` object, usable with [rasterize_scene()], | |
| 36 | #' [add_shape()], and [write_scene_to_obj()]. | |
| 37 | #' @seealso [draw_lathe_profile()] to draw a profile interactively. | |
| 38 | #' @export | |
| 39 | #' @examples | |
| 40 | #' # A closed bottle, specified as (radius, height) pairs. | |
| 41 | #' profile = rbind(c(0, 0), c(1, 0), c(1, 2), c(0.4, 2.5), | |
| 42 | #' c(0.4, 3), c(0, 3)) | |
| 43 | #' plot(profile, type="l") | |
| 44 | #' bottle = lathe_mesh(profile, material = material_list(diffuse = "steelblue")) | |
| 45 | #' rasterize_scene(bottle, lookfrom = c(5, 5, 7), lookat = c(0, 1.5, 0), | |
| 46 | #' fov = 30, light_info = directional_light(c(1, 2, 3))) | |
| 47 | #' | |
| 48 | #' # A hollow tumbler with a solid bottom and an open mouth. | |
| 49 | #' t_profile = rbind(c(0, 0), c(1, 0), c(1.1, 3), | |
| 50 | #' c(1, 3), c(0.9, 0.15), c(0, 0.15)) | |
| 51 | #' plot(t_profile, type="l") | |
| 52 | #' tumbler = lathe_mesh(t_profile) | |
| 53 | #' rasterize_scene(tumbler, lookfrom = c(5, 5, 7), lookat = c(0, 1.5, 0), | |
| 54 | #' fov = 30, light_info = directional_light(c(1, 2, 3)), | |
| 55 | #' shadow_map = FALSE) | |
| 56 | lathe_mesh = function( | |
| 57 | profile, | |
| 58 | segments = 128, | |
| 59 | smooth = TRUE, | |
| 60 | position = c(0, 0, 0), | |
| 61 | scale = c(1, 1, 1), | |
| 62 | angle = c(0, 0, 0), | |
| 63 | pivot_point = c(0, 0, 0), | |
| 64 | order_rotation = c(1, 2, 3), | |
| 65 | material = material_list() | |
| 66 | ) { | |
| 67 | 37x | if (is.data.frame(profile)) { |
| 68 | 1x | profile = as.matrix(profile) |
| 69 | } | |
| 70 | if ( | |
| 71 | 37x | !is.matrix(profile) || |
| 72 | 37x | !is.numeric(profile) || |
| 73 | 37x | ncol(profile) != 2L || |
| 74 | 37x | nrow(profile) < 2L || |
| 75 | 37x | any(!is.finite(profile)) |
| 76 | ) { | |
| 77 | 7x | stop( |
| 78 | 7x | "`profile` must be a finite numeric two-column matrix with at least two rows." |
| 79 | ) | |
| 80 | } | |
| 81 | 30x | if (any(profile[, 1] < 0)) { |
| 82 | 1x | stop("`profile` radii must be nonnegative.") |
| 83 | } | |
| 84 | if ( | |
| 85 | 29x | !is.numeric(segments) || |
| 86 | 29x | length(segments) != 1L || |
| 87 | 29x | !is.finite(segments) || |
| 88 | 29x | segments < 3 || |
| 89 | 29x | segments != floor(segments) || |
| 90 | 29x | segments > .Machine$integer.max |
| 91 | ) { | |
| 92 | 9x | stop( |
| 93 | 9x | "`segments` must be an integer of at least 3 within the R integer range." |
| 94 | ) | |
| 95 | } | |
| 96 | 20x | if (!is.logical(smooth) || length(smooth) != 1L || is.na(smooth)) { |
| 97 | 4x | stop("`smooth` must be TRUE or FALSE.") |
| 98 | } | |
| 99 | 16x | segments = as.integer(segments) |
| 100 | 16x | count = nrow(profile) |
| 101 | 16x | axis = profile[, 1] == 0 |
| 102 | 16x | if (any(axis[-c(1L, count)]) || all(axis)) { |
| 103 | 2x | stop( |
| 104 | 2x | "Zero radii are only allowed at profile endpoints, with positive radii between them." |
| 105 | ) | |
| 106 | } | |
| 107 | 14x | tangent = profile[-1L, , drop = FALSE] - profile[-count, , drop = FALSE] |
| 108 | 14x | lengths = sqrt(rowSums(tangent^2)) |
| 109 | if ( | |
| 110 | 14x | any(!is.finite(lengths)) || any(lengths == 0) || !is.finite(sum(lengths)) |
| 111 | ) { | |
| 112 | 1x | stop( |
| 113 | 1x | "Consecutive profile points must be distinct with finite, nonzero distances." |
| 114 | ) | |
| 115 | } | |
| 116 | 13x | tangent = tangent / lengths |
| 117 | 13x | averaged = rbind(tangent[1L, ], tangent) + |
| 118 | 13x | rbind(tangent, tangent[count - 1L, ]) |
| 119 | 13x | normal_lengths = sqrt(rowSums(averaged^2)) |
| 120 | 13x | if (any(normal_lengths < sqrt(.Machine$double.eps))) { |
| 121 | 1x | stop("`profile` must not reverse direction at consecutive segments.") |
| 122 | } | |
| 123 | 12x | averaged = averaged / normal_lengths |
| 124 | ||
| 125 | 12x | theta = 2 * pi * (seq_len(segments) - 1L) / segments |
| 126 | 12x | ring_sizes = ifelse(axis, 1L, segments) |
| 127 | 12x | offsets = c(0, cumsum(ring_sizes)) |
| 128 | 12x | vertices = normals = vector("list", count) |
| 129 | 12x | rings = vector("list", count) |
| 130 | 12x | for (i in seq_len(count)) { |
| 131 | 54x | angles = if (axis[i]) 0 else theta |
| 132 | 54x | vertices[[i]] = cbind( |
| 133 | 54x | profile[i, 1] * cos(angles), |
| 134 | 54x | profile[i, 2], |
| 135 | 54x | profile[i, 1] * sin(angles) |
| 136 | ) | |
| 137 | 54x | normals[[i]] = if (axis[i]) { |
| 138 | 14x | matrix(c(0, -sign(averaged[i, 1]), 0), nrow = 1L) |
| 139 | } else { | |
| 140 | 40x | cbind( |
| 141 | 40x | averaged[i, 2] * cos(angles), |
| 142 | 40x | -averaged[i, 1], |
| 143 | 40x | averaged[i, 2] * sin(angles) |
| 144 | ) | |
| 145 | } | |
| 146 | 54x | rings[[i]] = offsets[i] + seq_len(ring_sizes[i]) - 1L |
| 147 | } | |
| 148 | # UVs have an extra column at the seam, independent of geometric vertices. | |
| 149 | 12x | u = seq(0, 1, length.out = segments + 1) |
| 150 | 12x | v = c(0, cumsum(lengths)) / sum(lengths) |
| 151 | 12x | texcoords = cbind(rep(u, count), rep(v, each = segments + 1)) |
| 152 | 12x | faces = texture_faces = vector("list", count - 1L) |
| 153 | 12x | j = seq_len(segments) |
| 154 | 12x | k = j %% segments + 1L |
| 155 | 12x | for (i in seq_len(count - 1L)) { |
| 156 | 42x | lower = rings[[i]] |
| 157 | 42x | upper = rings[[i + 1L]] |
| 158 | 42x | lower_uv = (i - 1) * (segments + 1) + j - 1L |
| 159 | 42x | upper_uv = i * (segments + 1) + j - 1L |
| 160 | 42x | if (axis[i]) { |
| 161 | 7x | faces[[i]] = cbind(lower, upper[j], upper[k]) |
| 162 | 7x | texture_faces[[i]] = cbind(lower_uv, upper_uv, upper_uv + 1L) |
| 163 | 35x | } else if (axis[i + 1L]) { |
| 164 | 7x | faces[[i]] = cbind(lower[j], upper, lower[k]) |
| 165 | 7x | texture_faces[[i]] = cbind(lower_uv, upper_uv, lower_uv + 1L) |
| 166 | } else { | |
| 167 | 28x | faces[[i]] = rbind( |
| 168 | 28x | cbind(lower[j], upper[j], upper[k]), |
| 169 | 28x | cbind(lower[j], upper[k], lower[k]) |
| 170 | ) | |
| 171 | 28x | texture_faces[[i]] = rbind( |
| 172 | 28x | cbind(lower_uv, upper_uv, upper_uv + 1L), |
| 173 | 28x | cbind(lower_uv, upper_uv + 1L, lower_uv + 1L) |
| 174 | ) | |
| 175 | } | |
| 176 | } | |
| 177 | 12x | indices = do.call(rbind, faces) |
| 178 | 12x | mesh = construct_mesh( |
| 179 | 12x | vertices = do.call(rbind, vertices), |
| 180 | 12x | indices = indices, |
| 181 | 12x | normals = if (smooth) do.call(rbind, normals) else NULL, |
| 182 | 12x | norm_indices = if (smooth) indices else NULL, |
| 183 | 12x | texcoords = texcoords, |
| 184 | 12x | tex_indices = do.call(rbind, texture_faces), |
| 185 | 12x | material = material |
| 186 | ) | |
| 187 | 12x | if (any(scale != 1)) { |
| 188 | 1x | mesh = scale_mesh(mesh, scale = scale) |
| 189 | } | |
| 190 | 12x | if (any(angle != 0)) { |
| 191 | 1x | mesh = rotate_mesh( |
| 192 | 1x | mesh, |
| 193 | 1x | angle = angle, |
| 194 | 1x | pivot_point = pivot_point, |
| 195 | 1x | order_rotation = order_rotation |
| 196 | ) | |
| 197 | } | |
| 198 | 12x | translate_mesh(mesh, position) |
| 199 | } |
| 1 | #' Generate Surface | |
| 2 | #' | |
| 3 | #' @keywords internal | |
| 4 | generate_surface = function (heightmap, zscale = 1) { | |
| 5 | ! | nr = nrow(heightmap) |
| 6 | ! | nc = ncol(heightmap) |
| 7 | ! | vertex_matrix_row = matrix(seq_len(nr) - 1, nrow = nr, ncol = nc) - |
| 8 | ! | (nr - 1)/2 |
| 9 | ! | vertex_matrix_col = matrix(seq_len(nc) - 1, nrow = nr, ncol = nc, |
| 10 | ! | byrow = TRUE) - (nc - 1)/2 |
| 11 | ! | row_vert = c(vertex_matrix_row) |
| 12 | ! | col_vert = c(vertex_matrix_col) |
| 13 | ! | verts = matrix(c(row_vert, c(heightmap)/zscale, col_vert), |
| 14 | ! | ncol = 3L) |
| 15 | ! | offset_row_top = matrix(c(0L, nr, 1L), ncol = 3L, nrow = (nr - |
| 16 | ! | 1L) * (nc - 1L), byrow = TRUE) |
| 17 | ! | offset_row_bot = matrix(c(1L, nr, nr + 1L), ncol = 3L, nrow = (nr - |
| 18 | ! | 1L) * (nc - 1L), byrow = TRUE) |
| 19 | ! | indices_all = matrix(seq_len(length(heightmap)), nrow = nr, |
| 20 | ! | ncol = nc) |
| 21 | ! | indices_truncated = indices_all[seq(1L, nr - 1L), seq(1L, |
| 22 | ! | nc - 1L)] |
| 23 | ! | indices_matrix = matrix(c(indices_truncated), ncol = 3L, |
| 24 | ! | nrow = (nr - 1L) * (nc - 1L)) |
| 25 | ! | indices_top_triangle = indices_matrix + offset_row_top |
| 26 | ! | indices_bot_triangle = indices_matrix + offset_row_bot |
| 27 | ! | has_no_na = function(x) { |
| 28 | ! | na_mat = matrix(is.na(verts[x, 2]), ncol = 3L, nrow = length(x)/3L) |
| 29 | ! | return(na_mat[, 1L] | na_mat[, 2L] | na_mat[, 3L]) |
| 30 | } | |
| 31 | ! | remove_tri_top = has_no_na(indices_top_triangle) |
| 32 | ! | remove_tri_bot = has_no_na(indices_bot_triangle) |
| 33 | ! | remove_tri = remove_tri_top | remove_tri_bot |
| 34 | ! | indices_top_triangle = indices_top_triangle[!remove_tri, |
| 35 | ] | |
| 36 | ! | indices_bot_triangle = indices_bot_triangle[!remove_tri, |
| 37 | ] | |
| 38 | ! | interleved_triangles = matrix(c(t(cbind(indices_top_triangle, |
| 39 | ! | indices_bot_triangle))), nrow = 3L) |
| 40 | ! | verts[is.na(verts[, 2L]), 2L] = mean(verts[, 2L], na.rm = TRUE) |
| 41 | ! | texcoords_x = matrix(seq(0, 1, length.out = nr), nrow = nr, |
| 42 | ! | ncol = nc, byrow = FALSE) |
| 43 | ! | texcoords_y = matrix(seq(1, 0, length.out = nc), nrow = nr, |
| 44 | ! | ncol = nc, byrow = TRUE) |
| 45 | ! | texcoords = matrix(c(c(texcoords_x), c(texcoords_y)), ncol = 2L) |
| 46 | ! | return(list(verts = verts, inds = interleved_triangles, |
| 47 | ! | texcoords = texcoords)) |
| 48 | } |
| 1 | #'@title Scene From List | |
| 2 | #' | |
| 3 | #'@description Fast generation of rayvertex scenes from a list of objects (much faster than calling | |
| 4 | #'[add_shape()] on each object individually to build the scene). This returns a `ray_scene` object | |
| 5 | #'that cdoes | |
| 6 | #' | |
| 7 | #'@param scene_list List containing rayvertex mesh objects. | |
| 8 | #' | |
| 9 | #'@return `ray_scene` containing mesh info. | |
| 10 | #'@export | |
| 11 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 12 | #' #Build a scene out of cubes including 87 * 61 = 5307 objects | |
| 13 | #' scene = list() | |
| 14 | #' volcol = rainbow(103) | |
| 15 | #' counter = 1 | |
| 16 | #' for(i in 1:nrow(volcano)) { | |
| 17 | #' for(j in 1:ncol(volcano)) { | |
| 18 | #' scene[[counter]] = cube_mesh(position = c(i,(volcano[i,j]-94),j), | |
| 19 | #' material = material_list(diffuse = volcol[volcano[i,j]-92], | |
| 20 | #' ambient = volcol[volcano[i,j]-92], | |
| 21 | #' ambient_intensity = 0.2)) | |
| 22 | #' counter = counter + 1 | |
| 23 | #' } | |
| 24 | #' } | |
| 25 | #' #Quickly generate the | |
| 26 | #' new_scene = scene_from_list(scene) | |
| 27 | #' new_scene |> | |
| 28 | #' rotate_mesh(c(0,10,0), pivot_point = c(44,0,31)) |> | |
| 29 | #' add_shape(xz_rect_mesh(position=c(44,0,31),scale=500, | |
| 30 | #' material = material_list(diffuse="lightblue", | |
| 31 | #' ambient = "lightblue", | |
| 32 | #' ambient_intensity = 0.2))) |> | |
| 33 | #' rasterize_scene(lookfrom=c(500,500,500), lookat = c(44.00, 40.50, 31.00), | |
| 34 | #' width=800,height=800, fov=0, ortho_dimensions = c(140,140), | |
| 35 | #' light_info = directional_light(c(-0.6,1,0.6))) | |
| 36 | scene_from_list = function(scene_list) { | |
| 37 | ! | scene_list = Filter(Negate(is.null), scene_list) |
| 38 | ! | n = length(scene_list) |
| 39 | ! | n_shapes = 0L |
| 40 | ||
| 41 | ! | n_materials = 0L |
| 42 | ! | n_material_hashes = 0L |
| 43 | ! | number_materials = 0L |
| 44 | ||
| 45 | #Count the total number of shapes, materials, and material hashes | |
| 46 | ! | for (i in seq_len(n)) { |
| 47 | ! | n_shapes = n_shapes + length(scene_list[[i]]$shapes) |
| 48 | ! | n_materials = n_materials + length(scene_list[[i]]$materials) |
| 49 | ! | n_material_hashes = n_material_hashes + |
| 50 | ! | length(attr(scene_list[[i]], "material_hashes")) |
| 51 | } | |
| 52 | ||
| 53 | #initialize the `ray_scene` object with the right number of entries | |
| 54 | ! | new_scene = list() |
| 55 | ! | new_scene$shapes = vector(mode = "list", n) |
| 56 | ! | new_scene$vertices = vector(mode = "list", n) |
| 57 | ! | new_scene$texcoords = vector(mode = "list", n) |
| 58 | ! | new_scene$normals = vector(mode = "list", n) |
| 59 | ! | new_scene$materials = vector(mode = "list", n) |
| 60 | ! | attr(new_scene, "material_hashes") = vector(mode = "character") |
| 61 | #Fill in each shape and corresponding vertex info matrices | |
| 62 | ! | for (i in seq_len(n)) { |
| 63 | #Assign the shapes in the nth list entry | |
| 64 | ! | temp_scene = merge_scene(scene_list[[i]], TRUE) |
| 65 | ! | new_scene$shapes[[i]] = ray_shape(temp_scene$shapes[[1]]) |
| 66 | ||
| 67 | #Assign the vertex info for the nth list try | |
| 68 | ! | new_scene$vertices[[i]] = ray_vertex_data((temp_scene$vertices)) |
| 69 | ! | new_scene$texcoords[[i]] = ray_vertex_data((temp_scene$texcoords)) |
| 70 | ! | new_scene$normals[[i]] = ray_vertex_data((temp_scene$normals)) |
| 71 | ! | for (j in seq_along(temp_scene$materials)) { |
| 72 | ! | new_scene$materials[[i]][[j]] = (temp_scene$materials[[j]]) |
| 73 | } | |
| 74 | ! | attr(new_scene, "material_hashes") = c( |
| 75 | ! | attr(new_scene, "material_hashes"), |
| 76 | ! | attr(scene_list[[i]], "material_hashes") |
| 77 | ) | |
| 78 | } | |
| 79 | ! | new_scene$shapes = do.call(vctrs::vec_c, new_scene$shapes) |
| 80 | ! | new_scene$vertices = do.call(vctrs::vec_c, new_scene$vertices) |
| 81 | ! | new_scene$texcoords = do.call(vctrs::vec_c, new_scene$texcoords) |
| 82 | ! | new_scene$normals = do.call(vctrs::vec_c, new_scene$normals) |
| 83 | # new_scene$materials = do.call(vctrs::vec_c, new_scene$materials) | |
| 84 | ||
| 85 | ! | class(new_scene) = c("ray_mesh", "list") |
| 86 | ! | return(new_scene) |
| 87 | } |
| 1 | #' @title Add Plane UV Mapping to Mesh | |
| 2 | #' | |
| 3 | #' @description Applies a planar UV mapping to a mesh based on a given direction and set of U/V vectors. | |
| 4 | #' If `full_mesh_bbox` is true, the UV mapping is scaled based on the bounding box | |
| 5 | #' of the entire mesh. If false, each shape's bounding box is used. | |
| 6 | #' One of direction/u/v must be `NULL` and will be calculated from the others. | |
| 7 | #' | |
| 8 | #' @param mesh The mesh to which the UV mapping will be applied. | |
| 9 | #' @param direction Default `c(0, 1, 0)`. A vector specifying the direction for | |
| 10 | #' UV mapping. If not specified and `u`/`v` are both specified, this will be ignored. | |
| 11 | #' @param u Default `NULL`. A vector specifying the u direction. | |
| 12 | #' @param v Default `NULL`. A vector specifying the v direction. | |
| 13 | #' @param override_existing Default `FALSE`. Specifies whether existing UV | |
| 14 | #' coordinates should be overridden. | |
| 15 | #' @param full_mesh_bbox Default `TRUE`. Specifies whether the full mesh's | |
| 16 | #' bounding box is used for UV mapping. | |
| 17 | #' | |
| 18 | #' @return Modified mesh with added UV mapping. | |
| 19 | #' @export | |
| 20 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 21 | #' #Let's construct a mesh from the volcano dataset | |
| 22 | #' #Build the vertex matrix | |
| 23 | #' vertex_list = list() | |
| 24 | #' counter = 1 | |
| 25 | #' for(i in 1:nrow(volcano)) { | |
| 26 | #' for(j in 1:ncol(volcano)) { | |
| 27 | #' vertex_list[[counter]] = matrix(c(j,volcano[i,j]/3,i), ncol=3) | |
| 28 | #' counter = counter + 1 | |
| 29 | #' } | |
| 30 | #' } | |
| 31 | #' vertices = do.call(rbind,vertex_list) | |
| 32 | #' | |
| 33 | #' #Build the index matrix | |
| 34 | #' index_list = list() | |
| 35 | #' counter = 0 | |
| 36 | #' for(i in 1:(nrow(volcano)-1)) { | |
| 37 | #' for(j in 1:(ncol(volcano)-1)) { | |
| 38 | #' index_list[[counter+1]] = matrix(c(counter,counter+ncol(volcano),counter+1, | |
| 39 | #' counter+ncol(volcano),counter+ncol(volcano)+1,counter + 1), | |
| 40 | #' nrow=2, ncol=3, byrow=TRUE) | |
| 41 | #' counter = counter + 1 | |
| 42 | #' } | |
| 43 | #' counter = counter + 1 | |
| 44 | #' } | |
| 45 | #' indices = do.call("rbind",index_list) | |
| 46 | #' | |
| 47 | #' #Create a checkerboard image | |
| 48 | #' create_checkerboard_texture = function(filename, n = 16) { | |
| 49 | #' old_par = par(no.readonly = TRUE) | |
| 50 | #' on.exit(par(old_par)) | |
| 51 | #' plot.new() | |
| 52 | #' par(mar = c(0, 0, 0, 0)) | |
| 53 | #' checkerboard = matrix(c(1, 0), nrow = n+1, ncol = n) | |
| 54 | #' png(filename, width = 800, height = 800) | |
| 55 | #' image(1:(n+1), 1:n, checkerboard, col = c("dodgerblue", "red"), | |
| 56 | #' axes = FALSE, xlab = "", ylab = "") | |
| 57 | #' dev.off() | |
| 58 | #' } | |
| 59 | #' checkerboard_file = tempfile(fileext = ".png") | |
| 60 | #' create_checkerboard_texture(checkerboard_file) | |
| 61 | #' rayimage::plot_image(checkerboard_file) | |
| 62 | #' | |
| 63 | #' #Construct the mesh | |
| 64 | #' volc_mesh = construct_mesh(vertices = vertices, indices = indices, | |
| 65 | #' material = material_list(type="phong", diffuse="darkred", | |
| 66 | #' ambient = "darkred", ambient_intensity=0.2)) | |
| 67 | #' | |
| 68 | #' | |
| 69 | #' #Set the direction so that the checkerboard will be mapped to the surface like a carpet | |
| 70 | #' uv = add_plane_uv_mesh(volc_mesh, direction=c(0,200,0), u = c(1,0,0)) | |
| 71 | #' uv = set_material(uv, texture_location = checkerboard_file, | |
| 72 | #' ambient = "white", ambient_intensity=0.1) | |
| 73 | #' #Rasterize the scene | |
| 74 | #' rasterize_scene(center_mesh(uv), lookfrom=c(200,200,200),fov=0,width=1200,height=1200, | |
| 75 | #' light_info = directional_light(c(0,1,1)) |> | |
| 76 | #' add_light(directional_light(c(1,1,-1))),ortho_dimensions=c(120,120)) | |
| 77 | #' | |
| 78 | #' #Set the direction so that the checkerboard will be mapped directly at the camera | |
| 79 | #' uv = add_plane_uv_mesh(volc_mesh, direction=c(200,200,200), v = c(-1,1,-1)) | |
| 80 | #' uv = set_material(uv, texture_location = checkerboard_file, | |
| 81 | #' ambient = "white", ambient_intensity=0.1) | |
| 82 | #' #Rasterize the scene | |
| 83 | #' rasterize_scene(center_mesh(uv), lookfrom=c(200,200,200),fov=0,width=1200,height=1200, | |
| 84 | #' light_info = directional_light(c(0,1,1)) |> | |
| 85 | #' add_light(directional_light(c(1,1,-1))), ortho_dimensions=c(120,120)) | |
| 86 | add_plane_uv_mesh = function( | |
| 87 | mesh, | |
| 88 | direction = c(0, 1, 0), | |
| 89 | u = NULL, | |
| 90 | v = NULL, | |
| 91 | override_existing = FALSE, | |
| 92 | full_mesh_bbox = TRUE | |
| 93 | ) { | |
| 94 | ! | duv = c(FALSE, FALSE, FALSE) |
| 95 | if ( | |
| 96 | ! | (is.null(direction) || missing(direction)) && !is.null(u) && !is.null(v) |
| 97 | ) { | |
| 98 | ! | duv[1] = TRUE |
| 99 | } | |
| 100 | ! | if (!is.null(direction) && is.null(u) && !is.null(v)) { |
| 101 | ! | duv[2] = TRUE |
| 102 | } | |
| 103 | ! | if (!is.null(direction) && !is.null(u) && is.null(v)) { |
| 104 | ! | duv[3] = TRUE |
| 105 | } | |
| 106 | ! | if (sum(duv) != 1) { |
| 107 | ! | stop("Exactly one of `direction`/`u`/`v` must be NULL") |
| 108 | } | |
| 109 | ! | if (duv[1]) { |
| 110 | ! | u = u / sqrt(sum(u^2)) |
| 111 | ! | v = v / sqrt(sum(v^2)) |
| 112 | ! | direction = cross_prod(u, v) |
| 113 | ! | } else if (duv[2]) { |
| 114 | ! | direction = direction / sqrt(sum(direction^2)) |
| 115 | ! | v = v / sqrt(sum(v^2)) |
| 116 | ! | u = cross_prod(direction, v) |
| 117 | } else { | |
| 118 | ! | direction = direction / sqrt(sum(direction^2)) |
| 119 | ! | u = u / sqrt(sum(u^2)) |
| 120 | ! | v = cross_prod(u, direction) |
| 121 | } | |
| 122 | ||
| 123 | ! | rot_mat = matrix(c(u, direction, v), nrow = 3, ncol = 3, byrow = TRUE) |
| 124 | ||
| 125 | ! | if (full_mesh_bbox) { |
| 126 | ! | all_verts = do.call("rbind", mesh$vertices) |
| 127 | ! | all_verts = t(apply(all_verts, 1, \(x) rot_mat %*% x)) |
| 128 | ! | xrange = range(all_verts[, 1]) |
| 129 | ! | zrange = range(all_verts[, 3]) |
| 130 | ! | stopifnot(xrange[1] != xrange[2] && zrange[1] != zrange[2]) |
| 131 | } | |
| 132 | # Iterate over shapes | |
| 133 | ! | for (i in seq_along(mesh$shapes)) { |
| 134 | ! | shape = mesh$shapes[[i]] |
| 135 | ||
| 136 | # Check if UV coords exist and whether they should be overridden | |
| 137 | ! | if (!override_existing && any(shape$has_vertex_tex)) next |
| 138 | ||
| 139 | ! | vertices_bbox = mesh$vertices[[i]] |
| 140 | ! | vertices_bbox = t(apply(vertices_bbox, 1, \(x) rot_mat %*% x)) |
| 141 | ||
| 142 | ! | if (!full_mesh_bbox) { |
| 143 | ! | xrange = range(vertices_bbox[, 1]) |
| 144 | ! | zrange = range(vertices_bbox[, 3]) |
| 145 | ! | stopifnot(xrange[1] != xrange[2] && zrange[1] != zrange[2]) |
| 146 | } | |
| 147 | ||
| 148 | ! | vertices_bbox[, 1] = (vertices_bbox[, 1] - xrange[1]) / |
| 149 | ! | (xrange[2] - xrange[1]) |
| 150 | ! | vertices_bbox[, 3] = (vertices_bbox[, 3] - zrange[1]) / |
| 151 | ! | (zrange[2] - zrange[1]) |
| 152 | ||
| 153 | # Initialize a matrix to store UV coordinates | |
| 154 | ! | uv_coords = vertices_bbox[, c(3, 1)] |
| 155 | ||
| 156 | # Assign the UV coords to the shape | |
| 157 | ! | mesh$texcoords[i] = ray_vertex_data(uv_coords) |
| 158 | ! | mesh$shapes[[i]]$tex_indices = mesh$shapes[[i]]$indices |
| 159 | ! | mesh$shapes[[i]]$has_vertex_tex = rep(TRUE, nrow(mesh$shapes[[i]]$indices)) |
| 160 | } | |
| 161 | ||
| 162 | ! | return(mesh) |
| 163 | } | |
| 164 | ||
| 165 | #' @title Add Sphere UV Mapping to Mesh | |
| 166 | #' | |
| 167 | #' @description Applies a planar UV mapping to a mesh based on a spherical | |
| 168 | #' direction from the origin. | |
| 169 | #' | |
| 170 | #' @param mesh The mesh to which the UV mapping will be applied. | |
| 171 | #' @param origin Default `c(0, 0, 0)`. A vector specifying the origin to | |
| 172 | #' apply spherical UV coordinates. | |
| 173 | #' @param override_existing Default `FALSE`. Specifies whether existing UV | |
| 174 | #' coordinates should be overridden. | |
| 175 | #' | |
| 176 | #' @return Modified mesh with added UV mapping. | |
| 177 | #' @export | |
| 178 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 179 | #' #Let's construct a mesh from the volcano dataset | |
| 180 | #' | |
| 181 | add_sphere_uv_mesh = function( | |
| 182 | mesh, | |
| 183 | origin = c(0, 0, 0), | |
| 184 | override_existing = FALSE | |
| 185 | ) { | |
| 186 | 1x | stopifnot(length(origin) == 3 && is.numeric(origin)) |
| 187 | # Iterate over shapes | |
| 188 | 1x | for (i in seq_along(mesh$shapes)) { |
| 189 | 1x | shape = mesh$shapes[[i]] |
| 190 | ||
| 191 | # Check if UV coords exist and whether they should be overridden | |
| 192 | ! | if (!override_existing && any(shape$has_vertex_tex)) next |
| 193 | ||
| 194 | 1x | vertices = mesh$vertices[[i]] |
| 195 | ||
| 196 | 1x | vertices_centered = vertices - |
| 197 | 1x | matrix(origin, nrow = nrow(vertices), ncol = 3, byrow = TRUE) |
| 198 | ||
| 199 | # Initialize a matrix to store UV coordinates | |
| 200 | 1x | uv_coords = matrix(0, nrow = nrow(vertices_centered), ncol = 2) |
| 201 | ||
| 202 | # Calculate spherical coordinates | |
| 203 | 1x | for (j in 1:nrow(vertices_centered)) { |
| 204 | 98x | x = vertices_centered[j, 1] |
| 205 | 98x | y = vertices_centered[j, 2] |
| 206 | 98x | z = vertices_centered[j, 3] |
| 207 | ||
| 208 | 98x | r = sqrt(x^2 + y^2 + z^2) |
| 209 | 98x | theta = acos(y / r) |
| 210 | 98x | phi = -atan2(z, x) |
| 211 | # Normalize theta and phi to [0, 1] range | |
| 212 | 98x | u = (phi + pi) / (2 * pi) |
| 213 | 98x | v = 1 - theta / pi |
| 214 | ||
| 215 | 98x | uv_coords[j, ] = c(u, v) |
| 216 | } | |
| 217 | ||
| 218 | # Assign the UV coords to the shape | |
| 219 | 1x | mesh$texcoords[i] = ray_vertex_data(uv_coords) |
| 220 | 1x | mesh$shapes[[i]]$tex_indices = mesh$shapes[[i]]$indices |
| 221 | 1x | mesh$shapes[[i]]$has_vertex_tex = rep(TRUE, nrow(mesh$shapes[[i]]$indices)) |
| 222 | } | |
| 223 | ||
| 224 | 1x | return(mesh) |
| 225 | } | |
| 226 | ||
| 227 | #' @title Normalize Vector | |
| 228 | #' | |
| 229 | #' @description Computes a normalized vector | |
| 230 | #' | |
| 231 | #' @param v A numeric vector | |
| 232 | #' | |
| 233 | #' @return Normilzed vector | |
| 234 | #' | |
| 235 | #' @keywords internal | |
| 236 | normalize = function(v) { | |
| 237 | ! | s = sqrt(sum(v * v)) |
| 238 | ! | if (s == 0) stop("Zero-length vector") |
| 239 | ! | return(v / s) |
| 240 | } | |
| 241 | ||
| 242 | #' @title Cross Product | |
| 243 | #' | |
| 244 | #' @description Computes the cross product of two 3-dimensional vectors. | |
| 245 | #' | |
| 246 | #' @param x A numeric vector representing the first 3D vector. | |
| 247 | #' @param y A numeric vector representing the second 3D vector. | |
| 248 | #' | |
| 249 | #' @return A numeric vector representing the cross product of `x` and `y`. | |
| 250 | #' | |
| 251 | #' @keywords internal | |
| 252 | cross_prod = function(x, y) { | |
| 253 | 3046x | return(c( |
| 254 | 3046x | x[2] * y[3] - x[3] * y[2], |
| 255 | 3046x | -(x[1] * y[3] - x[3] * y[1]), |
| 256 | 3046x | x[1] * y[2] - x[2] * y[1] |
| 257 | )) | |
| 258 | } | |
| 259 | ||
| 260 | #' @title Generate Rotation Matrix from Direction | |
| 261 | #' | |
| 262 | #' @description Internal function to generate a rotation matrix that aligns the | |
| 263 | #' Y-axis with a given direction vector. It uses the Rodrigues' rotation formula. | |
| 264 | #' | |
| 265 | #' @param direction Default `c(0, 1, 0)`. A 3D vector representing the direction. | |
| 266 | #' The function normalizes this vector. | |
| 267 | #' @param up Default `c(0, 1, 0)`. A 3D vector representing the up direction. | |
| 268 | #' | |
| 269 | #' @return A 3x3 rotation matrix. | |
| 270 | #' | |
| 271 | #' @keywords internal | |
| 272 | generate_rotation_matrix_from_direction = function( | |
| 273 | direction = c(0, 1, 0), | |
| 274 | up = c(0, 1, 0) | |
| 275 | ) { | |
| 276 | # Ensure the vectors are unit vectors | |
| 277 | ! | direction = direction / sqrt(sum(direction^2)) |
| 278 | ! | up = up / sqrt(sum(direction^2)) |
| 279 | ||
| 280 | # The rotation axis is the cross product of the direction vector and the y-axis | |
| 281 | ! | rotation_axis = cross_prod(matrix(direction, ncol = 3), matrix(up, ncol = 3)) |
| 282 | ||
| 283 | # The sine of the angle is the magnitude of the rotation axis | |
| 284 | ! | sin_angle = sqrt(sum(rotation_axis^2)) |
| 285 | ||
| 286 | # The cosine of the angle is the dot product of the direction and the y-axis | |
| 287 | ! | cos_angle = sum(direction * up) |
| 288 | ||
| 289 | # Normalizing the rotation axis | |
| 290 | ! | rotation_axis = rotation_axis / sin_angle |
| 291 | ||
| 292 | # The rotation axis components | |
| 293 | ! | ux = rotation_axis[1] |
| 294 | ! | uy = rotation_axis[2] |
| 295 | ! | uz = rotation_axis[3] |
| 296 | ||
| 297 | # Constructing the rotation matrix using Rodrigues' rotation formula | |
| 298 | ! | R = matrix( |
| 299 | ! | c( |
| 300 | ! | cos_angle + ux^2 * (1 - cos_angle), |
| 301 | ! | ux * uy * (1 - cos_angle) - uz * sin_angle, |
| 302 | ! | ux * uz * (1 - cos_angle) + uy * sin_angle, |
| 303 | ! | uy * ux * (1 - cos_angle) + uz * sin_angle, |
| 304 | ! | cos_angle + uy^2 * (1 - cos_angle), |
| 305 | ! | uy * uz * (1 - cos_angle) - ux * sin_angle, |
| 306 | ! | uz * ux * (1 - cos_angle) - uy * sin_angle, |
| 307 | ! | uz * uy * (1 - cos_angle) + ux * sin_angle, |
| 308 | ! | cos_angle + uz^2 * (1 - cos_angle) |
| 309 | ), | |
| 310 | ! | nrow = 3, |
| 311 | ! | byrow = TRUE |
| 312 | ) | |
| 313 | ||
| 314 | ! | return(t(R)) |
| 315 | } |
| 1 | #' Sweep interpolation helper | |
| 2 | #' @keywords internal | |
| 3 | #' @noRd | |
| 4 | sweep_control_points = function(s_mat) { | |
| 5 | 45x | nr = nrow(s_mat) |
| 6 | 45x | nr2 = nr - 2 |
| 7 | 45x | if (nr == 1) { |
| 8 | ! | stop("Only one point passed, unable to draw curve.") |
| 9 | } | |
| 10 | 45x | if (nr == 2) { |
| 11 | 32x | vec = s_mat[2, ] - s_mat[1, ] |
| 12 | 32x | return(list(matrix( |
| 13 | 32x | c( |
| 14 | 32x | s_mat[1, ], |
| 15 | 32x | s_mat[1, ] + 1 / 3 * vec, |
| 16 | 32x | s_mat[1, ] + 2 / 3 * vec, |
| 17 | 32x | s_mat[2, ] |
| 18 | ), | |
| 19 | 32x | ncol = 3, |
| 20 | 32x | byrow = TRUE |
| 21 | ))) | |
| 22 | } | |
| 23 | 13x | spline_matrix = diag(nr2) * |
| 24 | 13x | 4 + |
| 25 | 13x | diag(nr2 + 1)[-1, -(nr2 + 1)] + |
| 26 | 13x | t(diag(nr2 + 1)[-1, -(nr2 + 1)]) |
| 27 | 13x | inv_spline_matrix = solve(spline_matrix) |
| 28 | 13x | if (nr == 3) { |
| 29 | 8x | new_b = 1 / 4 * (6 * s_mat[2, ] - s_mat[1, ] - s_mat[3, ]) |
| 30 | 8x | b_vec = rbind(s_mat[1, ], new_b, s_mat[3, ]) |
| 31 | 8x | return_points = list() |
| 32 | 8x | for (i in seq_len(nrow(s_mat) - 1)) { |
| 33 | 16x | vec = b_vec[i + 1, ] - b_vec[i, ] |
| 34 | 16x | return_points[[i]] = matrix( |
| 35 | 16x | c( |
| 36 | 16x | s_mat[i, ], |
| 37 | 16x | b_vec[i, ] + 1 / 3 * vec, |
| 38 | 16x | b_vec[i, ] + 2 / 3 * vec, |
| 39 | 16x | s_mat[i + 1, ] |
| 40 | ), | |
| 41 | 16x | ncol = 3, |
| 42 | 16x | byrow = TRUE |
| 43 | ) | |
| 44 | } | |
| 45 | 8x | return(return_points) |
| 46 | } | |
| 47 | 5x | s_vec = matrix(0, nrow = nr - 2, ncol = 3) |
| 48 | 5x | s_vec[1, ] = 6 * s_mat[2, ] - s_mat[1, ] |
| 49 | 5x | for (i in seq_len(nr - 4)) { |
| 50 | 5x | s_vec[i + 1, ] = 6 * s_mat[i + 2, ] |
| 51 | } | |
| 52 | 5x | s_vec[nr - 2, ] = 6 * s_mat[nr - 1, ] - s_mat[nr, ] |
| 53 | 5x | b_vec = inv_spline_matrix %*% s_vec |
| 54 | 5x | b_vec = rbind(s_mat[1, ], b_vec, s_mat[nr, ]) |
| 55 | 5x | return_points = list() |
| 56 | 5x | for (i in seq_len(nrow(s_mat) - 1)) { |
| 57 | 20x | vec = b_vec[i + 1, ] - b_vec[i, ] |
| 58 | 20x | return_points[[i]] = matrix( |
| 59 | 20x | c( |
| 60 | 20x | s_mat[i, ], |
| 61 | 20x | b_vec[i, ] + 1 / 3 * vec, |
| 62 | 20x | b_vec[i, ] + 2 / 3 * vec, |
| 63 | 20x | s_mat[ |
| 64 | 20x | i + |
| 65 | 20x | 1, |
| 66 | ] | |
| 67 | ), | |
| 68 | 20x | ncol = 3, |
| 69 | 20x | byrow = TRUE |
| 70 | ) | |
| 71 | } | |
| 72 | 5x | return(return_points) |
| 73 | } | |
| 74 | ||
| 75 | #' Sweep interpolation helper | |
| 76 | #' @keywords internal | |
| 77 | #' @noRd | |
| 78 | sweep_control_points_straight = function(s_mat) { | |
| 79 | 1x | nr = nrow(s_mat) |
| 80 | 1x | if (nr == 1) { |
| 81 | ! | stop("Only one point passed, unable to draw curve.") |
| 82 | } | |
| 83 | 1x | return_points = list() |
| 84 | 1x | for (i in seq_len(nrow(s_mat) - 1)) { |
| 85 | 2x | vec = s_mat[i + 1, ] - s_mat[i, ] |
| 86 | 2x | return_points[[i]] = matrix( |
| 87 | 2x | c( |
| 88 | 2x | s_mat[i, ], |
| 89 | 2x | s_mat[i, ] + 1 / 3 * vec, |
| 90 | 2x | s_mat[i, ] + 2 / 3 * vec, |
| 91 | 2x | s_mat[ |
| 92 | 2x | i + |
| 93 | 2x | 1, |
| 94 | ] | |
| 95 | ), | |
| 96 | 2x | ncol = 3, |
| 97 | 2x | byrow = TRUE |
| 98 | ) | |
| 99 | } | |
| 100 | 1x | return(return_points) |
| 101 | } | |
| 102 | ||
| 103 | #' Sweep interpolation helper | |
| 104 | #' @keywords internal | |
| 105 | #' @noRd | |
| 106 | sweep_quad_in_out = function(t) { | |
| 107 | ! | ifelse(t * 2 <= 1, (2 * t)^2 / 2, (2 - (2 * t - 2)^2) / 2) |
| 108 | } | |
| 109 | ||
| 110 | #' Sweep interpolation helper | |
| 111 | #' @keywords internal | |
| 112 | #' @noRd | |
| 113 | sweep_cubic_in_out = function(t) { | |
| 114 | ! | ifelse(t * 2 <= 1, (2 * t)^3 / 2, ((2 * t - 2)^3 + 2) / 2) |
| 115 | } | |
| 116 | ||
| 117 | #' Sweep interpolation helper | |
| 118 | #' @keywords internal | |
| 119 | #' @noRd | |
| 120 | sweep_exp_in_out = function(t) { | |
| 121 | ! | ifelse(t * 2 <= 1, 2^(-10 * (1 - 2 * t)) / 2, (2 - 2^(-10 * (2 * t - 1))) / 2) |
| 122 | } | |
| 123 | ||
| 124 | #' Sweep interpolation helper | |
| 125 | #' @keywords internal | |
| 126 | #' @noRd | |
| 127 | sweep_bezier = function(cp, t) { | |
| 128 | 11777x | return( |
| 129 | 11777x | cp[1, ] * |
| 130 | 11777x | (1 - t)^3 + |
| 131 | 11777x | cp[2, ] * 3 * t * (1 - t)^2 + |
| 132 | 11777x | cp[3, ] * 3 * t^2 * (1 - t) + |
| 133 | 11777x | cp[4, ] * |
| 134 | 11777x | t^3 |
| 135 | ) | |
| 136 | } | |
| 137 | ||
| 138 | #' Sweep interpolation helper | |
| 139 | #' @keywords internal | |
| 140 | #' @noRd | |
| 141 | sweep_bezier_deriv = function(cp, t) { | |
| 142 | 12107x | return( |
| 143 | 12107x | -3 * |
| 144 | 12107x | cp[1, ] * |
| 145 | 12107x | (1 - t)^2 + |
| 146 | 12107x | cp[2, ] * 3 * (1 - t)^2 - |
| 147 | 12107x | cp[2, ] * 6 * t * (1 - t) + |
| 148 | 12107x | cp[3, ] * |
| 149 | 12107x | 6 * |
| 150 | 12107x | t * |
| 151 | 12107x | (1 - t) - |
| 152 | 12107x | cp[3, ] * 3 * t^2 + |
| 153 | 12107x | 3 * cp[4, ] * t^2 |
| 154 | ) | |
| 155 | } | |
| 156 | ||
| 157 | #' Sweep interpolation helper | |
| 158 | #' @keywords internal | |
| 159 | #' @noRd | |
| 160 | sweep_bezier_2nd_deriv = function(cp, t) { | |
| 161 | 56x | return( |
| 162 | 56x | 6 * |
| 163 | 56x | cp[1, ] * |
| 164 | 56x | (1 - t) - |
| 165 | 56x | cp[2, ] * 6 * (1 - t) - |
| 166 | 56x | cp[2, ] * 6 * (1 - t) + |
| 167 | 56x | cp[2, ] * 6 * t + |
| 168 | 56x | cp[3, ] * 6 * (1 - t) - |
| 169 | 56x | cp[3, ] * 6 * t - |
| 170 | 56x | cp[3, ] * 6 * t + |
| 171 | 56x | 6 * cp[4, ] * t |
| 172 | ) | |
| 173 | } |
| 1 | #'@title Displace a Mesh | |
| 2 | #' | |
| 3 | #' @param mesh The mesh. | |
| 4 | #' @param displacement_texture Image or matrix/array that will be used to displace the mesh | |
| 5 | #' @param displacement_scale Default `1`. Intensity of the displacement effect. | |
| 6 | #' Higher values result in greater displacement. | |
| 7 | #' @param displacement_vector Default `FALSE`. Whether to use vector displacement. | |
| 8 | #' If `TRUE`, the displacement texture is interpreted as providing a 3D displacement vector. | |
| 9 | #' Otherwise, the texture is interpreted as providing a scalar displacement. | |
| 10 | #' @param id Default `NA` (all shapes). The shape index to have new normals calculated. | |
| 11 | #' @param verbose Default `TRUE`. Whether to print displacement texture information. | |
| 12 | #' | |
| 13 | #'@return raymesh object | |
| 14 | #'@export | |
| 15 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 16 | #' #Let's construct a mesh from the volcano dataset | |
| 17 | displace_mesh = function( | |
| 18 | mesh, | |
| 19 | displacement_texture, | |
| 20 | displacement_scale = 1, | |
| 21 | displacement_vector = FALSE, | |
| 22 | id = NA, | |
| 23 | verbose = TRUE | |
| 24 | ) { | |
| 25 | 1x | stopifnot(inherits(mesh, "ray_mesh")) |
| 26 | 1x | displacement_texture = rayimage::ray_read_image(displacement_texture) |
| 27 | 1x | if (displacement_vector) { |
| 28 | ! | disp_x = displacement_texture[,, 1] |
| 29 | ! | disp_y = displacement_texture[,, 2] |
| 30 | ! | disp_z = displacement_texture[,, 3] |
| 31 | } else { | |
| 32 | 1x | disp_x = t(displacement_texture[,, 1]) |
| 33 | 1x | disp_y = matrix(0, 0, 0) |
| 34 | 1x | disp_z = matrix(0, 0, 0) |
| 35 | } | |
| 36 | 1x | if (verbose) { |
| 37 | ! | message(sprintf( |
| 38 | ! | "Displacing mesh with %ix%i texture", |
| 39 | ! | dim(displacement_texture)[1], |
| 40 | ! | dim(displacement_texture)[2] |
| 41 | )) | |
| 42 | } | |
| 43 | 1x | if (is.na(id)) { |
| 44 | 1x | for (i in seq_len(length(mesh$shapes))) { |
| 45 | 1x | tangents = matrix(0, 0, 0) |
| 46 | 1x | tangent_right_handed = vector("logical", 0) |
| 47 | 1x | if (displacement_vector) { |
| 48 | ! | tangent_info = CalculateTangents(mesh, i - 1) |
| 49 | ! | tangents = tangent_info$tangents |
| 50 | ! | tangent_right_handed = tangent_info$tangent_right_handed |
| 51 | } | |
| 52 | 1x | new_vertices = DisplaceMesh( |
| 53 | 1x | mesh, |
| 54 | 1x | disp_x, |
| 55 | 1x | disp_y, |
| 56 | 1x | disp_z, |
| 57 | 1x | tangents, |
| 58 | 1x | tangent_right_handed, |
| 59 | 1x | displacement_scale, |
| 60 | 1x | displacement_vector, |
| 61 | 1x | i - 1 |
| 62 | ) | |
| 63 | 1x | mesh$vertices[i] = ray_vertex_data(new_vertices) |
| 64 | } | |
| 65 | 1x | mesh = smooth_normals_mesh(mesh) |
| 66 | } else { | |
| 67 | ! | stopifnot(id <= length(mesh$shapes)) |
| 68 | ! | tangents = matrix(0, 0, 0) |
| 69 | ! | tangent_right_handed = vector("logical", 0) |
| 70 | ! | if (displacement_vector) { |
| 71 | ! | tangent_info = CalculateTangents(mesh, id - 1) |
| 72 | ! | tangents = tangent_info$tangents |
| 73 | ! | tangent_right_handed = tangent_info$tangent_right_handed |
| 74 | } | |
| 75 | ! | new_vertices = DisplaceMesh( |
| 76 | ! | mesh, |
| 77 | ! | disp_x, |
| 78 | ! | disp_y, |
| 79 | ! | disp_z, |
| 80 | ! | tangents, |
| 81 | ! | tangent_right_handed, |
| 82 | ! | displacement_scale, |
| 83 | ! | displacement_vector, |
| 84 | ! | id - 1 |
| 85 | ) | |
| 86 | ! | mesh$vertices[id] = ray_vertex_data(new_vertices) |
| 87 | ! | mesh = smooth_normals_mesh(mesh, id) |
| 88 | } | |
| 89 | 1x | return(mesh) |
| 90 | } |
| 1 | #' Extrude a Profile Along a Path | |
| 2 | #' | |
| 3 | #' Construct an indexed sweep with independent geometry, normal, and texture | |
| 4 | #' indices. Geometry construction is independent of any renderer. | |
| 5 | #' | |
| 6 | #' @param points Matrix or data frame with three columns, or a list of numeric | |
| 7 | #' three-vectors, describing the path. With precomputed controls, a list of | |
| 8 | #' four-by-three cubic Bezier control-point matrices. | |
| 9 | #' @param polygon Default `NA`. Cross-section accepted by `xy.coords()`; | |
| 10 | #' defaults to a 30-sided circle with diameter one. Must be a simple polygon | |
| 11 | #' without holes. A repeated closing vertex is removed. | |
| 12 | #' @param polygon_end Default `NA`. Optional final profile with the same number | |
| 13 | #' of vertices. Corresponding rows are interpolated along the full path. | |
| 14 | #' @param breaks Default `NA`. Samples along the full path, including endpoints; | |
| 15 | #' defaults to 20 times the number of Bezier segments. Exact trim endpoints and | |
| 16 | #' polyline corners are inserted as needed. | |
| 17 | #' @param closed Default `FALSE`. Close the path and align its end frames. | |
| 18 | #' @param closed_smooth Default `TRUE`. Use C2-continuous periodic interpolation | |
| 19 | #' for a closed smooth path. Otherwise its closing segment has C1 continuity. | |
| 20 | #' Ignored for straight paths and precomputed controls. | |
| 21 | #' @param polygon_add_points Default `0`. Number of points to insert per | |
| 22 | #' profile edge before sweeping. | |
| 23 | #' @param twists Default `0`. Number of full profile rotations over the path. | |
| 24 | #' @param texture_repeats Default `1`. Texture repetitions along the full path. | |
| 25 | #' @param straight Default `FALSE`. Connect points with straight segments. | |
| 26 | #' @param precomputed_control_points Default `FALSE`. Interpret `points` as | |
| 27 | #' cubic Bezier controls instead of interpolation points. | |
| 28 | #' @param width Default `1`. Nonnegative profile scale, or numeric width values | |
| 29 | #' spaced evenly along the path. An `xy.coords()` representation supplies | |
| 30 | #' explicit positions from zero to one and widths. Zero-width rings form triangle fans. | |
| 31 | #' @param width_end Default `NA`. Final width when `width` is a scalar; | |
| 32 | #' otherwise ignored. Defaults to the initial width. | |
| 33 | #' @param width_ease Default `"spline"`. Shape-preserving cubic interpolation | |
| 34 | #' between widths. Other choices are `linear`, `quad`, `cubic`, and `exp`. | |
| 35 | #' @param smooth_normals Default `FALSE`. Include surface normals accounting | |
| 36 | #' for taper, twist, and changing profiles. Cap normals remain hard. | |
| 37 | #' @param u_min Default `0`. Start of the retained path interval. Closed paths | |
| 38 | #' can wrap across their seam. | |
| 39 | #' @param u_max Default `1`. End of the retained path interval. A full closed | |
| 40 | #' interval has no caps. Equal endpoints produce an empty mesh. | |
| 41 | #' @param linear_step Default `FALSE`. Interpret path coordinates as normalized | |
| 42 | #' arc length using adaptive sampling instead of Bezier parameter distance. | |
| 43 | #' @param end_caps Default `c(TRUE, TRUE)`. Include the starting and ending caps. | |
| 44 | #' @param initial_normal Default `NULL`. Initial direction of the profile's | |
| 45 | #' positive X axis, projected perpendicular to the path tangent. Must not be | |
| 46 | #' parallel to that tangent. By default curvature or a stable axis is used. | |
| 47 | #' @param smooth_angle Default `180`. Maximum profile turning angle in degrees | |
| 48 | #' to smooth. Smaller values preserve corners when `smooth_normals = TRUE`. | |
| 49 | #' @param arc_tolerance Default `1e-5`. Relative adaptive sampling tolerance, | |
| 50 | #' measured against the total control-polygon length. | |
| 51 | #' @param position Default `c(0, 0, 0)`. Translation of the completed mesh. | |
| 52 | #' @param scale Default `c(1, 1, 1)`. Scale of the mesh, uniformly or per axis. | |
| 53 | #' @param angle Default `c(0, 0, 0)`. Rotation angles in degrees. | |
| 54 | #' @param pivot_point Default `c(0, 0, 0)`. Point around which to rotate. | |
| 55 | #' @param order_rotation Default `c(1, 2, 3)`. Order to rotate the axes. | |
| 56 | #' @param material Default `material_list()`. Surface material. | |
| 57 | #' @param material_caps Default `NULL`. Cap material; defaults to `material`. | |
| 58 | #' @param separate_caps Default `FALSE`. Return surfaces and caps separately | |
| 59 | #' for independent editing or material assignment by another renderer. | |
| 60 | #' | |
| 61 | #' @details | |
| 62 | #' Closed sweeps correct accumulated frame rotation. Full loops and intervals | |
| 63 | #' crossing the seam require compatible endpoint profiles, widths, and twists. | |
| 64 | #' For example, a square profile permits quarter-turn seam rotations. Invalid | |
| 65 | #' seams raise an error. Profile winding is normalized while retaining the first | |
| 66 | #' vertex. Texture seams and shading creases use separate attribute indices. | |
| 67 | #' | |
| 68 | #' @return A `ray_mesh`, or `NULL` for an empty interval or entirely zero-width | |
| 69 | #' sweep. With `separate_caps = TRUE`, a list with `surface` and `caps` entries, | |
| 70 | #' each containing a `ray_mesh` or `NULL`. | |
| 71 | #' @seealso [extruded_polygon_mesh()], [lathe_mesh()] | |
| 72 | #' @export | |
| 73 | #' @examples | |
| 74 | #' path = rbind(c(0, 0, 0), c(0, 1, 1), c(1, 2, 1)) | |
| 75 | #' tube = extruded_path_mesh(path, width = 0.2, smooth_normals = TRUE) | |
| 76 | #' parts = extruded_path_mesh(path, width = 0.2, separate_caps = TRUE) | |
| 77 | extruded_path_mesh = function( | |
| 78 | points, | |
| 79 | polygon = NA, | |
| 80 | polygon_end = NA, | |
| 81 | breaks = NA, | |
| 82 | closed = FALSE, | |
| 83 | closed_smooth = TRUE, | |
| 84 | polygon_add_points = 0, | |
| 85 | twists = 0, | |
| 86 | texture_repeats = 1, | |
| 87 | straight = FALSE, | |
| 88 | precomputed_control_points = FALSE, | |
| 89 | width = 1, | |
| 90 | width_end = NA, | |
| 91 | width_ease = "spline", | |
| 92 | smooth_normals = FALSE, | |
| 93 | u_min = 0, | |
| 94 | u_max = 1, | |
| 95 | linear_step = FALSE, | |
| 96 | end_caps = c(TRUE, TRUE), | |
| 97 | initial_normal = NULL, | |
| 98 | smooth_angle = 180, | |
| 99 | arc_tolerance = 1e-5, | |
| 100 | position = c(0, 0, 0), | |
| 101 | scale = c(1, 1, 1), | |
| 102 | angle = c(0, 0, 0), | |
| 103 | pivot_point = c(0, 0, 0), | |
| 104 | order_rotation = c(1, 2, 3), | |
| 105 | material = material_list(), | |
| 106 | material_caps = NULL, | |
| 107 | separate_caps = FALSE | |
| 108 | ) { | |
| 109 | if ( | |
| 110 | 16x | !is.logical(separate_caps) || |
| 111 | 16x | length(separate_caps) != 1L || |
| 112 | 16x | is.na(separate_caps) |
| 113 | ) { | |
| 114 | 1x | stop("`separate_caps` must be TRUE or FALSE.", call. = FALSE) |
| 115 | } | |
| 116 | 15x | parts = sweep_mesh_data( |
| 117 | 15x | points = points, |
| 118 | 15x | polygon = polygon, |
| 119 | 15x | polygon_end = polygon_end, |
| 120 | 15x | breaks = breaks, |
| 121 | 15x | closed = closed, |
| 122 | 15x | closed_smooth = closed_smooth, |
| 123 | 15x | polygon_add_points = polygon_add_points, |
| 124 | 15x | twists = twists, |
| 125 | 15x | texture_repeats = texture_repeats, |
| 126 | 15x | straight = straight, |
| 127 | 15x | precomputed_control_points = precomputed_control_points, |
| 128 | 15x | width = width, |
| 129 | 15x | width_end = width_end, |
| 130 | 15x | width_ease = width_ease, |
| 131 | 15x | smooth_normals = smooth_normals, |
| 132 | 15x | u_min = u_min, |
| 133 | 15x | u_max = u_max, |
| 134 | 15x | linear_step = linear_step, |
| 135 | 15x | end_caps = end_caps, |
| 136 | 15x | initial_normal = initial_normal, |
| 137 | 15x | smooth_angle = smooth_angle, |
| 138 | 15x | arc_tolerance = arc_tolerance |
| 139 | ) | |
| 140 | 15x | if (is.null(material_caps)) { |
| 141 | 13x | material_caps = material |
| 142 | } | |
| 143 | 15x | group = function(pieces, mat) { |
| 144 | 25x | pieces = Filter(Negate(is.null), pieces) |
| 145 | 25x | if (!length(pieces)) { |
| 146 | 9x | return(NULL) |
| 147 | } | |
| 148 | 16x | meshes = lapply(pieces, function(piece) { |
| 149 | 21x | do.call(construct_mesh, c(piece, list(material = mat))) |
| 150 | }) | |
| 151 | 16x | extrusion_transform( |
| 152 | 16x | Reduce(add_shape, meshes), |
| 153 | 16x | position, |
| 154 | 16x | scale, |
| 155 | 16x | angle, |
| 156 | 16x | pivot_point, |
| 157 | 16x | order_rotation |
| 158 | ) | |
| 159 | } | |
| 160 | 15x | surface = group(lapply(parts, function(part) part$surface), material) |
| 161 | 10x | caps = group( |
| 162 | 10x | unlist(lapply(parts, function(part) part$caps), recursive = FALSE), |
| 163 | 10x | material_caps |
| 164 | ) | |
| 165 | 10x | if (separate_caps) { |
| 166 | 3x | list(surface = surface, caps = caps) |
| 167 | } else { | |
| 168 | 7x | add_shape(surface, caps) |
| 169 | } | |
| 170 | } | |
| 171 | ||
| 172 | #' Apply standard transforms to an extrusion | |
| 173 | #' @keywords internal | |
| 174 | #' @noRd | |
| 175 | extrusion_transform = function( | |
| 176 | mesh, | |
| 177 | position, | |
| 178 | scale, | |
| 179 | angle, | |
| 180 | pivot_point, | |
| 181 | order_rotation | |
| 182 | ) { | |
| 183 | 146x | for (name in c("position", "angle", "pivot_point")) { |
| 184 | 432x | value = get(name) |
| 185 | 432x | if (!is.numeric(value) || length(value) != 3L || any(!is.finite(value))) { |
| 186 | 6x | stop( |
| 187 | 6x | sprintf("`%s` must be a finite numeric three-vector.", name), |
| 188 | 6x | call. = FALSE |
| 189 | ) | |
| 190 | } | |
| 191 | } | |
| 192 | if ( | |
| 193 | 140x | !is.numeric(scale) || |
| 194 | 140x | !length(scale) %in% c(1L, 3L) || |
| 195 | 140x | any(!is.finite(scale)) || |
| 196 | 140x | any(scale == 0) |
| 197 | ) { | |
| 198 | 1x | stop( |
| 199 | 1x | "`scale` must contain one or three finite, nonzero numbers.", |
| 200 | 1x | call. = FALSE |
| 201 | ) | |
| 202 | } | |
| 203 | if ( | |
| 204 | 139x | !is.numeric(order_rotation) || |
| 205 | 139x | length(order_rotation) != 3L || |
| 206 | 139x | anyNA(order_rotation) || |
| 207 | 139x | !setequal(order_rotation, 1:3) |
| 208 | ) { | |
| 209 | 2x | stop("`order_rotation` must be a permutation of 1, 2, 3.", call. = FALSE) |
| 210 | } | |
| 211 | 137x | if (any(scale != 1)) { |
| 212 | 2x | mesh = scale_mesh(mesh, scale) |
| 213 | } | |
| 214 | 137x | if (any(angle != 0)) { |
| 215 | 3x | mesh = rotate_mesh( |
| 216 | 3x | mesh, |
| 217 | 3x | angle, |
| 218 | 3x | pivot_point = pivot_point, |
| 219 | 3x | order_rotation = order_rotation |
| 220 | ) | |
| 221 | } | |
| 222 | 137x | translate_mesh(mesh, position) |
| 223 | } |
| 1 | #'@title Rasterize Lines | |
| 2 | #' | |
| 3 | #'@description Render a 3D scene made out of lines using a software rasterizer. | |
| 4 | #' | |
| 5 | #'@param line_info The mesh object. | |
| 6 | #'@param filename Default `NULL`. Filename to save the image. If `NULL`, the image will be plotted. | |
| 7 | #'@param width Default `400`. Width of the rendered image. | |
| 8 | #'@param height Default `400`. Width of the rendered image. | |
| 9 | #'@param alpha_line Default `1`. Line transparency. | |
| 10 | #'@param parallel Default `TRUE`. Whether to use parallel processing. | |
| 11 | #'@param fov Default `20`. Width of the rendered image. | |
| 12 | #'@param lookfrom Default `c(0,0,10)`. Camera location. | |
| 13 | #'@param lookat Default `NULL`. Camera focal position, defaults to the center of the model. | |
| 14 | #'@param camera_up Default `c(0,1,0)`. Camera up vector. | |
| 15 | #'@param color Default `darkred`. Color of model if no material file present (or for faces using the default material). | |
| 16 | #'@param background Default `white`. Background color. | |
| 17 | #'@param debug Default `"none"`. | |
| 18 | #'@param near_plane Default `0.1`. | |
| 19 | #'@param far_plane Default `100`. | |
| 20 | #'@param block_size Default `4`. | |
| 21 | #'@param ortho_dimensions Default `c(1,1)`. Width and height of the orthographic camera. Will only be used if `fov = 0`. | |
| 22 | #'@param bloom Default `FALSE`. Whether to apply bloom to the image. If `TRUE`, | |
| 23 | #' this performs a convolution of the HDR image of the scene with a sharp, long-tailed | |
| 24 | #' exponential kernel, which does not visibly affect dimly pixels, but does result in emitters light | |
| 25 | #' slightly bleeding into adjacent pixels. | |
| 26 | #'@param antialias_lines Default `TRUE`. Whether to anti-alias lines in the scene. | |
| 27 | #' | |
| 28 | #'@return Rasterized image. | |
| 29 | #'@export | |
| 30 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 31 | #' #Generate a cube out of lines | |
| 32 | #' cube_outline = generate_line(start = c(-1, -1, -1), end = c(-1, -1, 1)) |> | |
| 33 | #' add_lines(generate_line(start = c(-1, -1, -1), end = c(-1, 1, -1))) |> | |
| 34 | #' add_lines(generate_line(start = c(-1, -1, -1), end = c(1, -1, -1))) |> | |
| 35 | #' add_lines(generate_line(start = c(-1, -1, 1), end = c(-1, 1, 1))) |> | |
| 36 | #' add_lines(generate_line(start = c(-1, -1, 1), end = c(1, -1, 1))) |> | |
| 37 | #' add_lines(generate_line(start = c(-1, 1, 1), end = c(-1, 1, -1))) |> | |
| 38 | #' add_lines(generate_line(start = c(-1, 1, 1), end = c(1, 1, 1))) |> | |
| 39 | #' add_lines(generate_line(start = c(1, 1, -1), end = c(1, -1, -1))) |> | |
| 40 | #' add_lines(generate_line(start = c(1, 1, -1), end = c(1, 1, 1))) |> | |
| 41 | #' add_lines(generate_line(start = c(1, -1, -1), end = c(1, -1, 1))) |> | |
| 42 | #' add_lines(generate_line(start = c(1, -1, 1), end = c(1, 1, 1))) |> | |
| 43 | #' add_lines(generate_line(start = c(-1, 1, -1), end = c(1, 1, -1))) | |
| 44 | #' rasterize_lines(cube_outline,fov=90,lookfrom=c(0,0,3)) | |
| 45 | #' #Scale the cube uniformly | |
| 46 | #' scaled_cube = color_lines(scale_lines(cube_outline,scale=0.5),color="red") | |
| 47 | #' rasterize_lines(add_lines(cube_outline,scaled_cube),fov=90,lookfrom=c(0,0,3)) | |
| 48 | #' #Scale the cube non-uniformly | |
| 49 | #' scaled_cube = color_lines(scale_lines(cube_outline,scale=c(0.8,2,0.4)),color="red") | |
| 50 | #' rasterize_lines(add_lines(cube_outline,scaled_cube),fov=60,lookfrom=c(3,3,3)) | |
| 51 | rasterize_lines = function( | |
| 52 | line_info = NULL, | |
| 53 | filename = NA, | |
| 54 | width = 800, | |
| 55 | height = 800, | |
| 56 | alpha_line = 1.0, | |
| 57 | parallel = TRUE, | |
| 58 | fov = 20, | |
| 59 | lookfrom = c(0, 0, 10), | |
| 60 | lookat = NULL, | |
| 61 | camera_up = c(0, 1, 0), #Sanitize lookfrom and lookat inputs | |
| 62 | color = "red", | |
| 63 | background = "black", | |
| 64 | debug = "none", | |
| 65 | near_plane = 0.1, | |
| 66 | far_plane = 100, | |
| 67 | block_size = 4, | |
| 68 | ortho_dimensions = c(1, 1), | |
| 69 | bloom = FALSE, | |
| 70 | antialias_lines = TRUE | |
| 71 | ) { | |
| 72 | ! | if (is.null(line_info)) { |
| 73 | ! | stop("no lines info passed to argument") |
| 74 | } | |
| 75 | ! | lineranges = rbind(line_info[, 1:3], line_info[, 4:6]) |
| 76 | ! | bounds = as.vector(t(apply(lineranges, 2, range))) |
| 77 | ||
| 78 | ! | if (is.null(lookat)) { |
| 79 | ! | lookat = (bounds[1:3] + bounds[4:6]) / 2 |
| 80 | ! | message(sprintf( |
| 81 | ! | "Setting `lookat` to: c(%0.2f, %0.2f, %0.2f)", |
| 82 | ! | lookat[1], |
| 83 | ! | lookat[2], |
| 84 | ! | lookat[3] |
| 85 | )) | |
| 86 | } | |
| 87 | ||
| 88 | ! | numbercores = getOption( |
| 89 | ! | "cores", |
| 90 | ! | default = getOption("Ncpus", default = parallel::detectCores()) |
| 91 | ) | |
| 92 | ! | if (identical(Sys.getenv("_R_CHECK_LIMIT_CORES_"), "TRUE")) { |
| 93 | ! | numbercores = min(as.integer(numbercores), 2L) |
| 94 | } | |
| 95 | ! | if (!parallel) { |
| 96 | ! | numbercores = 1L |
| 97 | } | |
| 98 | ||
| 99 | ! | color = convert_color(color) |
| 100 | ! | bg_color = convert_color(background) |
| 101 | ||
| 102 | ! | line_offset = 0 |
| 103 | ! | imagelist = rasterize_lines_rcpp( |
| 104 | ! | line_mat = line_info, |
| 105 | ! | nx = width, |
| 106 | ! | ny = height, |
| 107 | ! | model_color = color, |
| 108 | ! | lookfrom = lookfrom, |
| 109 | ! | lookat = lookat, |
| 110 | ! | fov = fov, |
| 111 | ! | near_clip = near_plane, |
| 112 | ! | far_clip = far_plane, |
| 113 | ! | bounds = bounds, |
| 114 | ! | camera_up = camera_up, |
| 115 | ! | alpha_line = alpha_line, |
| 116 | ! | line_offset = line_offset, |
| 117 | ! | ortho_dims = ortho_dimensions, |
| 118 | ! | aa_lines = antialias_lines |
| 119 | ) | |
| 120 | ! | if (debug == "normals") { |
| 121 | ! | norm_array = array(0, dim = c(dim(imagelist$r)[2:1], 3)) |
| 122 | ! | norm_array[,, 1] = (imagelist$normalx + 1) / 2 |
| 123 | ! | norm_array[,, 2] = (imagelist$normaly + 1) / 2 |
| 124 | ! | norm_array[,, 3] = (imagelist$normalz + 1) / 2 |
| 125 | ! | norm_array = rayimage::render_reorient( |
| 126 | ! | norm_array, |
| 127 | ! | transpose = TRUE, |
| 128 | ! | flipx = TRUE |
| 129 | ) | |
| 130 | ! | rayimage::plot_image(norm_array) |
| 131 | ! | return(invisible(norm_array)) |
| 132 | } | |
| 133 | ! | if (debug == "depth") { |
| 134 | ! | depth_array = array(0, dim = c(dim(imagelist$r)[2:1], 3)) |
| 135 | ! | depth_array[,, 1] = (imagelist$depth) |
| 136 | ! | depth_array[,, 2] = (imagelist$depth) |
| 137 | ! | depth_array[,, 3] = (imagelist$depth) |
| 138 | ! | depth_array = rayimage::render_reorient( |
| 139 | ! | depth_array, |
| 140 | ! | transpose = TRUE, |
| 141 | ! | flipx = TRUE |
| 142 | ) | |
| 143 | ! | depth_array[is.infinite(depth_array)] = 1.2 |
| 144 | ! | scale_factor = max(depth_array) - min(depth_array) |
| 145 | ! | depth_array = (depth_array - min(depth_array)) / scale_factor |
| 146 | ! | rayimage::plot_image(depth_array) |
| 147 | ! | return(invisible(depth_array)) |
| 148 | } | |
| 149 | ! | if (debug == "position") { |
| 150 | ! | pos_array = array(0, dim = c(dim(imagelist$r)[2:1], 3)) |
| 151 | ! | imagelist$positionx = rescale(imagelist$positionx, to = c(0, 1)) |
| 152 | ! | imagelist$positiony = rescale(imagelist$positiony, to = c(0, 1)) |
| 153 | ! | imagelist$positionz = rescale(imagelist$positionz, to = c(0, 1)) |
| 154 | ||
| 155 | ! | pos_array[,, 1] = (imagelist$positionx) |
| 156 | ! | pos_array[,, 2] = (imagelist$positiony) |
| 157 | ! | pos_array[,, 3] = (imagelist$positionz) |
| 158 | ! | pos_array = rayimage::render_reorient( |
| 159 | ! | pos_array, |
| 160 | ! | transpose = TRUE, |
| 161 | ! | flipx = TRUE |
| 162 | ) | |
| 163 | ! | pos_array[is.infinite(pos_array)] = 1 |
| 164 | ! | rayimage::plot_image(pos_array) |
| 165 | ! | return(invisible(pos_array)) |
| 166 | } | |
| 167 | ! | if (debug == "uv") { |
| 168 | ! | uv_array = array(0, dim = c(dim(imagelist$r)[2:1], 3)) |
| 169 | ! | uv_array[,, 1] = (imagelist$uvx) |
| 170 | ! | uv_array[,, 2] = (imagelist$uvy) |
| 171 | ! | uv_array[,, 3] = (imagelist$uvz) |
| 172 | ! | uv_array = rayimage::render_reorient( |
| 173 | ! | uv_array, |
| 174 | ! | transpose = TRUE, |
| 175 | ! | flipx = TRUE |
| 176 | ) | |
| 177 | ! | rayimage::plot_image(uv_array) |
| 178 | ! | return(invisible(uv_array)) |
| 179 | } | |
| 180 | ||
| 181 | ! | imagelist$r[is.infinite(imagelist$depth)] = bg_color[1] |
| 182 | ! | imagelist$g[is.infinite(imagelist$depth)] = bg_color[2] |
| 183 | ! | imagelist$b[is.infinite(imagelist$depth)] = bg_color[3] |
| 184 | ||
| 185 | ! | retmat = array(0, dim = c(dim(imagelist$r)[2:1], 3)) |
| 186 | ! | retmat[,, 1] = rayimage::render_reorient( |
| 187 | ! | imagelist$r, |
| 188 | ! | transpose = TRUE, |
| 189 | ! | flipx = TRUE |
| 190 | ) | |
| 191 | ! | retmat[,, 2] = rayimage::render_reorient( |
| 192 | ! | imagelist$g, |
| 193 | ! | transpose = TRUE, |
| 194 | ! | flipx = TRUE |
| 195 | ) | |
| 196 | ! | retmat[,, 3] = rayimage::render_reorient( |
| 197 | ! | imagelist$b, |
| 198 | ! | transpose = TRUE, |
| 199 | ! | flipx = TRUE |
| 200 | ) | |
| 201 | ! | if (bloom) { |
| 202 | ! | retmat = rayimage::render_convolution(retmat, min_value = 1) |
| 203 | } | |
| 204 | ||
| 205 | ! | retmat[retmat > 1] = 1 |
| 206 | ! | if (is.na(filename)) { |
| 207 | ! | rayimage::plot_image(retmat) |
| 208 | } else { | |
| 209 | ! | rayimage::ray_write_image(retmat, filename = filename) |
| 210 | } | |
| 211 | ! | return(invisible(retmat)) |
| 212 | } |
| 1 | #'@title Generate Lines | |
| 2 | #' | |
| 3 | #'@param start Default `c(0,0,0)`. Start of the line segment. | |
| 4 | #'@param end Default `c(0,1,0)`. End of the line segment.. | |
| 5 | #'@param color Default `white`. Color of the line segment. | |
| 6 | #'@return Line matrix | |
| 7 | #'@export | |
| 8 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 9 | #' # Make a spiral of lines | |
| 10 | #' t = seq(0,8*pi,length.out=361) | |
| 11 | #' line_mat = matrix(nrow=0,ncol=9) | |
| 12 | #' | |
| 13 | #' for(i in 1:360) { | |
| 14 | #' line_mat = add_lines(line_mat, | |
| 15 | #' generate_line(start = c(0.5*sin(t[i]), t[i]/(8*pi), 0.5*cos(t[i])), | |
| 16 | #' end = c(0.5*sin(t[i+1]), t[i+1]/(8*pi), 0.5*cos(t[i+1])))) | |
| 17 | #' } | |
| 18 | #' rasterize_lines(line_mat) | |
| 19 | #' #Change the line color | |
| 20 | #' line_mat = matrix(nrow=0,ncol=9) | |
| 21 | #' cols = hsv(seq(0,1,length.out=360)) | |
| 22 | #' for(i in 1:360) { | |
| 23 | #' line_mat = add_lines(line_mat, | |
| 24 | #' generate_line(start = c(sin(t[i]), 2*t[i]/(8*pi), cos(t[i])), | |
| 25 | #' end = c(sin(t[i+1]), 2*t[i+1]/(8*pi), cos(t[i+1])), | |
| 26 | #' color = cols[i])) | |
| 27 | #' } | |
| 28 | #' rasterize_lines(line_mat,lookfrom=c(0,10,10),fov=15) | |
| 29 | #' #Use in a scene with a mesh | |
| 30 | #' obj_mesh(r_obj(simple_r = TRUE),material=material_list(diffuse="dodgerblue")) |> | |
| 31 | #' rasterize_scene(line_info = line_mat, light_info = directional_light(c(0,1,1)), | |
| 32 | #' lookfrom=c(0,5,10),lookat=c(0,0.8,0),fov=15) | |
| 33 | generate_line = function( | |
| 34 | start = c(0, 0, 0), | |
| 35 | end = c(0, 1, 0), | |
| 36 | color = "white" | |
| 37 | ) { | |
| 38 | ! | color = convert_color(color) |
| 39 | ! | start = as.numeric(start) |
| 40 | ! | end = as.numeric(end) |
| 41 | ||
| 42 | ! | returnmat = matrix(c(start, end, color), nrow = 1, ncol = 9) |
| 43 | ! | colnames(returnmat) = c("x0", "y0", "z0", "x1", "y1", "z1", "r", "g", "b") |
| 44 | ! | returnmat |
| 45 | } | |
| 46 | ||
| 47 | #'@title Rotate Lines | |
| 48 | #' | |
| 49 | #'@param lines The existing line scene. | |
| 50 | #'@param angle Default `c(0,0,0)`. The rotation amount for the x/y/z axes, in degrees. | |
| 51 | #'@param pivot_point Default `c(0,0,0)`. The pivot point of the rotation. | |
| 52 | #'@param order_rotation Default `c(1,2,3)`. The order in which to perform the rotations.#' | |
| 53 | #'@return Rotated lines. | |
| 54 | #' | |
| 55 | #'@export | |
| 56 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 57 | #' #Generate a cube out of lines | |
| 58 | #' cube_outline = generate_line(start = c(-1, -1, -1), end = c(-1, -1, 1)) |> | |
| 59 | #' add_lines(generate_line(start = c(-1, -1, -1), end = c(-1, 1, -1))) |> | |
| 60 | #' add_lines(generate_line(start = c(-1, -1, -1), end = c(1, -1, -1))) |> | |
| 61 | #' add_lines(generate_line(start = c(-1, -1, 1), end = c(-1, 1, 1))) |> | |
| 62 | #' add_lines(generate_line(start = c(-1, -1, 1), end = c(1, -1, 1))) |> | |
| 63 | #' add_lines(generate_line(start = c(-1, 1, 1), end = c(-1, 1, -1))) |> | |
| 64 | #' add_lines(generate_line(start = c(-1, 1, 1), end = c(1, 1, 1))) |> | |
| 65 | #' add_lines(generate_line(start = c(1, 1, -1), end = c(1, -1, -1))) |> | |
| 66 | #' add_lines(generate_line(start = c(1, 1, -1), end = c(1, 1, 1))) |> | |
| 67 | #' add_lines(generate_line(start = c(1, -1, -1), end = c(1, -1, 1))) |> | |
| 68 | #' add_lines(generate_line(start = c(1, -1, 1), end = c(1, 1, 1))) |> | |
| 69 | #' add_lines(generate_line(start = c(-1, 1, -1), end = c(1, 1, -1))) | |
| 70 | #' rasterize_lines(cube_outline,lookfrom=c(0,6,10)) | |
| 71 | #' #Rotate the cube 30 degrees around the y-axis | |
| 72 | #' rotated_cube = color_lines(rotate_lines(cube_outline,angle=c(0,30,0)),color="red") | |
| 73 | #' rasterize_lines(add_lines(cube_outline,rotated_cube),lookfrom=c(0,6,10)) | |
| 74 | #' #Rotate the cube 30 degrees around each axis, in this order: x,y,z | |
| 75 | #' rotated_cube = color_lines(rotate_lines(cube_outline,angle=c(30,30,30)),color="red") | |
| 76 | #' rasterize_lines(add_lines(cube_outline,rotated_cube),lookfrom=c(0,6,10)) | |
| 77 | #' #Rotate the cube 30 degrees around each axis, in this order: z,y,x | |
| 78 | #' rotated_cube = color_lines(rotate_lines(cube_outline,angle=c(30,30,30), | |
| 79 | #' order_rotation = c(3,2,1)),color="red") | |
| 80 | #' rasterize_lines(add_lines(cube_outline,rotated_cube),lookfrom=c(0,6,10)) | |
| 81 | rotate_lines = function( | |
| 82 | lines, | |
| 83 | angle = c(0, 0, 0), | |
| 84 | pivot_point = c(0, 0, 0), | |
| 85 | order_rotation = c(1, 2, 3) | |
| 86 | ) { | |
| 87 | ! | angle = angle * pi / 180 |
| 88 | ! | lines[, 1] = lines[, 1] - pivot_point[1] |
| 89 | ! | lines[, 2] = lines[, 2] - pivot_point[2] |
| 90 | ! | lines[, 3] = lines[, 3] - pivot_point[3] |
| 91 | ! | lines[, 4] = lines[, 4] - pivot_point[1] |
| 92 | ! | lines[, 5] = lines[, 5] - pivot_point[2] |
| 93 | ! | lines[, 6] = lines[, 6] - pivot_point[3] |
| 94 | ! | rot_mat = generate_rot_matrix(angle, order_rotation) |
| 95 | ||
| 96 | ! | for (i in seq_len(nrow(lines))) { |
| 97 | ! | lines[i, 1:3] = lines[i, 1:3] %*% rot_mat |
| 98 | ! | lines[i, 4:6] = lines[i, 4:6] %*% rot_mat |
| 99 | } | |
| 100 | ! | lines[, 1] = lines[, 1] + pivot_point[1] |
| 101 | ! | lines[, 2] = lines[, 2] + pivot_point[2] |
| 102 | ! | lines[, 3] = lines[, 3] + pivot_point[3] |
| 103 | ! | lines[, 4] = lines[, 4] + pivot_point[1] |
| 104 | ! | lines[, 5] = lines[, 5] + pivot_point[2] |
| 105 | ! | lines[, 6] = lines[, 6] + pivot_point[3] |
| 106 | ! | return(lines) |
| 107 | } | |
| 108 | ||
| 109 | #'@title Scale Lines | |
| 110 | #' | |
| 111 | #'@param lines The line scene. | |
| 112 | #'@param scale Default `c(1,1,1)`. The scale amount, per axis. | |
| 113 | #' | |
| 114 | #'@return Scaled line matrix. | |
| 115 | #'@export | |
| 116 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 117 | #' #Generate a cube out of lines | |
| 118 | #' cube_outline = generate_line(start = c(-1, -1, -1), end = c(-1, -1, 1)) |> | |
| 119 | #' add_lines(generate_line(start = c(-1, -1, -1), end = c(-1, 1, -1))) |> | |
| 120 | #' add_lines(generate_line(start = c(-1, -1, -1), end = c(1, -1, -1))) |> | |
| 121 | #' add_lines(generate_line(start = c(-1, -1, 1), end = c(-1, 1, 1))) |> | |
| 122 | #' add_lines(generate_line(start = c(-1, -1, 1), end = c(1, -1, 1))) |> | |
| 123 | #' add_lines(generate_line(start = c(-1, 1, 1), end = c(-1, 1, -1))) |> | |
| 124 | #' add_lines(generate_line(start = c(-1, 1, 1), end = c(1, 1, 1))) |> | |
| 125 | #' add_lines(generate_line(start = c(1, 1, -1), end = c(1, -1, -1))) |> | |
| 126 | #' add_lines(generate_line(start = c(1, 1, -1), end = c(1, 1, 1))) |> | |
| 127 | #' add_lines(generate_line(start = c(1, -1, -1), end = c(1, -1, 1))) |> | |
| 128 | #' add_lines(generate_line(start = c(1, -1, 1), end = c(1, 1, 1))) |> | |
| 129 | #' add_lines(generate_line(start = c(-1, 1, -1), end = c(1, 1, -1))) | |
| 130 | #' rasterize_lines(cube_outline,fov=90,lookfrom=c(0,0,3)) | |
| 131 | #' #Scale the cube uniformly | |
| 132 | #' scaled_cube = color_lines(scale_lines(cube_outline,scale=0.5),color="red") | |
| 133 | #' rasterize_lines(add_lines(cube_outline,scaled_cube),fov=90,lookfrom=c(0,0,3)) | |
| 134 | #' #Scale the cube non-uniformly | |
| 135 | #' scaled_cube = color_lines(scale_lines(cube_outline,scale=c(0.8,2,0.4)),color="red") | |
| 136 | #' rasterize_lines(add_lines(cube_outline,scaled_cube),fov=60,lookfrom=c(3,3,3)) | |
| 137 | scale_lines = function(lines, scale = 1) { | |
| 138 | ! | if (length(scale) == 1) { |
| 139 | ! | scale = rep(scale, 3) |
| 140 | } | |
| 141 | ! | lines[, 1] = lines[, 1] * scale[1] |
| 142 | ! | lines[, 2] = lines[, 2] * scale[2] |
| 143 | ! | lines[, 3] = lines[, 3] * scale[3] |
| 144 | ! | lines[, 4] = lines[, 4] * scale[1] |
| 145 | ! | lines[, 5] = lines[, 5] * scale[2] |
| 146 | ! | lines[, 6] = lines[, 6] * scale[3] |
| 147 | ! | return(lines) |
| 148 | } | |
| 149 | ||
| 150 | #'@title Translate Lines | |
| 151 | #' | |
| 152 | #'@param lines The line scene. | |
| 153 | #'@param position Default `c(0,0,0)`. The translation vector. | |
| 154 | #' | |
| 155 | #'@return Translated line matrix. | |
| 156 | #'@export | |
| 157 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 158 | #' #Generate a cube out of lines | |
| 159 | #' cube_outline = generate_line(start = c(-1, -1, -1), end = c(-1, -1, 1)) |> | |
| 160 | #' add_lines(generate_line(start = c(-1, -1, -1), end = c(-1, 1, -1))) |> | |
| 161 | #' add_lines(generate_line(start = c(-1, -1, -1), end = c(1, -1, -1))) |> | |
| 162 | #' add_lines(generate_line(start = c(-1, -1, 1), end = c(-1, 1, 1))) |> | |
| 163 | #' add_lines(generate_line(start = c(-1, -1, 1), end = c(1, -1, 1))) |> | |
| 164 | #' add_lines(generate_line(start = c(-1, 1, 1), end = c(-1, 1, -1))) |> | |
| 165 | #' add_lines(generate_line(start = c(-1, 1, 1), end = c(1, 1, 1))) |> | |
| 166 | #' add_lines(generate_line(start = c(1, 1, -1), end = c(1, -1, -1))) |> | |
| 167 | #' add_lines(generate_line(start = c(1, 1, -1), end = c(1, 1, 1))) |> | |
| 168 | #' add_lines(generate_line(start = c(1, -1, -1), end = c(1, -1, 1))) |> | |
| 169 | #' add_lines(generate_line(start = c(1, -1, 1), end = c(1, 1, 1))) |> | |
| 170 | #' add_lines(generate_line(start = c(-1, 1, -1), end = c(1, 1, -1))) | |
| 171 | #' rasterize_lines(cube_outline,fov=40,lookfrom=c(1,2,10),lookat=c(0,0,0)) | |
| 172 | #' #Scale the cube uniformly | |
| 173 | #' translated_cube = color_lines(translate_lines(cube_outline,c(1,1,1)),"red") | |
| 174 | #' translated_cube2 = color_lines(translate_lines(cube_outline,c(-1,-1,-1)),"green") | |
| 175 | #' | |
| 176 | #' cube_outline |> | |
| 177 | #' add_lines(translated_cube) |> | |
| 178 | #' add_lines(translated_cube2) |> | |
| 179 | #' rasterize_lines(fov=40,lookfrom=c(1,2,10),lookat=c(0,0,0)) | |
| 180 | translate_lines = function(lines, position = 1) { | |
| 181 | ! | lines[, 1] = lines[, 1] + position[1] |
| 182 | ! | lines[, 2] = lines[, 2] + position[2] |
| 183 | ! | lines[, 3] = lines[, 3] + position[3] |
| 184 | ! | lines[, 4] = lines[, 4] + position[1] |
| 185 | ! | lines[, 5] = lines[, 5] + position[2] |
| 186 | ! | lines[, 6] = lines[, 6] + position[3] |
| 187 | ! | return(lines) |
| 188 | } | |
| 189 | ||
| 190 | #'@title Color Lines | |
| 191 | #' | |
| 192 | #'@param lines The line scene. | |
| 193 | #'@param color Default `white`. The color to convert the lines to. | |
| 194 | #' | |
| 195 | #'@return Colored line matrix. | |
| 196 | #'@export | |
| 197 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 198 | #' #Generate a cube out of lines | |
| 199 | #' cube_outline = generate_line(start = c(-1, -1, -1), end = c(-1, -1, 1)) |> | |
| 200 | #' add_lines(generate_line(start = c(-1, -1, -1), end = c(-1, 1, -1))) |> | |
| 201 | #' add_lines(generate_line(start = c(-1, -1, -1), end = c(1, -1, -1))) |> | |
| 202 | #' add_lines(generate_line(start = c(-1, -1, 1), end = c(-1, 1, 1))) |> | |
| 203 | #' add_lines(generate_line(start = c(-1, -1, 1), end = c(1, -1, 1))) |> | |
| 204 | #' add_lines(generate_line(start = c(-1, 1, 1), end = c(-1, 1, -1))) |> | |
| 205 | #' add_lines(generate_line(start = c(-1, 1, 1), end = c(1, 1, 1))) |> | |
| 206 | #' add_lines(generate_line(start = c(1, 1, -1), end = c(1, -1, -1))) |> | |
| 207 | #' add_lines(generate_line(start = c(1, 1, -1), end = c(1, 1, 1))) |> | |
| 208 | #' add_lines(generate_line(start = c(1, -1, -1), end = c(1, -1, 1))) |> | |
| 209 | #' add_lines(generate_line(start = c(1, -1, 1), end = c(1, 1, 1))) |> | |
| 210 | #' add_lines(generate_line(start = c(-1, 1, -1), end = c(1, 1, -1))) | |
| 211 | #' | |
| 212 | #' cube_outline |> | |
| 213 | #' color_lines(color="red") |> | |
| 214 | #' rasterize_lines() | |
| 215 | color_lines = function(lines, color = "white") { | |
| 216 | ! | color = convert_color(color) |
| 217 | ! | lines[, 7] = color[1] |
| 218 | ! | lines[, 8] = color[2] |
| 219 | ! | lines[, 9] = color[3] |
| 220 | ! | return(lines) |
| 221 | } | |
| 222 | ||
| 223 | ||
| 224 | #'@title Add Line | |
| 225 | #' | |
| 226 | #'@param lines Existing lines or empty (0-row) matrix. | |
| 227 | #'@param line Line to add, generated with [generate_line()] | |
| 228 | #' | |
| 229 | #'@return New line matrix. | |
| 230 | #'@export | |
| 231 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 232 | #' #Generate a cube out of lines | |
| 233 | #' cube_outline = generate_line(start = c(-1, -1, -1), end = c(-1, -1, 1)) |> | |
| 234 | #' add_lines(generate_line(start = c(-1, -1, -1), end = c(-1, 1, -1))) |> | |
| 235 | #' add_lines(generate_line(start = c(-1, -1, -1), end = c(1, -1, -1))) |> | |
| 236 | #' add_lines(generate_line(start = c(-1, -1, 1), end = c(-1, 1, 1))) |> | |
| 237 | #' add_lines(generate_line(start = c(-1, -1, 1), end = c(1, -1, 1))) |> | |
| 238 | #' add_lines(generate_line(start = c(-1, 1, 1), end = c(-1, 1, -1))) |> | |
| 239 | #' add_lines(generate_line(start = c(-1, 1, 1), end = c(1, 1, 1))) |> | |
| 240 | #' add_lines(generate_line(start = c(1, 1, -1), end = c(1, -1, -1))) |> | |
| 241 | #' add_lines(generate_line(start = c(1, 1, -1), end = c(1, 1, 1))) |> | |
| 242 | #' add_lines(generate_line(start = c(1, -1, -1), end = c(1, -1, 1))) |> | |
| 243 | #' add_lines(generate_line(start = c(1, -1, 1), end = c(1, 1, 1))) |> | |
| 244 | #' add_lines(generate_line(start = c(-1, 1, -1), end = c(1, 1, -1))) | |
| 245 | #' | |
| 246 | #' rasterize_lines(cube_outline,fov=90,lookfrom=c(0,0,3)) | |
| 247 | add_lines = function(lines, line) { | |
| 248 | ! | if (nrow(lines) == 0) { |
| 249 | ! | return(line) |
| 250 | } | |
| 251 | ! | return(rbind(lines, line)) |
| 252 | } |
| 1 | #'@title Load an OBJ file | |
| 2 | #' | |
| 3 | #'@description Loads an OBJ file and return a `ray_mesh` list structure. No processing is done on | |
| 4 | #'the object other than loading it (unlike `obj_model()`). | |
| 5 | #' | |
| 6 | #'@param filename Filename of the OBJ file. | |
| 7 | #'@param materialspath Directory where the MTL file is located. Defaults to the directory of `filename`. | |
| 8 | #'@export | |
| 9 | #' | |
| 10 | #'@return `ray_mesh` list object | |
| 11 | #'#Load an arrow OBJ | |
| 12 | #'sphere = read_obj(system.file("extdata", "arrow.txt", package="rayvertex")) | |
| 13 | read_obj = function(filename, materialspath = NULL) { | |
| 14 | 4x | filename = path.expand(filename) |
| 15 | 4x | sepval = "" |
| 16 | 4x | if(!file.exists(filename)) { |
| 17 | ! | stop(sprintf("file `%s` does not exist", filename)) |
| 18 | } | |
| 19 | 4x | if(is.null(materialspath)) { |
| 20 | 4x | dir = dirname(filename) |
| 21 | } else { | |
| 22 | ! | dir = materialspath |
| 23 | } | |
| 24 | 4x | lastchar = substr(dir, nchar(dir), nchar(dir)) |
| 25 | 4x | fsep = .Platform$file.sep |
| 26 | 4x | if(lastchar!=fsep) { |
| 27 | 4x | dir=paste0(dir,fsep) |
| 28 | } | |
| 29 | # if(!getOption("ray_loading", FALSE)) { | |
| 30 | # browser() | |
| 31 | # } | |
| 32 | 4x | obj_loaded = load_obj(filename, dir) |
| 33 | #Everything here is already wrapped in a list, so the constructor for | |
| 34 | #`ray_vertex_data` only needs a single list wrapper | |
| 35 | 4x | obj_loaded$vertices = ray_vertex_data(obj_loaded$vertices[[1]]) |
| 36 | 4x | obj_loaded$normals = ray_vertex_data(obj_loaded$normals[[1]]) |
| 37 | 4x | obj_loaded$texcoords = ray_vertex_data(obj_loaded$texcoords[[1]]) |
| 38 | 4x | for(i in seq_len(length(obj_loaded$shapes))) { |
| 39 | 4x | if(nrow(obj_loaded$shapes[[i]]$indices) == length(obj_loaded$shapes[[i]]$has_vertex_tex)) { |
| 40 | 4x | obj_loaded$shapes[[i]]$has_vertex_tex[apply(obj_loaded$shapes[[i]]$tex_indices,1,(function(x) any(x == -1)))] = FALSE |
| 41 | } | |
| 42 | 4x | if(nrow(obj_loaded$shapes[[i]]$indices) == length(obj_loaded$shapes[[i]]$has_vertex_normals)) { |
| 43 | 4x | obj_loaded$shapes[[i]]$has_vertex_normals[apply(obj_loaded$shapes[[i]]$norm_indices,1,(function(x) any(x == -1)))] = FALSE |
| 44 | } | |
| 45 | } | |
| 46 | 4x | single_indices = list() |
| 47 | 4x | single_tex_indices = list() |
| 48 | 4x | single_norm_indices = list() |
| 49 | 4x | single_material_ids = list() |
| 50 | 4x | single_has_vertex_tex = list() |
| 51 | 4x | single_has_vertex_normals = list() |
| 52 | ||
| 53 | 4x | for(i in seq_len(length(obj_loaded$shapes))) { |
| 54 | 4x | single_indices[[i]] = obj_loaded$shapes[[i]]$indices |
| 55 | 4x | single_tex_indices[[i]] = obj_loaded$shapes[[i]]$tex_indices |
| 56 | 4x | single_norm_indices[[i]] = obj_loaded$shapes[[i]]$norm_indices |
| 57 | 4x | single_material_ids[[i]] = obj_loaded$shapes[[i]]$material_ids |
| 58 | 4x | single_has_vertex_tex[[i]] = obj_loaded$shapes[[i]]$has_vertex_tex |
| 59 | 4x | single_has_vertex_normals[[i]] = obj_loaded$shapes[[i]]$has_vertex_normals |
| 60 | } | |
| 61 | ||
| 62 | # | |
| 63 | # obj_loaded$shapes = list(ray_shape(indices = do.call(rbind,single_indices), | |
| 64 | # tex_indices = do.call(rbind,single_tex_indices), | |
| 65 | # norm_indices = do.call(rbind,single_norm_indices), | |
| 66 | # material_ids = do.call(rbind,single_material_ids), | |
| 67 | # has_vertex_tex = do.call(c,single_has_vertex_tex), | |
| 68 | # has_vertex_normals = do.call(c,single_has_vertex_normals))) | |
| 69 | ||
| 70 | 4x | obj_loaded$shapes = ray_shape(list(indices = do.call(rbind,single_indices), |
| 71 | 4x | tex_indices = do.call(rbind,single_tex_indices), |
| 72 | 4x | norm_indices = do.call(rbind,single_norm_indices), |
| 73 | 4x | material_ids = do.call(rbind,single_material_ids), |
| 74 | 4x | has_vertex_tex = do.call(c,single_has_vertex_tex), |
| 75 | 4x | has_vertex_normals = do.call(c,single_has_vertex_normals))) |
| 76 | 4x | raw_materials = lapply(obj_loaded$materials[[1]], rayvertex_material) |
| 77 | # obj_loaded$materials = do.call(vctrs::vec_c, raw_materials) | |
| 78 | # obj_loaded$materials = vector(mode="list", length = 1) | |
| 79 | # obj_loaded$materials[[1]] = vector(mode="list", length = length(raw_materials)) | |
| 80 | # for(i in seq_len(length(raw_materials))) { | |
| 81 | # obj_loaded$materials[[1]][[i]] = rayvertex_material(raw_materials[[i]]) | |
| 82 | # } | |
| 83 | 4x | for(i in seq_len(length(obj_loaded$materials[[1]]))) { |
| 84 | 6x | if(!file.exists(obj_loaded$materials[[1]][[i]]$diffuse_texname) && nchar(obj_loaded$materials[[1]][[i]]$diffuse_texname) > 0 && |
| 85 | 6x | file.exists(sprintf("%s%s%s", dir,sepval,obj_loaded$materials[[1]][[i]]$diffuse_texname))) { |
| 86 | 1x | obj_loaded$materials[[1]][[i]]$diffuse_texname = sprintf("%s%s%s", dir,sepval,obj_loaded$materials[[1]][[i]]$diffuse_texname) |
| 87 | } | |
| 88 | 6x | if(!file.exists(obj_loaded$materials[[1]][[i]]$ambient_texname) && nchar(obj_loaded$materials[[1]][[i]]$ambient_texname) > 0 && |
| 89 | 6x | file.exists(sprintf("%s%s%s", dir,sepval,obj_loaded$materials[[1]][[i]]$ambient_texname))) { |
| 90 | ! | obj_loaded$materials[[1]][[i]]$ambient_texname = sprintf("%s%s%s", dir,sepval,obj_loaded$materials[[1]][[i]]$ambient_texname) |
| 91 | } | |
| 92 | 6x | if(!file.exists(obj_loaded$materials[[1]][[i]]$emissive_texname) && nchar(obj_loaded$materials[[1]][[i]]$emissive_texname) > 0 && |
| 93 | 6x | file.exists(sprintf("%s%s%s", dir,sepval,obj_loaded$materials[[1]][[i]]$emissive_texname))) { |
| 94 | ! | obj_loaded$materials[[1]][[i]]$emissive_texname = sprintf("%s%s%s", dir,sepval,obj_loaded$materials[[1]][[i]]$emissive_texname) |
| 95 | } | |
| 96 | 6x | if(!file.exists(obj_loaded$materials[[1]][[i]]$specular_texname) && nchar(obj_loaded$materials[[1]][[i]]$specular_texname) > 0 && |
| 97 | 6x | file.exists(sprintf("%s%s%s", dir,sepval,obj_loaded$materials[[1]][[i]]$specular_texname))) { |
| 98 | ! | obj_loaded$materials[[1]][[i]]$specular_texname = sprintf("%s%s%s", dir,sepval,obj_loaded$materials[[1]][[i]]$specular_texname) |
| 99 | } | |
| 100 | 6x | if(!file.exists(obj_loaded$materials[[1]][[i]]$normal_texname) && nchar(obj_loaded$materials[[1]][[i]]$normal_texname) > 0 && |
| 101 | 6x | file.exists(sprintf("%s%s%s", dir,sepval,obj_loaded$materials[[1]][[i]]$normal_texname))) { |
| 102 | ! | obj_loaded$materials[[1]][[i]]$normal_texname = sprintf("%s%s%s", dir,sepval,obj_loaded$materials[[1]][[i]]$normal_texname) |
| 103 | } | |
| 104 | 6x | if(obj_loaded$materials[[1]][[i]]$illum == 5) { |
| 105 | ! | obj_loaded$materials[[1]][[i]]$type = "color" |
| 106 | } else { | |
| 107 | 6x | obj_loaded$materials[[1]][[i]]$type = "diffuse" |
| 108 | } | |
| 109 | } | |
| 110 | 4x | hashes = rep("",length(obj_loaded$materials[[1]])) |
| 111 | 4x | for(i in seq_len(length(obj_loaded$materials[[1]]))) { |
| 112 | 6x | hashes[i] = digest::digest(obj_loaded$materials[[1]][[i]]) |
| 113 | } | |
| 114 | 4x | attr(obj_loaded, "material_hashes") = hashes |
| 115 | ||
| 116 | # class(obj_loaded) = c("ray_mesh", "list") | |
| 117 | 4x | ray_mesh(obj_loaded) |
| 118 | } | |
| 119 | ||
| 120 | #'@title Load an PLY file | |
| 121 | #' | |
| 122 | #'@keywords internal | |
| 123 | #' | |
| 124 | #'@return List | |
| 125 | read_ply = function(filename) { | |
| 126 | ! | filename = path.expand(filename) |
| 127 | ! | if(!file.exists(filename)) { |
| 128 | ! | stop(sprintf("file `%s` does not exist", filename)) |
| 129 | } | |
| 130 | ! | dir = dirname(filename) |
| 131 | ! | lastchar = substr(dir, nchar(dir), nchar(dir)) |
| 132 | ! | fsep = .Platform$file.sep |
| 133 | ! | if(lastchar!=fsep) { |
| 134 | ! | dir=paste0(dir,fsep) |
| 135 | } | |
| 136 | ! | ply_loaded = load_ply(filename, dir) |
| 137 | ! | for(i in seq_len(length(ply_loaded$shapes))) { |
| 138 | ! | if(nrow(ply_loaded$shapes[[i]]$indices) == length(ply_loaded$shapes[[i]]$has_vertex_tex)) { |
| 139 | ! | ply_loaded$shapes[[i]]$has_vertex_tex[apply(ply_loaded$shapes[[i]]$tex_indices,1,(function(x) any(x == -1)))] = FALSE |
| 140 | } | |
| 141 | ! | if(nrow(ply_loaded$shapes[[i]]$indices) == length(ply_loaded$shapes[[i]]$has_vertex_normals)) { |
| 142 | ! | ply_loaded$shapes[[i]]$has_vertex_normals[apply(ply_loaded$shapes[[i]]$norm_indices,1,(function(x) any(x == -1)))] = FALSE |
| 143 | } | |
| 144 | } | |
| 145 | ! | hashes = rep("",length(ply_loaded$materials)) |
| 146 | ! | for(i in seq_len(length(ply_loaded$materials))) { |
| 147 | ! | hashes[i] = digest::digest(ply_loaded$materials[[i]]) |
| 148 | } | |
| 149 | ! | attr(ply_loaded, "material_hashes") = hashes |
| 150 | ! | class(ply_loaded) = c("ray_mesh","list") |
| 151 | ! | ply_loaded |
| 152 | } |
| 1 | #'@title Translate Mesh | |
| 2 | #' | |
| 3 | #'@param mesh The mesh. | |
| 4 | #'@param position Default `c(0,0,0)`. The translation vector. | |
| 5 | #' | |
| 6 | #'@return Translated mesh | |
| 7 | #'@export | |
| 8 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 9 | #'#Translate a mesh in the Cornell box | |
| 10 | #'robj = obj_mesh(r_obj(), scale=150,angle=c(0,180,0)) | |
| 11 | #'generate_cornell_mesh() |> | |
| 12 | #' add_shape(translate_mesh(robj,c(400,100,155))) |> | |
| 13 | #' add_shape(translate_mesh(robj,c(555/2,200,555/2))) |> | |
| 14 | #' add_shape(translate_mesh(robj,c(155,300,400))) |> | |
| 15 | #' rasterize_scene(light_info=directional_light(direction=c(0.1,0.6,-1))) | |
| 16 | translate_mesh = function(mesh, position = c(0, 0, 0)) { | |
| 17 | 165x | for (j in seq_len(length(mesh$vertices))) { |
| 18 | 172x | mesh$vertices[[j]][, 1] = mesh$vertices[[j]][, 1] + position[1] |
| 19 | 172x | mesh$vertices[[j]][, 2] = mesh$vertices[[j]][, 2] + position[2] |
| 20 | 172x | mesh$vertices[[j]][, 3] = mesh$vertices[[j]][, 3] + position[3] |
| 21 | } | |
| 22 | 165x | class(mesh) = c("ray_mesh", "list") |
| 23 | ||
| 24 | 165x | return(mesh) |
| 25 | } | |
| 26 | ||
| 27 | #'@title Scale Mesh | |
| 28 | #' | |
| 29 | #'@param mesh The mesh. | |
| 30 | #'@param scale Default `c(1,1,1)`. The scale amount, per axis. | |
| 31 | #'@param center Default `c(0,0,0)`. The center of the scale. | |
| 32 | #' | |
| 33 | #'@return Scaled mesh | |
| 34 | #'@export | |
| 35 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 36 | #'#Scale a mesh in the Cornell box | |
| 37 | #'robj = obj_mesh(r_obj(), scale=150,angle=c(0,180,0)) | |
| 38 | #' | |
| 39 | #'generate_cornell_mesh() |> | |
| 40 | #' add_shape(scale_mesh(translate_mesh(robj,c(400,100,155)),0.5, center=c(400,100,155))) |> | |
| 41 | #' add_shape(scale_mesh(translate_mesh(robj,c(555/2,200,555/2)),1.5, center=c(555/2,200,555/2))) |> | |
| 42 | #' add_shape(scale_mesh(translate_mesh(robj,c(55,300,400)),c(0.5,2,0.5), center=c(155,300,400))) |> | |
| 43 | #' rasterize_scene(light_info=directional_light(direction=c(0.1,0.6,-1))) | |
| 44 | scale_mesh = function(mesh, scale = 1, center = c(0, 0, 0)) { | |
| 45 | 8x | if (length(scale) == 1) { |
| 46 | ! | scale = rep(scale, 3) |
| 47 | } | |
| 48 | 8x | scale_mat = diag(scale, 3, 3) |
| 49 | 8x | inv_scale_mat = diag(1 / scale, 3, 3) |
| 50 | 8x | for (j in seq_len(length(mesh$vertices))) { |
| 51 | 11x | mesh$vertices[[j]][, 1] = mesh$vertices[[j]][, 1] - center[1] |
| 52 | 11x | mesh$vertices[[j]][, 2] = mesh$vertices[[j]][, 2] - center[2] |
| 53 | 11x | mesh$vertices[[j]][, 3] = mesh$vertices[[j]][, 3] - center[3] |
| 54 | 11x | mesh$vertices[[j]] = mesh$vertices[[j]] %*% scale_mat |
| 55 | 11x | mesh$vertices[[j]][, 1] = mesh$vertices[[j]][, 1] + center[1] |
| 56 | 11x | mesh$vertices[[j]][, 2] = mesh$vertices[[j]][, 2] + center[2] |
| 57 | 11x | mesh$vertices[[j]][, 3] = mesh$vertices[[j]][, 3] + center[3] |
| 58 | ||
| 59 | 11x | if (!is.null(mesh$normals[[j]]) && nrow(mesh$normals[[j]]) > 0) { |
| 60 | 10x | mesh$normals[[j]] = mesh$normals[[j]] %*% t(inv_scale_mat) |
| 61 | ||
| 62 | # Normalize the normals | |
| 63 | 10x | lengths = sqrt(apply(mesh$normals[[j]] * mesh$normals[[j]], 1, sum)) |
| 64 | 10x | lengths[lengths == 0] = 1 |
| 65 | 10x | norm_mat = matrix(lengths, ncol = 3, nrow = length(lengths)) |
| 66 | 10x | mesh$normals[[j]] = mesh$normals[[j]] / norm_mat |
| 67 | } | |
| 68 | } | |
| 69 | 8x | class(mesh) = c("ray_mesh", "list") |
| 70 | ||
| 71 | 8x | return(mesh) |
| 72 | } | |
| 73 | ||
| 74 | #'@title Scale Mesh to Unit Bounding Box | |
| 75 | #' | |
| 76 | #'@param mesh The mesh. | |
| 77 | #'@param center_mesh Default `FALSE`. Whether to center the mesh at the origin after scaling. | |
| 78 | #' | |
| 79 | #'@return Scaled mesh | |
| 80 | #'@export | |
| 81 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 82 | #'#Scale the Cornell box (and contents) down to the unit box. | |
| 83 | #'robj = obj_mesh(r_obj(), scale=150,angle=c(0,180,0)) | |
| 84 | #' | |
| 85 | #'generate_cornell_mesh() |> | |
| 86 | #' add_shape(scale_mesh(translate_mesh(robj,c(400,100,155)),0.5, center=c(400,100,155))) |> | |
| 87 | #' add_shape(scale_mesh(translate_mesh(robj,c(555/2,200,555/2)),1.5, center=c(555/2,200,555/2))) |> | |
| 88 | #' add_shape(scale_mesh(translate_mesh(robj,c(55,300,400)),c(0.5,2,0.5), center=c(155,300,400))) |> | |
| 89 | #' scale_unit_mesh(center_mesh = TRUE) |> | |
| 90 | #' rasterize_scene(light_info=directional_light(direction=c(0.1,0.6,-1)), | |
| 91 | #' lookfrom = c(0,0,-2), lookat=c(0,0,0)) | |
| 92 | scale_unit_mesh = function(mesh, center_mesh = FALSE) { | |
| 93 | ! | center = get_mesh_center(mesh) |
| 94 | ! | bbox = get_mesh_bbox(mesh) |
| 95 | ! | scale_xyz = bbox["max", ] - bbox["min", ] |
| 96 | ! | scale_xyz[scale_xyz == 0] = 1 |
| 97 | ! | scale = 1 / scale_xyz |
| 98 | ! | mesh = scale_mesh(mesh, scale = scale, center = center) |
| 99 | ! | if (center_mesh) { |
| 100 | ! | mesh = center_mesh(mesh) |
| 101 | } | |
| 102 | ! | return(mesh) |
| 103 | } | |
| 104 | ||
| 105 | #'@title Center Mesh | |
| 106 | #' | |
| 107 | #'@description Centers the mesh at the origin. | |
| 108 | #' | |
| 109 | #'@param mesh The mesh object. | |
| 110 | #' | |
| 111 | #'@return Centered mesh | |
| 112 | #'@export | |
| 113 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 114 | #' #Center the Cornell box and the R OBJ at the origin | |
| 115 | #' center_mesh(generate_cornell_mesh()) |> | |
| 116 | #' add_shape(center_mesh(obj_mesh(r_obj(),scale=100,angle=c(0,180,0)))) |> | |
| 117 | #' rasterize_scene(lookfrom=c(0,0,-1100),fov=40,lookat=c(0,0,0), | |
| 118 | #' light_info = directional_light(c(0.4,0.4,-1)) |> | |
| 119 | #' add_light(point_light(c(0,450,0), falloff_quad = 0.0, constant = 0.0002, falloff = 0.005))) | |
| 120 | center_mesh = function(mesh) { | |
| 121 | 1x | center_mat = matrix(c(Inf, -Inf), nrow = 2, ncol = 3) |
| 122 | 1x | for (j in seq_len(length(mesh$vertices))) { |
| 123 | 1x | center_tmp = apply(mesh$vertices[[j]], 2, range) |
| 124 | 1x | center_mat[1, ] = pmin(center_tmp[1, ], center_mat[1, ]) |
| 125 | 1x | center_mat[2, ] = pmax(center_tmp[2, ], center_mat[2, ]) |
| 126 | } | |
| 127 | 1x | center = apply(center_mat, 2, mean) |
| 128 | ||
| 129 | 1x | mesh = translate_mesh(mesh, -center) |
| 130 | 1x | class(mesh) = c("ray_mesh", "list") |
| 131 | 1x | return(mesh) |
| 132 | } | |
| 133 | ||
| 134 | #'@title Get Mesh Center | |
| 135 | #' | |
| 136 | #'@description Calculates the coordinates of the center of a mesh | |
| 137 | #' | |
| 138 | #'@param mesh The mesh object. | |
| 139 | #' | |
| 140 | #'@return Length-3 numeric vector | |
| 141 | #'@export | |
| 142 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 143 | #' #Calculates the center of the mesh | |
| 144 | #' get_mesh_center(generate_cornell_mesh()) | |
| 145 | get_mesh_center = function(mesh) { | |
| 146 | 1x | center_mat = matrix(c(Inf, -Inf), nrow = 2, ncol = 3) |
| 147 | 1x | for (j in seq_len(length(mesh$vertices))) { |
| 148 | 1x | center_tmp = apply(mesh$vertices[[j]], 2, range) |
| 149 | 1x | center_mat[1, ] = pmin(center_tmp[1, ], center_mat[1, ]) |
| 150 | 1x | center_mat[2, ] = pmax(center_tmp[2, ], center_mat[2, ]) |
| 151 | } | |
| 152 | 1x | center = apply(center_mat, 2, mean) |
| 153 | 1x | return(center) |
| 154 | } | |
| 155 | ||
| 156 | #'@title Get Mesh Bounding Box | |
| 157 | #' | |
| 158 | #'@description Calculates the bounding box of a mesh | |
| 159 | #' | |
| 160 | #'@param mesh The mesh object. | |
| 161 | #' | |
| 162 | #'@return 2x3 numeric matrix | |
| 163 | #'@export | |
| 164 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 165 | #' #Calculates the center of the mesh | |
| 166 | #' get_mesh_bbox(generate_cornell_mesh()) | |
| 167 | get_mesh_bbox = function(mesh) { | |
| 168 | 4x | center_mat = matrix(c(Inf, -Inf), nrow = 2, ncol = 3) |
| 169 | 4x | for (j in seq_len(length(mesh$vertices))) { |
| 170 | 6x | center_tmp = apply(mesh$vertices[[j]], 2, range) |
| 171 | 6x | center_mat[1, ] = pmin(center_tmp[1, ], center_mat[1, ]) |
| 172 | 6x | center_mat[2, ] = pmax(center_tmp[2, ], center_mat[2, ]) |
| 173 | } | |
| 174 | 4x | colnames(center_mat) = c("x", "y", "z") |
| 175 | 4x | rownames(center_mat) = c("min", "max") |
| 176 | 4x | return(center_mat) |
| 177 | } | |
| 178 | ||
| 179 | #'@title Generate Rotation Matrix | |
| 180 | #' | |
| 181 | #'@param angle The angle | |
| 182 | #'@param order_rotation Default `c(1,2,3)`. | |
| 183 | #'@return Matrix | |
| 184 | #'@keywords internal | |
| 185 | generate_rot_matrix = function(angle, order_rotation) { | |
| 186 | 7x | rots = list() |
| 187 | 7x | rots[[1]] = matrix( |
| 188 | 7x | c( |
| 189 | 7x | 1, |
| 190 | 7x | 0, |
| 191 | 7x | 0, |
| 192 | 7x | 0, |
| 193 | 7x | cos(angle[1]), |
| 194 | 7x | sin(angle[1]), |
| 195 | 7x | 0, |
| 196 | 7x | -sin(angle[1]), |
| 197 | 7x | cos(angle[1]) |
| 198 | ), | |
| 199 | 7x | 3, |
| 200 | 7x | 3 |
| 201 | ) | |
| 202 | 7x | rots[[2]] = matrix( |
| 203 | 7x | c( |
| 204 | 7x | cos(angle[2]), |
| 205 | 7x | 0, |
| 206 | 7x | -sin(angle[2]), |
| 207 | 7x | 0, |
| 208 | 7x | 1, |
| 209 | 7x | 0, |
| 210 | 7x | sin(angle[2]), |
| 211 | 7x | 0, |
| 212 | 7x | cos(angle[2]) |
| 213 | ), | |
| 214 | 7x | 3, |
| 215 | 7x | 3 |
| 216 | ) | |
| 217 | 7x | rots[[3]] = matrix( |
| 218 | 7x | c( |
| 219 | 7x | cos(angle[3]), |
| 220 | 7x | sin(angle[3]), |
| 221 | 7x | 0, |
| 222 | 7x | -sin(angle[3]), |
| 223 | 7x | cos(angle[3]), |
| 224 | 7x | 0, |
| 225 | 7x | 0, |
| 226 | 7x | 0, |
| 227 | 7x | 1 |
| 228 | ), | |
| 229 | 7x | 3, |
| 230 | 7x | 3 |
| 231 | ) | |
| 232 | 7x | returnmat = matrix(c(1, 0, 0, 0, 1, 0, 0, 0, 1), 3, 3) |
| 233 | 7x | for (i in 1:3) { |
| 234 | 21x | returnmat = returnmat %*% rots[[order_rotation[i]]] |
| 235 | } | |
| 236 | 7x | return(returnmat) |
| 237 | } | |
| 238 | ||
| 239 | #'@title Rotate Mesh | |
| 240 | #' | |
| 241 | #'@param mesh The mesh. | |
| 242 | #'@param angle Default `c(0,0,0)`. The rotation amount for the x/y/z axes, in degrees. | |
| 243 | #'@param pivot_point Default `c(0,0,0)`. The pivot point of the rotation. | |
| 244 | #'@param order_rotation Default `c(1,2,3)`. The order in which to perform the rotations. | |
| 245 | #' | |
| 246 | #'@return Rotated Mesh | |
| 247 | #'@export | |
| 248 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 249 | #'#Rotate a mesh in the Cornell box | |
| 250 | #'robj = obj_mesh(r_obj(), scale=150,angle=c(0,180,0)) | |
| 251 | #' | |
| 252 | #'generate_cornell_mesh() |> | |
| 253 | #' add_shape(rotate_mesh(translate_mesh(robj,c(400,100,155)),c(0,30,0), | |
| 254 | #' pivot_point=c(400,100,155))) |> | |
| 255 | #' add_shape(rotate_mesh(translate_mesh(robj,c(555/2,200,555/2)),c(-30,60,30), | |
| 256 | #' pivot_point=c(555/2,200,555/2))) |> | |
| 257 | #' add_shape(rotate_mesh(translate_mesh(robj,c(155,300,400)),c(-30,60,30), | |
| 258 | #' pivot_point=c(155,300,400), order_rotation=c(3,2,1))) |> | |
| 259 | #' rasterize_scene(light_info=directional_light(direction=c(0.1,0.6,-1))) | |
| 260 | rotate_mesh = function( | |
| 261 | mesh, | |
| 262 | angle = c(0, 0, 0), | |
| 263 | pivot_point = c(0, 0, 0), | |
| 264 | order_rotation = c(1, 2, 3) | |
| 265 | ) { | |
| 266 | 7x | angle = angle * pi / 180 |
| 267 | 7x | rot_mat = generate_rot_matrix(angle, order_rotation) |
| 268 | 7x | inv_t = t(solve(rot_mat)) |
| 269 | 7x | for (j in seq_len(length(mesh$vertices))) { |
| 270 | 10x | mesh$vertices[[j]][, 1] = mesh$vertices[[j]][, 1] - pivot_point[1] |
| 271 | 10x | mesh$vertices[[j]][, 2] = mesh$vertices[[j]][, 2] - pivot_point[2] |
| 272 | 10x | mesh$vertices[[j]][, 3] = mesh$vertices[[j]][, 3] - pivot_point[3] |
| 273 | 10x | mesh$vertices[[j]] = mesh$vertices[[j]] %*% rot_mat |
| 274 | 10x | mesh$vertices[[j]][, 1] = mesh$vertices[[j]][, 1] + pivot_point[1] |
| 275 | 10x | mesh$vertices[[j]][, 2] = mesh$vertices[[j]][, 2] + pivot_point[2] |
| 276 | 10x | mesh$vertices[[j]][, 3] = mesh$vertices[[j]][, 3] + pivot_point[3] |
| 277 | ||
| 278 | 10x | if (!is.null(mesh$normals[[j]]) && nrow(mesh$normals[[j]]) > 0) { |
| 279 | 8x | mesh$normals[[j]] = mesh$normals[[j]] %*% inv_t |
| 280 | } | |
| 281 | } | |
| 282 | 7x | class(mesh) = c("ray_mesh", "list") |
| 283 | ||
| 284 | 7x | return(mesh) |
| 285 | } | |
| 286 | ||
| 287 | #' @title Transform Mesh (3x3 or 4x4, row-vector) | |
| 288 | #' | |
| 289 | #' @param mesh The mesh. | |
| 290 | #' @param transform_matrix 3x3 (linear only) or 4x4 row-vector homogeneous. | |
| 291 | #' | |
| 292 | #' @return Transformed mesh. For 4x4, applies rotation/scale and translation. | |
| 293 | #' @export | |
| 294 | transform_mesh = function(mesh, transform_matrix) { | |
| 295 | ! | dm = dim(transform_matrix) |
| 296 | ! | if (is.null(dm) || !(dm[1] %in% c(3, 4) && dm[2] %in% c(3, 4))) { |
| 297 | ! | stop("transform_matrix must be 3x3 or 4x4") |
| 298 | } | |
| 299 | ||
| 300 | ! | R3 = transform_matrix[1:3, 1:3] |
| 301 | ! | tvec = c(0, 0, 0) |
| 302 | ! | if (all(dm == c(4, 4))) { |
| 303 | # row-vector homogeneous: translation is the last ROW (first 3 entries) | |
| 304 | ! | tvec = transform_matrix[4, 1:3] |
| 305 | } | |
| 306 | ||
| 307 | ! | inv_t = t(solve(R3)) # for normals |
| 308 | ||
| 309 | ! | for (j in seq_len(length(mesh$vertices))) { |
| 310 | ! | V = mesh$vertices[[j]] # n×3 row vectors |
| 311 | ! | V = V %*% R3 |
| 312 | ! | if (all(dm == c(4, 4))) { |
| 313 | ! | V[, 1] = V[, 1] + tvec[1] |
| 314 | ! | V[, 2] = V[, 2] + tvec[2] |
| 315 | ! | V[, 3] = V[, 3] + tvec[3] |
| 316 | } | |
| 317 | ! | mesh$vertices[[j]] = V |
| 318 | ||
| 319 | ! | if (!is.null(mesh$normals[[j]]) && nrow(mesh$normals[[j]]) > 0) { |
| 320 | ! | mesh$normals[[j]] = mesh$normals[[j]] %*% inv_t |
| 321 | } | |
| 322 | } | |
| 323 | ! | class(mesh) = c("ray_mesh", "list") |
| 324 | ! | mesh |
| 325 | } | |
| 326 | ||
| 327 | #' @title Look-At Transform (row-vector convention) | |
| 328 | #' | |
| 329 | #' @description Builds a 4x4 transform whose rows are the world-space basis | |
| 330 | #' (right, up, forward). Use with [transform_mesh()] (rotation) and | |
| 331 | #' [translate_mesh()] (position). | |
| 332 | #' | |
| 333 | #' @param pos Default `c(0,0,0)`. World-space origin of the local frame. | |
| 334 | #' @param look Default `c(0,0,1)`. World-space point to look at. | |
| 335 | #' @param up Default `c(0,1,0)`. World-space up direction (need not be unit length). | |
| 336 | #' | |
| 337 | #' @return 4x4 numeric matrix. The upper-left 3x3 is the rotation used by | |
| 338 | #' [transform_mesh()]. The last column contains `pos` for convenience, but | |
| 339 | #' translation should be applied via [translate_mesh()]. | |
| 340 | #' @export | |
| 341 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 342 | #' m = sphere_mesh(radius = 0.5) | |
| 343 | #' pos = c(-1,0,0) # place Moon on the left | |
| 344 | #' look = c(0,0,0) # look toward the origin (e.g., Earth/camera) | |
| 345 | #' up = c(0,1,0) | |
| 346 | #' | |
| 347 | #' M = lookat_transform(pos = pos, look = look, up = up) | |
| 348 | #' | |
| 349 | #' m |> | |
| 350 | #' transform_mesh(M) |> | |
| 351 | #' translate_mesh(pos) |> | |
| 352 | #' rasterize_scene(lookfrom = c(0,0,0), lookat = pos, | |
| 353 | #' light_info = directional_light(direction = c(1,0,0))) | |
| 354 | lookat_transform = function( | |
| 355 | pos = c(0, 0, 0), | |
| 356 | look = c(0, 0, 1), | |
| 357 | up = c(0, 1, 0) | |
| 358 | ) { | |
| 359 | ! | dir = normalize(look - pos) |
| 360 | ! | right = cross_prod(normalize(up), dir) |
| 361 | ! | rlen = sqrt(sum(right * right)) |
| 362 | ! | if (!is.finite(rlen) || rlen < 1e-12) { |
| 363 | ! | stop( |
| 364 | ! | '"up" vector and viewing direction are collinear; cannot build look-at transform' |
| 365 | ) | |
| 366 | } | |
| 367 | ! | right = right / rlen |
| 368 | ! | newUp = cross_prod(dir, right) |
| 369 | ||
| 370 | ! | M = diag(4) |
| 371 | ! | M[1, 1:3] = right |
| 372 | ! | M[2, 1:3] = newUp |
| 373 | ! | M[3, 1:3] = dir |
| 374 | ! | M[4, 1:3] = pos |
| 375 | ! | M |
| 376 | } |
| 1 | #' Construct Displacement Sphere | |
| 2 | #' | |
| 3 | #' @param displacement_texture Image or matrix/array that will be used to displace the sphere. | |
| 4 | #' @param displacement_scale Default `1`. Scale of the displacement. | |
| 5 | #' @param use_cube Default `FALSE`. Whether to use a subdivided cube instead of a UV sphere. Use this | |
| 6 | #' if you want to visualize areas near the poles. | |
| 7 | #' @param cube_subdivision_levels Default `NA`. Number of times to subdivide the cube before | |
| 8 | #' projecting it to a sphere. When `NA`, this is calculated from the displacement texture | |
| 9 | #' resolution as `max(1, ceiling(log((width * height) / 12) / log(4)))`, where | |
| 10 | #' `width * height` is the number of pixels in the texture, `12` is the number of starting | |
| 11 | #' cube triangles, and each subdivision level increases the triangle count by about `4`. | |
| 12 | #' @param displace Default `TRUE`. Whether to displace the sphere, or just generate the initial mesh | |
| 13 | #' for later displacement. | |
| 14 | #' @param verbose Default `TRUE`. Whether to print displacement texture information. | |
| 15 | #' @param position Default `c(0,0,0)`. Position of the mesh. | |
| 16 | #' @param scale Default `c(1,1,1)`. Scale of the mesh. Can also be a single numeric value scaling all axes uniformly. | |
| 17 | #' @param angle Default `c(0,0,0)`. Angle to rotate the mesh. | |
| 18 | #' @param pivot_point Default `c(0,0,0)`. Point around which to rotate the mesh. | |
| 19 | #' @param order_rotation Default `c(1,2,3)`. Order to rotate the axes. | |
| 20 | #' @param material Default [material_list()] (default values). Specify the material of the object. | |
| 21 | #' | |
| 22 | #' @return raymesh object | |
| 23 | #' @export | |
| 24 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 25 | #' texture_dim = 800 | |
| 26 | #' u = seq(0, 2 * pi, length.out = texture_dim) | |
| 27 | #' v = seq(0, 2 * pi, length.out = texture_dim) | |
| 28 | #' knit_texture = outer(u, v, function(x, y) { | |
| 29 | #' sin(10 * x + 0.75 * sin(10 * y))^2 + 0.35 * cos(12 * y)^2 | |
| 30 | #' }) | |
| 31 | #' knit_texture = (knit_texture - min(knit_texture)) / diff(range(knit_texture)) | |
| 32 | #' knit_texture = array( | |
| 33 | #' rep(knit_texture, 3), | |
| 34 | #' dim = c(texture_dim, texture_dim, 3) | |
| 35 | #' ) | |
| 36 | #' rayimage::plot_image(knit_texture) | |
| 37 | #' light_info = directional_light(c(1,1,1), color="dodgerblue",intensity=0.8) |> | |
| 38 | #' add_light(directional_light(c(-1,-1,0.1), color="red",intensity=0.8)) |> | |
| 39 | #' add_light(directional_light(c(0.5,1,0.5),intensity=0.8)) | |
| 40 | #' displacement_sphere(knit_texture, | |
| 41 | #' displacement_scale = 0.08, verbose = TRUE) |> | |
| 42 | #' rasterize_scene(light_info = light_info, fov=15) | |
| 43 | #' | |
| 44 | #' #The default sphere has issues near the poles | |
| 45 | #' displacement_sphere(knit_texture, displacement_scale = 0.08) |> | |
| 46 | #' rasterize_scene(light_info = light_info, fov=10, lookfrom=c(0,10,10)) | |
| 47 | #' | |
| 48 | #' # A cube will render more nicely near the poles | |
| 49 | #' displacement_sphere(knit_texture, use_cube = TRUE, displacement_scale = 0.08) |> | |
| 50 | #' rasterize_scene(light_info = light_info, fov=10, lookfrom=c(0,10,10)) | |
| 51 | displacement_sphere = function( | |
| 52 | displacement_texture, | |
| 53 | displacement_scale = 1, | |
| 54 | use_cube = FALSE, | |
| 55 | cube_subdivision_levels = NA, | |
| 56 | displace = TRUE, | |
| 57 | verbose = TRUE, | |
| 58 | position = c(0, 0, 0), | |
| 59 | scale = c(1, 1, 1), | |
| 60 | angle = c(0, 0, 0), | |
| 61 | pivot_point = c(0, 0, 0), | |
| 62 | order_rotation = c(1, 2, 3), | |
| 63 | material = material_list() | |
| 64 | ) { | |
| 65 | 1x | displacement_texture = rayimage::ray_read_image( |
| 66 | 1x | displacement_texture, |
| 67 | 1x | convert_to_array = FALSE |
| 68 | ) | |
| 69 | ||
| 70 | 1x | if (use_cube) { |
| 71 | 1x | map_cube_to_sphere = function(mesh) { |
| 72 | 1x | project_vertex_to_sphere = function(x) { |
| 73 | 98x | x / sqrt(sum(x * x)) |
| 74 | } | |
| 75 | ||
| 76 | 1x | mesh$vertices[[1]] = t(apply( |
| 77 | 1x | mesh$vertices[[1]], |
| 78 | 1x | 1, |
| 79 | 1x | project_vertex_to_sphere |
| 80 | )) | |
| 81 | 1x | add_sphere_uv_mesh(mesh, override_existing = TRUE) |> |
| 82 | 1x | smooth_normals_mesh() |
| 83 | } | |
| 84 | 1x | if (is.na(cube_subdivision_levels)) { |
| 85 | 1x | initial_triangles = 12 |
| 86 | 1x | subdivision_factor = 4 |
| 87 | 1x | pixels = prod(dim(displacement_texture)[1:2]) |
| 88 | 1x | cube_subdivision_levels = max( |
| 89 | 1x | 1, |
| 90 | 1x | ceiling(log(pixels / initial_triangles) / log(subdivision_factor)) |
| 91 | ) | |
| 92 | } | |
| 93 | ||
| 94 | 1x | raymesh_new = cube_mesh() |> |
| 95 | 1x | subdivide_mesh(subdivision_levels = cube_subdivision_levels) |> |
| 96 | 1x | map_cube_to_sphere() |
| 97 | } else { | |
| 98 | ! | map_grid_to_sphere <- function(x, y) { |
| 99 | # Convert x and y to degrees | |
| 100 | ! | longitude = x * 180 # Scale -1 to 1 to -180 to 180 |
| 101 | ! | latitude = y * 90 # Scale -1 to 1 to -90 to 90 |
| 102 | ||
| 103 | # Convert degrees to radians | |
| 104 | ! | longitude_rad = longitude * pi / 180 |
| 105 | ! | latitude_rad = latitude * pi / 180 |
| 106 | ||
| 107 | # Convert spherical to Cartesian coordinates | |
| 108 | ! | X = cos(latitude_rad) * cos(longitude_rad) |
| 109 | ! | Z = cos(latitude_rad) * sin(longitude_rad) |
| 110 | ! | Y = sin(latitude_rad) |
| 111 | ||
| 112 | # Return a matrix of sphere coordinates | |
| 113 | ! | return(cbind(X, Y, Z)) |
| 114 | } | |
| 115 | ! | raymesh_surface = generate_surface(matrix( |
| 116 | ! | 0, |
| 117 | ! | ncol = nrow(displacement_texture), |
| 118 | ! | nrow = ncol(displacement_texture) |
| 119 | )) | |
| 120 | ! | range_x = range(raymesh_surface$verts[, 1]) |
| 121 | ! | raymesh_surface$verts[, 1] = raymesh_surface$verts[, 1] / range_x[2] |
| 122 | ! | range_z = range(raymesh_surface$verts[, 3]) |
| 123 | ! | raymesh_surface$verts[, 3] = raymesh_surface$verts[, 3] / range_z[2] |
| 124 | ! | raymesh_surface$verts[, 2] = 0 |
| 125 | ||
| 126 | ! | spherized_mesh_verts = map_grid_to_sphere( |
| 127 | ! | raymesh_surface$verts[, 1], |
| 128 | ! | raymesh_surface$verts[, 3] |
| 129 | ) | |
| 130 | ||
| 131 | ! | new_texcoords = matrix( |
| 132 | ! | c(c(-raymesh_surface$verts[, 1], raymesh_surface$verts[, 3]) / 2 + 0.5), |
| 133 | ! | ncol = 2 |
| 134 | ) | |
| 135 | ||
| 136 | ! | raymesh_new = construct_mesh( |
| 137 | ! | vertices = spherized_mesh_verts, |
| 138 | ! | indices = t(raymesh_surface$inds) - 1, |
| 139 | ! | tex_indices = t(raymesh_surface$inds) - 1, |
| 140 | ! | norm_indices = t(raymesh_surface$inds) - 1, |
| 141 | ! | texcoords = new_texcoords, |
| 142 | ! | normals = t(apply(spherized_mesh_verts, 1, \(x) x / sqrt(sum(x * x)))), |
| 143 | ! | material = material |
| 144 | ) | |
| 145 | } | |
| 146 | 1x | if (any(scale != 1)) { |
| 147 | ! | raymesh_new = scale_mesh(raymesh_new, scale = scale) |
| 148 | } | |
| 149 | 1x | if (any(angle != 0)) { |
| 150 | ! | raymesh_new = rotate_mesh( |
| 151 | ! | raymesh_new, |
| 152 | ! | angle = angle, |
| 153 | ! | pivot_point = pivot_point, |
| 154 | ! | order_rotation = order_rotation |
| 155 | ) | |
| 156 | } | |
| 157 | 1x | raymesh_new = translate_mesh(raymesh_new, position) |
| 158 | 1x | if (displace) { |
| 159 | 1x | return(displace_mesh( |
| 160 | 1x | raymesh_new, |
| 161 | 1x | displacement_texture, |
| 162 | 1x | displacement_scale, |
| 163 | 1x | verbose = verbose |
| 164 | )) | |
| 165 | } else { | |
| 166 | ! | return(raymesh_new) |
| 167 | } | |
| 168 | } |
| 1 | #' @title Subdivide Mesh | |
| 2 | #' | |
| 3 | #' @description Applies Loop subdivision to the scene (or selected meshes). | |
| 4 | #' | |
| 5 | #' @param scene The scene to subdivide. | |
| 6 | #' @param id Default `NA`, all shapes. The index of which shape to subdivide. | |
| 7 | #' @param subdivision_levels Default `1`. | |
| 8 | #' Number of Loop subdivisions to be applied to the mesh. | |
| 9 | #' @param simple Default `FALSE`. Whether to use simple subdivision, which does | |
| 10 | #' not change the appearance of the mesh but does create a finer mesh. | |
| 11 | #' @param normals Default `TRUE`. Whether to calculate subdivided vertex normals. | |
| 12 | #' @param verbose Default `FALSE`. | |
| 13 | #' @return Scene with shape added. | |
| 14 | #' @export | |
| 15 | #' | |
| 16 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 17 | #' #Subdivide the included R mesh | |
| 18 | #' obj_mesh(r_obj(),position=c(-0.5,0,0)) |> | |
| 19 | #' add_shape(subdivide_mesh(obj_mesh(r_obj(),position=c(0.5,0,0)), | |
| 20 | #' subdivision_levels = 2)) |> | |
| 21 | #' rasterize_scene(light_info = directional_light(direction=c(0.2,0.5,1)),fov=13) | |
| 22 | subdivide_mesh = function( | |
| 23 | scene, | |
| 24 | id = NA, | |
| 25 | subdivision_levels = 2, | |
| 26 | simple = FALSE, | |
| 27 | normals = TRUE, | |
| 28 | verbose = FALSE | |
| 29 | ) { | |
| 30 | 1x | if (subdivision_levels == 1) { |
| 31 | ! | return(scene) |
| 32 | } | |
| 33 | 1x | if (is.na(id)) { |
| 34 | 1x | for (i in seq_along(scene$shapes)) { |
| 35 | 1x | new_shape_info = LoopSubdivide( |
| 36 | 1x | mesh = scene, |
| 37 | 1x | shape_i = i - 1, |
| 38 | 1x | nLevels = subdivision_levels, |
| 39 | 1x | verbose = verbose, |
| 40 | 1x | simple_subdivision = simple |
| 41 | ) | |
| 42 | 1x | scene$shapes[[i]]$indices = new_shape_info$indices |
| 43 | 1x | scene$shapes[[i]]$tex_indices = new_shape_info$indices |
| 44 | 1x | scene$shapes[[i]]$norm_indices = new_shape_info$indices |
| 45 | 1x | scene$shapes[[i]]$material_ids = new_shape_info$face_material_id |
| 46 | 1x | scene$shapes[[i]]$has_vertex_tex = new_shape_info$has_vertex_tex |
| 47 | 1x | scene$shapes[[i]]$has_vertex_normals = new_shape_info$has_vertex_normals |
| 48 | 1x | if (normals) { |
| 49 | 1x | scene$shapes[[i]]$has_vertex_normals = new_shape_info$has_vertex_normals |
| 50 | } else { | |
| 51 | ! | scene$shapes[[i]]$has_vertex_normals = rep( |
| 52 | ! | FALSE, |
| 53 | ! | nrow(new_shape_info$indices) |
| 54 | ) | |
| 55 | } | |
| 56 | 1x | scene$vertices[[i]] = new_shape_info$vertices |
| 57 | 1x | if (normals) { |
| 58 | 1x | scene$normals[[i]] = new_shape_info$normals |
| 59 | } else { | |
| 60 | ! | scene$normals[[i]] = matrix(0, ncol = 3, nrow = 0) |
| 61 | } | |
| 62 | 1x | scene$texcoords[[i]] = new_shape_info$texcoords |
| 63 | } | |
| 64 | } else { | |
| 65 | ! | stopifnot(id <= length(scene$shapes)) |
| 66 | ! | new_shape_info = LoopSubdivide( |
| 67 | ! | mesh = scene, |
| 68 | ! | shape_i = id - 1, |
| 69 | ! | nLevels = subdivision_levels, |
| 70 | ! | verbose = verbose, |
| 71 | ! | simple_subdivision = simple |
| 72 | ) | |
| 73 | ! | scene$shapes[[id]]$indices = new_shape_info$indices |
| 74 | ! | scene$shapes[[id]]$tex_indices = new_shape_info$indices |
| 75 | ! | scene$shapes[[id]]$norm_indices = new_shape_info$indices |
| 76 | ! | scene$shapes[[id]]$material_ids = new_shape_info$face_material_id |
| 77 | ! | scene$shapes[[id]]$has_vertex_tex = new_shape_info$has_vertex_tex |
| 78 | ! | if (normals) { |
| 79 | ! | scene$shapes[[id]]$has_vertex_normals = new_shape_info$has_vertex_normals |
| 80 | } else { | |
| 81 | ! | scene$shapes[[id]]$has_vertex_normals = rep( |
| 82 | ! | FALSE, |
| 83 | ! | nrow(new_shape_info$indices) |
| 84 | ) | |
| 85 | } | |
| 86 | ! | scene$vertices[[id]] = new_shape_info$vertices |
| 87 | ! | if (normals) { |
| 88 | ! | scene$normals[[id]] = new_shape_info$normals |
| 89 | } else { | |
| 90 | ! | scene$normals[[id]] = matrix(0, ncol = 3, nrow = 0) |
| 91 | } | |
| 92 | ! | scene$texcoords[[id]] = new_shape_info$texcoords |
| 93 | } | |
| 94 | 1x | return(scene) |
| 95 | } |
| 1 | #'@title Merge scene | |
| 2 | #' | |
| 3 | #'@description Merge the shapes to one | |
| 4 | #' | |
| 5 | #'@keywords internal | |
| 6 | #'@return Merged scene | |
| 7 | merge_scene = function(old_scene, flatten_materials = TRUE) { | |
| 8 | 6x | if(length(old_scene$shapes) == 1) { |
| 9 | 4x | old_scene$vertices = old_scene$vertices[[1]] |
| 10 | 4x | old_scene$texcoords = old_scene$texcoords[[1]] |
| 11 | 4x | old_scene$normals = old_scene$normals[[1]] |
| 12 | 4x | old_scene$materials = old_scene$materials[[1]] |
| 13 | ||
| 14 | 4x | return(old_scene) |
| 15 | } | |
| 16 | 2x | indices = list() |
| 17 | 2x | tex_indices = list() |
| 18 | 2x | norm_indices = list() |
| 19 | 2x | material_ids = list() |
| 20 | 2x | has_vertex_tex = list() |
| 21 | 2x | has_vertex_normals = list() |
| 22 | 2x | materials = list() |
| 23 | ||
| 24 | 2x | max_vertices = 0L |
| 25 | 2x | max_texcoords = 0L |
| 26 | 2x | max_normals = 0L |
| 27 | 2x | max_materials = 0L |
| 28 | 2x | for(i in seq_len(length(old_scene$shapes))) { |
| 29 | 5x | indices[[i]] = old_scene$shapes[[i]]$indices + max_vertices |
| 30 | 5x | tex_indices[[i]] = old_scene$shapes[[i]]$tex_indices + max_texcoords |
| 31 | 5x | norm_indices[[i]] = old_scene$shapes[[i]]$norm_indices + max_normals |
| 32 | 5x | material_ids[[i]] = ifelse(old_scene$shapes[[i]]$material_ids != -1L, |
| 33 | 5x | old_scene$shapes[[i]]$material_ids + max_materials, |
| 34 | 5x | -1L) |
| 35 | 5x | has_vertex_tex[[i]] = old_scene$shapes[[i]]$has_vertex_tex |
| 36 | 5x | has_vertex_normals[[i]] = old_scene$shapes[[i]]$has_vertex_normals |
| 37 | ||
| 38 | 5x | max_vertices = max_vertices + nrow(old_scene$vertices[[i]]) |
| 39 | 5x | max_texcoords = max_texcoords + nrow(old_scene$texcoords[[i]]) |
| 40 | 5x | max_normals = max_normals + nrow(old_scene$normals[[i]]) |
| 41 | 5x | max_materials = max_materials + length(old_scene$materials[[i]]) |
| 42 | } | |
| 43 | ||
| 44 | 2x | scene = list() |
| 45 | 2x | scene$shapes = list() |
| 46 | 2x | scene$shapes[[1]] = list() |
| 47 | ||
| 48 | 2x | scene$shapes[[1]]$indices = do.call(rbind,indices) |
| 49 | 2x | scene$shapes[[1]]$tex_indices = do.call(rbind,tex_indices) |
| 50 | 2x | scene$shapes[[1]]$norm_indices = do.call(rbind,norm_indices) |
| 51 | 2x | scene$shapes[[1]]$material_ids = unlist(material_ids) |
| 52 | 2x | scene$shapes[[1]]$has_vertex_tex = unlist(has_vertex_tex) |
| 53 | 2x | scene$shapes[[1]]$has_vertex_normals = unlist(has_vertex_normals) |
| 54 | 2x | scene$vertices = unlist(do.call(rbind, old_scene$vertices), recursive = FALSE) |
| 55 | 2x | scene$texcoords = unlist(do.call(rbind, old_scene$texcoords), recursive = FALSE) |
| 56 | 2x | scene$normals = unlist(do.call(rbind, old_scene$normals), recursive = FALSE) |
| 57 | ||
| 58 | #Flatten materials | |
| 59 | 2x | num_materials = 0 |
| 60 | 2x | for(i in seq_len(length(old_scene$materials))) { |
| 61 | 5x | num_materials = num_materials + length(old_scene$materials[[i]]) |
| 62 | } | |
| 63 | 2x | if(flatten_materials) { |
| 64 | 2x | scene$materials = vector(mode="list", length = num_materials) |
| 65 | } else { | |
| 66 | ! | scene$materials = list(list(vector(mode="list", length = num_materials))) |
| 67 | } | |
| 68 | ||
| 69 | 2x | counter = 1 |
| 70 | 2x | for(i in seq_len(length(old_scene$materials))) { |
| 71 | 5x | n_mats = length(old_scene$materials[[i]]) |
| 72 | 5x | for(j in seq_len(n_mats)) { |
| 73 | 5x | if(flatten_materials) { |
| 74 | 5x | scene$materials[[counter]] = old_scene$materials[[i]][[j]] |
| 75 | 5x | counter = counter + 1 |
| 76 | } else { | |
| 77 | ! | scene$materials[[1]][[j]] = old_scene$materials[[i]][[j]] |
| 78 | } | |
| 79 | } | |
| 80 | } | |
| 81 | 2x | attr(scene, "material_hashes") = attr(old_scene, "material_hashes") |
| 82 | ||
| 83 | 2x | class(scene) = c("ray_mesh", "list") |
| 84 | ||
| 85 | 2x | return(scene) |
| 86 | } |
| 1 | #'@title Calculate Smooth Mesh Normals | |
| 2 | #' | |
| 3 | #'@param mesh The mesh. | |
| 4 | #'@param id Default `NA` (all shapes). The shape index to have new normals calculated. | |
| 5 | #' | |
| 6 | #'@return Mesh with new vertex normals | |
| 7 | #'@export | |
| 8 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 9 | #' #Let's construct a mesh from the volcano dataset | |
| 10 | #' #Build the vertex matrix | |
| 11 | #' vertex_list = list() | |
| 12 | #' counter = 1 | |
| 13 | #' for(i in 1:nrow(volcano)) { | |
| 14 | #' for(j in 1:ncol(volcano)) { | |
| 15 | #' vertex_list[[counter]] = matrix(c(j,volcano[i,j],i), ncol=3) | |
| 16 | #' counter = counter + 1 | |
| 17 | #' } | |
| 18 | #' } | |
| 19 | #' vertices = do.call(rbind,vertex_list) | |
| 20 | #' | |
| 21 | #' #Build the index matrix | |
| 22 | #' index_list = list() | |
| 23 | #' counter = 0 | |
| 24 | #' for(i in 1:(nrow(volcano)-1)) { | |
| 25 | #' for(j in 1:(ncol(volcano)-1)) { | |
| 26 | #' index_list[[counter+1]] = matrix(c(counter,counter+ncol(volcano),counter+1, | |
| 27 | #' counter+ncol(volcano),counter+ncol(volcano)+1,counter + 1), | |
| 28 | #' nrow=2, ncol=3, byrow=TRUE) | |
| 29 | #' counter = counter + 1 | |
| 30 | #' } | |
| 31 | #' counter = counter + 1 | |
| 32 | #' } | |
| 33 | #' indices = do.call(rbind,index_list) | |
| 34 | #' #Construct the mesh | |
| 35 | #' volc_mesh = construct_mesh(vertices = vertices, indices = indices, | |
| 36 | #' material = material_list(type="diffuse", diffuse="darkred", | |
| 37 | #' ambient = "darkred", ambient_intensity=0.2)) | |
| 38 | #' #Rasterize the no-normal scene | |
| 39 | #' scale_mesh(volc_mesh, scale = c(1,1/3,1)) |> | |
| 40 | #' center_mesh() |> | |
| 41 | #' rasterize_scene(lookfrom=c(-50,50,100),lookat=c(7,-15,0), fov=40,width=800,height=800, | |
| 42 | #' light_info = directional_light(c(0,1,1)) |> | |
| 43 | #' add_light(directional_light(c(1,1,-1)))) | |
| 44 | #' | |
| 45 | #' #Smooth the mesh | |
| 46 | #' volc_mesh_smooth = smooth_normals_mesh(volc_mesh) | |
| 47 | #' | |
| 48 | #' #Rasterize the scene | |
| 49 | #' scale_mesh(volc_mesh_smooth, scale = c(1,1/3,1)) |> | |
| 50 | #' center_mesh() |> | |
| 51 | #' rasterize_scene(lookfrom=c(-50,50,100),lookat=c(7,-15,0), fov=40,width=800,height=800, | |
| 52 | #' light_info = directional_light(c(0,1,1)) |> | |
| 53 | #' add_light(directional_light(c(1,1,-1)))) | |
| 54 | smooth_normals_mesh = function(mesh, id = NA) { | |
| 55 | 2x | stopifnot(inherits(mesh, "ray_mesh")) |
| 56 | 2x | if (is.na(id)) { |
| 57 | 2x | for (i in seq_len(length(mesh$shapes))) { |
| 58 | 2x | new_normals = CalculateNormals(mesh, i - 1) |
| 59 | 2x | mesh$shapes[[i]]$norm_indices = mesh$shapes[[i]]$indices |
| 60 | 2x | mesh$shapes[[i]]$has_vertex_normals = rep( |
| 61 | 2x | TRUE, |
| 62 | 2x | length(mesh$shapes[[i]]$indices) |
| 63 | ) | |
| 64 | 2x | mesh$normals[i] = ray_vertex_data(new_normals) |
| 65 | } | |
| 66 | } else { | |
| 67 | ! | stopifnot(id <= length(mesh$shapes)) |
| 68 | ! | new_normals = CalculateNormals(mesh, id - 1) |
| 69 | ! | mesh$shapes[[id]]$norm_indices = mesh$shapes[[id]]$indices |
| 70 | ! | mesh$shapes[[id]]$has_vertex_normals = rep( |
| 71 | ! | TRUE, |
| 72 | ! | length(mesh$shapes[[id]]$indices) |
| 73 | ) | |
| 74 | ! | mesh$normals[id] = ray_vertex_data(new_normals) |
| 75 | } | |
| 76 | 2x | return(mesh) |
| 77 | } |
| 1 | #'@title Point light | |
| 2 | #' | |
| 3 | #'@description The falloff of the point light intensity is given by the following equation (referenc: | |
| 4 | #' | |
| 5 | #'Intensity = intensity / (constant + falloff * distance + falloff_quad * (distance * distance)); | |
| 6 | #' | |
| 7 | #'@param position A two-dimensional matrix, where each entry in the matrix is the elevation at that point. All points are assumed to be evenly spaced. | |
| 8 | #'@param color Default `400`. Width of the rendered image. | |
| 9 | #'@param intensity Default `1`. Intensity of the point light. | |
| 10 | #'@param constant Default `1`. Constant term. See description for details. | |
| 11 | #'@param falloff Default `1`. Linear falloff term. See description for details. | |
| 12 | #'@param falloff_quad Default `1`. Quadratic falloff term. See description for details. | |
| 13 | ||
| 14 | #'@return A matrix representing the light information. | |
| 15 | #'@export | |
| 16 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 17 | #'#Add point lights and vary the intensity | |
| 18 | #'lights_int = point_light(position=c(100,100,400), color="white", intensity=0.125, | |
| 19 | #' falloff_quad = 0.0, constant = 0.0002, falloff = 0.005) |> | |
| 20 | #' add_light(point_light(position=c(100,455,400), color="white", intensity=0.25, | |
| 21 | #' falloff_quad = 0.0, constant = 0.0002, falloff = 0.005)) |> | |
| 22 | #' add_light(point_light(position=c(455,100,400), color="white", intensity=0.5, | |
| 23 | #' falloff_quad = 0.0, constant = 0.0002, falloff = 0.005)) |> | |
| 24 | #' add_light(point_light(position=c(455,455,400), color="white", intensity=1, | |
| 25 | #' falloff_quad = 0.0, constant = 0.0002, falloff = 0.005)) | |
| 26 | #' | |
| 27 | #'generate_cornell_mesh(light=FALSE) |> | |
| 28 | #' rasterize_scene(light_info = lights_int) | |
| 29 | #' | |
| 30 | #'#Add point lights and vary the color | |
| 31 | #'lights_c = point_light(position=c(100,100,500), color="red", | |
| 32 | #' falloff_quad = 0.0, constant = 0.0002, falloff = 0.005) |> | |
| 33 | #' add_light(point_light(position=c(100,455,500), color="blue", | |
| 34 | #' falloff_quad = 0.0, constant = 0.0002, falloff = 0.005)) |> | |
| 35 | #' add_light(point_light(position=c(455,100,500), color="purple", | |
| 36 | #' falloff_quad = 0.0, constant = 0.0002, falloff = 0.005)) |> | |
| 37 | #' add_light(point_light(position=c(455,455,500), color="yellow", | |
| 38 | #' falloff_quad = 0.0, constant = 0.0002, falloff = 0.005)) | |
| 39 | #' | |
| 40 | #'generate_cornell_mesh(light=FALSE) |> | |
| 41 | #' rasterize_scene(light_info = lights_c) | |
| 42 | #' | |
| 43 | #'#Add point lights and vary the falloff term | |
| 44 | #'lights_fo = point_light(position=c(100,100,500), color="white", | |
| 45 | #' falloff_quad = 0.0, constant = 0.0002, falloff = 0.005) |> | |
| 46 | #' add_light(point_light(position=c(100,455,500), color="white", | |
| 47 | #' falloff_quad = 0.0, constant = 0.0002, falloff = 0.01)) |> | |
| 48 | #' add_light(point_light(position=c(455,100,500), color="white", | |
| 49 | #' falloff_quad = 0.0, constant = 0.0002, falloff = 0.02)) |> | |
| 50 | #' add_light(point_light(position=c(455,455,500), color="white", | |
| 51 | #' falloff_quad = 0.0, constant = 0.0002, falloff = 0.04)) | |
| 52 | #' | |
| 53 | #'generate_cornell_mesh(light=FALSE) |> | |
| 54 | #' rasterize_scene(light_info = lights_fo) | |
| 55 | #' | |
| 56 | #'#Add point lights and vary the quadradic falloff term | |
| 57 | #'lights_quad = point_light(position=c(100,100,500), color="white", | |
| 58 | #' falloff_quad = 0.0001, constant = 0.0002, falloff = 0.005) |> | |
| 59 | #' add_light(point_light(position=c(100,455,500), color="white", | |
| 60 | #' falloff_quad = 0.0002, constant = 0.0002, falloff = 0.005)) |> | |
| 61 | #' add_light(point_light(position=c(455,100,500), color="white", | |
| 62 | #' falloff_quad = 0.0004, constant = 0.0002, falloff = 0.005)) |> | |
| 63 | #' add_light(point_light(position=c(455,455,500), color="white", | |
| 64 | #' falloff_quad = 0.0008, constant = 0.0002, falloff = 0.005)) | |
| 65 | #' | |
| 66 | #'generate_cornell_mesh(light=FALSE) |> | |
| 67 | #' rasterize_scene(light_info = lights_quad) | |
| 68 | point_light = function( | |
| 69 | position = c(0, 0, 0), | |
| 70 | color = "white", | |
| 71 | intensity = 1, | |
| 72 | constant = 1, | |
| 73 | falloff = 1, | |
| 74 | falloff_quad = 1 | |
| 75 | ) { | |
| 76 | ! | color = convert_color(color) |
| 77 | ! | returnmat = matrix( |
| 78 | ! | c(position, color, constant, falloff, falloff_quad, intensity), |
| 79 | ! | nrow = 1, |
| 80 | ! | ncol = 10 |
| 81 | ) | |
| 82 | ! | colnames(returnmat) = c( |
| 83 | ! | "x", |
| 84 | ! | "y", |
| 85 | ! | "z", |
| 86 | ! | "r", |
| 87 | ! | "g", |
| 88 | ! | "b", |
| 89 | ! | "constant", |
| 90 | ! | "falloff", |
| 91 | ! | "falloff_quad", |
| 92 | ! | "intensity" |
| 93 | ) | |
| 94 | ! | returnmat |
| 95 | } | |
| 96 | ||
| 97 | #'@title Generate Directional Lights | |
| 98 | #' | |
| 99 | #'@param direction Default `c(0,1,0)`. Direction of the light. | |
| 100 | #'@param color Default `white`. COlor of the light. | |
| 101 | #'@param intensity Default `1`. Intensity of the light. | |
| 102 | #' | |
| 103 | #'@return A matrix representing the light information. | |
| 104 | #'@export | |
| 105 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 106 | #'#Add a light to scene (manually specify the light automatically added to the Cornell Box | |
| 107 | #'lights = point_light(position=c(555/2,450,555/2), | |
| 108 | #' falloff_quad = 0.0, constant = 0.0002, falloff = 0.005) | |
| 109 | #'generate_cornell_mesh(light=FALSE) |> | |
| 110 | #' rasterize_scene(light_info = lights) | |
| 111 | #' | |
| 112 | #'#Add a directional light | |
| 113 | #'lights_d = add_light(lights, directional_light(direction=c(1,1.5,-1))) | |
| 114 | #' | |
| 115 | #'generate_cornell_mesh(light=FALSE) |> | |
| 116 | #' rasterize_scene(light_info = lights_d) | |
| 117 | #' | |
| 118 | #'#Change the intensity and color | |
| 119 | #'lights_d = add_light(lights, | |
| 120 | #' directional_light(direction=c(1,1.5,-1),color="orange", intensity=0.5)) | |
| 121 | #' | |
| 122 | #'generate_cornell_mesh(light=FALSE) |> | |
| 123 | #' rasterize_scene(light_info = lights_d) | |
| 124 | directional_light = function( | |
| 125 | direction = c(0, 1, 0), | |
| 126 | color = "white", | |
| 127 | intensity = 1 | |
| 128 | ) { | |
| 129 | 5x | color = convert_color(color) |
| 130 | 5x | returnmat = matrix( |
| 131 | 5x | c(direction, color, 0, 0, 0, intensity), |
| 132 | 5x | nrow = 1, |
| 133 | 5x | ncol = 10 |
| 134 | ) | |
| 135 | 5x | colnames(returnmat) = c( |
| 136 | 5x | "x", |
| 137 | 5x | "y", |
| 138 | 5x | "z", |
| 139 | 5x | "r", |
| 140 | 5x | "g", |
| 141 | 5x | "b", |
| 142 | 5x | "constant", |
| 143 | 5x | "falloff", |
| 144 | 5x | "falloff_quad", |
| 145 | 5x | "intensity" |
| 146 | ) | |
| 147 | 5x | returnmat |
| 148 | } | |
| 149 | ||
| 150 | #'@title Add light | |
| 151 | #' | |
| 152 | #'@param lights Current light scene. | |
| 153 | #'@param light New light to add. | |
| 154 | #' | |
| 155 | #'@return A matrix representing the light information. | |
| 156 | #'@export | |
| 157 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 158 | #'#Add a light to scene (manually specify the light automatically added to the Cornell Box | |
| 159 | #'lights = point_light(position=c(555/2,450,555/2), | |
| 160 | #' falloff_quad = 0.0, constant = 0.0002, falloff = 0.005) | |
| 161 | #'generate_cornell_mesh(light=FALSE) |> | |
| 162 | #' rasterize_scene(light_info = lights) | |
| 163 | #' | |
| 164 | #'#Add directional lights and a point light | |
| 165 | #'lights_d = add_light(lights, directional_light(direction=c(1,1.5,-1), intensity=0.2)) |> | |
| 166 | #' add_light(directional_light(direction=c(-1,1.5,-1),color="red", intensity=0.2)) |> | |
| 167 | #' add_light(point_light(position=c(555/2,50,555/2), color="blue", intensity=0.3, | |
| 168 | #' falloff_quad = 0.0, constant = 0.0002, falloff = 0.005)) | |
| 169 | #' | |
| 170 | #'generate_cornell_mesh(light=FALSE) |> | |
| 171 | #' rasterize_scene(light_info = lights_d) | |
| 172 | add_light = function(lights, light) { | |
| 173 | ! | rbind(lights, light) |
| 174 | } |
| 1 | #'@title Add Shape | |
| 2 | #' | |
| 3 | #'@description Add shape to the scene. | |
| 4 | #' | |
| 5 | #'@param scene The scene to add the shape. | |
| 6 | #'@param shape The mesh to add to the scene. | |
| 7 | ||
| 8 | #'@return Scene with shape added. | |
| 9 | #'@export | |
| 10 | #' | |
| 11 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 12 | #'#Generate several spheres in the cornell box | |
| 13 | #'scene = generate_cornell_mesh() | |
| 14 | #'set.seed(1) | |
| 15 | #' | |
| 16 | #'for(i in 1:30) { | |
| 17 | #' col = hsv(runif(1)) | |
| 18 | #' scene = add_shape(scene, sphere_mesh(position=runif(3)*400+155/2, | |
| 19 | #' material=material_list(diffuse=col, type="phong", | |
| 20 | #' ambient=col,ambient_intensity=0.2), | |
| 21 | #' radius=30)) | |
| 22 | #'} | |
| 23 | #'rasterize_scene(scene, light_info=directional_light(direction=c(0.1,0.6,-1))) | |
| 24 | add_shape = function(scene, shape = NULL) { | |
| 25 | 14x | if (is.null(shape)) { |
| 26 | 3x | return(scene) |
| 27 | } | |
| 28 | 11x | if (is.null(scene)) { |
| 29 | ! | return(shape) |
| 30 | } | |
| 31 | 11x | new_hashes = c(attr(scene, "material_hashes"), attr(shape, "material_hashes")) |
| 32 | 11x | scene$shapes = vctrs::vec_c(scene$shapes, shape$shapes) |
| 33 | 11x | scene$vertices = vctrs::vec_c(scene$vertices, shape$vertices) |
| 34 | 11x | scene$normals = vctrs::vec_c(scene$normals, shape$normals) |
| 35 | 11x | scene$texcoords = vctrs::vec_c(scene$texcoords, shape$texcoords) |
| 36 | 11x | scene$materials = vctrs::vec_c(scene$materials, shape$materials) |
| 37 | # new_scene = ray_mesh(scene) | |
| 38 | 11x | new_scene = (scene) |
| 39 | ||
| 40 | 11x | attr(new_scene, "material_hashes") = new_hashes |
| 41 | 11x | if (!is.null(attr(shape, "cornell")) || !is.null(attr(scene, "cornell"))) { |
| 42 | ! | attr(new_scene, "cornell") = TRUE |
| 43 | ! | if (!is.null(attr(shape, "cornell"))) { |
| 44 | ! | attr(new_scene, "cornell_light") = attr(shape, "cornell_light") |
| 45 | } else { | |
| 46 | ! | attr(new_scene, "cornell_light") = attr(scene, "cornell_light") |
| 47 | } | |
| 48 | } | |
| 49 | 11x | return(new_scene) |
| 50 | } |
| 1 | #'@title Remove Duplicates | |
| 2 | #' | |
| 3 | #'@param scene The scene | |
| 4 | #'@return Scene with shape added. | |
| 5 | #' | |
| 6 | #'@keywords internal | |
| 7 | remove_duplicate_materials = function(scene) { | |
| 8 | #Generate unique set of materials in scene | |
| 9 | 6x | scene_material_hashes = attr(scene, "material_hashes") |
| 10 | 6x | unique_materials = unique(scene_material_hashes) |
| 11 | #Allocate new_id vector | |
| 12 | 6x | new_ids = rep(0L,length(scene_material_hashes)) |
| 13 | ||
| 14 | #Generate vector for all old non-unique IDs (zero indexed) | |
| 15 | 6x | old_ids = seq_along(scene$materials) - 1L |
| 16 | 6x | new_mat = list() |
| 17 | #Go through each hash and determine which entry it is in the unique_material vector | |
| 18 | 6x | for(i in seq_along(scene$materials)) { |
| 19 | 9x | new_ids[i] = min(which(scene_material_hashes[i] == unique_materials)) - 1L |
| 20 | } | |
| 21 | # for(i in seq_len(length(scene$shapes))) { | |
| 22 | # scene$shapes[[i]]$material_ids[scene$shapes[[i]]$material_ids == -1L] = 0L | |
| 23 | # scene$shapes[[i]]$material_ids = new_ids[scene$shapes[[i]]$material_ids + 1L] | |
| 24 | # } | |
| 25 | 6x | scene$shapes[[1]]$material_ids[scene$shapes[[1]]$material_ids == -1L] = 0L |
| 26 | 6x | scene$shapes[[1]]$material_ids = new_ids[scene$shapes[[1]]$material_ids + 1L] |
| 27 | 6x | unique_ids = unique(new_ids) |
| 28 | 6x | new_mat = list() |
| 29 | 6x | for(i in seq_len(length(unique_ids))) { |
| 30 | 7x | new_mat[[i]] = scene$materials[[min(which(new_ids == (i-1L)))]] |
| 31 | } | |
| 32 | 6x | scene$materials = new_mat |
| 33 | 6x | attr(scene, "material_hashes") = unique_materials |
| 34 | 6x | class(scene) = c("ray_mesh", "list") |
| 35 | ||
| 36 | 6x | return(scene) |
| 37 | } |
| 1 | #'@title Manually construct a mesh | |
| 2 | #' | |
| 3 | #'@param vertices Nx3 matrix of vertex coordinates.. | |
| 4 | #'@param indices Nx3 integer matrix, where each row defines a triangle using the | |
| 5 | #'vertices defined in `vertices`. | |
| 6 | #'@param normals Default `NULL`. Nx3 matrix of normals. | |
| 7 | #'@param norm_indices Nx3 integer matrix, where each row defines the normal for a vertex using the | |
| 8 | #'normals defined in `normals` for the corresponding triangle in `indices`. | |
| 9 | #'Required to be the same number of rows as `indices`. | |
| 10 | #'@param texcoords Default `NULL`. Nx2 matrix of texture coordinates. | |
| 11 | #'@param tex_indices Nx3 integer matrix, where each row defines the texture coordinates for a triangle | |
| 12 | #' using the tex coords defined in `texcoors` for the corresponding triangle in `indices`. | |
| 13 | #'Required to be the same number of rows as `indices`. | |
| 14 | #' @param material Default [material_list()] (default values). Specify the material of the object. | |
| 15 | #' | |
| 16 | #'@return List containing mesh info. | |
| 17 | #'@export | |
| 18 | #'@examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 19 | #'#Let's construct a mesh from the volcano dataset | |
| 20 | #' #Build the vertex matrix | |
| 21 | #' vertex_list = list() | |
| 22 | #' counter = 1 | |
| 23 | #' for(i in 1:nrow(volcano)) { | |
| 24 | #' for(j in 1:ncol(volcano)) { | |
| 25 | #' vertex_list[[counter]] = matrix(c(j,volcano[i,j],i), ncol=3) | |
| 26 | #' counter = counter + 1 | |
| 27 | #' } | |
| 28 | #' } | |
| 29 | #' vertices = do.call(rbind,vertex_list) | |
| 30 | #' | |
| 31 | #' #Build the index matrix | |
| 32 | #' index_list = list() | |
| 33 | #' counter = 0 | |
| 34 | #' for(i in 1:(nrow(volcano)-1)) { | |
| 35 | #' for(j in 1:(ncol(volcano)-1)) { | |
| 36 | #' index_list[[counter+1]] = matrix(c(counter,counter+ncol(volcano),counter+1, | |
| 37 | #' counter+ncol(volcano),counter+ncol(volcano)+1,counter + 1), | |
| 38 | #' nrow=2, ncol=3, byrow=TRUE) | |
| 39 | #' counter = counter + 1 | |
| 40 | #' } | |
| 41 | #' counter = counter + 1 | |
| 42 | #' } | |
| 43 | #' indices = do.call(rbind,index_list) | |
| 44 | #' | |
| 45 | #' #Construct the mesh | |
| 46 | #' volc_mesh = construct_mesh(vertices = vertices, indices = indices, | |
| 47 | #' material = material_list(type="phong", diffuse="darkred", | |
| 48 | #' ambient = "darkred", ambient_intensity=0.2)) | |
| 49 | #' | |
| 50 | #' #Rasterize the scene | |
| 51 | #' rasterize_scene(volc_mesh, lookfrom=c(-50,230,100),fov=60,width=1200,height=1200, | |
| 52 | #' light_info = directional_light(c(0,1,1)) |> | |
| 53 | #' add_light(directional_light(c(1,1,-1)))) | |
| 54 | construct_mesh = function( | |
| 55 | vertices, | |
| 56 | indices, | |
| 57 | normals = NULL, | |
| 58 | norm_indices = NULL, | |
| 59 | texcoords = NULL, | |
| 60 | tex_indices = NULL, | |
| 61 | material = material_list() | |
| 62 | ) { | |
| 63 | 164x | mesh = list() |
| 64 | 164x | mesh$shapes = list() |
| 65 | 164x | if (is.null(normals)) { |
| 66 | 133x | normals = matrix(0, nrow = 0, ncol = 3) |
| 67 | } | |
| 68 | 164x | if (is.null(texcoords)) { |
| 69 | 131x | texcoords = matrix(0, nrow = 0, ncol = 2) |
| 70 | } | |
| 71 | 164x | if (is.null(norm_indices)) { |
| 72 | 133x | norm_indices = matrix(-1, nrow = nrow(indices), ncol = 3) |
| 73 | } | |
| 74 | 164x | if (is.null(tex_indices)) { |
| 75 | 131x | tex_indices = matrix(-1, nrow = nrow(indices), ncol = 3) |
| 76 | } | |
| 77 | 164x | mesh$vertices = ray_vertex_data(vertices) |
| 78 | 164x | mesh$texcoords = ray_vertex_data(texcoords) |
| 79 | 164x | mesh$normals = ray_vertex_data(normals) |
| 80 | 164x | mesh$shapes = ray_shape(list( |
| 81 | 164x | indices = indices, |
| 82 | 164x | norm_indices = norm_indices, |
| 83 | 164x | tex_indices = tex_indices, |
| 84 | 164x | material_ids = rep(0, nrow(indices)), |
| 85 | 164x | has_vertex_tex = apply(tex_indices, 1, (function(x) all(x != -1))), |
| 86 | 164x | has_vertex_normals = apply(norm_indices, 1, (function(x) all(x != -1))) |
| 87 | )) | |
| 88 | 164x | mesh$materials = list() |
| 89 | 164x | mesh$materials[[1]] = list(material) |
| 90 | 164x | attr(mesh, "material_hashes") = digest::digest(material) |
| 91 | 164x | class(mesh) = c("ray_mesh", class(mesh)) |
| 92 | 164x | return(mesh) |
| 93 | } |
| 1 | #' R 3D Model | |
| 2 | #' | |
| 3 | #' 3D obj model of R logo (created from the R SVG logo with the `raybevel` package), | |
| 4 | #' to be used with `obj_model()` | |
| 5 | #' | |
| 6 | #' @param simple_r Default `FALSE`. If `TRUE`, this will return a 3D R (instead of the R logo). | |
| 7 | #' @return File location of the 3d_r_logo.obj file (saved with a .txt extension) | |
| 8 | #' @export | |
| 9 | #' | |
| 10 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 11 | #' #Load and render the included example R object file. | |
| 12 | #' obj_mesh(r_obj()) |> | |
| 13 | #' rasterize_scene(lookfrom = c(0, 1, 10), | |
| 14 | #' fov=7,light_info = directional_light(c(1,1,1))) | |
| 15 | r_obj = function(simple_r = FALSE) { | |
| 16 | ! | if (!simple_r) { |
| 17 | ! | system.file("extdata", "3d_r_logo.txt", package = "rayvertex") |
| 18 | } else { | |
| 19 | ! | system.file("extdata", "r_obj.txt", package = "rayvertex") |
| 20 | } | |
| 21 | } |
| 1 | #' Validate Scene | |
| 2 | #' | |
| 3 | #' @param scene Make sure that there are no out of bounds issues and all the materials are valid | |
| 4 | #' | |
| 5 | #' @return Color vector | |
| 6 | #' @keywords internal | |
| 7 | validate_scene = function(scene) { | |
| 8 | ! | n_shapes = 0L |
| 9 | ||
| 10 | ! | n_materials = 0L |
| 11 | ! | n_material_hashes = 0L |
| 12 | ! | number_materials = 0L |
| 13 | ||
| 14 | ! | n_shapes = length(scene$shapes) |
| 15 | ||
| 16 | ! | if(n_shapes != length(scene$vertices)) { |
| 17 | ! | stop(sprintf("length of scene$shapes[[%d]] (%d) is not equal to length of scene$vertices[[%d]] (%d)", |
| 18 | ! | i,n_shapes, i, length(scene$vertices))) |
| 19 | } | |
| 20 | ! | if(n_shapes != length(scene$texcoords)) { |
| 21 | ! | stop(sprintf("length of scene[[%d]]$shapes (%d) is not equal to length of scene[[%d]]$texcoords (%d)", |
| 22 | ! | i,n_shapes, i, length(scene$texcoords))) |
| 23 | } | |
| 24 | ! | if(n_shapes != length(scene$normals)) { |
| 25 | ! | stop(sprintf("length of scene[[%d]]$shapes (%d) is not equal to length of scene[[%d]]$normals (%d)", |
| 26 | ! | i,n_shapes, i, length(scene$normals))) |
| 27 | } | |
| 28 | #Count the total number of shapes, materials, and material hashes | |
| 29 | ! | for(i in seq_len(n_shapes)) { |
| 30 | ! | if(!(max(scene$shapes[[i]]$indices) < nrow(scene$vertices[[i]]))) { |
| 31 | ! | stop(sprintf("Max index (%d) in scene$shape[[%d]] greater than number of vertices (%d) in scene$vertices[[%d]]", |
| 32 | ! | max(scene$shapes[[i]]$indices),i, nrow(scene$vertices[[i]]), i)) |
| 33 | } | |
| 34 | ! | if(!(max(scene$shapes[[i]]$tex_indices) < nrow(scene$texcoords[[i]]))) { |
| 35 | ! | stop(sprintf("Max tex index (%d) in scene$shape[[%d]] greater than number of texcoords (%d) in scene$texcoords[[%d]]", |
| 36 | ! | max(scene$shapes[[i]]$tex_indices),i, nrow(scene$texcoords[[i]]), i)) |
| 37 | } | |
| 38 | ! | if(!(max(scene$shapes[[i]]$norm_indices) < nrow(scene$normals[[i]]))) { |
| 39 | ! | stop(sprintf("Max norm index (%d) in scene$shape[[%d]] greater than number of normals (%d) in scene$normals[[%d]]", |
| 40 | ! | max(scene$shapes[[i]]$norm_indices),i, nrow(scene$normals[[i]]), i)) |
| 41 | } | |
| 42 | } | |
| 43 | ! | for(i in seq_len(length(scene$materials))) { |
| 44 | ! | mat_len = length(scene$materials[[i]]) |
| 45 | ! | for(j in seq_len(mat_len)) { |
| 46 | ! | if(length(scene$materials[[i]][[j]]) != 26) { |
| 47 | ! | stop(sprintf("Material %d (sub-material %d) does not have the right number of entries", i, j)) |
| 48 | } | |
| 49 | } | |
| 50 | } | |
| 51 | ! | message("Scene passed validation") |
| 52 | } |
| 1 | #' Flip Orientation | |
| 2 | #' | |
| 3 | #' @param mesh The mesh to swap orientations. | |
| 4 | #' | |
| 5 | #' @return Mesh with flipped vertex orientation | |
| 6 | #' @export | |
| 7 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 8 | #' # Flip a mesh | |
| 9 | #' sphere_mesh(position=c(-1,0,0)) |> | |
| 10 | #' add_shape(flip_orientation_mesh(sphere_mesh(position=c(1,0,0)))) |> | |
| 11 | #' rasterize_scene(debug="normals",fov=30) | |
| 12 | flip_orientation_mesh = function(mesh) { | |
| 13 | ! | for (i in seq_along(mesh$shapes)) { |
| 14 | ! | mesh$shapes[[i]]$indices = mesh$shapes[[i]]$indices[, 3:1] |
| 15 | ! | mesh$shapes[[i]]$norm_indices = mesh$shapes[[i]]$norm_indices[, 3:1] |
| 16 | ! | mesh$shapes[[i]]$tex_indices = mesh$shapes[[i]]$tex_indices[, 3:1] |
| 17 | } | |
| 18 | ! | return(mesh) |
| 19 | } |
| 1 | #' Swap Y/Z Axis | |
| 2 | #' | |
| 3 | #' @param mesh A raymesh object. | |
| 4 | #' | |
| 5 | #' @return Mesh with Y and Z axis exchanged | |
| 6 | #' @export | |
| 7 | #' @examplesIf interactive() || isTRUE(as.logical(Sys.getenv("IN_PKGDOWN"))) | |
| 8 | #' # Flip a mesh that's originally aligned along the y-axis | |
| 9 | #' cyl_mat = material_list(ambient="red", ambient_intensity=0.3, | |
| 10 | #' diffuse="red", diffuse_intensity=0.7) | |
| 11 | #' change_material(cylinder_mesh(length = 3, position=c(0,2,0), material = cyl_mat), | |
| 12 | #' diffuse="green", ambient="green") |> | |
| 13 | #' add_shape(swap_yz(cylinder_mesh(position=c(0,2,0), length=3, material = cyl_mat))) |> | |
| 14 | #' rasterize_scene(lookfrom=c(10,10,10), lookat=c(0,0,0), fov=40, | |
| 15 | #' light_info = directional_light(c(1,1,-1)), | |
| 16 | #' line_info = generate_line(end=c(10,0,0)) |> | |
| 17 | #' add_lines(generate_line(end=c(0,10,0),color="green")) |> | |
| 18 | #' add_lines(generate_line(end=c(0,0,10),color="red"))) | |
| 19 | swap_yz = function(mesh) { | |
| 20 | ! | for (i in seq_along(mesh$vertices)) { |
| 21 | ! | mesh$vertices[[i]] = mesh$vertices[[i]][, c(1, 3, 2)] |
| 22 | } | |
| 23 | ! | for (i in seq_along(mesh$shapes)) { |
| 24 | ! | mesh$shapes[[i]]$indices = mesh$shapes[[i]]$indices[, 3:1] |
| 25 | ! | mesh$shapes[[i]]$norm_indices = mesh$shapes[[i]]$norm_indices[, 3:1] |
| 26 | ! | mesh$shapes[[i]]$tex_indices = mesh$shapes[[i]]$tex_indices[, 3:1] |
| 27 | } | |
| 28 | ! | for (i in seq_along(mesh$normals)) { |
| 29 | ! | mesh$normals[[i]] = mesh$normals[[i]][, c(1, 3, 2)] |
| 30 | } | |
| 31 | ! | return(mesh) |
| 32 | } |
| 1 | #' Extruded Polygon Mesh | |
| 2 | #' | |
| 3 | #' Build polygon caps and walls with shared geometric vertices, including | |
| 4 | #' multiple holes, spatial features, and multipart polygons. | |
| 5 | #' | |
| 6 | #' @param polygon Default `NULL`. Coordinates accepted by `xy.coords()`, an | |
| 7 | #' `sf` object containing POLYGON or MULTIPOLYGON features, or a | |
| 8 | #' `SpatialPolygons`/`SpatialPolygonsDataFrame` object. Open rings are closed; | |
| 9 | #' consecutive duplicate and redundant collinear vertices are removed. Rings | |
| 10 | #' must be simple with nonzero area. Holes must be strictly inside their exterior | |
| 11 | #' and must not touch or overlap. Z and M coordinates are ignored. | |
| 12 | #' @param plane Default `"xz"`. Coordinate-plane orientation: `xz`, `zx`, `xy`, | |
| 13 | #' `yx`, `yz`, or `zy`, matched without regard to case. Preserves rayrender's | |
| 14 | #' historical coordinate permutation and first-coordinate mirror. | |
| 15 | #' @param top Default `1`. Finite extrusion height. Either height order is | |
| 16 | #' supported with outward-facing triangles. Equal heights produce one flat cap. | |
| 17 | #' @param bottom Default `0`. Finite starting height of the extrusion. | |
| 18 | #' @param holes Default `NULL`. For direct coordinates, strictly increasing | |
| 19 | #' one-based start indices of the holes in the original input, before cleanup. | |
| 20 | #' `NULL` or `0` means no holes. Spatial inputs determine holes from their rings. | |
| 21 | #' @param center Default `FALSE`. Center the combined polygon extent before | |
| 22 | #' applying the plane mapping and mesh transforms. | |
| 23 | #' @param flip_horizontal Default `FALSE`. Flip the first polygon coordinate. | |
| 24 | #' @param flip_vertical Default `FALSE`. Flip the second polygon coordinate. | |
| 25 | #' @param data_column_top Default `NULL`. Numeric `sf` column supplying each | |
| 26 | #' feature's top height. A missing column warns and uses `top`. | |
| 27 | #' @param data_column_bottom Default `NULL`. Numeric `sf` column supplying each | |
| 28 | #' feature's bottom height. A missing column warns and uses `bottom`. | |
| 29 | #' @param scale_data Default `1`. Scale for heights read from data columns. | |
| 30 | #' @param position Default `c(0, 0, 0)`. Translation of the completed mesh. | |
| 31 | #' @param scale Default `c(1, 1, 1)`. Finite, nonzero mesh scale, uniformly or | |
| 32 | #' per axis. Reflected scales preserve outward triangle winding. | |
| 33 | #' @param angle Default `c(0, 0, 0)`. Rotation angles in degrees. | |
| 34 | #' @param pivot_point Default `c(0, 0, 0)`. Point around which to rotate. | |
| 35 | #' @param order_rotation Default `c(1, 2, 3)`. Order to rotate the axes. | |
| 36 | #' @param material Default `material_list()`. Mesh material. | |
| 37 | #' | |
| 38 | #' @return A `ray_mesh` containing all polygon components. Equal-height features | |
| 39 | #' contribute flat surfaces, which cannot enclose participating media. | |
| 40 | #' @seealso [extruded_path_mesh()], [lathe_mesh()] | |
| 41 | #' @export | |
| 42 | #' @examples | |
| 43 | #' outline = rbind(c(-1, -1), c(1, -1), c(1, 1), c(-1, 1)) | |
| 44 | #' block = extruded_polygon_mesh(outline, top = 2) | |
| 45 | #' hole = outline * 0.3 | |
| 46 | #' frame = extruded_polygon_mesh(rbind(outline, hole), holes = 5, top = 0.5) | |
| 47 | extruded_polygon_mesh = function( | |
| 48 | polygon = NULL, | |
| 49 | plane = "xz", | |
| 50 | top = 1, | |
| 51 | bottom = 0, | |
| 52 | holes = NULL, | |
| 53 | center = FALSE, | |
| 54 | flip_horizontal = FALSE, | |
| 55 | flip_vertical = FALSE, | |
| 56 | data_column_top = NULL, | |
| 57 | data_column_bottom = NULL, | |
| 58 | scale_data = 1, | |
| 59 | position = c(0, 0, 0), | |
| 60 | scale = c(1, 1, 1), | |
| 61 | angle = c(0, 0, 0), | |
| 62 | pivot_point = c(0, 0, 0), | |
| 63 | order_rotation = c(1, 2, 3), | |
| 64 | material = material_list() | |
| 65 | ) { | |
| 66 | 193x | data = polygon_mesh_data( |
| 67 | 193x | polygon, |
| 68 | 193x | plane, |
| 69 | 193x | top, |
| 70 | 193x | bottom, |
| 71 | 193x | holes, |
| 72 | 193x | center, |
| 73 | 193x | flip_horizontal, |
| 74 | 193x | flip_vertical, |
| 75 | 193x | data_column_top, |
| 76 | 193x | data_column_bottom, |
| 77 | 193x | scale_data, |
| 78 | 193x | scale |
| 79 | ) | |
| 80 | 130x | mesh = construct_mesh(data$vertices, data$indices, material = material) |
| 81 | 130x | extrusion_transform(mesh, position, 1, angle, pivot_point, order_rotation) |
| 82 | } |
| 1 | #include "assert.h" | |
| 2 | #include <string> | |
| 3 | #include <stdexcept> | |
| 4 | ||
| 5 | // Function to throw error if condition is false | |
| 6 | ! | void assertCondition(bool condition, const char* conditionStr) { |
| 7 | ! | if (!condition) { |
| 8 | ! | std::string message = "Assertion failed: "; |
| 9 | ! | message += conditionStr; |
| 10 | ! | throw std::runtime_error(message); |
| 11 | } | |
| 12 | } |
| 1 | #include "calcnormals.h" | |
| 2 | #include "glm.hpp" | |
| 3 | #include "defines.h" | |
| 4 | #include "Rcpp.h" | |
| 5 | ||
| 6 | using namespace Rcpp; | |
| 7 | ||
| 8 | 384x | inline bool any_is_nan(const vec3& c) { |
| 9 | 384x | return(std::isnan(c[0]) || std::isnan(c[1]) || std::isnan(c[2])); |
| 10 | } | |
| 11 | ||
| 12 | // Calculate normal for a given face using three vertices | |
| 13 | 384x | vec3 CalculateFaceNormal(const vec3& p0, const vec3& p1, const vec3& p2) { |
| 14 | 384x | vec3 v0 = p1 - p0; |
| 15 | 384x | vec3 v1 = p2 - p0; |
| 16 | 384x | vec3 cross_product = cross(v0, v1); |
| 17 | 768x | return(glm::normalize(cross_product)); |
| 18 | } | |
| 19 | ||
| 20 | // [[Rcpp::export]] | |
| 21 | 2x | NumericMatrix CalculateNormals(List raymesh, int shape_id) { |
| 22 | 4x | List vertex_list = as<List>(raymesh["vertices"]); |
| 23 | 2x | List shape_list = as<List>(raymesh["shapes"]); |
| 24 | ||
| 25 | 2x | NumericMatrix vertices = as<NumericMatrix>(vertex_list(shape_id)); |
| 26 | 2x | List shape = as<List>(shape_list(shape_id)); |
| 27 | 2x | IntegerMatrix idx = as<IntegerMatrix>(shape["indices"]); |
| 28 | 2x | int vertexCount = vertices.nrow(); |
| 29 | 2x | int triangleCount = idx.nrow(); |
| 30 | ||
| 31 | // Initialize vertex normals to zero | |
| 32 | 2x | std::vector<vec3> vertexNormals(vertexCount); |
| 33 | 198x | for (int i = 0; i < vertexCount; i++) { |
| 34 | 196x | vertexNormals[i] = vec3(0.f, 0.f, 0.f); |
| 35 | } | |
| 36 | 2x | std::vector<vec3> vertexArray(vertexCount); |
| 37 | 198x | for (int i = 0; i < vertexCount; i++) { |
| 38 | 196x | vertexArray[i] = vec3(vertices(i,0), vertices(i,1),vertices(i,2)); |
| 39 | } | |
| 40 | ||
| 41 | // std::vector<int> triangleArray = trianglemesh->vertexIndices; | |
| 42 | 2x | IntegerMatrix triangleArray = transpose(idx); |
| 43 | // point3f* vertexArray = trianglemesh->p.get(); | |
| 44 | ||
| 45 | // Calculate normals for each face and accumulate at each vertex | |
| 46 | 386x | for (int k = 0; k < triangleCount * 3; k += 3) { |
| 47 | 384x | int i0 = triangleArray[k+0]; |
| 48 | 384x | int i1 = triangleArray[k+1]; |
| 49 | 384x | int i2 = triangleArray[k+2]; |
| 50 | // ASSERT(i0 < vertexCount); | |
| 51 | // ASSERT(i1 < vertexCount); | |
| 52 | // ASSERT(i2 < vertexCount); | |
| 53 | ||
| 54 | 384x | vec3 p0 = vertexArray[i0]; |
| 55 | 384x | vec3 p1 = vertexArray[i1]; |
| 56 | 384x | vec3 p2 = vertexArray[i2]; |
| 57 | ||
| 58 | 384x | vec3 faceNormal = CalculateFaceNormal(p0, p1, p2); |
| 59 | ||
| 60 | 384x | if(any_is_nan(faceNormal)) { |
| 61 | ! | continue; |
| 62 | } | |
| 63 | 384x | vertexNormals[i0] += faceNormal; |
| 64 | 384x | vertexNormals[i1] += faceNormal; |
| 65 | 384x | vertexNormals[i2] += faceNormal; |
| 66 | } | |
| 67 | ||
| 68 | // Normalize the vertex normals | |
| 69 | 198x | for (int i = 0; i < vertexCount; i++) { |
| 70 | 196x | vertexNormals[i] = glm::normalize(vertexNormals[i]); |
| 71 | } | |
| 72 | 2x | NumericMatrix newNormals(vertexCount, 3); |
| 73 | 198x | for (int i = 0; i < vertexCount; i++) { |
| 74 | 196x | newNormals(i,0) = vertexNormals[i][0]; |
| 75 | 196x | newNormals(i,1) = vertexNormals[i][1]; |
| 76 | 196x | newNormals(i,2) = vertexNormals[i][2]; |
| 77 | } | |
| 78 | 2x | return(newNormals); |
| 79 | } |
| 1 | /// @ref core | |
| 2 | ||
| 3 | #include "compute_vector_relational.hpp" | |
| 4 | ||
| 5 | namespace glm | |
| 6 | { | |
| 7 | // -- Implicit basic constructors -- | |
| 8 | ||
| 9 | # if GLM_CONFIG_DEFAULTED_FUNCTIONS == GLM_DISABLE | |
| 10 | template<typename T, qualifier Q> | |
| 11 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec() | |
| 12 | # if GLM_CONFIG_CTOR_INIT != GLM_CTOR_INIT_DISABLE | |
| 13 | : x(0), y(0), z(0) | |
| 14 | # endif | |
| 15 | {} | |
| 16 | ||
| 17 | template<typename T, qualifier Q> | |
| 18 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(vec<3, T, Q> const& v) | |
| 19 | : x(v.x), y(v.y), z(v.z) | |
| 20 | {} | |
| 21 | # endif | |
| 22 | ||
| 23 | template<typename T, qualifier Q> | |
| 24 | template<qualifier P> | |
| 25 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(vec<3, T, P> const& v) | |
| 26 | : x(v.x), y(v.y), z(v.z) | |
| 27 | {} | |
| 28 | ||
| 29 | // -- Explicit basic constructors -- | |
| 30 | ||
| 31 | template<typename T, qualifier Q> | |
| 32 | 6176x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(T scalar) |
| 33 | 6176x | : x(scalar), y(scalar), z(scalar) |
| 34 | {} | |
| 35 | ||
| 36 | template <typename T, qualifier Q> | |
| 37 | 39631302x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(T _x, T _y, T _z) |
| 38 | 39631302x | : x(_x), y(_y), z(_z) |
| 39 | {} | |
| 40 | ||
| 41 | // -- Conversion scalar constructors -- | |
| 42 | ||
| 43 | template<typename T, qualifier Q> | |
| 44 | template<typename U, qualifier P> | |
| 45 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(vec<1, U, P> const& v) | |
| 46 | : x(static_cast<T>(v.x)) | |
| 47 | , y(static_cast<T>(v.x)) | |
| 48 | , z(static_cast<T>(v.x)) | |
| 49 | {} | |
| 50 | ||
| 51 | template<typename T, qualifier Q> | |
| 52 | template<typename X, typename Y, typename Z> | |
| 53 | 210462x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(X _x, Y _y, Z _z) |
| 54 | 210462x | : x(static_cast<T>(_x)) |
| 55 | 210462x | , y(static_cast<T>(_y)) |
| 56 | 210462x | , z(static_cast<T>(_z)) |
| 57 | {} | |
| 58 | ||
| 59 | template<typename T, qualifier Q> | |
| 60 | template<typename X, typename Y, typename Z> | |
| 61 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(vec<1, X, Q> const& _x, Y _y, Z _z) | |
| 62 | : x(static_cast<T>(_x.x)) | |
| 63 | , y(static_cast<T>(_y)) | |
| 64 | , z(static_cast<T>(_z)) | |
| 65 | {} | |
| 66 | ||
| 67 | template<typename T, qualifier Q> | |
| 68 | template<typename X, typename Y, typename Z> | |
| 69 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(X _x, vec<1, Y, Q> const& _y, Z _z) | |
| 70 | : x(static_cast<T>(_x)) | |
| 71 | , y(static_cast<T>(_y.x)) | |
| 72 | , z(static_cast<T>(_z)) | |
| 73 | {} | |
| 74 | ||
| 75 | template<typename T, qualifier Q> | |
| 76 | template<typename X, typename Y, typename Z> | |
| 77 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(vec<1, X, Q> const& _x, vec<1, Y, Q> const& _y, Z _z) | |
| 78 | : x(static_cast<T>(_x.x)) | |
| 79 | , y(static_cast<T>(_y.x)) | |
| 80 | , z(static_cast<T>(_z)) | |
| 81 | {} | |
| 82 | ||
| 83 | template<typename T, qualifier Q> | |
| 84 | template<typename X, typename Y, typename Z> | |
| 85 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(X _x, Y _y, vec<1, Z, Q> const& _z) | |
| 86 | : x(static_cast<T>(_x)) | |
| 87 | , y(static_cast<T>(_y)) | |
| 88 | , z(static_cast<T>(_z.x)) | |
| 89 | {} | |
| 90 | ||
| 91 | template<typename T, qualifier Q> | |
| 92 | template<typename X, typename Y, typename Z> | |
| 93 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(vec<1, X, Q> const& _x, Y _y, vec<1, Z, Q> const& _z) | |
| 94 | : x(static_cast<T>(_x.x)) | |
| 95 | , y(static_cast<T>(_y)) | |
| 96 | , z(static_cast<T>(_z.x)) | |
| 97 | {} | |
| 98 | ||
| 99 | template<typename T, qualifier Q> | |
| 100 | template<typename X, typename Y, typename Z> | |
| 101 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(X _x, vec<1, Y, Q> const& _y, vec<1, Z, Q> const& _z) | |
| 102 | : x(static_cast<T>(_x)) | |
| 103 | , y(static_cast<T>(_y.x)) | |
| 104 | , z(static_cast<T>(_z.x)) | |
| 105 | {} | |
| 106 | ||
| 107 | template<typename T, qualifier Q> | |
| 108 | template<typename X, typename Y, typename Z> | |
| 109 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(vec<1, X, Q> const& _x, vec<1, Y, Q> const& _y, vec<1, Z, Q> const& _z) | |
| 110 | : x(static_cast<T>(_x.x)) | |
| 111 | , y(static_cast<T>(_y.x)) | |
| 112 | , z(static_cast<T>(_z.x)) | |
| 113 | {} | |
| 114 | ||
| 115 | // -- Conversion vector constructors -- | |
| 116 | ||
| 117 | template<typename T, qualifier Q> | |
| 118 | template<typename A, typename B, qualifier P> | |
| 119 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(vec<2, A, P> const& _xy, B _z) | |
| 120 | : x(static_cast<T>(_xy.x)) | |
| 121 | , y(static_cast<T>(_xy.y)) | |
| 122 | , z(static_cast<T>(_z)) | |
| 123 | {} | |
| 124 | ||
| 125 | template<typename T, qualifier Q> | |
| 126 | template<typename A, typename B, qualifier P> | |
| 127 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(vec<2, A, P> const& _xy, vec<1, B, P> const& _z) | |
| 128 | : x(static_cast<T>(_xy.x)) | |
| 129 | , y(static_cast<T>(_xy.y)) | |
| 130 | , z(static_cast<T>(_z.x)) | |
| 131 | {} | |
| 132 | ||
| 133 | template<typename T, qualifier Q> | |
| 134 | template<typename A, typename B, qualifier P> | |
| 135 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(A _x, vec<2, B, P> const& _yz) | |
| 136 | : x(static_cast<T>(_x)) | |
| 137 | , y(static_cast<T>(_yz.x)) | |
| 138 | , z(static_cast<T>(_yz.y)) | |
| 139 | {} | |
| 140 | ||
| 141 | template<typename T, qualifier Q> | |
| 142 | template<typename A, typename B, qualifier P> | |
| 143 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(vec<1, A, P> const& _x, vec<2, B, P> const& _yz) | |
| 144 | : x(static_cast<T>(_x.x)) | |
| 145 | , y(static_cast<T>(_yz.x)) | |
| 146 | , z(static_cast<T>(_yz.y)) | |
| 147 | {} | |
| 148 | ||
| 149 | template<typename T, qualifier Q> | |
| 150 | template<typename U, qualifier P> | |
| 151 | ! | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(vec<3, U, P> const& v) |
| 152 | ! | : x(static_cast<T>(v.x)) |
| 153 | ! | , y(static_cast<T>(v.y)) |
| 154 | ! | , z(static_cast<T>(v.z)) |
| 155 | {} | |
| 156 | ||
| 157 | template<typename T, qualifier Q> | |
| 158 | template<typename U, qualifier P> | |
| 159 | 2629591x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>::vec(vec<4, U, P> const& v) |
| 160 | 2629591x | : x(static_cast<T>(v.x)) |
| 161 | 2629591x | , y(static_cast<T>(v.y)) |
| 162 | 2629591x | , z(static_cast<T>(v.z)) |
| 163 | {} | |
| 164 | ||
| 165 | // -- Component accesses -- | |
| 166 | ||
| 167 | template<typename T, qualifier Q> | |
| 168 | 1470x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR T & vec<3, T, Q>::operator[](typename vec<3, T, Q>::length_type i) |
| 169 | { | |
| 170 | assert(i >= 0 && i < this->length()); | |
| 171 | 1470x | switch(i) |
| 172 | { | |
| 173 | 490x | default: |
| 174 | case 0: | |
| 175 | 490x | return x; |
| 176 | 490x | case 1: |
| 177 | 490x | return y; |
| 178 | 490x | case 2: |
| 179 | 490x | return z; |
| 180 | } | |
| 181 | } | |
| 182 | ||
| 183 | template<typename T, qualifier Q> | |
| 184 | 1359x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR T const& vec<3, T, Q>::operator[](typename vec<3, T, Q>::length_type i) const |
| 185 | { | |
| 186 | assert(i >= 0 && i < this->length()); | |
| 187 | 1359x | switch(i) |
| 188 | { | |
| 189 | 453x | default: |
| 190 | case 0: | |
| 191 | 453x | return x; |
| 192 | 453x | case 1: |
| 193 | 453x | return y; |
| 194 | 453x | case 2: |
| 195 | 453x | return z; |
| 196 | } | |
| 197 | } | |
| 198 | ||
| 199 | // -- Unary arithmetic operators -- | |
| 200 | ||
| 201 | # if GLM_CONFIG_DEFAULTED_FUNCTIONS == GLM_DISABLE | |
| 202 | template<typename T, qualifier Q> | |
| 203 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>& vec<3, T, Q>::operator=(vec<3, T, Q> const& v) | |
| 204 | { | |
| 205 | this->x = v.x; | |
| 206 | this->y = v.y; | |
| 207 | this->z = v.z; | |
| 208 | return *this; | |
| 209 | } | |
| 210 | # endif | |
| 211 | ||
| 212 | template<typename T, qualifier Q> | |
| 213 | template<typename U> | |
| 214 | ! | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q>& vec<3, T, Q>::operator=(vec<3, U, Q> const& v) |
| 215 | { | |
| 216 | ! | this->x = static_cast<T>(v.x); |
| 217 | ! | this->y = static_cast<T>(v.y); |
| 218 | ! | this->z = static_cast<T>(v.z); |
| 219 | ! | return *this; |
| 220 | } | |
| 221 | ||
| 222 | template<typename T, qualifier Q> | |
| 223 | template<typename U> | |
| 224 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator+=(U scalar) | |
| 225 | { | |
| 226 | this->x += static_cast<T>(scalar); | |
| 227 | this->y += static_cast<T>(scalar); | |
| 228 | this->z += static_cast<T>(scalar); | |
| 229 | return *this; | |
| 230 | } | |
| 231 | ||
| 232 | template<typename T, qualifier Q> | |
| 233 | template<typename U> | |
| 234 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator+=(vec<1, U, Q> const& v) | |
| 235 | { | |
| 236 | this->x += static_cast<T>(v.x); | |
| 237 | this->y += static_cast<T>(v.x); | |
| 238 | this->z += static_cast<T>(v.x); | |
| 239 | return *this; | |
| 240 | } | |
| 241 | ||
| 242 | template<typename T, qualifier Q> | |
| 243 | template<typename U> | |
| 244 | 669904x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator+=(vec<3, U, Q> const& v) |
| 245 | { | |
| 246 | 669904x | this->x += static_cast<T>(v.x); |
| 247 | 669904x | this->y += static_cast<T>(v.y); |
| 248 | 669904x | this->z += static_cast<T>(v.z); |
| 249 | 669904x | return *this; |
| 250 | } | |
| 251 | ||
| 252 | template<typename T, qualifier Q> | |
| 253 | template<typename U> | |
| 254 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator-=(U scalar) | |
| 255 | { | |
| 256 | this->x -= static_cast<T>(scalar); | |
| 257 | this->y -= static_cast<T>(scalar); | |
| 258 | this->z -= static_cast<T>(scalar); | |
| 259 | return *this; | |
| 260 | } | |
| 261 | ||
| 262 | template<typename T, qualifier Q> | |
| 263 | template<typename U> | |
| 264 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator-=(vec<1, U, Q> const& v) | |
| 265 | { | |
| 266 | this->x -= static_cast<T>(v.x); | |
| 267 | this->y -= static_cast<T>(v.x); | |
| 268 | this->z -= static_cast<T>(v.x); | |
| 269 | return *this; | |
| 270 | } | |
| 271 | ||
| 272 | template<typename T, qualifier Q> | |
| 273 | template<typename U> | |
| 274 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator-=(vec<3, U, Q> const& v) | |
| 275 | { | |
| 276 | this->x -= static_cast<T>(v.x); | |
| 277 | this->y -= static_cast<T>(v.y); | |
| 278 | this->z -= static_cast<T>(v.z); | |
| 279 | return *this; | |
| 280 | } | |
| 281 | ||
| 282 | template<typename T, qualifier Q> | |
| 283 | template<typename U> | |
| 284 | ! | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator*=(U scalar) |
| 285 | { | |
| 286 | ! | this->x *= static_cast<T>(scalar); |
| 287 | ! | this->y *= static_cast<T>(scalar); |
| 288 | ! | this->z *= static_cast<T>(scalar); |
| 289 | ! | return *this; |
| 290 | } | |
| 291 | ||
| 292 | template<typename T, qualifier Q> | |
| 293 | template<typename U> | |
| 294 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator*=(vec<1, U, Q> const& v) | |
| 295 | { | |
| 296 | this->x *= static_cast<T>(v.x); | |
| 297 | this->y *= static_cast<T>(v.x); | |
| 298 | this->z *= static_cast<T>(v.x); | |
| 299 | return *this; | |
| 300 | } | |
| 301 | ||
| 302 | template<typename T, qualifier Q> | |
| 303 | template<typename U> | |
| 304 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator*=(vec<3, U, Q> const& v) | |
| 305 | { | |
| 306 | this->x *= static_cast<T>(v.x); | |
| 307 | this->y *= static_cast<T>(v.y); | |
| 308 | this->z *= static_cast<T>(v.z); | |
| 309 | return *this; | |
| 310 | } | |
| 311 | ||
| 312 | template<typename T, qualifier Q> | |
| 313 | template<typename U> | |
| 314 | 833053x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator/=(U v) |
| 315 | { | |
| 316 | 833053x | this->x /= static_cast<T>(v); |
| 317 | 833053x | this->y /= static_cast<T>(v); |
| 318 | 833053x | this->z /= static_cast<T>(v); |
| 319 | 833053x | return *this; |
| 320 | } | |
| 321 | ||
| 322 | template<typename T, qualifier Q> | |
| 323 | template<typename U> | |
| 324 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator/=(vec<1, U, Q> const& v) | |
| 325 | { | |
| 326 | this->x /= static_cast<T>(v.x); | |
| 327 | this->y /= static_cast<T>(v.x); | |
| 328 | this->z /= static_cast<T>(v.x); | |
| 329 | return *this; | |
| 330 | } | |
| 331 | ||
| 332 | template<typename T, qualifier Q> | |
| 333 | template<typename U> | |
| 334 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator/=(vec<3, U, Q> const& v) | |
| 335 | { | |
| 336 | this->x /= static_cast<T>(v.x); | |
| 337 | this->y /= static_cast<T>(v.y); | |
| 338 | this->z /= static_cast<T>(v.z); | |
| 339 | return *this; | |
| 340 | } | |
| 341 | ||
| 342 | // -- Increment and decrement operators -- | |
| 343 | ||
| 344 | template<typename T, qualifier Q> | |
| 345 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator++() | |
| 346 | { | |
| 347 | ++this->x; | |
| 348 | ++this->y; | |
| 349 | ++this->z; | |
| 350 | return *this; | |
| 351 | } | |
| 352 | ||
| 353 | template<typename T, qualifier Q> | |
| 354 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator--() | |
| 355 | { | |
| 356 | --this->x; | |
| 357 | --this->y; | |
| 358 | --this->z; | |
| 359 | return *this; | |
| 360 | } | |
| 361 | ||
| 362 | template<typename T, qualifier Q> | |
| 363 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> vec<3, T, Q>::operator++(int) | |
| 364 | { | |
| 365 | vec<3, T, Q> Result(*this); | |
| 366 | ++*this; | |
| 367 | return Result; | |
| 368 | } | |
| 369 | ||
| 370 | template<typename T, qualifier Q> | |
| 371 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> vec<3, T, Q>::operator--(int) | |
| 372 | { | |
| 373 | vec<3, T, Q> Result(*this); | |
| 374 | --*this; | |
| 375 | return Result; | |
| 376 | } | |
| 377 | ||
| 378 | // -- Unary bit operators -- | |
| 379 | ||
| 380 | template<typename T, qualifier Q> | |
| 381 | template<typename U> | |
| 382 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator%=(U scalar) | |
| 383 | { | |
| 384 | this->x %= scalar; | |
| 385 | this->y %= scalar; | |
| 386 | this->z %= scalar; | |
| 387 | return *this; | |
| 388 | } | |
| 389 | ||
| 390 | template<typename T, qualifier Q> | |
| 391 | template<typename U> | |
| 392 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator%=(vec<1, U, Q> const& v) | |
| 393 | { | |
| 394 | this->x %= v.x; | |
| 395 | this->y %= v.x; | |
| 396 | this->z %= v.x; | |
| 397 | return *this; | |
| 398 | } | |
| 399 | ||
| 400 | template<typename T, qualifier Q> | |
| 401 | template<typename U> | |
| 402 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator%=(vec<3, U, Q> const& v) | |
| 403 | { | |
| 404 | this->x %= v.x; | |
| 405 | this->y %= v.y; | |
| 406 | this->z %= v.z; | |
| 407 | return *this; | |
| 408 | } | |
| 409 | ||
| 410 | template<typename T, qualifier Q> | |
| 411 | template<typename U> | |
| 412 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator&=(U scalar) | |
| 413 | { | |
| 414 | this->x &= scalar; | |
| 415 | this->y &= scalar; | |
| 416 | this->z &= scalar; | |
| 417 | return *this; | |
| 418 | } | |
| 419 | ||
| 420 | template<typename T, qualifier Q> | |
| 421 | template<typename U> | |
| 422 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator&=(vec<1, U, Q> const& v) | |
| 423 | { | |
| 424 | this->x &= v.x; | |
| 425 | this->y &= v.x; | |
| 426 | this->z &= v.x; | |
| 427 | return *this; | |
| 428 | } | |
| 429 | ||
| 430 | template<typename T, qualifier Q> | |
| 431 | template<typename U> | |
| 432 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator&=(vec<3, U, Q> const& v) | |
| 433 | { | |
| 434 | this->x &= v.x; | |
| 435 | this->y &= v.y; | |
| 436 | this->z &= v.z; | |
| 437 | return *this; | |
| 438 | } | |
| 439 | ||
| 440 | template<typename T, qualifier Q> | |
| 441 | template<typename U> | |
| 442 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator|=(U scalar) | |
| 443 | { | |
| 444 | this->x |= scalar; | |
| 445 | this->y |= scalar; | |
| 446 | this->z |= scalar; | |
| 447 | return *this; | |
| 448 | } | |
| 449 | ||
| 450 | template<typename T, qualifier Q> | |
| 451 | template<typename U> | |
| 452 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator|=(vec<1, U, Q> const& v) | |
| 453 | { | |
| 454 | this->x |= v.x; | |
| 455 | this->y |= v.x; | |
| 456 | this->z |= v.x; | |
| 457 | return *this; | |
| 458 | } | |
| 459 | ||
| 460 | template<typename T, qualifier Q> | |
| 461 | template<typename U> | |
| 462 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator|=(vec<3, U, Q> const& v) | |
| 463 | { | |
| 464 | this->x |= v.x; | |
| 465 | this->y |= v.y; | |
| 466 | this->z |= v.z; | |
| 467 | return *this; | |
| 468 | } | |
| 469 | ||
| 470 | template<typename T, qualifier Q> | |
| 471 | template<typename U> | |
| 472 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator^=(U scalar) | |
| 473 | { | |
| 474 | this->x ^= scalar; | |
| 475 | this->y ^= scalar; | |
| 476 | this->z ^= scalar; | |
| 477 | return *this; | |
| 478 | } | |
| 479 | ||
| 480 | template<typename T, qualifier Q> | |
| 481 | template<typename U> | |
| 482 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator^=(vec<1, U, Q> const& v) | |
| 483 | { | |
| 484 | this->x ^= v.x; | |
| 485 | this->y ^= v.x; | |
| 486 | this->z ^= v.x; | |
| 487 | return *this; | |
| 488 | } | |
| 489 | ||
| 490 | template<typename T, qualifier Q> | |
| 491 | template<typename U> | |
| 492 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator^=(vec<3, U, Q> const& v) | |
| 493 | { | |
| 494 | this->x ^= v.x; | |
| 495 | this->y ^= v.y; | |
| 496 | this->z ^= v.z; | |
| 497 | return *this; | |
| 498 | } | |
| 499 | ||
| 500 | template<typename T, qualifier Q> | |
| 501 | template<typename U> | |
| 502 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator<<=(U scalar) | |
| 503 | { | |
| 504 | this->x <<= scalar; | |
| 505 | this->y <<= scalar; | |
| 506 | this->z <<= scalar; | |
| 507 | return *this; | |
| 508 | } | |
| 509 | ||
| 510 | template<typename T, qualifier Q> | |
| 511 | template<typename U> | |
| 512 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator<<=(vec<1, U, Q> const& v) | |
| 513 | { | |
| 514 | this->x <<= static_cast<T>(v.x); | |
| 515 | this->y <<= static_cast<T>(v.x); | |
| 516 | this->z <<= static_cast<T>(v.x); | |
| 517 | return *this; | |
| 518 | } | |
| 519 | ||
| 520 | template<typename T, qualifier Q> | |
| 521 | template<typename U> | |
| 522 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator<<=(vec<3, U, Q> const& v) | |
| 523 | { | |
| 524 | this->x <<= static_cast<T>(v.x); | |
| 525 | this->y <<= static_cast<T>(v.y); | |
| 526 | this->z <<= static_cast<T>(v.z); | |
| 527 | return *this; | |
| 528 | } | |
| 529 | ||
| 530 | template<typename T, qualifier Q> | |
| 531 | template<typename U> | |
| 532 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator>>=(U scalar) | |
| 533 | { | |
| 534 | this->x >>= static_cast<T>(scalar); | |
| 535 | this->y >>= static_cast<T>(scalar); | |
| 536 | this->z >>= static_cast<T>(scalar); | |
| 537 | return *this; | |
| 538 | } | |
| 539 | ||
| 540 | template<typename T, qualifier Q> | |
| 541 | template<typename U> | |
| 542 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator>>=(vec<1, U, Q> const& v) | |
| 543 | { | |
| 544 | this->x >>= static_cast<T>(v.x); | |
| 545 | this->y >>= static_cast<T>(v.x); | |
| 546 | this->z >>= static_cast<T>(v.x); | |
| 547 | return *this; | |
| 548 | } | |
| 549 | ||
| 550 | template<typename T, qualifier Q> | |
| 551 | template<typename U> | |
| 552 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> & vec<3, T, Q>::operator>>=(vec<3, U, Q> const& v) | |
| 553 | { | |
| 554 | this->x >>= static_cast<T>(v.x); | |
| 555 | this->y >>= static_cast<T>(v.y); | |
| 556 | this->z >>= static_cast<T>(v.z); | |
| 557 | return *this; | |
| 558 | } | |
| 559 | ||
| 560 | // -- Unary arithmetic operators -- | |
| 561 | ||
| 562 | template<typename T, qualifier Q> | |
| 563 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator+(vec<3, T, Q> const& v) | |
| 564 | { | |
| 565 | return v; | |
| 566 | } | |
| 567 | ||
| 568 | template<typename T, qualifier Q> | |
| 569 | 98x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator-(vec<3, T, Q> const& v) |
| 570 | { | |
| 571 | 196x | return vec<3, T, Q>( |
| 572 | 98x | -v.x, |
| 573 | 98x | -v.y, |
| 574 | 98x | -v.z); |
| 575 | } | |
| 576 | ||
| 577 | // -- Binary arithmetic operators -- | |
| 578 | ||
| 579 | template<typename T, qualifier Q> | |
| 580 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator+(vec<3, T, Q> const& v, T scalar) | |
| 581 | { | |
| 582 | return vec<3, T, Q>( | |
| 583 | v.x + scalar, | |
| 584 | v.y + scalar, | |
| 585 | v.z + scalar); | |
| 586 | } | |
| 587 | ||
| 588 | template<typename T, qualifier Q> | |
| 589 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator+(vec<3, T, Q> const& v, vec<1, T, Q> const& scalar) | |
| 590 | { | |
| 591 | return vec<3, T, Q>( | |
| 592 | v.x + scalar.x, | |
| 593 | v.y + scalar.x, | |
| 594 | v.z + scalar.x); | |
| 595 | } | |
| 596 | ||
| 597 | template<typename T, qualifier Q> | |
| 598 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator+(T scalar, vec<3, T, Q> const& v) | |
| 599 | { | |
| 600 | return vec<3, T, Q>( | |
| 601 | scalar + v.x, | |
| 602 | scalar + v.y, | |
| 603 | scalar + v.z); | |
| 604 | } | |
| 605 | ||
| 606 | template<typename T, qualifier Q> | |
| 607 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator+(vec<1, T, Q> const& scalar, vec<3, T, Q> const& v) | |
| 608 | { | |
| 609 | return vec<3, T, Q>( | |
| 610 | scalar.x + v.x, | |
| 611 | scalar.x + v.y, | |
| 612 | scalar.x + v.z); | |
| 613 | } | |
| 614 | ||
| 615 | template<typename T, qualifier Q> | |
| 616 | 4998132x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator+(vec<3, T, Q> const& v1, vec<3, T, Q> const& v2) |
| 617 | { | |
| 618 | ! | return vec<3, T, Q>( |
| 619 | 4998132x | v1.x + v2.x, |
| 620 | 4998132x | v1.y + v2.y, |
| 621 | 4998132x | v1.z + v2.z); |
| 622 | } | |
| 623 | ||
| 624 | template<typename T, qualifier Q> | |
| 625 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator-(vec<3, T, Q> const& v, T scalar) | |
| 626 | { | |
| 627 | return vec<3, T, Q>( | |
| 628 | v.x - scalar, | |
| 629 | v.y - scalar, | |
| 630 | v.z - scalar); | |
| 631 | } | |
| 632 | ||
| 633 | template<typename T, qualifier Q> | |
| 634 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator-(vec<3, T, Q> const& v, vec<1, T, Q> const& scalar) | |
| 635 | { | |
| 636 | return vec<3, T, Q>( | |
| 637 | v.x - scalar.x, | |
| 638 | v.y - scalar.x, | |
| 639 | v.z - scalar.x); | |
| 640 | } | |
| 641 | ||
| 642 | template<typename T, qualifier Q> | |
| 643 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator-(T scalar, vec<3, T, Q> const& v) | |
| 644 | { | |
| 645 | return vec<3, T, Q>( | |
| 646 | scalar - v.x, | |
| 647 | scalar - v.y, | |
| 648 | scalar - v.z); | |
| 649 | } | |
| 650 | ||
| 651 | template<typename T, qualifier Q> | |
| 652 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator-(vec<1, T, Q> const& scalar, vec<3, T, Q> const& v) | |
| 653 | { | |
| 654 | return vec<3, T, Q>( | |
| 655 | scalar.x - v.x, | |
| 656 | scalar.x - v.y, | |
| 657 | scalar.x - v.z); | |
| 658 | } | |
| 659 | ||
| 660 | template<typename T, qualifier Q> | |
| 661 | 741865x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator-(vec<3, T, Q> const& v1, vec<3, T, Q> const& v2) |
| 662 | { | |
| 663 | ! | return vec<3, T, Q>( |
| 664 | 741865x | v1.x - v2.x, |
| 665 | 741865x | v1.y - v2.y, |
| 666 | 741865x | v1.z - v2.z); |
| 667 | } | |
| 668 | ||
| 669 | template<typename T, qualifier Q> | |
| 670 | 12163153x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator*(vec<3, T, Q> const& v, T scalar) |
| 671 | { | |
| 672 | 196x | return vec<3, T, Q>( |
| 673 | 12163153x | v.x * scalar, |
| 674 | 12163153x | v.y * scalar, |
| 675 | 12163153x | v.z * scalar); |
| 676 | } | |
| 677 | ||
| 678 | template<typename T, qualifier Q> | |
| 679 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator*(vec<3, T, Q> const& v, vec<1, T, Q> const& scalar) | |
| 680 | { | |
| 681 | return vec<3, T, Q>( | |
| 682 | v.x * scalar.x, | |
| 683 | v.y * scalar.x, | |
| 684 | v.z * scalar.x); | |
| 685 | } | |
| 686 | ||
| 687 | template<typename T, qualifier Q> | |
| 688 | 668974x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator*(T scalar, vec<3, T, Q> const& v) |
| 689 | { | |
| 690 | 4800x | return vec<3, T, Q>( |
| 691 | 668974x | scalar * v.x, |
| 692 | 668974x | scalar * v.y, |
| 693 | 668974x | scalar * v.z); |
| 694 | } | |
| 695 | ||
| 696 | template<typename T, qualifier Q> | |
| 697 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator*(vec<1, T, Q> const& scalar, vec<3, T, Q> const& v) | |
| 698 | { | |
| 699 | return vec<3, T, Q>( | |
| 700 | scalar.x * v.x, | |
| 701 | scalar.x * v.y, | |
| 702 | scalar.x * v.z); | |
| 703 | } | |
| 704 | ||
| 705 | template<typename T, qualifier Q> | |
| 706 | 667327x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator*(vec<3, T, Q> const& v1, vec<3, T, Q> const& v2) |
| 707 | { | |
| 708 | 196x | return vec<3, T, Q>( |
| 709 | 667327x | v1.x * v2.x, |
| 710 | 667327x | v1.y * v2.y, |
| 711 | 667327x | v1.z * v2.z); |
| 712 | } | |
| 713 | ||
| 714 | template<typename T, qualifier Q> | |
| 715 | 5x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator/(vec<3, T, Q> const& v, T scalar) |
| 716 | { | |
| 717 | return vec<3, T, Q>( | |
| 718 | 5x | v.x / scalar, |
| 719 | 5x | v.y / scalar, |
| 720 | 5x | v.z / scalar); |
| 721 | } | |
| 722 | ||
| 723 | template<typename T, qualifier Q> | |
| 724 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator/(vec<3, T, Q> const& v, vec<1, T, Q> const& scalar) | |
| 725 | { | |
| 726 | return vec<3, T, Q>( | |
| 727 | v.x / scalar.x, | |
| 728 | v.y / scalar.x, | |
| 729 | v.z / scalar.x); | |
| 730 | } | |
| 731 | ||
| 732 | template<typename T, qualifier Q> | |
| 733 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator/(T scalar, vec<3, T, Q> const& v) | |
| 734 | { | |
| 735 | return vec<3, T, Q>( | |
| 736 | scalar / v.x, | |
| 737 | scalar / v.y, | |
| 738 | scalar / v.z); | |
| 739 | } | |
| 740 | ||
| 741 | template<typename T, qualifier Q> | |
| 742 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator/(vec<1, T, Q> const& scalar, vec<3, T, Q> const& v) | |
| 743 | { | |
| 744 | return vec<3, T, Q>( | |
| 745 | scalar.x / v.x, | |
| 746 | scalar.x / v.y, | |
| 747 | scalar.x / v.z); | |
| 748 | } | |
| 749 | ||
| 750 | template<typename T, qualifier Q> | |
| 751 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator/(vec<3, T, Q> const& v1, vec<3, T, Q> const& v2) | |
| 752 | { | |
| 753 | return vec<3, T, Q>( | |
| 754 | v1.x / v2.x, | |
| 755 | v1.y / v2.y, | |
| 756 | v1.z / v2.z); | |
| 757 | } | |
| 758 | ||
| 759 | // -- Binary bit operators -- | |
| 760 | ||
| 761 | template<typename T, qualifier Q> | |
| 762 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator%(vec<3, T, Q> const& v, T scalar) | |
| 763 | { | |
| 764 | return vec<3, T, Q>( | |
| 765 | v.x % scalar, | |
| 766 | v.y % scalar, | |
| 767 | v.z % scalar); | |
| 768 | } | |
| 769 | ||
| 770 | template<typename T, qualifier Q> | |
| 771 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator%(vec<3, T, Q> const& v, vec<1, T, Q> const& scalar) | |
| 772 | { | |
| 773 | return vec<3, T, Q>( | |
| 774 | v.x % scalar.x, | |
| 775 | v.y % scalar.x, | |
| 776 | v.z % scalar.x); | |
| 777 | } | |
| 778 | ||
| 779 | template<typename T, qualifier Q> | |
| 780 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator%(T scalar, vec<3, T, Q> const& v) | |
| 781 | { | |
| 782 | return vec<3, T, Q>( | |
| 783 | scalar % v.x, | |
| 784 | scalar % v.y, | |
| 785 | scalar % v.z); | |
| 786 | } | |
| 787 | ||
| 788 | template<typename T, qualifier Q> | |
| 789 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator%(vec<1, T, Q> const& scalar, vec<3, T, Q> const& v) | |
| 790 | { | |
| 791 | return vec<3, T, Q>( | |
| 792 | scalar.x % v.x, | |
| 793 | scalar.x % v.y, | |
| 794 | scalar.x % v.z); | |
| 795 | } | |
| 796 | ||
| 797 | template<typename T, qualifier Q> | |
| 798 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator%(vec<3, T, Q> const& v1, vec<3, T, Q> const& v2) | |
| 799 | { | |
| 800 | return vec<3, T, Q>( | |
| 801 | v1.x % v2.x, | |
| 802 | v1.y % v2.y, | |
| 803 | v1.z % v2.z); | |
| 804 | } | |
| 805 | ||
| 806 | template<typename T, qualifier Q> | |
| 807 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator&(vec<3, T, Q> const& v, T scalar) | |
| 808 | { | |
| 809 | return vec<3, T, Q>( | |
| 810 | v.x & scalar, | |
| 811 | v.y & scalar, | |
| 812 | v.z & scalar); | |
| 813 | } | |
| 814 | ||
| 815 | template<typename T, qualifier Q> | |
| 816 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator&(vec<3, T, Q> const& v, vec<1, T, Q> const& scalar) | |
| 817 | { | |
| 818 | return vec<3, T, Q>( | |
| 819 | v.x & scalar.x, | |
| 820 | v.y & scalar.x, | |
| 821 | v.z & scalar.x); | |
| 822 | } | |
| 823 | ||
| 824 | template<typename T, qualifier Q> | |
| 825 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator&(T scalar, vec<3, T, Q> const& v) | |
| 826 | { | |
| 827 | return vec<3, T, Q>( | |
| 828 | scalar & v.x, | |
| 829 | scalar & v.y, | |
| 830 | scalar & v.z); | |
| 831 | } | |
| 832 | ||
| 833 | template<typename T, qualifier Q> | |
| 834 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator&(vec<1, T, Q> const& scalar, vec<3, T, Q> const& v) | |
| 835 | { | |
| 836 | return vec<3, T, Q>( | |
| 837 | scalar.x & v.x, | |
| 838 | scalar.x & v.y, | |
| 839 | scalar.x & v.z); | |
| 840 | } | |
| 841 | ||
| 842 | template<typename T, qualifier Q> | |
| 843 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator&(vec<3, T, Q> const& v1, vec<3, T, Q> const& v2) | |
| 844 | { | |
| 845 | return vec<3, T, Q>( | |
| 846 | v1.x & v2.x, | |
| 847 | v1.y & v2.y, | |
| 848 | v1.z & v2.z); | |
| 849 | } | |
| 850 | ||
| 851 | template<typename T, qualifier Q> | |
| 852 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator|(vec<3, T, Q> const& v, T scalar) | |
| 853 | { | |
| 854 | return vec<3, T, Q>( | |
| 855 | v.x | scalar, | |
| 856 | v.y | scalar, | |
| 857 | v.z | scalar); | |
| 858 | } | |
| 859 | ||
| 860 | template<typename T, qualifier Q> | |
| 861 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator|(vec<3, T, Q> const& v, vec<1, T, Q> const& scalar) | |
| 862 | { | |
| 863 | return vec<3, T, Q>( | |
| 864 | v.x | scalar.x, | |
| 865 | v.y | scalar.x, | |
| 866 | v.z | scalar.x); | |
| 867 | } | |
| 868 | ||
| 869 | template<typename T, qualifier Q> | |
| 870 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator|(T scalar, vec<3, T, Q> const& v) | |
| 871 | { | |
| 872 | return vec<3, T, Q>( | |
| 873 | scalar | v.x, | |
| 874 | scalar | v.y, | |
| 875 | scalar | v.z); | |
| 876 | } | |
| 877 | ||
| 878 | template<typename T, qualifier Q> | |
| 879 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator|(vec<1, T, Q> const& scalar, vec<3, T, Q> const& v) | |
| 880 | { | |
| 881 | return vec<3, T, Q>( | |
| 882 | scalar.x | v.x, | |
| 883 | scalar.x | v.y, | |
| 884 | scalar.x | v.z); | |
| 885 | } | |
| 886 | ||
| 887 | template<typename T, qualifier Q> | |
| 888 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator|(vec<3, T, Q> const& v1, vec<3, T, Q> const& v2) | |
| 889 | { | |
| 890 | return vec<3, T, Q>( | |
| 891 | v1.x | v2.x, | |
| 892 | v1.y | v2.y, | |
| 893 | v1.z | v2.z); | |
| 894 | } | |
| 895 | ||
| 896 | template<typename T, qualifier Q> | |
| 897 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator^(vec<3, T, Q> const& v, T scalar) | |
| 898 | { | |
| 899 | return vec<3, T, Q>( | |
| 900 | v.x ^ scalar, | |
| 901 | v.y ^ scalar, | |
| 902 | v.z ^ scalar); | |
| 903 | } | |
| 904 | ||
| 905 | template<typename T, qualifier Q> | |
| 906 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator^(vec<3, T, Q> const& v, vec<1, T, Q> const& scalar) | |
| 907 | { | |
| 908 | return vec<3, T, Q>( | |
| 909 | v.x ^ scalar.x, | |
| 910 | v.y ^ scalar.x, | |
| 911 | v.z ^ scalar.x); | |
| 912 | } | |
| 913 | ||
| 914 | template<typename T, qualifier Q> | |
| 915 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator^(T scalar, vec<3, T, Q> const& v) | |
| 916 | { | |
| 917 | return vec<3, T, Q>( | |
| 918 | scalar ^ v.x, | |
| 919 | scalar ^ v.y, | |
| 920 | scalar ^ v.z); | |
| 921 | } | |
| 922 | ||
| 923 | template<typename T, qualifier Q> | |
| 924 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator^(vec<1, T, Q> const& scalar, vec<3, T, Q> const& v) | |
| 925 | { | |
| 926 | return vec<3, T, Q>( | |
| 927 | scalar.x ^ v.x, | |
| 928 | scalar.x ^ v.y, | |
| 929 | scalar.x ^ v.z); | |
| 930 | } | |
| 931 | ||
| 932 | template<typename T, qualifier Q> | |
| 933 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator^(vec<3, T, Q> const& v1, vec<3, T, Q> const& v2) | |
| 934 | { | |
| 935 | return vec<3, T, Q>( | |
| 936 | v1.x ^ v2.x, | |
| 937 | v1.y ^ v2.y, | |
| 938 | v1.z ^ v2.z); | |
| 939 | } | |
| 940 | ||
| 941 | template<typename T, qualifier Q> | |
| 942 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator<<(vec<3, T, Q> const& v, T scalar) | |
| 943 | { | |
| 944 | return vec<3, T, Q>( | |
| 945 | v.x << scalar, | |
| 946 | v.y << scalar, | |
| 947 | v.z << scalar); | |
| 948 | } | |
| 949 | ||
| 950 | template<typename T, qualifier Q> | |
| 951 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator<<(vec<3, T, Q> const& v, vec<1, T, Q> const& scalar) | |
| 952 | { | |
| 953 | return vec<3, T, Q>( | |
| 954 | v.x << scalar.x, | |
| 955 | v.y << scalar.x, | |
| 956 | v.z << scalar.x); | |
| 957 | } | |
| 958 | ||
| 959 | template<typename T, qualifier Q> | |
| 960 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator<<(T scalar, vec<3, T, Q> const& v) | |
| 961 | { | |
| 962 | return vec<3, T, Q>( | |
| 963 | scalar << v.x, | |
| 964 | scalar << v.y, | |
| 965 | scalar << v.z); | |
| 966 | } | |
| 967 | ||
| 968 | template<typename T, qualifier Q> | |
| 969 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator<<(vec<1, T, Q> const& scalar, vec<3, T, Q> const& v) | |
| 970 | { | |
| 971 | return vec<3, T, Q>( | |
| 972 | scalar.x << v.x, | |
| 973 | scalar.x << v.y, | |
| 974 | scalar.x << v.z); | |
| 975 | } | |
| 976 | ||
| 977 | template<typename T, qualifier Q> | |
| 978 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator<<(vec<3, T, Q> const& v1, vec<3, T, Q> const& v2) | |
| 979 | { | |
| 980 | return vec<3, T, Q>( | |
| 981 | v1.x << v2.x, | |
| 982 | v1.y << v2.y, | |
| 983 | v1.z << v2.z); | |
| 984 | } | |
| 985 | ||
| 986 | template<typename T, qualifier Q> | |
| 987 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator>>(vec<3, T, Q> const& v, T scalar) | |
| 988 | { | |
| 989 | return vec<3, T, Q>( | |
| 990 | v.x >> scalar, | |
| 991 | v.y >> scalar, | |
| 992 | v.z >> scalar); | |
| 993 | } | |
| 994 | ||
| 995 | template<typename T, qualifier Q> | |
| 996 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator>>(vec<3, T, Q> const& v, vec<1, T, Q> const& scalar) | |
| 997 | { | |
| 998 | return vec<3, T, Q>( | |
| 999 | v.x >> scalar.x, | |
| 1000 | v.y >> scalar.x, | |
| 1001 | v.z >> scalar.x); | |
| 1002 | } | |
| 1003 | ||
| 1004 | template<typename T, qualifier Q> | |
| 1005 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator>>(T scalar, vec<3, T, Q> const& v) | |
| 1006 | { | |
| 1007 | return vec<3, T, Q>( | |
| 1008 | scalar >> v.x, | |
| 1009 | scalar >> v.y, | |
| 1010 | scalar >> v.z); | |
| 1011 | } | |
| 1012 | ||
| 1013 | template<typename T, qualifier Q> | |
| 1014 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator>>(vec<1, T, Q> const& scalar, vec<3, T, Q> const& v) | |
| 1015 | { | |
| 1016 | return vec<3, T, Q>( | |
| 1017 | scalar.x >> v.x, | |
| 1018 | scalar.x >> v.y, | |
| 1019 | scalar.x >> v.z); | |
| 1020 | } | |
| 1021 | ||
| 1022 | template<typename T, qualifier Q> | |
| 1023 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator>>(vec<3, T, Q> const& v1, vec<3, T, Q> const& v2) | |
| 1024 | { | |
| 1025 | return vec<3, T, Q>( | |
| 1026 | v1.x >> v2.x, | |
| 1027 | v1.y >> v2.y, | |
| 1028 | v1.z >> v2.z); | |
| 1029 | } | |
| 1030 | ||
| 1031 | template<typename T, qualifier Q> | |
| 1032 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, T, Q> operator~(vec<3, T, Q> const& v) | |
| 1033 | { | |
| 1034 | return vec<3, T, Q>( | |
| 1035 | ~v.x, | |
| 1036 | ~v.y, | |
| 1037 | ~v.z); | |
| 1038 | } | |
| 1039 | ||
| 1040 | // -- Boolean operators -- | |
| 1041 | ||
| 1042 | template<typename T, qualifier Q> | |
| 1043 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR bool operator==(vec<3, T, Q> const& v1, vec<3, T, Q> const& v2) | |
| 1044 | { | |
| 1045 | return | |
| 1046 | detail::compute_equal<T, std::numeric_limits<T>::is_iec559>::call(v1.x, v2.x) && | |
| 1047 | detail::compute_equal<T, std::numeric_limits<T>::is_iec559>::call(v1.y, v2.y) && | |
| 1048 | detail::compute_equal<T, std::numeric_limits<T>::is_iec559>::call(v1.z, v2.z); | |
| 1049 | } | |
| 1050 | ||
| 1051 | template<typename T, qualifier Q> | |
| 1052 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR bool operator!=(vec<3, T, Q> const& v1, vec<3, T, Q> const& v2) | |
| 1053 | { | |
| 1054 | return !(v1 == v2); | |
| 1055 | } | |
| 1056 | ||
| 1057 | template<qualifier Q> | |
| 1058 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, bool, Q> operator&&(vec<3, bool, Q> const& v1, vec<3, bool, Q> const& v2) | |
| 1059 | { | |
| 1060 | return vec<3, bool, Q>(v1.x && v2.x, v1.y && v2.y, v1.z && v2.z); | |
| 1061 | } | |
| 1062 | ||
| 1063 | template<qualifier Q> | |
| 1064 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<3, bool, Q> operator||(vec<3, bool, Q> const& v1, vec<3, bool, Q> const& v2) | |
| 1065 | { | |
| 1066 | return vec<3, bool, Q>(v1.x || v2.x, v1.y || v2.y, v1.z || v2.z); | |
| 1067 | } | |
| 1068 | }//namespace glm |
| 1 | #include "../exponential.hpp" | |
| 2 | #include "../common.hpp" | |
| 3 | ||
| 4 | namespace glm{ | |
| 5 | namespace detail | |
| 6 | { | |
| 7 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 8 | struct compute_length | |
| 9 | { | |
| 10 | 20x | GLM_FUNC_QUALIFIER static T call(vec<L, T, Q> const& v) |
| 11 | { | |
| 12 | 20x | return sqrt(dot(v, v)); |
| 13 | } | |
| 14 | }; | |
| 15 | ||
| 16 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 17 | struct compute_distance | |
| 18 | { | |
| 19 | GLM_FUNC_QUALIFIER static T call(vec<L, T, Q> const& p0, vec<L, T, Q> const& p1) | |
| 20 | { | |
| 21 | return length(p1 - p0); | |
| 22 | } | |
| 23 | }; | |
| 24 | ||
| 25 | template<typename V, typename T, bool Aligned> | |
| 26 | struct compute_dot{}; | |
| 27 | ||
| 28 | template<typename T, qualifier Q, bool Aligned> | |
| 29 | struct compute_dot<vec<1, T, Q>, T, Aligned> | |
| 30 | { | |
| 31 | GLM_FUNC_QUALIFIER static T call(vec<1, T, Q> const& a, vec<1, T, Q> const& b) | |
| 32 | { | |
| 33 | return a.x * b.x; | |
| 34 | } | |
| 35 | }; | |
| 36 | ||
| 37 | template<typename T, qualifier Q, bool Aligned> | |
| 38 | struct compute_dot<vec<2, T, Q>, T, Aligned> | |
| 39 | { | |
| 40 | GLM_FUNC_QUALIFIER static T call(vec<2, T, Q> const& a, vec<2, T, Q> const& b) | |
| 41 | { | |
| 42 | vec<2, T, Q> tmp(a * b); | |
| 43 | return tmp.x + tmp.y; | |
| 44 | } | |
| 45 | }; | |
| 46 | ||
| 47 | template<typename T, qualifier Q, bool Aligned> | |
| 48 | struct compute_dot<vec<3, T, Q>, T, Aligned> | |
| 49 | { | |
| 50 | 667327x | GLM_FUNC_QUALIFIER static T call(vec<3, T, Q> const& a, vec<3, T, Q> const& b) |
| 51 | { | |
| 52 | 667327x | vec<3, T, Q> tmp(a * b); |
| 53 | 667327x | return tmp.x + tmp.y + tmp.z; |
| 54 | } | |
| 55 | }; | |
| 56 | ||
| 57 | template<typename T, qualifier Q, bool Aligned> | |
| 58 | struct compute_dot<vec<4, T, Q>, T, Aligned> | |
| 59 | { | |
| 60 | 684x | GLM_FUNC_QUALIFIER static T call(vec<4, T, Q> const& a, vec<4, T, Q> const& b) |
| 61 | { | |
| 62 | 684x | vec<4, T, Q> tmp(a * b); |
| 63 | 684x | return (tmp.x + tmp.y) + (tmp.z + tmp.w); |
| 64 | } | |
| 65 | }; | |
| 66 | ||
| 67 | template<typename T, qualifier Q, bool Aligned> | |
| 68 | struct compute_cross | |
| 69 | { | |
| 70 | 371048x | GLM_FUNC_QUALIFIER static vec<3, T, Q> call(vec<3, T, Q> const& x, vec<3, T, Q> const& y) |
| 71 | { | |
| 72 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'cross' accepts only floating-point inputs"); | |
| 73 | ||
| 74 | 196x | return vec<3, T, Q>( |
| 75 | 371048x | x.y * y.z - y.y * x.z, |
| 76 | 371048x | x.z * y.x - y.z * x.x, |
| 77 | 371048x | x.x * y.y - y.x * x.y); |
| 78 | } | |
| 79 | }; | |
| 80 | ||
| 81 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 82 | struct compute_normalize | |
| 83 | { | |
| 84 | 1485x | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& v) |
| 85 | { | |
| 86 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'normalize' accepts only floating-point inputs"); | |
| 87 | ||
| 88 | 1485x | return v * inversesqrt(dot(v, v)); |
| 89 | } | |
| 90 | }; | |
| 91 | ||
| 92 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 93 | struct compute_faceforward | |
| 94 | { | |
| 95 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& N, vec<L, T, Q> const& I, vec<L, T, Q> const& Nref) | |
| 96 | { | |
| 97 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'normalize' accepts only floating-point inputs"); | |
| 98 | ||
| 99 | return dot(Nref, I) < static_cast<T>(0) ? N : -N; | |
| 100 | } | |
| 101 | }; | |
| 102 | ||
| 103 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 104 | struct compute_reflect | |
| 105 | { | |
| 106 | ! | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& I, vec<L, T, Q> const& N) |
| 107 | { | |
| 108 | ! | return I - N * dot(N, I) * static_cast<T>(2); |
| 109 | } | |
| 110 | }; | |
| 111 | ||
| 112 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 113 | struct compute_refract | |
| 114 | { | |
| 115 | ! | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& I, vec<L, T, Q> const& N, T eta) |
| 116 | { | |
| 117 | ! | T const dotValue(dot(N, I)); |
| 118 | ! | T const k(static_cast<T>(1) - eta * eta * (static_cast<T>(1) - dotValue * dotValue)); |
| 119 | ! | vec<L, T, Q> const Result = |
| 120 | ! | (k >= static_cast<T>(0)) ? (eta * I - (eta * dotValue + std::sqrt(k)) * N) : vec<L, T, Q>(0); |
| 121 | ! | return Result; |
| 122 | } | |
| 123 | }; | |
| 124 | }//namespace detail | |
| 125 | ||
| 126 | // length | |
| 127 | template<typename genType> | |
| 128 | GLM_FUNC_QUALIFIER genType length(genType x) | |
| 129 | { | |
| 130 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'length' accepts only floating-point inputs"); | |
| 131 | ||
| 132 | return abs(x); | |
| 133 | } | |
| 134 | ||
| 135 | template<length_t L, typename T, qualifier Q> | |
| 136 | 20x | GLM_FUNC_QUALIFIER T length(vec<L, T, Q> const& v) |
| 137 | { | |
| 138 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'length' accepts only floating-point inputs"); | |
| 139 | ||
| 140 | 20x | return detail::compute_length<L, T, Q, detail::is_aligned<Q>::value>::call(v); |
| 141 | } | |
| 142 | ||
| 143 | // distance | |
| 144 | template<typename genType> | |
| 145 | GLM_FUNC_QUALIFIER genType distance(genType const& p0, genType const& p1) | |
| 146 | { | |
| 147 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'distance' accepts only floating-point inputs"); | |
| 148 | ||
| 149 | return length(p1 - p0); | |
| 150 | } | |
| 151 | ||
| 152 | template<length_t L, typename T, qualifier Q> | |
| 153 | GLM_FUNC_QUALIFIER T distance(vec<L, T, Q> const& p0, vec<L, T, Q> const& p1) | |
| 154 | { | |
| 155 | return detail::compute_distance<L, T, Q, detail::is_aligned<Q>::value>::call(p0, p1); | |
| 156 | } | |
| 157 | ||
| 158 | // dot | |
| 159 | template<typename T> | |
| 160 | GLM_FUNC_QUALIFIER T dot(T x, T y) | |
| 161 | { | |
| 162 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'dot' accepts only floating-point inputs"); | |
| 163 | return x * y; | |
| 164 | } | |
| 165 | ||
| 166 | template<length_t L, typename T, qualifier Q> | |
| 167 | 668011x | GLM_FUNC_QUALIFIER T dot(vec<L, T, Q> const& x, vec<L, T, Q> const& y) |
| 168 | { | |
| 169 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'dot' accepts only floating-point inputs"); | |
| 170 | 668011x | return detail::compute_dot<vec<L, T, Q>, T, detail::is_aligned<Q>::value>::call(x, y); |
| 171 | } | |
| 172 | ||
| 173 | // cross | |
| 174 | template<typename T, qualifier Q> | |
| 175 | 371048x | GLM_FUNC_QUALIFIER vec<3, T, Q> cross(vec<3, T, Q> const& x, vec<3, T, Q> const& y) |
| 176 | { | |
| 177 | 371048x | return detail::compute_cross<T, Q, detail::is_aligned<Q>::value>::call(x, y); |
| 178 | } | |
| 179 | /* | |
| 180 | // normalize | |
| 181 | template<typename genType> | |
| 182 | GLM_FUNC_QUALIFIER genType normalize(genType const& x) | |
| 183 | { | |
| 184 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'normalize' accepts only floating-point inputs"); | |
| 185 | ||
| 186 | return x < genType(0) ? genType(-1) : genType(1); | |
| 187 | } | |
| 188 | */ | |
| 189 | template<length_t L, typename T, qualifier Q> | |
| 190 | 1485x | GLM_FUNC_QUALIFIER vec<L, T, Q> normalize(vec<L, T, Q> const& x) |
| 191 | { | |
| 192 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'normalize' accepts only floating-point inputs"); | |
| 193 | ||
| 194 | 1485x | return detail::compute_normalize<L, T, Q, detail::is_aligned<Q>::value>::call(x); |
| 195 | } | |
| 196 | ||
| 197 | // faceforward | |
| 198 | template<typename genType> | |
| 199 | GLM_FUNC_QUALIFIER genType faceforward(genType const& N, genType const& I, genType const& Nref) | |
| 200 | { | |
| 201 | return dot(Nref, I) < static_cast<genType>(0) ? N : -N; | |
| 202 | } | |
| 203 | ||
| 204 | template<length_t L, typename T, qualifier Q> | |
| 205 | GLM_FUNC_QUALIFIER vec<L, T, Q> faceforward(vec<L, T, Q> const& N, vec<L, T, Q> const& I, vec<L, T, Q> const& Nref) | |
| 206 | { | |
| 207 | return detail::compute_faceforward<L, T, Q, detail::is_aligned<Q>::value>::call(N, I, Nref); | |
| 208 | } | |
| 209 | ||
| 210 | // reflect | |
| 211 | template<typename genType> | |
| 212 | GLM_FUNC_QUALIFIER genType reflect(genType const& I, genType const& N) | |
| 213 | { | |
| 214 | return I - N * dot(N, I) * genType(2); | |
| 215 | } | |
| 216 | ||
| 217 | template<length_t L, typename T, qualifier Q> | |
| 218 | ! | GLM_FUNC_QUALIFIER vec<L, T, Q> reflect(vec<L, T, Q> const& I, vec<L, T, Q> const& N) |
| 219 | { | |
| 220 | ! | return detail::compute_reflect<L, T, Q, detail::is_aligned<Q>::value>::call(I, N); |
| 221 | } | |
| 222 | ||
| 223 | // refract | |
| 224 | template<typename genType> | |
| 225 | GLM_FUNC_QUALIFIER genType refract(genType const& I, genType const& N, genType eta) | |
| 226 | { | |
| 227 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'refract' accepts only floating-point inputs"); | |
| 228 | genType const dotValue(dot(N, I)); | |
| 229 | genType const k(static_cast<genType>(1) - eta * eta * (static_cast<genType>(1) - dotValue * dotValue)); | |
| 230 | return (eta * I - (eta * dotValue + sqrt(k)) * N) * static_cast<genType>(k >= static_cast<genType>(0)); | |
| 231 | } | |
| 232 | ||
| 233 | template<length_t L, typename T, qualifier Q> | |
| 234 | ! | GLM_FUNC_QUALIFIER vec<L, T, Q> refract(vec<L, T, Q> const& I, vec<L, T, Q> const& N, T eta) |
| 235 | { | |
| 236 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'refract' accepts only floating-point inputs"); | |
| 237 | ! | return detail::compute_refract<L, T, Q, detail::is_aligned<Q>::value>::call(I, N, eta); |
| 238 | } | |
| 239 | }//namespace glm | |
| 240 | ||
| 241 | #if GLM_CONFIG_SIMD == GLM_ENABLE | |
| 242 | # include "func_geometric_simd.inl" | |
| 243 | #endif |
| 1 | /// @ref core | |
| 2 | /// @file glm/detail/func_exponential.inl | |
| 3 | ||
| 4 | #include "../vector_relational.hpp" | |
| 5 | #include "_vectorize.hpp" | |
| 6 | #include <limits> | |
| 7 | #include <cmath> | |
| 8 | #include <cassert> | |
| 9 | ||
| 10 | namespace glm{ | |
| 11 | namespace detail | |
| 12 | { | |
| 13 | # if GLM_HAS_CXX11_STL | |
| 14 | using std::log2; | |
| 15 | # else | |
| 16 | template<typename genType> | |
| 17 | genType log2(genType Value) | |
| 18 | { | |
| 19 | return std::log(Value) * static_cast<genType>(1.4426950408889634073599246810019); | |
| 20 | } | |
| 21 | # endif | |
| 22 | ||
| 23 | template<length_t L, typename T, qualifier Q, bool isFloat, bool Aligned> | |
| 24 | struct compute_log2 | |
| 25 | { | |
| 26 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& v) | |
| 27 | { | |
| 28 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'log2' only accept floating-point inputs. Include <glm/gtc/integer.hpp> for integer inputs."); | |
| 29 | ||
| 30 | return detail::functor1<vec, L, T, T, Q>::call(log2, v); | |
| 31 | } | |
| 32 | }; | |
| 33 | ||
| 34 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 35 | struct compute_sqrt | |
| 36 | { | |
| 37 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x) | |
| 38 | { | |
| 39 | return detail::functor1<vec, L, T, T, Q>::call(std::sqrt, x); | |
| 40 | } | |
| 41 | }; | |
| 42 | ||
| 43 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 44 | struct compute_inversesqrt | |
| 45 | { | |
| 46 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x) | |
| 47 | { | |
| 48 | return static_cast<T>(1) / sqrt(x); | |
| 49 | } | |
| 50 | }; | |
| 51 | ||
| 52 | template<length_t L, bool Aligned> | |
| 53 | struct compute_inversesqrt<L, float, lowp, Aligned> | |
| 54 | { | |
| 55 | GLM_FUNC_QUALIFIER static vec<L, float, lowp> call(vec<L, float, lowp> const& x) | |
| 56 | { | |
| 57 | vec<L, float, lowp> tmp(x); | |
| 58 | vec<L, float, lowp> xhalf(tmp * 0.5f); | |
| 59 | vec<L, uint, lowp>* p = reinterpret_cast<vec<L, uint, lowp>*>(const_cast<vec<L, float, lowp>*>(&x)); | |
| 60 | vec<L, uint, lowp> i = vec<L, uint, lowp>(0x5f375a86) - (*p >> vec<L, uint, lowp>(1)); | |
| 61 | vec<L, float, lowp>* ptmp = reinterpret_cast<vec<L, float, lowp>*>(&i); | |
| 62 | tmp = *ptmp; | |
| 63 | tmp = tmp * (1.5f - xhalf * tmp * tmp); | |
| 64 | return tmp; | |
| 65 | } | |
| 66 | }; | |
| 67 | }//namespace detail | |
| 68 | ||
| 69 | // pow | |
| 70 | using std::pow; | |
| 71 | template<length_t L, typename T, qualifier Q> | |
| 72 | GLM_FUNC_QUALIFIER vec<L, T, Q> pow(vec<L, T, Q> const& base, vec<L, T, Q> const& exponent) | |
| 73 | { | |
| 74 | return detail::functor2<vec, L, T, Q>::call(pow, base, exponent); | |
| 75 | } | |
| 76 | ||
| 77 | // exp | |
| 78 | using std::exp; | |
| 79 | template<length_t L, typename T, qualifier Q> | |
| 80 | GLM_FUNC_QUALIFIER vec<L, T, Q> exp(vec<L, T, Q> const& x) | |
| 81 | { | |
| 82 | return detail::functor1<vec, L, T, T, Q>::call(exp, x); | |
| 83 | } | |
| 84 | ||
| 85 | // log | |
| 86 | using std::log; | |
| 87 | template<length_t L, typename T, qualifier Q> | |
| 88 | GLM_FUNC_QUALIFIER vec<L, T, Q> log(vec<L, T, Q> const& x) | |
| 89 | { | |
| 90 | return detail::functor1<vec, L, T, T, Q>::call(log, x); | |
| 91 | } | |
| 92 | ||
| 93 | # if GLM_HAS_CXX11_STL | |
| 94 | using std::exp2; | |
| 95 | # else | |
| 96 | //exp2, ln2 = 0.69314718055994530941723212145818f | |
| 97 | template<typename genType> | |
| 98 | GLM_FUNC_QUALIFIER genType exp2(genType x) | |
| 99 | { | |
| 100 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'exp2' only accept floating-point inputs"); | |
| 101 | ||
| 102 | return std::exp(static_cast<genType>(0.69314718055994530941723212145818) * x); | |
| 103 | } | |
| 104 | # endif | |
| 105 | ||
| 106 | template<length_t L, typename T, qualifier Q> | |
| 107 | GLM_FUNC_QUALIFIER vec<L, T, Q> exp2(vec<L, T, Q> const& x) | |
| 108 | { | |
| 109 | return detail::functor1<vec, L, T, T, Q>::call(exp2, x); | |
| 110 | } | |
| 111 | ||
| 112 | // log2, ln2 = 0.69314718055994530941723212145818f | |
| 113 | template<typename genType> | |
| 114 | GLM_FUNC_QUALIFIER genType log2(genType x) | |
| 115 | { | |
| 116 | return log2(vec<1, genType>(x)).x; | |
| 117 | } | |
| 118 | ||
| 119 | template<length_t L, typename T, qualifier Q> | |
| 120 | GLM_FUNC_QUALIFIER vec<L, T, Q> log2(vec<L, T, Q> const& x) | |
| 121 | { | |
| 122 | return detail::compute_log2<L, T, Q, std::numeric_limits<T>::is_iec559, detail::is_aligned<Q>::value>::call(x); | |
| 123 | } | |
| 124 | ||
| 125 | // sqrt | |
| 126 | using std::sqrt; | |
| 127 | template<length_t L, typename T, qualifier Q> | |
| 128 | GLM_FUNC_QUALIFIER vec<L, T, Q> sqrt(vec<L, T, Q> const& x) | |
| 129 | { | |
| 130 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'sqrt' only accept floating-point inputs"); | |
| 131 | return detail::compute_sqrt<L, T, Q, detail::is_aligned<Q>::value>::call(x); | |
| 132 | } | |
| 133 | ||
| 134 | // inversesqrt | |
| 135 | template<typename genType> | |
| 136 | 1485x | GLM_FUNC_QUALIFIER genType inversesqrt(genType x) |
| 137 | { | |
| 138 | 1485x | return static_cast<genType>(1) / sqrt(x); |
| 139 | } | |
| 140 | ||
| 141 | template<length_t L, typename T, qualifier Q> | |
| 142 | GLM_FUNC_QUALIFIER vec<L, T, Q> inversesqrt(vec<L, T, Q> const& x) | |
| 143 | { | |
| 144 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'inversesqrt' only accept floating-point inputs"); | |
| 145 | return detail::compute_inversesqrt<L, T, Q, detail::is_aligned<Q>::value>::call(x); | |
| 146 | } | |
| 147 | }//namespace glm | |
| 148 | ||
| 149 | #if GLM_CONFIG_SIMD == GLM_ENABLE | |
| 150 | # include "func_exponential_simd.inl" | |
| 151 | #endif | |
| 152 |
| 1 | #include "calctangents.h" | |
| 2 | #include "defines.h" | |
| 3 | #include "glm.hpp" | |
| 4 | #include "assert.h" | |
| 5 | using namespace Rcpp; | |
| 6 | ||
| 7 | ! | inline vec3 Reject(vec3 t, vec3 n) { |
| 8 | ! | return(normalize(t - dot(t,n) * n)); |
| 9 | } | |
| 10 | ||
| 11 | 799398x | inline double DifferenceOfProducts(double a, double b, double c, double d) { |
| 12 | 799398x | double cd = c * d; |
| 13 | 799398x | double err = std::fma(-c, d, cd); |
| 14 | 799398x | double dop = std::fma(a, b, -cd); |
| 15 | 799398x | return(dop + err); |
| 16 | } | |
| 17 | ||
| 18 | // [[Rcpp::export]] | |
| 19 | ! | List CalculateTangents(Rcpp::List raymesh, int shape_id) { |
| 20 | ! | NumericMatrix texcoords = as<NumericMatrix>(as<List>(raymesh["texcoords"])(shape_id)); |
| 21 | ! | NumericMatrix normals = as<NumericMatrix>(as<List>(raymesh["normals"])(shape_id)); |
| 22 | ! | NumericMatrix vertices = as<NumericMatrix>(as<List>(raymesh["vertices"])(shape_id)); |
| 23 | ! | List single_shape = as<List>(raymesh["shapes"])(shape_id); |
| 24 | ! | IntegerMatrix indices = transpose(as<IntegerMatrix>(single_shape["indices"])); |
| 25 | ! | std::vector<vec3> p(vertices.nrow()); |
| 26 | ! | std::vector<vec2> uv(texcoords.nrow()); |
| 27 | ! | std::vector<vec3> norm(texcoords.nrow()); |
| 28 | ||
| 29 | ! | for(int i = 0; i < vertices.nrow(); i++) { |
| 30 | ! | p[i] = vec3(vertices(i,0),vertices(i,1),vertices(i,2)); |
| 31 | } | |
| 32 | ! | for(int i = 0; i < normals.nrow(); i++) { |
| 33 | ! | norm[i] = vec3(normals(i,0),normals(i,1),normals(i,2)); |
| 34 | } | |
| 35 | ! | for(int i = 0; i < texcoords.nrow(); i++) { |
| 36 | ! | uv[i] = vec2(texcoords(i,0),texcoords(i,1)); |
| 37 | } | |
| 38 | ! | int nVertices = vertices.nrow(); |
| 39 | ||
| 40 | ! | int triangleCount = indices.ncol(); |
| 41 | ! | int vertexCount = nVertices; |
| 42 | ||
| 43 | ! | std::vector<vec3> tangent(vertexCount); |
| 44 | ! | std::vector<vec3> bitangent(vertexCount); |
| 45 | ||
| 46 | ! | for (int i = 0; i < vertexCount; i++) { |
| 47 | ! | tangent[i] = vec3(0.f, 0.f, 0.f); |
| 48 | ! | bitangent[i] = vec3(0.f, 0.f, 0.f); |
| 49 | } | |
| 50 | ||
| 51 | ! | IntegerVector tangent_right_handed(vertexCount); |
| 52 | ! | NumericMatrix tangentArray(vertexCount,3); |
| 53 | ||
| 54 | // Calculate tangent and bitangent for each triangle and add to all three vertices. | |
| 55 | ! | for (int k = 0; k < triangleCount * 3; k += 3) { |
| 56 | ! | int i0 = indices[k+0]; |
| 57 | ! | int i1 = indices[k+1]; |
| 58 | ! | int i2 = indices[k+2]; |
| 59 | ASSERT(i0 < triangleCount); | |
| 60 | ASSERT(i1 < triangleCount); | |
| 61 | ASSERT(i2 < triangleCount); | |
| 62 | ASSERT(i0 < vertexCount); | |
| 63 | ASSERT(i1 < vertexCount); | |
| 64 | ASSERT(i2 < vertexCount); | |
| 65 | ||
| 66 | ! | vec3 p0 = p[i0]; |
| 67 | ! | vec3 p1 = p[i1]; |
| 68 | ! | vec3 p2 = p[i2]; |
| 69 | ! | vec2 w0 = uv[i0]; |
| 70 | ! | vec2 w1 = uv[i1]; |
| 71 | ! | vec2 w2 = uv[i2]; |
| 72 | ! | vec3 e1 = p1 - p0; |
| 73 | ! | vec3 e2 = p2 - p0; |
| 74 | ! | Float x1 = w1[0] - w0[0]; |
| 75 | ! | Float x2 = w2[0] - w0[0]; |
| 76 | ! | Float y1 = w1[1] - w0[1]; |
| 77 | ! | Float y2 = w2[1] - w0[1]; |
| 78 | ! | Float inv_dop = DifferenceOfProducts(x1, y2, x2, y1); |
| 79 | ! | if(inv_dop == 0) { |
| 80 | ! | continue; |
| 81 | } | |
| 82 | ! | Float r = 1.f / inv_dop; |
| 83 | ! | vec3 t = (e1 * y2 - e2 * y1) * r; |
| 84 | ! | vec3 b = (e2 * x1 - e1 * x2) * r; |
| 85 | ! | tangent[i0] += t; |
| 86 | ! | tangent[i1] += t; |
| 87 | ! | tangent[i2] += t; |
| 88 | ! | bitangent[i0] += b; |
| 89 | ! | bitangent[i1] += b; |
| 90 | ! | bitangent[i2] += b; |
| 91 | } | |
| 92 | // Orthonormalize each tangent and calculate the handedness. | |
| 93 | ! | for (int i = 0; i < vertexCount; i++) { |
| 94 | ! | vec3& t = tangent[i]; |
| 95 | ! | vec3& b = bitangent[i]; |
| 96 | ! | vec3& n = norm[i]; |
| 97 | ! | vec3 tgnt = Reject(t, n); |
| 98 | ! | tangentArray(i,0) = tgnt[0]; |
| 99 | ! | tangentArray(i,1) = tgnt[1]; |
| 100 | ! | tangentArray(i,2) = tgnt[2]; |
| 101 | ! | tangent_right_handed[i] = dot(cross(t, b), n) > 0.f; |
| 102 | } | |
| 103 | ! | return(List::create(_["tangent_right_handed"] = tangent_right_handed, |
| 104 | ! | _["tangents"] = tangentArray)); |
| 105 | } |
| 1 | /// @ref core | |
| 2 | ||
| 3 | #include "./compute_vector_relational.hpp" | |
| 4 | ||
| 5 | namespace glm | |
| 6 | { | |
| 7 | // -- Implicit basic constructors -- | |
| 8 | ||
| 9 | # if GLM_CONFIG_DEFAULTED_FUNCTIONS == GLM_DISABLE | |
| 10 | template<typename T, qualifier Q> | |
| 11 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q>::vec() | |
| 12 | # if GLM_CONFIG_CTOR_INIT != GLM_CTOR_INIT_DISABLE | |
| 13 | : x(0), y(0) | |
| 14 | # endif | |
| 15 | {} | |
| 16 | ||
| 17 | template<typename T, qualifier Q> | |
| 18 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q>::vec(vec<2, T, Q> const& v) | |
| 19 | : x(v.x), y(v.y) | |
| 20 | {} | |
| 21 | # endif | |
| 22 | ||
| 23 | template<typename T, qualifier Q> | |
| 24 | template<qualifier P> | |
| 25 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q>::vec(vec<2, T, P> const& v) | |
| 26 | : x(v.x), y(v.y) | |
| 27 | {} | |
| 28 | ||
| 29 | // -- Explicit basic constructors -- | |
| 30 | ||
| 31 | template<typename T, qualifier Q> | |
| 32 | ! | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q>::vec(T scalar) |
| 33 | ! | : x(scalar), y(scalar) |
| 34 | {} | |
| 35 | ||
| 36 | template<typename T, qualifier Q> | |
| 37 | 1346x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q>::vec(T _x, T _y) |
| 38 | 1346x | : x(_x), y(_y) |
| 39 | {} | |
| 40 | ||
| 41 | // -- Conversion scalar constructors -- | |
| 42 | ||
| 43 | template<typename T, qualifier Q> | |
| 44 | template<typename U, qualifier P> | |
| 45 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q>::vec(vec<1, U, P> const& v) | |
| 46 | : x(static_cast<T>(v.x)) | |
| 47 | , y(static_cast<T>(v.x)) | |
| 48 | {} | |
| 49 | ||
| 50 | template<typename T, qualifier Q> | |
| 51 | template<typename A, typename B> | |
| 52 | 161266x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q>::vec(A _x, B _y) |
| 53 | 161266x | : x(static_cast<T>(_x)) |
| 54 | 161266x | , y(static_cast<T>(_y)) |
| 55 | {} | |
| 56 | ||
| 57 | template<typename T, qualifier Q> | |
| 58 | template<typename A, typename B> | |
| 59 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q>::vec(vec<1, A, Q> const& _x, B _y) | |
| 60 | : x(static_cast<T>(_x.x)) | |
| 61 | , y(static_cast<T>(_y)) | |
| 62 | {} | |
| 63 | ||
| 64 | template<typename T, qualifier Q> | |
| 65 | template<typename A, typename B> | |
| 66 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q>::vec(A _x, vec<1, B, Q> const& _y) | |
| 67 | : x(static_cast<T>(_x)) | |
| 68 | , y(static_cast<T>(_y.x)) | |
| 69 | {} | |
| 70 | ||
| 71 | template<typename T, qualifier Q> | |
| 72 | template<typename A, typename B> | |
| 73 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q>::vec(vec<1, A, Q> const& _x, vec<1, B, Q> const& _y) | |
| 74 | : x(static_cast<T>(_x.x)) | |
| 75 | , y(static_cast<T>(_y.x)) | |
| 76 | {} | |
| 77 | ||
| 78 | // -- Conversion vector constructors -- | |
| 79 | ||
| 80 | template<typename T, qualifier Q> | |
| 81 | template<typename U, qualifier P> | |
| 82 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q>::vec(vec<2, U, P> const& v) | |
| 83 | : x(static_cast<T>(v.x)) | |
| 84 | , y(static_cast<T>(v.y)) | |
| 85 | {} | |
| 86 | ||
| 87 | template<typename T, qualifier Q> | |
| 88 | template<typename U, qualifier P> | |
| 89 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q>::vec(vec<3, U, P> const& v) | |
| 90 | : x(static_cast<T>(v.x)) | |
| 91 | , y(static_cast<T>(v.y)) | |
| 92 | {} | |
| 93 | ||
| 94 | template<typename T, qualifier Q> | |
| 95 | template<typename U, qualifier P> | |
| 96 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q>::vec(vec<4, U, P> const& v) | |
| 97 | : x(static_cast<T>(v.x)) | |
| 98 | , y(static_cast<T>(v.y)) | |
| 99 | {} | |
| 100 | ||
| 101 | // -- Component accesses -- | |
| 102 | ||
| 103 | template<typename T, qualifier Q> | |
| 104 | 392x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR T & vec<2, T, Q>::operator[](typename vec<2, T, Q>::length_type i) |
| 105 | { | |
| 106 | assert(i >= 0 && i < this->length()); | |
| 107 | 392x | switch(i) |
| 108 | { | |
| 109 | 196x | default: |
| 110 | case 0: | |
| 111 | 196x | return x; |
| 112 | 196x | case 1: |
| 113 | 196x | return y; |
| 114 | } | |
| 115 | } | |
| 116 | ||
| 117 | template<typename T, qualifier Q> | |
| 118 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR T const& vec<2, T, Q>::operator[](typename vec<2, T, Q>::length_type i) const | |
| 119 | { | |
| 120 | assert(i >= 0 && i < this->length()); | |
| 121 | switch(i) | |
| 122 | { | |
| 123 | default: | |
| 124 | case 0: | |
| 125 | return x; | |
| 126 | case 1: | |
| 127 | return y; | |
| 128 | } | |
| 129 | } | |
| 130 | ||
| 131 | // -- Unary arithmetic operators -- | |
| 132 | ||
| 133 | # if GLM_CONFIG_DEFAULTED_FUNCTIONS == GLM_DISABLE | |
| 134 | template<typename T, qualifier Q> | |
| 135 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator=(vec<2, T, Q> const& v) | |
| 136 | { | |
| 137 | this->x = v.x; | |
| 138 | this->y = v.y; | |
| 139 | return *this; | |
| 140 | } | |
| 141 | # endif | |
| 142 | ||
| 143 | template<typename T, qualifier Q> | |
| 144 | template<typename U> | |
| 145 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator=(vec<2, U, Q> const& v) | |
| 146 | { | |
| 147 | this->x = static_cast<T>(v.x); | |
| 148 | this->y = static_cast<T>(v.y); | |
| 149 | return *this; | |
| 150 | } | |
| 151 | ||
| 152 | template<typename T, qualifier Q> | |
| 153 | template<typename U> | |
| 154 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator+=(U scalar) | |
| 155 | { | |
| 156 | this->x += static_cast<T>(scalar); | |
| 157 | this->y += static_cast<T>(scalar); | |
| 158 | return *this; | |
| 159 | } | |
| 160 | ||
| 161 | template<typename T, qualifier Q> | |
| 162 | template<typename U> | |
| 163 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator+=(vec<1, U, Q> const& v) | |
| 164 | { | |
| 165 | this->x += static_cast<T>(v.x); | |
| 166 | this->y += static_cast<T>(v.x); | |
| 167 | return *this; | |
| 168 | } | |
| 169 | ||
| 170 | template<typename T, qualifier Q> | |
| 171 | template<typename U> | |
| 172 | 1026x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator+=(vec<2, U, Q> const& v) |
| 173 | { | |
| 174 | 1026x | this->x += static_cast<T>(v.x); |
| 175 | 1026x | this->y += static_cast<T>(v.y); |
| 176 | 1026x | return *this; |
| 177 | } | |
| 178 | ||
| 179 | template<typename T, qualifier Q> | |
| 180 | template<typename U> | |
| 181 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator-=(U scalar) | |
| 182 | { | |
| 183 | this->x -= static_cast<T>(scalar); | |
| 184 | this->y -= static_cast<T>(scalar); | |
| 185 | return *this; | |
| 186 | } | |
| 187 | ||
| 188 | template<typename T, qualifier Q> | |
| 189 | template<typename U> | |
| 190 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator-=(vec<1, U, Q> const& v) | |
| 191 | { | |
| 192 | this->x -= static_cast<T>(v.x); | |
| 193 | this->y -= static_cast<T>(v.x); | |
| 194 | return *this; | |
| 195 | } | |
| 196 | ||
| 197 | template<typename T, qualifier Q> | |
| 198 | template<typename U> | |
| 199 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator-=(vec<2, U, Q> const& v) | |
| 200 | { | |
| 201 | this->x -= static_cast<T>(v.x); | |
| 202 | this->y -= static_cast<T>(v.y); | |
| 203 | return *this; | |
| 204 | } | |
| 205 | ||
| 206 | template<typename T, qualifier Q> | |
| 207 | template<typename U> | |
| 208 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator*=(U scalar) | |
| 209 | { | |
| 210 | this->x *= static_cast<T>(scalar); | |
| 211 | this->y *= static_cast<T>(scalar); | |
| 212 | return *this; | |
| 213 | } | |
| 214 | ||
| 215 | template<typename T, qualifier Q> | |
| 216 | template<typename U> | |
| 217 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator*=(vec<1, U, Q> const& v) | |
| 218 | { | |
| 219 | this->x *= static_cast<T>(v.x); | |
| 220 | this->y *= static_cast<T>(v.x); | |
| 221 | return *this; | |
| 222 | } | |
| 223 | ||
| 224 | template<typename T, qualifier Q> | |
| 225 | template<typename U> | |
| 226 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator*=(vec<2, U, Q> const& v) | |
| 227 | { | |
| 228 | this->x *= static_cast<T>(v.x); | |
| 229 | this->y *= static_cast<T>(v.y); | |
| 230 | return *this; | |
| 231 | } | |
| 232 | ||
| 233 | template<typename T, qualifier Q> | |
| 234 | template<typename U> | |
| 235 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator/=(U scalar) | |
| 236 | { | |
| 237 | this->x /= static_cast<T>(scalar); | |
| 238 | this->y /= static_cast<T>(scalar); | |
| 239 | return *this; | |
| 240 | } | |
| 241 | ||
| 242 | template<typename T, qualifier Q> | |
| 243 | template<typename U> | |
| 244 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator/=(vec<1, U, Q> const& v) | |
| 245 | { | |
| 246 | this->x /= static_cast<T>(v.x); | |
| 247 | this->y /= static_cast<T>(v.x); | |
| 248 | return *this; | |
| 249 | } | |
| 250 | ||
| 251 | template<typename T, qualifier Q> | |
| 252 | template<typename U> | |
| 253 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator/=(vec<2, U, Q> const& v) | |
| 254 | { | |
| 255 | this->x /= static_cast<T>(v.x); | |
| 256 | this->y /= static_cast<T>(v.y); | |
| 257 | return *this; | |
| 258 | } | |
| 259 | ||
| 260 | // -- Increment and decrement operators -- | |
| 261 | ||
| 262 | template<typename T, qualifier Q> | |
| 263 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator++() | |
| 264 | { | |
| 265 | ++this->x; | |
| 266 | ++this->y; | |
| 267 | return *this; | |
| 268 | } | |
| 269 | ||
| 270 | template<typename T, qualifier Q> | |
| 271 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator--() | |
| 272 | { | |
| 273 | --this->x; | |
| 274 | --this->y; | |
| 275 | return *this; | |
| 276 | } | |
| 277 | ||
| 278 | template<typename T, qualifier Q> | |
| 279 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> vec<2, T, Q>::operator++(int) | |
| 280 | { | |
| 281 | vec<2, T, Q> Result(*this); | |
| 282 | ++*this; | |
| 283 | return Result; | |
| 284 | } | |
| 285 | ||
| 286 | template<typename T, qualifier Q> | |
| 287 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> vec<2, T, Q>::operator--(int) | |
| 288 | { | |
| 289 | vec<2, T, Q> Result(*this); | |
| 290 | --*this; | |
| 291 | return Result; | |
| 292 | } | |
| 293 | ||
| 294 | // -- Unary bit operators -- | |
| 295 | ||
| 296 | template<typename T, qualifier Q> | |
| 297 | template<typename U> | |
| 298 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator%=(U scalar) | |
| 299 | { | |
| 300 | this->x %= static_cast<T>(scalar); | |
| 301 | this->y %= static_cast<T>(scalar); | |
| 302 | return *this; | |
| 303 | } | |
| 304 | ||
| 305 | template<typename T, qualifier Q> | |
| 306 | template<typename U> | |
| 307 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator%=(vec<1, U, Q> const& v) | |
| 308 | { | |
| 309 | this->x %= static_cast<T>(v.x); | |
| 310 | this->y %= static_cast<T>(v.x); | |
| 311 | return *this; | |
| 312 | } | |
| 313 | ||
| 314 | template<typename T, qualifier Q> | |
| 315 | template<typename U> | |
| 316 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator%=(vec<2, U, Q> const& v) | |
| 317 | { | |
| 318 | this->x %= static_cast<T>(v.x); | |
| 319 | this->y %= static_cast<T>(v.y); | |
| 320 | return *this; | |
| 321 | } | |
| 322 | ||
| 323 | template<typename T, qualifier Q> | |
| 324 | template<typename U> | |
| 325 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator&=(U scalar) | |
| 326 | { | |
| 327 | this->x &= static_cast<T>(scalar); | |
| 328 | this->y &= static_cast<T>(scalar); | |
| 329 | return *this; | |
| 330 | } | |
| 331 | ||
| 332 | template<typename T, qualifier Q> | |
| 333 | template<typename U> | |
| 334 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator&=(vec<1, U, Q> const& v) | |
| 335 | { | |
| 336 | this->x &= static_cast<T>(v.x); | |
| 337 | this->y &= static_cast<T>(v.x); | |
| 338 | return *this; | |
| 339 | } | |
| 340 | ||
| 341 | template<typename T, qualifier Q> | |
| 342 | template<typename U> | |
| 343 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator&=(vec<2, U, Q> const& v) | |
| 344 | { | |
| 345 | this->x &= static_cast<T>(v.x); | |
| 346 | this->y &= static_cast<T>(v.y); | |
| 347 | return *this; | |
| 348 | } | |
| 349 | ||
| 350 | template<typename T, qualifier Q> | |
| 351 | template<typename U> | |
| 352 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator|=(U scalar) | |
| 353 | { | |
| 354 | this->x |= static_cast<T>(scalar); | |
| 355 | this->y |= static_cast<T>(scalar); | |
| 356 | return *this; | |
| 357 | } | |
| 358 | ||
| 359 | template<typename T, qualifier Q> | |
| 360 | template<typename U> | |
| 361 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator|=(vec<1, U, Q> const& v) | |
| 362 | { | |
| 363 | this->x |= static_cast<T>(v.x); | |
| 364 | this->y |= static_cast<T>(v.x); | |
| 365 | return *this; | |
| 366 | } | |
| 367 | ||
| 368 | template<typename T, qualifier Q> | |
| 369 | template<typename U> | |
| 370 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator|=(vec<2, U, Q> const& v) | |
| 371 | { | |
| 372 | this->x |= static_cast<T>(v.x); | |
| 373 | this->y |= static_cast<T>(v.y); | |
| 374 | return *this; | |
| 375 | } | |
| 376 | ||
| 377 | template<typename T, qualifier Q> | |
| 378 | template<typename U> | |
| 379 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator^=(U scalar) | |
| 380 | { | |
| 381 | this->x ^= static_cast<T>(scalar); | |
| 382 | this->y ^= static_cast<T>(scalar); | |
| 383 | return *this; | |
| 384 | } | |
| 385 | ||
| 386 | template<typename T, qualifier Q> | |
| 387 | template<typename U> | |
| 388 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator^=(vec<1, U, Q> const& v) | |
| 389 | { | |
| 390 | this->x ^= static_cast<T>(v.x); | |
| 391 | this->y ^= static_cast<T>(v.x); | |
| 392 | return *this; | |
| 393 | } | |
| 394 | ||
| 395 | template<typename T, qualifier Q> | |
| 396 | template<typename U> | |
| 397 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator^=(vec<2, U, Q> const& v) | |
| 398 | { | |
| 399 | this->x ^= static_cast<T>(v.x); | |
| 400 | this->y ^= static_cast<T>(v.y); | |
| 401 | return *this; | |
| 402 | } | |
| 403 | ||
| 404 | template<typename T, qualifier Q> | |
| 405 | template<typename U> | |
| 406 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator<<=(U scalar) | |
| 407 | { | |
| 408 | this->x <<= static_cast<T>(scalar); | |
| 409 | this->y <<= static_cast<T>(scalar); | |
| 410 | return *this; | |
| 411 | } | |
| 412 | ||
| 413 | template<typename T, qualifier Q> | |
| 414 | template<typename U> | |
| 415 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator<<=(vec<1, U, Q> const& v) | |
| 416 | { | |
| 417 | this->x <<= static_cast<T>(v.x); | |
| 418 | this->y <<= static_cast<T>(v.x); | |
| 419 | return *this; | |
| 420 | } | |
| 421 | ||
| 422 | template<typename T, qualifier Q> | |
| 423 | template<typename U> | |
| 424 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator<<=(vec<2, U, Q> const& v) | |
| 425 | { | |
| 426 | this->x <<= static_cast<T>(v.x); | |
| 427 | this->y <<= static_cast<T>(v.y); | |
| 428 | return *this; | |
| 429 | } | |
| 430 | ||
| 431 | template<typename T, qualifier Q> | |
| 432 | template<typename U> | |
| 433 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator>>=(U scalar) | |
| 434 | { | |
| 435 | this->x >>= static_cast<T>(scalar); | |
| 436 | this->y >>= static_cast<T>(scalar); | |
| 437 | return *this; | |
| 438 | } | |
| 439 | ||
| 440 | template<typename T, qualifier Q> | |
| 441 | template<typename U> | |
| 442 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator>>=(vec<1, U, Q> const& v) | |
| 443 | { | |
| 444 | this->x >>= static_cast<T>(v.x); | |
| 445 | this->y >>= static_cast<T>(v.x); | |
| 446 | return *this; | |
| 447 | } | |
| 448 | ||
| 449 | template<typename T, qualifier Q> | |
| 450 | template<typename U> | |
| 451 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> & vec<2, T, Q>::operator>>=(vec<2, U, Q> const& v) | |
| 452 | { | |
| 453 | this->x >>= static_cast<T>(v.x); | |
| 454 | this->y >>= static_cast<T>(v.y); | |
| 455 | return *this; | |
| 456 | } | |
| 457 | ||
| 458 | // -- Unary arithmetic operators -- | |
| 459 | ||
| 460 | template<typename T, qualifier Q> | |
| 461 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator+(vec<2, T, Q> const& v) | |
| 462 | { | |
| 463 | return v; | |
| 464 | } | |
| 465 | ||
| 466 | template<typename T, qualifier Q> | |
| 467 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator-(vec<2, T, Q> const& v) | |
| 468 | { | |
| 469 | return vec<2, T, Q>( | |
| 470 | -v.x, | |
| 471 | -v.y); | |
| 472 | } | |
| 473 | ||
| 474 | // -- Binary arithmetic operators -- | |
| 475 | ||
| 476 | template<typename T, qualifier Q> | |
| 477 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator+(vec<2, T, Q> const& v, T scalar) | |
| 478 | { | |
| 479 | return vec<2, T, Q>( | |
| 480 | v.x + scalar, | |
| 481 | v.y + scalar); | |
| 482 | } | |
| 483 | ||
| 484 | template<typename T, qualifier Q> | |
| 485 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator+(vec<2, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 486 | { | |
| 487 | return vec<2, T, Q>( | |
| 488 | v1.x + v2.x, | |
| 489 | v1.y + v2.x); | |
| 490 | } | |
| 491 | ||
| 492 | template<typename T, qualifier Q> | |
| 493 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator+(T scalar, vec<2, T, Q> const& v) | |
| 494 | { | |
| 495 | return vec<2, T, Q>( | |
| 496 | scalar + v.x, | |
| 497 | scalar + v.y); | |
| 498 | } | |
| 499 | ||
| 500 | template<typename T, qualifier Q> | |
| 501 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator+(vec<1, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 502 | { | |
| 503 | return vec<2, T, Q>( | |
| 504 | v1.x + v2.x, | |
| 505 | v1.x + v2.y); | |
| 506 | } | |
| 507 | ||
| 508 | template<typename T, qualifier Q> | |
| 509 | ! | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator+(vec<2, T, Q> const& v1, vec<2, T, Q> const& v2) |
| 510 | { | |
| 511 | ! | return vec<2, T, Q>( |
| 512 | ! | v1.x + v2.x, |
| 513 | ! | v1.y + v2.y); |
| 514 | } | |
| 515 | ||
| 516 | template<typename T, qualifier Q> | |
| 517 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator-(vec<2, T, Q> const& v, T scalar) | |
| 518 | { | |
| 519 | return vec<2, T, Q>( | |
| 520 | v.x - scalar, | |
| 521 | v.y - scalar); | |
| 522 | } | |
| 523 | ||
| 524 | template<typename T, qualifier Q> | |
| 525 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator-(vec<2, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 526 | { | |
| 527 | return vec<2, T, Q>( | |
| 528 | v1.x - v2.x, | |
| 529 | v1.y - v2.x); | |
| 530 | } | |
| 531 | ||
| 532 | template<typename T, qualifier Q> | |
| 533 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator-(T scalar, vec<2, T, Q> const& v) | |
| 534 | { | |
| 535 | return vec<2, T, Q>( | |
| 536 | scalar - v.x, | |
| 537 | scalar - v.y); | |
| 538 | } | |
| 539 | ||
| 540 | template<typename T, qualifier Q> | |
| 541 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator-(vec<1, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 542 | { | |
| 543 | return vec<2, T, Q>( | |
| 544 | v1.x - v2.x, | |
| 545 | v1.x - v2.y); | |
| 546 | } | |
| 547 | ||
| 548 | template<typename T, qualifier Q> | |
| 549 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator-(vec<2, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 550 | { | |
| 551 | return vec<2, T, Q>( | |
| 552 | v1.x - v2.x, | |
| 553 | v1.y - v2.y); | |
| 554 | } | |
| 555 | ||
| 556 | template<typename T, qualifier Q> | |
| 557 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator*(vec<2, T, Q> const& v, T scalar) | |
| 558 | { | |
| 559 | return vec<2, T, Q>( | |
| 560 | v.x * scalar, | |
| 561 | v.y * scalar); | |
| 562 | } | |
| 563 | ||
| 564 | template<typename T, qualifier Q> | |
| 565 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator*(vec<2, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 566 | { | |
| 567 | return vec<2, T, Q>( | |
| 568 | v1.x * v2.x, | |
| 569 | v1.y * v2.x); | |
| 570 | } | |
| 571 | ||
| 572 | template<typename T, qualifier Q> | |
| 573 | 1248x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator*(T scalar, vec<2, T, Q> const& v) |
| 574 | { | |
| 575 | 2496x | return vec<2, T, Q>( |
| 576 | 1248x | scalar * v.x, |
| 577 | 1248x | scalar * v.y); |
| 578 | } | |
| 579 | ||
| 580 | template<typename T, qualifier Q> | |
| 581 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator*(vec<1, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 582 | { | |
| 583 | return vec<2, T, Q>( | |
| 584 | v1.x * v2.x, | |
| 585 | v1.x * v2.y); | |
| 586 | } | |
| 587 | ||
| 588 | template<typename T, qualifier Q> | |
| 589 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator*(vec<2, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 590 | { | |
| 591 | return vec<2, T, Q>( | |
| 592 | v1.x * v2.x, | |
| 593 | v1.y * v2.y); | |
| 594 | } | |
| 595 | ||
| 596 | template<typename T, qualifier Q> | |
| 597 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator/(vec<2, T, Q> const& v, T scalar) | |
| 598 | { | |
| 599 | return vec<2, T, Q>( | |
| 600 | v.x / scalar, | |
| 601 | v.y / scalar); | |
| 602 | } | |
| 603 | ||
| 604 | template<typename T, qualifier Q> | |
| 605 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator/(vec<2, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 606 | { | |
| 607 | return vec<2, T, Q>( | |
| 608 | v1.x / v2.x, | |
| 609 | v1.y / v2.x); | |
| 610 | } | |
| 611 | ||
| 612 | template<typename T, qualifier Q> | |
| 613 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator/(T scalar, vec<2, T, Q> const& v) | |
| 614 | { | |
| 615 | return vec<2, T, Q>( | |
| 616 | scalar / v.x, | |
| 617 | scalar / v.y); | |
| 618 | } | |
| 619 | ||
| 620 | template<typename T, qualifier Q> | |
| 621 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator/(vec<1, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 622 | { | |
| 623 | return vec<2, T, Q>( | |
| 624 | v1.x / v2.x, | |
| 625 | v1.x / v2.y); | |
| 626 | } | |
| 627 | ||
| 628 | template<typename T, qualifier Q> | |
| 629 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator/(vec<2, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 630 | { | |
| 631 | return vec<2, T, Q>( | |
| 632 | v1.x / v2.x, | |
| 633 | v1.y / v2.y); | |
| 634 | } | |
| 635 | ||
| 636 | // -- Binary bit operators -- | |
| 637 | ||
| 638 | template<typename T, qualifier Q> | |
| 639 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator%(vec<2, T, Q> const& v, T scalar) | |
| 640 | { | |
| 641 | return vec<2, T, Q>( | |
| 642 | v.x % scalar, | |
| 643 | v.y % scalar); | |
| 644 | } | |
| 645 | ||
| 646 | template<typename T, qualifier Q> | |
| 647 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator%(vec<2, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 648 | { | |
| 649 | return vec<2, T, Q>( | |
| 650 | v1.x % v2.x, | |
| 651 | v1.y % v2.x); | |
| 652 | } | |
| 653 | ||
| 654 | template<typename T, qualifier Q> | |
| 655 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator%(T scalar, vec<2, T, Q> const& v) | |
| 656 | { | |
| 657 | return vec<2, T, Q>( | |
| 658 | scalar % v.x, | |
| 659 | scalar % v.y); | |
| 660 | } | |
| 661 | ||
| 662 | template<typename T, qualifier Q> | |
| 663 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator%(vec<1, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 664 | { | |
| 665 | return vec<2, T, Q>( | |
| 666 | v1.x % v2.x, | |
| 667 | v1.x % v2.y); | |
| 668 | } | |
| 669 | ||
| 670 | template<typename T, qualifier Q> | |
| 671 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator%(vec<2, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 672 | { | |
| 673 | return vec<2, T, Q>( | |
| 674 | v1.x % v2.x, | |
| 675 | v1.y % v2.y); | |
| 676 | } | |
| 677 | ||
| 678 | template<typename T, qualifier Q> | |
| 679 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator&(vec<2, T, Q> const& v, T scalar) | |
| 680 | { | |
| 681 | return vec<2, T, Q>( | |
| 682 | v.x & scalar, | |
| 683 | v.y & scalar); | |
| 684 | } | |
| 685 | ||
| 686 | template<typename T, qualifier Q> | |
| 687 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator&(vec<2, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 688 | { | |
| 689 | return vec<2, T, Q>( | |
| 690 | v1.x & v2.x, | |
| 691 | v1.y & v2.x); | |
| 692 | } | |
| 693 | ||
| 694 | template<typename T, qualifier Q> | |
| 695 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator&(T scalar, vec<2, T, Q> const& v) | |
| 696 | { | |
| 697 | return vec<2, T, Q>( | |
| 698 | scalar & v.x, | |
| 699 | scalar & v.y); | |
| 700 | } | |
| 701 | ||
| 702 | template<typename T, qualifier Q> | |
| 703 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator&(vec<1, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 704 | { | |
| 705 | return vec<2, T, Q>( | |
| 706 | v1.x & v2.x, | |
| 707 | v1.x & v2.y); | |
| 708 | } | |
| 709 | ||
| 710 | template<typename T, qualifier Q> | |
| 711 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator&(vec<2, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 712 | { | |
| 713 | return vec<2, T, Q>( | |
| 714 | v1.x & v2.x, | |
| 715 | v1.y & v2.y); | |
| 716 | } | |
| 717 | ||
| 718 | template<typename T, qualifier Q> | |
| 719 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator|(vec<2, T, Q> const& v, T scalar) | |
| 720 | { | |
| 721 | return vec<2, T, Q>( | |
| 722 | v.x | scalar, | |
| 723 | v.y | scalar); | |
| 724 | } | |
| 725 | ||
| 726 | template<typename T, qualifier Q> | |
| 727 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator|(vec<2, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 728 | { | |
| 729 | return vec<2, T, Q>( | |
| 730 | v1.x | v2.x, | |
| 731 | v1.y | v2.x); | |
| 732 | } | |
| 733 | ||
| 734 | template<typename T, qualifier Q> | |
| 735 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator|(T scalar, vec<2, T, Q> const& v) | |
| 736 | { | |
| 737 | return vec<2, T, Q>( | |
| 738 | scalar | v.x, | |
| 739 | scalar | v.y); | |
| 740 | } | |
| 741 | ||
| 742 | template<typename T, qualifier Q> | |
| 743 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator|(vec<1, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 744 | { | |
| 745 | return vec<2, T, Q>( | |
| 746 | v1.x | v2.x, | |
| 747 | v1.x | v2.y); | |
| 748 | } | |
| 749 | ||
| 750 | template<typename T, qualifier Q> | |
| 751 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator|(vec<2, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 752 | { | |
| 753 | return vec<2, T, Q>( | |
| 754 | v1.x | v2.x, | |
| 755 | v1.y | v2.y); | |
| 756 | } | |
| 757 | ||
| 758 | template<typename T, qualifier Q> | |
| 759 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator^(vec<2, T, Q> const& v, T scalar) | |
| 760 | { | |
| 761 | return vec<2, T, Q>( | |
| 762 | v.x ^ scalar, | |
| 763 | v.y ^ scalar); | |
| 764 | } | |
| 765 | ||
| 766 | template<typename T, qualifier Q> | |
| 767 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator^(vec<2, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 768 | { | |
| 769 | return vec<2, T, Q>( | |
| 770 | v1.x ^ v2.x, | |
| 771 | v1.y ^ v2.x); | |
| 772 | } | |
| 773 | ||
| 774 | template<typename T, qualifier Q> | |
| 775 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator^(T scalar, vec<2, T, Q> const& v) | |
| 776 | { | |
| 777 | return vec<2, T, Q>( | |
| 778 | scalar ^ v.x, | |
| 779 | scalar ^ v.y); | |
| 780 | } | |
| 781 | ||
| 782 | template<typename T, qualifier Q> | |
| 783 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator^(vec<1, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 784 | { | |
| 785 | return vec<2, T, Q>( | |
| 786 | v1.x ^ v2.x, | |
| 787 | v1.x ^ v2.y); | |
| 788 | } | |
| 789 | ||
| 790 | template<typename T, qualifier Q> | |
| 791 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator^(vec<2, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 792 | { | |
| 793 | return vec<2, T, Q>( | |
| 794 | v1.x ^ v2.x, | |
| 795 | v1.y ^ v2.y); | |
| 796 | } | |
| 797 | ||
| 798 | template<typename T, qualifier Q> | |
| 799 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator<<(vec<2, T, Q> const& v, T scalar) | |
| 800 | { | |
| 801 | return vec<2, T, Q>( | |
| 802 | v.x << scalar, | |
| 803 | v.y << scalar); | |
| 804 | } | |
| 805 | ||
| 806 | template<typename T, qualifier Q> | |
| 807 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator<<(vec<2, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 808 | { | |
| 809 | return vec<2, T, Q>( | |
| 810 | v1.x << v2.x, | |
| 811 | v1.y << v2.x); | |
| 812 | } | |
| 813 | ||
| 814 | template<typename T, qualifier Q> | |
| 815 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator<<(T scalar, vec<2, T, Q> const& v) | |
| 816 | { | |
| 817 | return vec<2, T, Q>( | |
| 818 | scalar << v.x, | |
| 819 | scalar << v.y); | |
| 820 | } | |
| 821 | ||
| 822 | template<typename T, qualifier Q> | |
| 823 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator<<(vec<1, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 824 | { | |
| 825 | return vec<2, T, Q>( | |
| 826 | v1.x << v2.x, | |
| 827 | v1.x << v2.y); | |
| 828 | } | |
| 829 | ||
| 830 | template<typename T, qualifier Q> | |
| 831 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator<<(vec<2, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 832 | { | |
| 833 | return vec<2, T, Q>( | |
| 834 | v1.x << v2.x, | |
| 835 | v1.y << v2.y); | |
| 836 | } | |
| 837 | ||
| 838 | template<typename T, qualifier Q> | |
| 839 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator>>(vec<2, T, Q> const& v, T scalar) | |
| 840 | { | |
| 841 | return vec<2, T, Q>( | |
| 842 | v.x >> scalar, | |
| 843 | v.y >> scalar); | |
| 844 | } | |
| 845 | ||
| 846 | template<typename T, qualifier Q> | |
| 847 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator>>(vec<2, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 848 | { | |
| 849 | return vec<2, T, Q>( | |
| 850 | v1.x >> v2.x, | |
| 851 | v1.y >> v2.x); | |
| 852 | } | |
| 853 | ||
| 854 | template<typename T, qualifier Q> | |
| 855 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator>>(T scalar, vec<2, T, Q> const& v) | |
| 856 | { | |
| 857 | return vec<2, T, Q>( | |
| 858 | scalar >> v.x, | |
| 859 | scalar >> v.y); | |
| 860 | } | |
| 861 | ||
| 862 | template<typename T, qualifier Q> | |
| 863 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator>>(vec<1, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 864 | { | |
| 865 | return vec<2, T, Q>( | |
| 866 | v1.x >> v2.x, | |
| 867 | v1.x >> v2.y); | |
| 868 | } | |
| 869 | ||
| 870 | template<typename T, qualifier Q> | |
| 871 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator>>(vec<2, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 872 | { | |
| 873 | return vec<2, T, Q>( | |
| 874 | v1.x >> v2.x, | |
| 875 | v1.y >> v2.y); | |
| 876 | } | |
| 877 | ||
| 878 | template<typename T, qualifier Q> | |
| 879 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, T, Q> operator~(vec<2, T, Q> const& v) | |
| 880 | { | |
| 881 | return vec<2, T, Q>( | |
| 882 | ~v.x, | |
| 883 | ~v.y); | |
| 884 | } | |
| 885 | ||
| 886 | // -- Boolean operators -- | |
| 887 | ||
| 888 | template<typename T, qualifier Q> | |
| 889 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR bool operator==(vec<2, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 890 | { | |
| 891 | return | |
| 892 | detail::compute_equal<T, std::numeric_limits<T>::is_iec559>::call(v1.x, v2.x) && | |
| 893 | detail::compute_equal<T, std::numeric_limits<T>::is_iec559>::call(v1.y, v2.y); | |
| 894 | } | |
| 895 | ||
| 896 | template<typename T, qualifier Q> | |
| 897 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR bool operator!=(vec<2, T, Q> const& v1, vec<2, T, Q> const& v2) | |
| 898 | { | |
| 899 | return !(v1 == v2); | |
| 900 | } | |
| 901 | ||
| 902 | template<qualifier Q> | |
| 903 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, bool, Q> operator&&(vec<2, bool, Q> const& v1, vec<2, bool, Q> const& v2) | |
| 904 | { | |
| 905 | return vec<2, bool, Q>(v1.x && v2.x, v1.y && v2.y); | |
| 906 | } | |
| 907 | ||
| 908 | template<qualifier Q> | |
| 909 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<2, bool, Q> operator||(vec<2, bool, Q> const& v1, vec<2, bool, Q> const& v2) | |
| 910 | { | |
| 911 | return vec<2, bool, Q>(v1.x || v2.x, v1.y || v2.y); | |
| 912 | } | |
| 913 | }//namespace glm |
| 1 | #include "displacement.h" | |
| 2 | #ifndef STBIMAGEH | |
| 3 | #define STBIMAGEH | |
| 4 | #include "stbimageheaders/stb_image.h" | |
| 5 | #endif | |
| 6 | // #include "assert.h" | |
| 7 | // #include "trianglemesh.h" | |
| 8 | // #include "texturecache.h" | |
| 9 | #include "Rcpp.h" | |
| 10 | using namespace Rcpp; | |
| 11 | #include "defines.h" | |
| 12 | #include "assert.h" | |
| 13 | ||
| 14 | ! | inline bool any_is_nan(const vec3& c) { |
| 15 | ! | return(std::isnan(c[0]) || std::isnan(c[1]) || std::isnan(c[2])); |
| 16 | } | |
| 17 | ||
| 18 | // [[Rcpp::export]] | |
| 19 | 1x | NumericMatrix DisplaceMesh(Rcpp::List raymesh, |
| 20 | NumericMatrix displacement_texture, | |
| 21 | NumericMatrix displacement_texture_y, | |
| 22 | NumericMatrix displacement_texture_z, | |
| 23 | NumericMatrix tangents, | |
| 24 | LogicalVector tangent_right_handed, | |
| 25 | double displacement_scale, | |
| 26 | bool displacement_vector, | |
| 27 | int shape_id) { | |
| 28 | 2x | NumericMatrix texcoords = as<NumericMatrix>(as<List>(raymesh["texcoords"])(shape_id)); |
| 29 | 2x | NumericMatrix normals = as<NumericMatrix>(as<List>(raymesh["normals"])(shape_id)); |
| 30 | 2x | NumericMatrix vertices = as<NumericMatrix>(as<List>(raymesh["vertices"])(shape_id)); |
| 31 | 1x | std::vector<vec3> p(vertices.nrow()); |
| 32 | 99x | for(int i = 0; i < vertices.nrow(); i++) { |
| 33 | 98x | p[i] = vec3(vertices(i,0),vertices(i,1),vertices(i,2)); |
| 34 | } | |
| 35 | 1x | bool has_tex = texcoords.nrow() > 0; |
| 36 | 1x | size_t nNormals = normals.nrow(); |
| 37 | 1x | size_t nTex = texcoords.nrow(); |
| 38 | 1x | size_t nVertices = vertices.nrow(); |
| 39 | ||
| 40 | 1x | if(!has_tex) { |
| 41 | ! | throw std::runtime_error("Texcoords required for displacement mapping: no texcoords on mesh."); |
| 42 | } | |
| 43 | 1x | if(nNormals != nVertices || |
| 44 | nNormals != nTex ) { | |
| 45 | ! | throw std::runtime_error("Number of normals (" + std::to_string(nNormals) + |
| 46 | ! | ") and UV coords (" + std::to_string(nTex) + |
| 47 | ! | ") in mesh must be exactly equal to number of vertices (" + |
| 48 | ! | std::to_string(nVertices) + |
| 49 | ! | ")for displacement mapping."); |
| 50 | } | |
| 51 | 1x | int nx = displacement_texture.nrow()-1; |
| 52 | 1x | int ny = displacement_texture.ncol()-1; |
| 53 | ||
| 54 | 1x | if(!displacement_vector) { |
| 55 | 99x | for(size_t i = 0; i < nVertices; i++) { |
| 56 | 98x | vec2 uv = vec2(texcoords(i,0),texcoords(i,1)); |
| 57 | 98x | int ii = uv[0] * (double)nx; |
| 58 | 98x | int jj = (1-uv[1]) * (double)ny; |
| 59 | ||
| 60 | 98x | if (ii < 0) ii = 0; |
| 61 | 98x | if (jj < 0) jj = 0; |
| 62 | 98x | if (ii > nx) ii = nx; |
| 63 | 98x | if (jj > ny) jj = ny; |
| 64 | ||
| 65 | 98x | double disp = displacement_texture(ii, jj); |
| 66 | ||
| 67 | 98x | vec3 displace_n = displacement_scale * glm::normalize(vec3(normals(i,0), |
| 68 | ! | normals(i,1), |
| 69 | 196x | normals(i,2))) * disp; |
| 70 | 98x | p[i] += displace_n; |
| 71 | } | |
| 72 | } else { | |
| 73 | ASSERT(nVertices == nTex); | |
| 74 | ASSERT(nVertices == tangent_right_handed.size()); | |
| 75 | ||
| 76 | ! | for(size_t i = 0; i < nVertices; i++) { |
| 77 | ! | vec2 uv = vec2(texcoords(i,0),texcoords(i,1)); |
| 78 | ! | int ii = uv[0] * (double)nx; |
| 79 | ! | int jj = (1-uv[1]) * (double)ny; |
| 80 | ||
| 81 | ! | if (ii < 0) ii = 0; |
| 82 | ! | if (jj < 0) jj = 0; |
| 83 | ! | if (ii > nx) ii = nx; |
| 84 | ! | if (jj > ny) jj = ny; |
| 85 | ! | double disp_x = displacement_texture(ii, jj); |
| 86 | ! | double disp_y = displacement_texture_y(ii, jj); |
| 87 | ! | double disp_z = displacement_texture_z(ii, jj); |
| 88 | ||
| 89 | ! | vec3 disp = normalize(vec3(disp_x,disp_y,disp_z)); |
| 90 | ! | vec3 tangent = normalize(vec3(tangents(i,0),tangents(i,1),tangents(i,2))); |
| 91 | ! | if(any_is_nan(tangent)) { |
| 92 | ! | continue; |
| 93 | } | |
| 94 | ! | vec3 n = normalize(vec3(normals(i,0),normals(i,0),normals(i,0))); |
| 95 | ! | vec3 bitangent = tangent_right_handed[i] ? -cross(n, tangent) : cross(n, tangent); |
| 96 | ||
| 97 | ! | vec3 displace_n = displacement_scale * (tangent * disp[0] + bitangent * disp[1] + n * disp[2]); |
| 98 | ! | if(any_is_nan(displace_n)) { |
| 99 | ! | continue; |
| 100 | } | |
| 101 | ! | p[i] += displace_n; |
| 102 | } | |
| 103 | } | |
| 104 | 1x | NumericMatrix new_vertices(vertices.nrow(),3); |
| 105 | 99x | for(int i = 0; i < vertices.nrow(); i++) { |
| 106 | 98x | new_vertices(i,0) = p[i][0]; |
| 107 | 98x | new_vertices(i,1) = p[i][1]; |
| 108 | 98x | new_vertices(i,2) = p[i][2]; |
| 109 | } | |
| 110 | 1x | return(new_vertices); |
| 111 | } |
| 1 | #include "filltri.h" | |
| 2 | ||
| 3 | ! | inline Float DifferenceOfProducts(Float a, Float b, Float c, Float d) { |
| 4 | ! | Float cd = c * d; |
| 5 | ! | Float err = std::fma(-c, d, cd); |
| 6 | ! | Float dop = std::fma(a, b, -cd); |
| 7 | ! | return(dop + err); |
| 8 | } | |
| 9 | ||
| 10 | 799398x | inline Float edgeFunction(const vec3 &a, const vec3 &b, const vec3 &c) { |
| 11 | 799398x | return(DifferenceOfProducts((c.x - a.x),(b.y - a.y),(c.y - a.y),(b.x - a.x))); |
| 12 | } | |
| 13 | ||
| 14 | 80512x | void fill_tri_blocks(std::vector<std::vector<int> >& block_faces, |
| 15 | std::vector<std::vector<std::vector<vec4> > >& ndc_verts, | |
| 16 | std::vector<std::vector<std::vector<Float> > >& ndc_inv_w, | |
| 17 | vec2 min_block_bound, | |
| 18 | vec2 max_block_bound, | |
| 19 | std::vector<IShader*> shaders, | |
| 20 | Rcpp::NumericMatrix &zbuffer, | |
| 21 | rayimage& image, | |
| 22 | rayimage& normal_buffer, | |
| 23 | rayimage& position_buffer, | |
| 24 | rayimage& uv_buffer, | |
| 25 | std::vector<ModelInfo> &models, | |
| 26 | bool depth, | |
| 27 | std::vector<std::map<Float, alpha_info> >& alpha_depths, | |
| 28 | Rcpp::IntegerMatrix* material_id_buffer) { | |
| 29 | 80512x | unsigned int ny = image.height(); |
| 30 | 80512x | bool write_material_ids = (!depth && material_id_buffer != nullptr); |
| 31 | ||
| 32 | 161024x | for(unsigned int model_num = 0; model_num < models.size(); model_num++ ) { |
| 33 | 80512x | ModelInfo &shp = models[model_num]; |
| 34 | 450364x | for(unsigned int entry=0; entry < block_faces[model_num].size(); entry++) { |
| 35 | 369852x | int face = block_faces[model_num][entry]; |
| 36 | 369852x | int global_face = shp.index_offset + face; |
| 37 | ||
| 38 | 369852x | vec3 v1 = ndc_verts[model_num][0][face] * ndc_inv_w[model_num][0][face]; |
| 39 | 369852x | vec3 v2 = ndc_verts[model_num][1][face] * ndc_inv_w[model_num][1][face]; |
| 40 | 369852x | vec3 v3 = ndc_verts[model_num][2][face] * ndc_inv_w[model_num][2][face]; |
| 41 | ||
| 42 | 369852x | Float v1_ndc_inv_w = ndc_inv_w[model_num][0][face]; |
| 43 | 369852x | Float v2_ndc_inv_w = ndc_inv_w[model_num][1][face]; |
| 44 | 369852x | Float v3_ndc_inv_w = ndc_inv_w[model_num][2][face]; |
| 45 | ||
| 46 | 369852x | int mat_num = shp.materials[face] >= 0 && shp.materials[face] < (int)shaders.size() ? |
| 47 | 369852x | shp.materials[face] : (int)shaders.size()-1; |
| 48 | ||
| 49 | 369852x | int culling = shaders[mat_num]->get_culling(); |
| 50 | ||
| 51 | 369852x | bool not_culled = culling == 1 ? cross(v2-v1, v3-v2).z > 0 : |
| 52 | 369852x | culling == 2 ? cross(v2-v1, v3-v2).z < 0 : true; |
| 53 | 369852x | not_culled = !depth ? not_culled : true; |
| 54 | ||
| 55 | 369852x | if(not_culled) { |
| 56 | vec3 bound_min = vec3(fmin(v1.x,fmin(v2.x,v3.x)), | |
| 57 | fmin(v1.y,fmin(v2.y,v3.y)), | |
| 58 | 199974x | fmin(v1.z,fmin(v2.z,v3.z))); |
| 59 | vec3 bound_max = vec3(fmax(v1.x,fmax(v2.x,v3.x)), | |
| 60 | fmax(v1.y,fmax(v2.y,v3.y)), | |
| 61 | 199974x | fmax(v1.z,fmax(v2.z,v3.z))); |
| 62 | ||
| 63 | // NOTE: if your original code had different clamp logic, keep that. | |
| 64 | 199974x | unsigned int xmin = std::min(std::max((int)floor(bound_min.x), |
| 65 | 399948x | (int)min_block_bound.x ), |
| 66 | 199974x | (int)max_block_bound.x); |
| 67 | 199974x | unsigned int xmax = std::max(std::min((int)ceil(bound_max.x), |
| 68 | 399948x | (int)max_block_bound.x), |
| 69 | 199974x | (int)min_block_bound.x); |
| 70 | 199974x | unsigned int ymin = std::min(std::max((int)floor(bound_min.y), |
| 71 | 399948x | (int)min_block_bound.y), |
| 72 | 199974x | (int)max_block_bound.y); |
| 73 | 199974x | unsigned int ymax = std::max(std::min((int)ceil(bound_max.y), |
| 74 | 399948x | (int)max_block_bound.y ), |
| 75 | 199974x | (int)min_block_bound.y); |
| 76 | ||
| 77 | 199974x | Float area = edgeFunction(v3, v2, v1); |
| 78 | 199974x | if(area == 0.0f) { |
| 79 | 166x | continue; |
| 80 | } | |
| 81 | 199808x | Float inv_area = 1.0f/area; |
| 82 | ||
| 83 | vec4 color; | |
| 84 | vec3 position; | |
| 85 | vec3 normal; | |
| 86 | ||
| 87 | 199808x | Float p_step_32 = -(v2.x-v3.x); |
| 88 | 199808x | Float p_step_13 = -(v3.x-v1.x); |
| 89 | 199808x | Float p_step_21 = -(v1.x-v2.x); |
| 90 | ||
| 91 | 199808x | Float pi_step_32 = (v2.y-v3.y); |
| 92 | 199808x | Float pi_step_13 = (v3.y-v1.y); |
| 93 | 199808x | Float pi_step_21 = (v1.y-v2.y); |
| 94 | ||
| 95 | 199808x | vec3 p = vec3((Float)xmin + 0.5f, (Float)ymin + 0.5f, 0.0f); |
| 96 | ||
| 97 | 199808x | Float w1_init = edgeFunction(v3, v2, p); |
| 98 | 199808x | Float w2_init = edgeFunction(v1, v3, p); |
| 99 | 199808x | Float w3_init = edgeFunction(v2, v1, p); |
| 100 | ||
| 101 | //This updates w1_p and w1 from their base value--repeated addition results in | |
| 102 | //tearing of polygons due to loss of precision. | |
| 103 | 966454x | for (uint32_t i = xmin; i < xmax; i++) { |
| 104 | 766646x | Float w1_p = w1_init + (i-xmin) * pi_step_32; |
| 105 | 766646x | Float w2_p = w2_init + (i-xmin) * pi_step_13; |
| 106 | 766646x | Float w3_p = w3_init + (i-xmin) * pi_step_21; |
| 107 | 3716645x | for (uint32_t j = ymin; j < ymax; j++) { |
| 108 | 2949999x | Float w1 = w1_p + (j-ymin) * p_step_32; |
| 109 | 2949999x | Float w2 = w2_p + (j-ymin) * p_step_13; |
| 110 | 2949999x | Float w3 = w3_p + (j-ymin) * p_step_21; |
| 111 | ||
| 112 | 2949999x | bool inside = culling == 1 ? (w1 >= 0 && w2 >= 0 && w3 >= 0) : |
| 113 | ! | culling == 2 ? (w1 <= 0 && w2 <= 0 && w3 <= 0) : |
| 114 | ! | ((w1 >= 0 && w2 >= 0 && w3 >= 0) || |
| 115 | ! | (w1 <= 0 && w2 <= 0 && w3 <= 0)); |
| 116 | 2949999x | if (inside) { |
| 117 | 833053x | vec3 bc = vec3(w1, w2, w3)*inv_area; |
| 118 | 833053x | vec3 bc_clip = vec3(bc.x*v1_ndc_inv_w, |
| 119 | 833053x | bc.y*v2_ndc_inv_w, |
| 120 | 833053x | bc.z*v3_ndc_inv_w); |
| 121 | 833053x | bc_clip /= (bc_clip.x + bc_clip.y + bc_clip.z); |
| 122 | ||
| 123 | //Using bc_clip results in wrong zbuffer values here--bug? | |
| 124 | // Float z = v1.z * bc_clip.x + v2.z * bc_clip.y + v3.z * bc_clip.z; | |
| 125 | 833053x | Float z = v1.z * bc.x + v2.z * bc.y + v3.z * bc.z; |
| 126 | 833053x | if(z > zbuffer(i,j)) continue; |
| 127 | ||
| 128 | 832871x | bool discard = shaders[mat_num]->fragment(bc_clip, color, position, normal, global_face); |
| 129 | 832871x | bool is_translucent = shaders[mat_num]->is_translucent(); |
| 130 | 832871x | if(!discard) { |
| 131 | 832871x | if (depth) { |
| 132 | 166395x | if(color.w >= 1.0f) { |
| 133 | 166395x | zbuffer(i,j) = z; |
| 134 | 166395x | image.set_color(i,j,vec3(position)); |
| 135 | } else { | |
| 136 | alpha_info tmp_data; | |
| 137 | ! | if(is_translucent) { |
| 138 | ! | tmp_data.color = color; |
| 139 | } else { | |
| 140 | ! | tmp_data.color = vec4(0.0,0.0,0.0,color.w); |
| 141 | } | |
| 142 | ! | tmp_data.normal = normal; |
| 143 | ! | tmp_data.position = position; |
| 144 | ! | tmp_data.uv = bc_clip; |
| 145 | ! | alpha_depths[j + ny*i][z] = tmp_data; |
| 146 | } | |
| 147 | } else { | |
| 148 | // Main color pass. | |
| 149 | 666476x | if(color.w >= 1.0f) { |
| 150 | // Opaque (or effectively opaque): commit as topmost | |
| 151 | 666476x | zbuffer(i,j) = z; |
| 152 | 666476x | image.set_color(i,j,vec4(color)); |
| 153 | 666476x | normal_buffer.set_color(i,j,normal); |
| 154 | 666476x | position_buffer.set_color(i,j,position); |
| 155 | 666476x | uv_buffer.set_color(i,j,bc_clip); |
| 156 | ||
| 157 | 666476x | if(write_material_ids) { |
| 158 | 666476x | (*material_id_buffer)(i, j) = mat_num; |
| 159 | } | |
| 160 | } else { | |
| 161 | // Translucent: store for later compositing. | |
| 162 | alpha_info tmp_data; | |
| 163 | ! | tmp_data.color = color; |
| 164 | ! | tmp_data.normal = normal; |
| 165 | ! | tmp_data.position = position; |
| 166 | ! | tmp_data.uv = bc_clip; |
| 167 | ! | alpha_depths[j + ny*i][z] = tmp_data; |
| 168 | // Note: if we want correct material IDs after blending | |
| 169 | // translucent layers, we'll also need material_id in | |
| 170 | // alpha_info and update material_id_buffer in the | |
| 171 | // final resolve loop. | |
| 172 | } | |
| 173 | } | |
| 174 | } | |
| 175 | } | |
| 176 | } | |
| 177 | } | |
| 178 | } | |
| 179 | } | |
| 180 | } | |
| 181 | } |
| 1 | /// @ref core | |
| 2 | ||
| 3 | #include "compute_vector_relational.hpp" | |
| 4 | ||
| 5 | namespace glm{ | |
| 6 | namespace detail | |
| 7 | { | |
| 8 | template<typename T, qualifier Q, bool Aligned> | |
| 9 | struct compute_vec4_add | |
| 10 | { | |
| 11 | 23845972x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static vec<4, T, Q> call(vec<4, T, Q> const& a, vec<4, T, Q> const& b) |
| 12 | { | |
| 13 | 23845972x | return vec<4, T, Q>(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); |
| 14 | } | |
| 15 | }; | |
| 16 | ||
| 17 | template<typename T, qualifier Q, bool Aligned> | |
| 18 | struct compute_vec4_sub | |
| 19 | { | |
| 20 | 108x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static vec<4, T, Q> call(vec<4, T, Q> const& a, vec<4, T, Q> const& b) |
| 21 | { | |
| 22 | 108x | return vec<4, T, Q>(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); |
| 23 | } | |
| 24 | }; | |
| 25 | ||
| 26 | template<typename T, qualifier Q, bool Aligned> | |
| 27 | struct compute_vec4_mul | |
| 28 | { | |
| 29 | 9971773x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static vec<4, T, Q> call(vec<4, T, Q> const& a, vec<4, T, Q> const& b) |
| 30 | { | |
| 31 | 9971773x | return vec<4, T, Q>(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w); |
| 32 | } | |
| 33 | }; | |
| 34 | ||
| 35 | template<typename T, qualifier Q, bool Aligned> | |
| 36 | struct compute_vec4_div | |
| 37 | { | |
| 38 | 1331122x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static vec<4, T, Q> call(vec<4, T, Q> const& a, vec<4, T, Q> const& b) |
| 39 | { | |
| 40 | 1331122x | return vec<4, T, Q>(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w); |
| 41 | } | |
| 42 | }; | |
| 43 | ||
| 44 | template<typename T, qualifier Q, bool Aligned> | |
| 45 | struct compute_vec4_mod | |
| 46 | { | |
| 47 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static vec<4, T, Q> call(vec<4, T, Q> const& a, vec<4, T, Q> const& b) | |
| 48 | { | |
| 49 | return vec<4, T, Q>(a.x % b.x, a.y % b.y, a.z % b.z, a.w % b.w); | |
| 50 | } | |
| 51 | }; | |
| 52 | ||
| 53 | template<typename T, qualifier Q, int IsInt, std::size_t Size, bool Aligned> | |
| 54 | struct compute_vec4_and | |
| 55 | { | |
| 56 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static vec<4, T, Q> call(vec<4, T, Q> const& a, vec<4, T, Q> const& b) | |
| 57 | { | |
| 58 | return vec<4, T, Q>(a.x & b.x, a.y & b.y, a.z & b.z, a.w & b.w); | |
| 59 | } | |
| 60 | }; | |
| 61 | ||
| 62 | template<typename T, qualifier Q, int IsInt, std::size_t Size, bool Aligned> | |
| 63 | struct compute_vec4_or | |
| 64 | { | |
| 65 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static vec<4, T, Q> call(vec<4, T, Q> const& a, vec<4, T, Q> const& b) | |
| 66 | { | |
| 67 | return vec<4, T, Q>(a.x | b.x, a.y | b.y, a.z | b.z, a.w | b.w); | |
| 68 | } | |
| 69 | }; | |
| 70 | ||
| 71 | template<typename T, qualifier Q, int IsInt, std::size_t Size, bool Aligned> | |
| 72 | struct compute_vec4_xor | |
| 73 | { | |
| 74 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static vec<4, T, Q> call(vec<4, T, Q> const& a, vec<4, T, Q> const& b) | |
| 75 | { | |
| 76 | return vec<4, T, Q>(a.x ^ b.x, a.y ^ b.y, a.z ^ b.z, a.w ^ b.w); | |
| 77 | } | |
| 78 | }; | |
| 79 | ||
| 80 | template<typename T, qualifier Q, int IsInt, std::size_t Size, bool Aligned> | |
| 81 | struct compute_vec4_shift_left | |
| 82 | { | |
| 83 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static vec<4, T, Q> call(vec<4, T, Q> const& a, vec<4, T, Q> const& b) | |
| 84 | { | |
| 85 | return vec<4, T, Q>(a.x << b.x, a.y << b.y, a.z << b.z, a.w << b.w); | |
| 86 | } | |
| 87 | }; | |
| 88 | ||
| 89 | template<typename T, qualifier Q, int IsInt, std::size_t Size, bool Aligned> | |
| 90 | struct compute_vec4_shift_right | |
| 91 | { | |
| 92 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static vec<4, T, Q> call(vec<4, T, Q> const& a, vec<4, T, Q> const& b) | |
| 93 | { | |
| 94 | return vec<4, T, Q>(a.x >> b.x, a.y >> b.y, a.z >> b.z, a.w >> b.w); | |
| 95 | } | |
| 96 | }; | |
| 97 | ||
| 98 | template<typename T, qualifier Q, int IsInt, std::size_t Size, bool Aligned> | |
| 99 | struct compute_vec4_equal | |
| 100 | { | |
| 101 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static bool call(vec<4, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 102 | { | |
| 103 | return | |
| 104 | detail::compute_equal<T, std::numeric_limits<T>::is_iec559>::call(v1.x, v2.x) && | |
| 105 | detail::compute_equal<T, std::numeric_limits<T>::is_iec559>::call(v1.y, v2.y) && | |
| 106 | detail::compute_equal<T, std::numeric_limits<T>::is_iec559>::call(v1.z, v2.z) && | |
| 107 | detail::compute_equal<T, std::numeric_limits<T>::is_iec559>::call(v1.w, v2.w); | |
| 108 | } | |
| 109 | }; | |
| 110 | ||
| 111 | template<typename T, qualifier Q, int IsInt, std::size_t Size, bool Aligned> | |
| 112 | struct compute_vec4_nequal | |
| 113 | { | |
| 114 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static bool call(vec<4, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 115 | { | |
| 116 | return !compute_vec4_equal<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(v1, v2); | |
| 117 | } | |
| 118 | }; | |
| 119 | ||
| 120 | template<typename T, qualifier Q, int IsInt, std::size_t Size, bool Aligned> | |
| 121 | struct compute_vec4_bitwise_not | |
| 122 | { | |
| 123 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static vec<4, T, Q> call(vec<4, T, Q> const& v) | |
| 124 | { | |
| 125 | return vec<4, T, Q>(~v.x, ~v.y, ~v.z, ~v.w); | |
| 126 | } | |
| 127 | }; | |
| 128 | }//namespace detail | |
| 129 | ||
| 130 | // -- Implicit basic constructors -- | |
| 131 | ||
| 132 | # if GLM_CONFIG_DEFAULTED_FUNCTIONS == GLM_DISABLE | |
| 133 | template<typename T, qualifier Q> | |
| 134 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec() | |
| 135 | # if GLM_CONFIG_CTOR_INIT != GLM_CTOR_INIT_DISABLE | |
| 136 | : x(0), y(0), z(0), w(0) | |
| 137 | # endif | |
| 138 | {} | |
| 139 | ||
| 140 | template<typename T, qualifier Q> | |
| 141 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<4, T, Q> const& v) | |
| 142 | : x(v.x), y(v.y), z(v.z), w(v.w) | |
| 143 | {} | |
| 144 | # endif | |
| 145 | ||
| 146 | template<typename T, qualifier Q> | |
| 147 | template<qualifier P> | |
| 148 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<4, T, P> const& v) | |
| 149 | : x(v.x), y(v.y), z(v.z), w(v.w) | |
| 150 | {} | |
| 151 | ||
| 152 | // -- Explicit basic constructors -- | |
| 153 | ||
| 154 | template<typename T, qualifier Q> | |
| 155 | 11277249x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(T scalar) |
| 156 | 11277249x | : x(scalar), y(scalar), z(scalar), w(scalar) |
| 157 | {} | |
| 158 | ||
| 159 | template <typename T, qualifier Q> | |
| 160 | 51885759x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(T _x, T _y, T _z, T _w) |
| 161 | 51885759x | : x(_x), y(_y), z(_z), w(_w) |
| 162 | {} | |
| 163 | ||
| 164 | // -- Conversion scalar constructors -- | |
| 165 | ||
| 166 | template<typename T, qualifier Q> | |
| 167 | template<typename U, qualifier P> | |
| 168 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<1, U, P> const& v) | |
| 169 | : x(static_cast<T>(v.x)) | |
| 170 | , y(static_cast<T>(v.x)) | |
| 171 | , z(static_cast<T>(v.x)) | |
| 172 | , w(static_cast<T>(v.x)) | |
| 173 | {} | |
| 174 | ||
| 175 | template<typename T, qualifier Q> | |
| 176 | template<typename X, typename Y, typename Z, typename W> | |
| 177 | 158x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(X _x, Y _y, Z _z, W _w) |
| 178 | 158x | : x(static_cast<T>(_x)) |
| 179 | 158x | , y(static_cast<T>(_y)) |
| 180 | 158x | , z(static_cast<T>(_z)) |
| 181 | 158x | , w(static_cast<T>(_w)) |
| 182 | {} | |
| 183 | ||
| 184 | template<typename T, qualifier Q> | |
| 185 | template<typename X, typename Y, typename Z, typename W> | |
| 186 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<1, X, Q> const& _x, Y _y, Z _z, W _w) | |
| 187 | : x(static_cast<T>(_x.x)) | |
| 188 | , y(static_cast<T>(_y)) | |
| 189 | , z(static_cast<T>(_z)) | |
| 190 | , w(static_cast<T>(_w)) | |
| 191 | {} | |
| 192 | ||
| 193 | template<typename T, qualifier Q> | |
| 194 | template<typename X, typename Y, typename Z, typename W> | |
| 195 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(X _x, vec<1, Y, Q> const& _y, Z _z, W _w) | |
| 196 | : x(static_cast<T>(_x)) | |
| 197 | , y(static_cast<T>(_y.x)) | |
| 198 | , z(static_cast<T>(_z)) | |
| 199 | , w(static_cast<T>(_w)) | |
| 200 | {} | |
| 201 | ||
| 202 | template<typename T, qualifier Q> | |
| 203 | template<typename X, typename Y, typename Z, typename W> | |
| 204 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<1, X, Q> const& _x, vec<1, Y, Q> const& _y, Z _z, W _w) | |
| 205 | : x(static_cast<T>(_x.x)) | |
| 206 | , y(static_cast<T>(_y.x)) | |
| 207 | , z(static_cast<T>(_z)) | |
| 208 | , w(static_cast<T>(_w)) | |
| 209 | {} | |
| 210 | ||
| 211 | template<typename T, qualifier Q> | |
| 212 | template<typename X, typename Y, typename Z, typename W> | |
| 213 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(X _x, Y _y, vec<1, Z, Q> const& _z, W _w) | |
| 214 | : x(static_cast<T>(_x)) | |
| 215 | , y(static_cast<T>(_y)) | |
| 216 | , z(static_cast<T>(_z.x)) | |
| 217 | , w(static_cast<T>(_w)) | |
| 218 | {} | |
| 219 | ||
| 220 | template<typename T, qualifier Q> | |
| 221 | template<typename X, typename Y, typename Z, typename W> | |
| 222 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<1, X, Q> const& _x, Y _y, vec<1, Z, Q> const& _z, W _w) | |
| 223 | : x(static_cast<T>(_x.x)) | |
| 224 | , y(static_cast<T>(_y)) | |
| 225 | , z(static_cast<T>(_z.x)) | |
| 226 | , w(static_cast<T>(_w)) | |
| 227 | {} | |
| 228 | ||
| 229 | template<typename T, qualifier Q> | |
| 230 | template<typename X, typename Y, typename Z, typename W> | |
| 231 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(X _x, vec<1, Y, Q> const& _y, vec<1, Z, Q> const& _z, W _w) | |
| 232 | : x(static_cast<T>(_x)) | |
| 233 | , y(static_cast<T>(_y.x)) | |
| 234 | , z(static_cast<T>(_z.x)) | |
| 235 | , w(static_cast<T>(_w)) | |
| 236 | {} | |
| 237 | ||
| 238 | template<typename T, qualifier Q> | |
| 239 | template<typename X, typename Y, typename Z, typename W> | |
| 240 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<1, X, Q> const& _x, vec<1, Y, Q> const& _y, vec<1, Z, Q> const& _z, W _w) | |
| 241 | : x(static_cast<T>(_x.x)) | |
| 242 | , y(static_cast<T>(_y.x)) | |
| 243 | , z(static_cast<T>(_z.x)) | |
| 244 | , w(static_cast<T>(_w)) | |
| 245 | {} | |
| 246 | ||
| 247 | template<typename T, qualifier Q> | |
| 248 | template<typename X, typename Y, typename Z, typename W> | |
| 249 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<1, X, Q> const& _x, Y _y, Z _z, vec<1, W, Q> const& _w) | |
| 250 | : x(static_cast<T>(_x.x)) | |
| 251 | , y(static_cast<T>(_y)) | |
| 252 | , z(static_cast<T>(_z)) | |
| 253 | , w(static_cast<T>(_w.x)) | |
| 254 | {} | |
| 255 | ||
| 256 | template<typename T, qualifier Q> | |
| 257 | template<typename X, typename Y, typename Z, typename W> | |
| 258 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(X _x, vec<1, Y, Q> const& _y, Z _z, vec<1, W, Q> const& _w) | |
| 259 | : x(static_cast<T>(_x)) | |
| 260 | , y(static_cast<T>(_y.x)) | |
| 261 | , z(static_cast<T>(_z)) | |
| 262 | , w(static_cast<T>(_w.x)) | |
| 263 | {} | |
| 264 | ||
| 265 | template<typename T, qualifier Q> | |
| 266 | template<typename X, typename Y, typename Z, typename W> | |
| 267 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<1, X, Q> const& _x, vec<1, Y, Q> const& _y, Z _z, vec<1, W, Q> const& _w) | |
| 268 | : x(static_cast<T>(_x.x)) | |
| 269 | , y(static_cast<T>(_y.x)) | |
| 270 | , z(static_cast<T>(_z)) | |
| 271 | , w(static_cast<T>(_w.x)) | |
| 272 | {} | |
| 273 | ||
| 274 | template<typename T, qualifier Q> | |
| 275 | template<typename X, typename Y, typename Z, typename W> | |
| 276 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(X _x, Y _y, vec<1, Z, Q> const& _z, vec<1, W, Q> const& _w) | |
| 277 | : x(static_cast<T>(_x)) | |
| 278 | , y(static_cast<T>(_y)) | |
| 279 | , z(static_cast<T>(_z.x)) | |
| 280 | , w(static_cast<T>(_w.x)) | |
| 281 | {} | |
| 282 | ||
| 283 | template<typename T, qualifier Q> | |
| 284 | template<typename X, typename Y, typename Z, typename W> | |
| 285 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<1, X, Q> const& _x, Y _y, vec<1, Z, Q> const& _z, vec<1, W, Q> const& _w) | |
| 286 | : x(static_cast<T>(_x.x)) | |
| 287 | , y(static_cast<T>(_y)) | |
| 288 | , z(static_cast<T>(_z.x)) | |
| 289 | , w(static_cast<T>(_w.x)) | |
| 290 | {} | |
| 291 | ||
| 292 | template<typename T, qualifier Q> | |
| 293 | template<typename X, typename Y, typename Z, typename W> | |
| 294 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(X _x, vec<1, Y, Q> const& _y, vec<1, Z, Q> const& _z, vec<1, W, Q> const& _w) | |
| 295 | : x(static_cast<T>(_x)) | |
| 296 | , y(static_cast<T>(_y.x)) | |
| 297 | , z(static_cast<T>(_z.x)) | |
| 298 | , w(static_cast<T>(_w.x)) | |
| 299 | {} | |
| 300 | ||
| 301 | template<typename T, qualifier Q> | |
| 302 | template<typename X, typename Y, typename Z, typename W> | |
| 303 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<1, X, Q> const& _x, vec<1, Y, Q> const& _y, vec<1, Z, Q> const& _z, vec<1, W, Q> const& _w) | |
| 304 | : x(static_cast<T>(_x.x)) | |
| 305 | , y(static_cast<T>(_y.x)) | |
| 306 | , z(static_cast<T>(_z.x)) | |
| 307 | , w(static_cast<T>(_w.x)) | |
| 308 | {} | |
| 309 | ||
| 310 | // -- Conversion vector constructors -- | |
| 311 | ||
| 312 | template<typename T, qualifier Q> | |
| 313 | template<typename A, typename B, typename C, qualifier P> | |
| 314 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<2, A, P> const& _xy, B _z, C _w) | |
| 315 | : x(static_cast<T>(_xy.x)) | |
| 316 | , y(static_cast<T>(_xy.y)) | |
| 317 | , z(static_cast<T>(_z)) | |
| 318 | , w(static_cast<T>(_w)) | |
| 319 | {} | |
| 320 | ||
| 321 | template<typename T, qualifier Q> | |
| 322 | template<typename A, typename B, typename C, qualifier P> | |
| 323 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<2, A, P> const& _xy, vec<1, B, P> const& _z, C _w) | |
| 324 | : x(static_cast<T>(_xy.x)) | |
| 325 | , y(static_cast<T>(_xy.y)) | |
| 326 | , z(static_cast<T>(_z.x)) | |
| 327 | , w(static_cast<T>(_w)) | |
| 328 | {} | |
| 329 | ||
| 330 | template<typename T, qualifier Q> | |
| 331 | template<typename A, typename B, typename C, qualifier P> | |
| 332 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<2, A, P> const& _xy, B _z, vec<1, C, P> const& _w) | |
| 333 | : x(static_cast<T>(_xy.x)) | |
| 334 | , y(static_cast<T>(_xy.y)) | |
| 335 | , z(static_cast<T>(_z)) | |
| 336 | , w(static_cast<T>(_w.x)) | |
| 337 | {} | |
| 338 | ||
| 339 | template<typename T, qualifier Q> | |
| 340 | template<typename A, typename B, typename C, qualifier P> | |
| 341 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<2, A, P> const& _xy, vec<1, B, P> const& _z, vec<1, C, P> const& _w) | |
| 342 | : x(static_cast<T>(_xy.x)) | |
| 343 | , y(static_cast<T>(_xy.y)) | |
| 344 | , z(static_cast<T>(_z.x)) | |
| 345 | , w(static_cast<T>(_w.x)) | |
| 346 | {} | |
| 347 | ||
| 348 | template<typename T, qualifier Q> | |
| 349 | template<typename A, typename B, typename C, qualifier P> | |
| 350 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(A _x, vec<2, B, P> const& _yz, C _w) | |
| 351 | : x(static_cast<T>(_x)) | |
| 352 | , y(static_cast<T>(_yz.x)) | |
| 353 | , z(static_cast<T>(_yz.y)) | |
| 354 | , w(static_cast<T>(_w)) | |
| 355 | {} | |
| 356 | ||
| 357 | template<typename T, qualifier Q> | |
| 358 | template<typename A, typename B, typename C, qualifier P> | |
| 359 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<1, A, P> const& _x, vec<2, B, P> const& _yz, C _w) | |
| 360 | : x(static_cast<T>(_x.x)) | |
| 361 | , y(static_cast<T>(_yz.x)) | |
| 362 | , z(static_cast<T>(_yz.y)) | |
| 363 | , w(static_cast<T>(_w)) | |
| 364 | {} | |
| 365 | ||
| 366 | template<typename T, qualifier Q> | |
| 367 | template<typename A, typename B, typename C, qualifier P> | |
| 368 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(A _x, vec<2, B, P> const& _yz, vec<1, C, P> const& _w) | |
| 369 | : x(static_cast<T>(_x)) | |
| 370 | , y(static_cast<T>(_yz.x)) | |
| 371 | , z(static_cast<T>(_yz.y)) | |
| 372 | , w(static_cast<T>(_w.x)) | |
| 373 | {} | |
| 374 | ||
| 375 | template<typename T, qualifier Q> | |
| 376 | template<typename A, typename B, typename C, qualifier P> | |
| 377 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<1, A, P> const& _x, vec<2, B, P> const& _yz, vec<1, C, P> const& _w) | |
| 378 | : x(static_cast<T>(_x.x)) | |
| 379 | , y(static_cast<T>(_yz.x)) | |
| 380 | , z(static_cast<T>(_yz.y)) | |
| 381 | , w(static_cast<T>(_w.x)) | |
| 382 | {} | |
| 383 | ||
| 384 | template<typename T, qualifier Q> | |
| 385 | template<typename A, typename B, typename C, qualifier P> | |
| 386 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(A _x, B _y, vec<2, C, P> const& _zw) | |
| 387 | : x(static_cast<T>(_x)) | |
| 388 | , y(static_cast<T>(_y)) | |
| 389 | , z(static_cast<T>(_zw.x)) | |
| 390 | , w(static_cast<T>(_zw.y)) | |
| 391 | {} | |
| 392 | ||
| 393 | template<typename T, qualifier Q> | |
| 394 | template<typename A, typename B, typename C, qualifier P> | |
| 395 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<1, A, P> const& _x, B _y, vec<2, C, P> const& _zw) | |
| 396 | : x(static_cast<T>(_x.x)) | |
| 397 | , y(static_cast<T>(_y)) | |
| 398 | , z(static_cast<T>(_zw.x)) | |
| 399 | , w(static_cast<T>(_zw.y)) | |
| 400 | {} | |
| 401 | ||
| 402 | template<typename T, qualifier Q> | |
| 403 | template<typename A, typename B, typename C, qualifier P> | |
| 404 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(A _x, vec<1, B, P> const& _y, vec<2, C, P> const& _zw) | |
| 405 | : x(static_cast<T>(_x)) | |
| 406 | , y(static_cast<T>(_y.x)) | |
| 407 | , z(static_cast<T>(_zw.x)) | |
| 408 | , w(static_cast<T>(_zw.y)) | |
| 409 | {} | |
| 410 | ||
| 411 | template<typename T, qualifier Q> | |
| 412 | template<typename A, typename B, typename C, qualifier P> | |
| 413 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<1, A, P> const& _x, vec<1, B, P> const& _y, vec<2, C, P> const& _zw) | |
| 414 | : x(static_cast<T>(_x.x)) | |
| 415 | , y(static_cast<T>(_y.x)) | |
| 416 | , z(static_cast<T>(_zw.x)) | |
| 417 | , w(static_cast<T>(_zw.y)) | |
| 418 | {} | |
| 419 | ||
| 420 | template<typename T, qualifier Q> | |
| 421 | template<typename A, typename B, qualifier P> | |
| 422 | 2852987x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<3, A, P> const& _xyz, B _w) |
| 423 | 2852987x | : x(static_cast<T>(_xyz.x)) |
| 424 | 2852987x | , y(static_cast<T>(_xyz.y)) |
| 425 | 2852987x | , z(static_cast<T>(_xyz.z)) |
| 426 | 2852987x | , w(static_cast<T>(_w)) |
| 427 | {} | |
| 428 | ||
| 429 | template<typename T, qualifier Q> | |
| 430 | template<typename A, typename B, qualifier P> | |
| 431 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<3, A, P> const& _xyz, vec<1, B, P> const& _w) | |
| 432 | : x(static_cast<T>(_xyz.x)) | |
| 433 | , y(static_cast<T>(_xyz.y)) | |
| 434 | , z(static_cast<T>(_xyz.z)) | |
| 435 | , w(static_cast<T>(_w.x)) | |
| 436 | {} | |
| 437 | ||
| 438 | template<typename T, qualifier Q> | |
| 439 | template<typename A, typename B, qualifier P> | |
| 440 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(A _x, vec<3, B, P> const& _yzw) | |
| 441 | : x(static_cast<T>(_x)) | |
| 442 | , y(static_cast<T>(_yzw.x)) | |
| 443 | , z(static_cast<T>(_yzw.y)) | |
| 444 | , w(static_cast<T>(_yzw.z)) | |
| 445 | {} | |
| 446 | ||
| 447 | template<typename T, qualifier Q> | |
| 448 | template<typename A, typename B, qualifier P> | |
| 449 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<1, A, P> const& _x, vec<3, B, P> const& _yzw) | |
| 450 | : x(static_cast<T>(_x.x)) | |
| 451 | , y(static_cast<T>(_yzw.x)) | |
| 452 | , z(static_cast<T>(_yzw.y)) | |
| 453 | , w(static_cast<T>(_yzw.z)) | |
| 454 | {} | |
| 455 | ||
| 456 | template<typename T, qualifier Q> | |
| 457 | template<typename A, typename B, qualifier P> | |
| 458 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<2, A, P> const& _xy, vec<2, B, P> const& _zw) | |
| 459 | : x(static_cast<T>(_xy.x)) | |
| 460 | , y(static_cast<T>(_xy.y)) | |
| 461 | , z(static_cast<T>(_zw.x)) | |
| 462 | , w(static_cast<T>(_zw.y)) | |
| 463 | {} | |
| 464 | ||
| 465 | template<typename T, qualifier Q> | |
| 466 | template<typename U, qualifier P> | |
| 467 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>::vec(vec<4, U, P> const& v) | |
| 468 | : x(static_cast<T>(v.x)) | |
| 469 | , y(static_cast<T>(v.y)) | |
| 470 | , z(static_cast<T>(v.z)) | |
| 471 | , w(static_cast<T>(v.w)) | |
| 472 | {} | |
| 473 | ||
| 474 | // -- Component accesses -- | |
| 475 | ||
| 476 | template<typename T, qualifier Q> | |
| 477 | 20632340x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR T& vec<4, T, Q>::operator[](typename vec<4, T, Q>::length_type i) |
| 478 | { | |
| 479 | assert(i >= 0 && i < this->length()); | |
| 480 | 20632340x | switch(i) |
| 481 | { | |
| 482 | 1996835x | default: |
| 483 | case 0: | |
| 484 | 1996835x | return x; |
| 485 | 1996727x | case 1: |
| 486 | 1996727x | return y; |
| 487 | 16638654x | case 2: |
| 488 | 16638654x | return z; |
| 489 | 124x | case 3: |
| 490 | 124x | return w; |
| 491 | } | |
| 492 | } | |
| 493 | ||
| 494 | template<typename T, qualifier Q> | |
| 495 | 5519672x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR T const& vec<4, T, Q>::operator[](typename vec<4, T, Q>::length_type i) const |
| 496 | { | |
| 497 | assert(i >= 0 && i < this->length()); | |
| 498 | 5519672x | switch(i) |
| 499 | { | |
| 500 | 1379918x | default: |
| 501 | case 0: | |
| 502 | 1379918x | return x; |
| 503 | 1379918x | case 1: |
| 504 | 1379918x | return y; |
| 505 | 1379918x | case 2: |
| 506 | 1379918x | return z; |
| 507 | 1379918x | case 3: |
| 508 | 1379918x | return w; |
| 509 | } | |
| 510 | } | |
| 511 | ||
| 512 | // -- Unary arithmetic operators -- | |
| 513 | ||
| 514 | # if GLM_CONFIG_DEFAULTED_FUNCTIONS == GLM_DISABLE | |
| 515 | template<typename T, qualifier Q> | |
| 516 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>& vec<4, T, Q>::operator=(vec<4, T, Q> const& v) | |
| 517 | { | |
| 518 | this->x = v.x; | |
| 519 | this->y = v.y; | |
| 520 | this->z = v.z; | |
| 521 | this->w = v.w; | |
| 522 | return *this; | |
| 523 | } | |
| 524 | # endif | |
| 525 | ||
| 526 | template<typename T, qualifier Q> | |
| 527 | template<typename U> | |
| 528 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q>& vec<4, T, Q>::operator=(vec<4, U, Q> const& v) | |
| 529 | { | |
| 530 | this->x = static_cast<T>(v.x); | |
| 531 | this->y = static_cast<T>(v.y); | |
| 532 | this->z = static_cast<T>(v.z); | |
| 533 | this->w = static_cast<T>(v.w); | |
| 534 | return *this; | |
| 535 | } | |
| 536 | ||
| 537 | template<typename T, qualifier Q> | |
| 538 | template<typename U> | |
| 539 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator+=(U scalar) | |
| 540 | { | |
| 541 | return (*this = detail::compute_vec4_add<T, Q, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(scalar))); | |
| 542 | } | |
| 543 | ||
| 544 | template<typename T, qualifier Q> | |
| 545 | template<typename U> | |
| 546 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator+=(vec<1, U, Q> const& v) | |
| 547 | { | |
| 548 | return (*this = detail::compute_vec4_add<T, Q, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v.x))); | |
| 549 | } | |
| 550 | ||
| 551 | template<typename T, qualifier Q> | |
| 552 | template<typename U> | |
| 553 | 23845972x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator+=(vec<4, U, Q> const& v) |
| 554 | { | |
| 555 | 23845972x | return (*this = detail::compute_vec4_add<T, Q, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v))); |
| 556 | } | |
| 557 | ||
| 558 | template<typename T, qualifier Q> | |
| 559 | template<typename U> | |
| 560 | ! | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator-=(U scalar) |
| 561 | { | |
| 562 | ! | return (*this = detail::compute_vec4_sub<T, Q, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(scalar))); |
| 563 | } | |
| 564 | ||
| 565 | template<typename T, qualifier Q> | |
| 566 | template<typename U> | |
| 567 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator-=(vec<1, U, Q> const& v) | |
| 568 | { | |
| 569 | return (*this = detail::compute_vec4_sub<T, Q, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v.x))); | |
| 570 | } | |
| 571 | ||
| 572 | template<typename T, qualifier Q> | |
| 573 | template<typename U> | |
| 574 | 108x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator-=(vec<4, U, Q> const& v) |
| 575 | { | |
| 576 | 108x | return (*this = detail::compute_vec4_sub<T, Q, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v))); |
| 577 | } | |
| 578 | ||
| 579 | template<typename T, qualifier Q> | |
| 580 | template<typename U> | |
| 581 | 3848151x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator*=(U scalar) |
| 582 | { | |
| 583 | 3848151x | return (*this = detail::compute_vec4_mul<T, Q, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(scalar))); |
| 584 | } | |
| 585 | ||
| 586 | template<typename T, qualifier Q> | |
| 587 | template<typename U> | |
| 588 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator*=(vec<1, U, Q> const& v) | |
| 589 | { | |
| 590 | return (*this = detail::compute_vec4_mul<T, Q, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v.x))); | |
| 591 | } | |
| 592 | ||
| 593 | template<typename T, qualifier Q> | |
| 594 | template<typename U> | |
| 595 | 6123622x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator*=(vec<4, U, Q> const& v) |
| 596 | { | |
| 597 | 6123622x | return (*this = detail::compute_vec4_mul<T, Q, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v))); |
| 598 | } | |
| 599 | ||
| 600 | template<typename T, qualifier Q> | |
| 601 | template<typename U> | |
| 602 | 1331122x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator/=(U scalar) |
| 603 | { | |
| 604 | 1331122x | return (*this = detail::compute_vec4_div<T, Q, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(scalar))); |
| 605 | } | |
| 606 | ||
| 607 | template<typename T, qualifier Q> | |
| 608 | template<typename U> | |
| 609 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator/=(vec<1, U, Q> const& v) | |
| 610 | { | |
| 611 | return (*this = detail::compute_vec4_div<T, Q, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v.x))); | |
| 612 | } | |
| 613 | ||
| 614 | template<typename T, qualifier Q> | |
| 615 | template<typename U> | |
| 616 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator/=(vec<4, U, Q> const& v) | |
| 617 | { | |
| 618 | return (*this = detail::compute_vec4_div<T, Q, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v))); | |
| 619 | } | |
| 620 | ||
| 621 | // -- Increment and decrement operators -- | |
| 622 | ||
| 623 | template<typename T, qualifier Q> | |
| 624 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator++() | |
| 625 | { | |
| 626 | ++this->x; | |
| 627 | ++this->y; | |
| 628 | ++this->z; | |
| 629 | ++this->w; | |
| 630 | return *this; | |
| 631 | } | |
| 632 | ||
| 633 | template<typename T, qualifier Q> | |
| 634 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator--() | |
| 635 | { | |
| 636 | --this->x; | |
| 637 | --this->y; | |
| 638 | --this->z; | |
| 639 | --this->w; | |
| 640 | return *this; | |
| 641 | } | |
| 642 | ||
| 643 | template<typename T, qualifier Q> | |
| 644 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> vec<4, T, Q>::operator++(int) | |
| 645 | { | |
| 646 | vec<4, T, Q> Result(*this); | |
| 647 | ++*this; | |
| 648 | return Result; | |
| 649 | } | |
| 650 | ||
| 651 | template<typename T, qualifier Q> | |
| 652 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> vec<4, T, Q>::operator--(int) | |
| 653 | { | |
| 654 | vec<4, T, Q> Result(*this); | |
| 655 | --*this; | |
| 656 | return Result; | |
| 657 | } | |
| 658 | ||
| 659 | // -- Unary bit operators -- | |
| 660 | ||
| 661 | template<typename T, qualifier Q> | |
| 662 | template<typename U> | |
| 663 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator%=(U scalar) | |
| 664 | { | |
| 665 | return (*this = detail::compute_vec4_mod<T, Q, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(scalar))); | |
| 666 | } | |
| 667 | ||
| 668 | template<typename T, qualifier Q> | |
| 669 | template<typename U> | |
| 670 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator%=(vec<1, U, Q> const& v) | |
| 671 | { | |
| 672 | return (*this = detail::compute_vec4_mod<T, Q, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v))); | |
| 673 | } | |
| 674 | ||
| 675 | template<typename T, qualifier Q> | |
| 676 | template<typename U> | |
| 677 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator%=(vec<4, U, Q> const& v) | |
| 678 | { | |
| 679 | return (*this = detail::compute_vec4_mod<T, Q, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v))); | |
| 680 | } | |
| 681 | ||
| 682 | template<typename T, qualifier Q> | |
| 683 | template<typename U> | |
| 684 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator&=(U scalar) | |
| 685 | { | |
| 686 | return (*this = detail::compute_vec4_and<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(scalar))); | |
| 687 | } | |
| 688 | ||
| 689 | template<typename T, qualifier Q> | |
| 690 | template<typename U> | |
| 691 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator&=(vec<1, U, Q> const& v) | |
| 692 | { | |
| 693 | return (*this = detail::compute_vec4_and<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v))); | |
| 694 | } | |
| 695 | ||
| 696 | template<typename T, qualifier Q> | |
| 697 | template<typename U> | |
| 698 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator&=(vec<4, U, Q> const& v) | |
| 699 | { | |
| 700 | return (*this = detail::compute_vec4_and<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v))); | |
| 701 | } | |
| 702 | ||
| 703 | template<typename T, qualifier Q> | |
| 704 | template<typename U> | |
| 705 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator|=(U scalar) | |
| 706 | { | |
| 707 | return (*this = detail::compute_vec4_or<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(scalar))); | |
| 708 | } | |
| 709 | ||
| 710 | template<typename T, qualifier Q> | |
| 711 | template<typename U> | |
| 712 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator|=(vec<1, U, Q> const& v) | |
| 713 | { | |
| 714 | return (*this = detail::compute_vec4_or<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v))); | |
| 715 | } | |
| 716 | ||
| 717 | template<typename T, qualifier Q> | |
| 718 | template<typename U> | |
| 719 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator|=(vec<4, U, Q> const& v) | |
| 720 | { | |
| 721 | return (*this = detail::compute_vec4_or<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v))); | |
| 722 | } | |
| 723 | ||
| 724 | template<typename T, qualifier Q> | |
| 725 | template<typename U> | |
| 726 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator^=(U scalar) | |
| 727 | { | |
| 728 | return (*this = detail::compute_vec4_xor<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(scalar))); | |
| 729 | } | |
| 730 | ||
| 731 | template<typename T, qualifier Q> | |
| 732 | template<typename U> | |
| 733 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator^=(vec<1, U, Q> const& v) | |
| 734 | { | |
| 735 | return (*this = detail::compute_vec4_xor<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v))); | |
| 736 | } | |
| 737 | ||
| 738 | template<typename T, qualifier Q> | |
| 739 | template<typename U> | |
| 740 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator^=(vec<4, U, Q> const& v) | |
| 741 | { | |
| 742 | return (*this = detail::compute_vec4_xor<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v))); | |
| 743 | } | |
| 744 | ||
| 745 | template<typename T, qualifier Q> | |
| 746 | template<typename U> | |
| 747 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator<<=(U scalar) | |
| 748 | { | |
| 749 | return (*this = detail::compute_vec4_shift_left<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(scalar))); | |
| 750 | } | |
| 751 | ||
| 752 | template<typename T, qualifier Q> | |
| 753 | template<typename U> | |
| 754 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator<<=(vec<1, U, Q> const& v) | |
| 755 | { | |
| 756 | return (*this = detail::compute_vec4_shift_left<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v))); | |
| 757 | } | |
| 758 | ||
| 759 | template<typename T, qualifier Q> | |
| 760 | template<typename U> | |
| 761 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator<<=(vec<4, U, Q> const& v) | |
| 762 | { | |
| 763 | return (*this = detail::compute_vec4_shift_left<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v))); | |
| 764 | } | |
| 765 | ||
| 766 | template<typename T, qualifier Q> | |
| 767 | template<typename U> | |
| 768 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator>>=(U scalar) | |
| 769 | { | |
| 770 | return (*this = detail::compute_vec4_shift_right<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(scalar))); | |
| 771 | } | |
| 772 | ||
| 773 | template<typename T, qualifier Q> | |
| 774 | template<typename U> | |
| 775 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator>>=(vec<1, U, Q> const& v) | |
| 776 | { | |
| 777 | return (*this = detail::compute_vec4_shift_right<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v))); | |
| 778 | } | |
| 779 | ||
| 780 | template<typename T, qualifier Q> | |
| 781 | template<typename U> | |
| 782 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> & vec<4, T, Q>::operator>>=(vec<4, U, Q> const& v) | |
| 783 | { | |
| 784 | return (*this = detail::compute_vec4_shift_right<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(*this, vec<4, T, Q>(v))); | |
| 785 | } | |
| 786 | ||
| 787 | // -- Unary constant operators -- | |
| 788 | ||
| 789 | template<typename T, qualifier Q> | |
| 790 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator+(vec<4, T, Q> const& v) | |
| 791 | { | |
| 792 | return v; | |
| 793 | } | |
| 794 | ||
| 795 | template<typename T, qualifier Q> | |
| 796 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator-(vec<4, T, Q> const& v) | |
| 797 | { | |
| 798 | return vec<4, T, Q>(0) -= v; | |
| 799 | } | |
| 800 | ||
| 801 | // -- Binary arithmetic operators -- | |
| 802 | ||
| 803 | template<typename T, qualifier Q> | |
| 804 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator+(vec<4, T, Q> const& v, T const & scalar) | |
| 805 | { | |
| 806 | return vec<4, T, Q>(v) += scalar; | |
| 807 | } | |
| 808 | ||
| 809 | template<typename T, qualifier Q> | |
| 810 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator+(vec<4, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 811 | { | |
| 812 | return vec<4, T, Q>(v1) += v2; | |
| 813 | } | |
| 814 | ||
| 815 | template<typename T, qualifier Q> | |
| 816 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator+(T scalar, vec<4, T, Q> const& v) | |
| 817 | { | |
| 818 | return vec<4, T, Q>(v) += scalar; | |
| 819 | } | |
| 820 | ||
| 821 | template<typename T, qualifier Q> | |
| 822 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator+(vec<1, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 823 | { | |
| 824 | return vec<4, T, Q>(v2) += v1; | |
| 825 | } | |
| 826 | ||
| 827 | template<typename T, qualifier Q> | |
| 828 | 5874545x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator+(vec<4, T, Q> const& v1, vec<4, T, Q> const& v2) |
| 829 | { | |
| 830 | 5874545x | return vec<4, T, Q>(v1) += v2; |
| 831 | } | |
| 832 | ||
| 833 | template<typename T, qualifier Q> | |
| 834 | ! | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator-(vec<4, T, Q> const& v, T const & scalar) |
| 835 | { | |
| 836 | ! | return vec<4, T, Q>(v) -= scalar; |
| 837 | } | |
| 838 | ||
| 839 | template<typename T, qualifier Q> | |
| 840 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator-(vec<4, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 841 | { | |
| 842 | return vec<4, T, Q>(v1) -= v2; | |
| 843 | } | |
| 844 | ||
| 845 | template<typename T, qualifier Q> | |
| 846 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator-(T scalar, vec<4, T, Q> const& v) | |
| 847 | { | |
| 848 | return vec<4, T, Q>(scalar) -= v; | |
| 849 | } | |
| 850 | ||
| 851 | template<typename T, qualifier Q> | |
| 852 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator-(vec<1, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 853 | { | |
| 854 | return vec<4, T, Q>(v1.x) -= v2; | |
| 855 | } | |
| 856 | ||
| 857 | template<typename T, qualifier Q> | |
| 858 | 108x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator-(vec<4, T, Q> const& v1, vec<4, T, Q> const& v2) |
| 859 | { | |
| 860 | 108x | return vec<4, T, Q>(v1) -= v2; |
| 861 | } | |
| 862 | ||
| 863 | template<typename T, qualifier Q> | |
| 864 | 3848151x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator*(vec<4, T, Q> const& v, T const & scalar) |
| 865 | { | |
| 866 | 3848151x | return vec<4, T, Q>(v) *= scalar; |
| 867 | } | |
| 868 | ||
| 869 | template<typename T, qualifier Q> | |
| 870 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator*(vec<4, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 871 | { | |
| 872 | return vec<4, T, Q>(v1) *= v2; | |
| 873 | } | |
| 874 | ||
| 875 | template<typename T, qualifier Q> | |
| 876 | ! | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator*(T scalar, vec<4, T, Q> const& v) |
| 877 | { | |
| 878 | ! | return vec<4, T, Q>(v) *= scalar; |
| 879 | } | |
| 880 | ||
| 881 | template<typename T, qualifier Q> | |
| 882 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator*(vec<1, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 883 | { | |
| 884 | return vec<4, T, Q>(v2) *= v1; | |
| 885 | } | |
| 886 | ||
| 887 | template<typename T, qualifier Q> | |
| 888 | 6123622x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator*(vec<4, T, Q> const& v1, vec<4, T, Q> const& v2) |
| 889 | { | |
| 890 | 6123622x | return vec<4, T, Q>(v1) *= v2; |
| 891 | } | |
| 892 | ||
| 893 | template<typename T, qualifier Q> | |
| 894 | 665539x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator/(vec<4, T, Q> const& v, T const & scalar) |
| 895 | { | |
| 896 | 665539x | return vec<4, T, Q>(v) /= scalar; |
| 897 | } | |
| 898 | ||
| 899 | template<typename T, qualifier Q> | |
| 900 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator/(vec<4, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 901 | { | |
| 902 | return vec<4, T, Q>(v1) /= v2; | |
| 903 | } | |
| 904 | ||
| 905 | template<typename T, qualifier Q> | |
| 906 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator/(T scalar, vec<4, T, Q> const& v) | |
| 907 | { | |
| 908 | return vec<4, T, Q>(scalar) /= v; | |
| 909 | } | |
| 910 | ||
| 911 | template<typename T, qualifier Q> | |
| 912 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator/(vec<1, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 913 | { | |
| 914 | return vec<4, T, Q>(v1.x) /= v2; | |
| 915 | } | |
| 916 | ||
| 917 | template<typename T, qualifier Q> | |
| 918 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator/(vec<4, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 919 | { | |
| 920 | return vec<4, T, Q>(v1) /= v2; | |
| 921 | } | |
| 922 | ||
| 923 | // -- Binary bit operators -- | |
| 924 | ||
| 925 | template<typename T, qualifier Q> | |
| 926 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator%(vec<4, T, Q> const& v, T scalar) | |
| 927 | { | |
| 928 | return vec<4, T, Q>(v) %= scalar; | |
| 929 | } | |
| 930 | ||
| 931 | template<typename T, qualifier Q> | |
| 932 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator%(vec<4, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 933 | { | |
| 934 | return vec<4, T, Q>(v1) %= v2.x; | |
| 935 | } | |
| 936 | ||
| 937 | template<typename T, qualifier Q> | |
| 938 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator%(T scalar, vec<4, T, Q> const& v) | |
| 939 | { | |
| 940 | return vec<4, T, Q>(scalar) %= v; | |
| 941 | } | |
| 942 | ||
| 943 | template<typename T, qualifier Q> | |
| 944 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator%(vec<1, T, Q> const& scalar, vec<4, T, Q> const& v) | |
| 945 | { | |
| 946 | return vec<4, T, Q>(scalar.x) %= v; | |
| 947 | } | |
| 948 | ||
| 949 | template<typename T, qualifier Q> | |
| 950 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator%(vec<4, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 951 | { | |
| 952 | return vec<4, T, Q>(v1) %= v2; | |
| 953 | } | |
| 954 | ||
| 955 | template<typename T, qualifier Q> | |
| 956 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator&(vec<4, T, Q> const& v, T scalar) | |
| 957 | { | |
| 958 | return vec<4, T, Q>(v) &= scalar; | |
| 959 | } | |
| 960 | ||
| 961 | template<typename T, qualifier Q> | |
| 962 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator&(vec<4, T, Q> const& v, vec<1, T, Q> const& scalar) | |
| 963 | { | |
| 964 | return vec<4, T, Q>(v) &= scalar; | |
| 965 | } | |
| 966 | ||
| 967 | template<typename T, qualifier Q> | |
| 968 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator&(T scalar, vec<4, T, Q> const& v) | |
| 969 | { | |
| 970 | return vec<4, T, Q>(scalar) &= v; | |
| 971 | } | |
| 972 | ||
| 973 | template<typename T, qualifier Q> | |
| 974 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator&(vec<1, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 975 | { | |
| 976 | return vec<4, T, Q>(v1.x) &= v2; | |
| 977 | } | |
| 978 | ||
| 979 | template<typename T, qualifier Q> | |
| 980 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator&(vec<4, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 981 | { | |
| 982 | return vec<4, T, Q>(v1) &= v2; | |
| 983 | } | |
| 984 | ||
| 985 | template<typename T, qualifier Q> | |
| 986 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator|(vec<4, T, Q> const& v, T scalar) | |
| 987 | { | |
| 988 | return vec<4, T, Q>(v) |= scalar; | |
| 989 | } | |
| 990 | ||
| 991 | template<typename T, qualifier Q> | |
| 992 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator|(vec<4, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 993 | { | |
| 994 | return vec<4, T, Q>(v1) |= v2.x; | |
| 995 | } | |
| 996 | ||
| 997 | template<typename T, qualifier Q> | |
| 998 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator|(T scalar, vec<4, T, Q> const& v) | |
| 999 | { | |
| 1000 | return vec<4, T, Q>(scalar) |= v; | |
| 1001 | } | |
| 1002 | ||
| 1003 | template<typename T, qualifier Q> | |
| 1004 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator|(vec<1, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 1005 | { | |
| 1006 | return vec<4, T, Q>(v1.x) |= v2; | |
| 1007 | } | |
| 1008 | ||
| 1009 | template<typename T, qualifier Q> | |
| 1010 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator|(vec<4, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 1011 | { | |
| 1012 | return vec<4, T, Q>(v1) |= v2; | |
| 1013 | } | |
| 1014 | ||
| 1015 | template<typename T, qualifier Q> | |
| 1016 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator^(vec<4, T, Q> const& v, T scalar) | |
| 1017 | { | |
| 1018 | return vec<4, T, Q>(v) ^= scalar; | |
| 1019 | } | |
| 1020 | ||
| 1021 | template<typename T, qualifier Q> | |
| 1022 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator^(vec<4, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 1023 | { | |
| 1024 | return vec<4, T, Q>(v1) ^= v2.x; | |
| 1025 | } | |
| 1026 | ||
| 1027 | template<typename T, qualifier Q> | |
| 1028 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator^(T scalar, vec<4, T, Q> const& v) | |
| 1029 | { | |
| 1030 | return vec<4, T, Q>(scalar) ^= v; | |
| 1031 | } | |
| 1032 | ||
| 1033 | template<typename T, qualifier Q> | |
| 1034 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator^(vec<1, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 1035 | { | |
| 1036 | return vec<4, T, Q>(v1.x) ^= v2; | |
| 1037 | } | |
| 1038 | ||
| 1039 | template<typename T, qualifier Q> | |
| 1040 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator^(vec<4, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 1041 | { | |
| 1042 | return vec<4, T, Q>(v1) ^= v2; | |
| 1043 | } | |
| 1044 | ||
| 1045 | template<typename T, qualifier Q> | |
| 1046 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator<<(vec<4, T, Q> const& v, T scalar) | |
| 1047 | { | |
| 1048 | return vec<4, T, Q>(v) <<= scalar; | |
| 1049 | } | |
| 1050 | ||
| 1051 | template<typename T, qualifier Q> | |
| 1052 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator<<(vec<4, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 1053 | { | |
| 1054 | return vec<4, T, Q>(v1) <<= v2.x; | |
| 1055 | } | |
| 1056 | ||
| 1057 | template<typename T, qualifier Q> | |
| 1058 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator<<(T scalar, vec<4, T, Q> const& v) | |
| 1059 | { | |
| 1060 | return vec<4, T, Q>(scalar) <<= v; | |
| 1061 | } | |
| 1062 | ||
| 1063 | template<typename T, qualifier Q> | |
| 1064 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator<<(vec<1, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 1065 | { | |
| 1066 | return vec<4, T, Q>(v1.x) <<= v2; | |
| 1067 | } | |
| 1068 | ||
| 1069 | template<typename T, qualifier Q> | |
| 1070 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator<<(vec<4, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 1071 | { | |
| 1072 | return vec<4, T, Q>(v1) <<= v2; | |
| 1073 | } | |
| 1074 | ||
| 1075 | template<typename T, qualifier Q> | |
| 1076 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator>>(vec<4, T, Q> const& v, T scalar) | |
| 1077 | { | |
| 1078 | return vec<4, T, Q>(v) >>= scalar; | |
| 1079 | } | |
| 1080 | ||
| 1081 | template<typename T, qualifier Q> | |
| 1082 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator>>(vec<4, T, Q> const& v1, vec<1, T, Q> const& v2) | |
| 1083 | { | |
| 1084 | return vec<4, T, Q>(v1) >>= v2.x; | |
| 1085 | } | |
| 1086 | ||
| 1087 | template<typename T, qualifier Q> | |
| 1088 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator>>(T scalar, vec<4, T, Q> const& v) | |
| 1089 | { | |
| 1090 | return vec<4, T, Q>(scalar) >>= v; | |
| 1091 | } | |
| 1092 | ||
| 1093 | template<typename T, qualifier Q> | |
| 1094 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator>>(vec<1, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 1095 | { | |
| 1096 | return vec<4, T, Q>(v1.x) >>= v2; | |
| 1097 | } | |
| 1098 | ||
| 1099 | template<typename T, qualifier Q> | |
| 1100 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator>>(vec<4, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 1101 | { | |
| 1102 | return vec<4, T, Q>(v1) >>= v2; | |
| 1103 | } | |
| 1104 | ||
| 1105 | template<typename T, qualifier Q> | |
| 1106 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, T, Q> operator~(vec<4, T, Q> const& v) | |
| 1107 | { | |
| 1108 | return detail::compute_vec4_bitwise_not<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(v); | |
| 1109 | } | |
| 1110 | ||
| 1111 | // -- Boolean operators -- | |
| 1112 | ||
| 1113 | template<typename T, qualifier Q> | |
| 1114 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR bool operator==(vec<4, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 1115 | { | |
| 1116 | return detail::compute_vec4_equal<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(v1, v2); | |
| 1117 | } | |
| 1118 | ||
| 1119 | template<typename T, qualifier Q> | |
| 1120 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR bool operator!=(vec<4, T, Q> const& v1, vec<4, T, Q> const& v2) | |
| 1121 | { | |
| 1122 | return detail::compute_vec4_nequal<T, Q, detail::is_int<T>::value, sizeof(T) * 8, detail::is_aligned<Q>::value>::call(v1, v2); | |
| 1123 | } | |
| 1124 | ||
| 1125 | template<qualifier Q> | |
| 1126 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, bool, Q> operator&&(vec<4, bool, Q> const& v1, vec<4, bool, Q> const& v2) | |
| 1127 | { | |
| 1128 | return vec<4, bool, Q>(v1.x && v2.x, v1.y && v2.y, v1.z && v2.z, v1.w && v2.w); | |
| 1129 | } | |
| 1130 | ||
| 1131 | template<qualifier Q> | |
| 1132 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<4, bool, Q> operator||(vec<4, bool, Q> const& v1, vec<4, bool, Q> const& v2) | |
| 1133 | { | |
| 1134 | return vec<4, bool, Q>(v1.x || v2.x, v1.y || v2.y, v1.z || v2.z, v1.w || v2.w); | |
| 1135 | } | |
| 1136 | }//namespace glm | |
| 1137 | ||
| 1138 | #if GLM_CONFIG_SIMD == GLM_ENABLE | |
| 1139 | # include "type_vec4_simd.inl" | |
| 1140 | #endif |
| 1 | #ifndef SHADERSH | |
| 2 | #define SHADERSH | |
| 3 | ||
| 4 | #include "glm.hpp" | |
| 5 | #include "model.h" | |
| 6 | #include "gtc/matrix_transform.hpp" | |
| 7 | #include "gtc/matrix_access.hpp" | |
| 8 | #include "gtc/matrix_inverse.hpp" | |
| 9 | #include "light.h" | |
| 10 | #include "defines.h" | |
| 11 | #include "rayimage.h" | |
| 12 | ||
| 13 | #include "material.h" | |
| 14 | ||
| 15 | ! | static void get_sphere_uv(const vec3& dir, vec2& uv) { |
| 16 | ! | Float phi = atan2(dir.z, dir.x); |
| 17 | ! | Float theta = asin(dir.y); |
| 18 | ! | uv.x = 1 - (phi + M_PI) / (2*M_PI); |
| 19 | ! | uv.y = (theta + M_PI/2) / M_PI; |
| 20 | } | |
| 21 | ||
| 22 | ||
| 23 | class IShader { | |
| 24 | public: | |
| 25 | virtual vec4 vertex(int iface, int nthvert, ModelInfo& model) = 0; | |
| 26 | virtual bool fragment(vec3& bc, vec4 &color, vec3& pos, vec3& normal, int iface) = 0; | |
| 27 | virtual ~IShader(); | |
| 28 | virtual int get_culling() = 0; | |
| 29 | virtual bool is_translucent() = 0; | |
| 30 | }; | |
| 31 | ||
| 32 | ||
| 33 | ||
| 34 | class GouraudShader : public IShader { | |
| 35 | public: | |
| 36 | GouraudShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, | |
| 37 | bool has_shadow_map, Float shadow_map_bias, | |
| 38 | material_info mat_info, std::vector<Light>& point_lights, | |
| 39 | std::vector<DirectionalLight> directional_lights, | |
| 40 | std::vector<rayimage>& shadowbuffers, | |
| 41 | std::vector<rayimage>& transparency_buffers, | |
| 42 | std::vector<vec3>& vec_varying_intensity, | |
| 43 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 44 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 45 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 46 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 47 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 48 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 49 | reflection_map_info reflection_map, bool has_reflection, bool has_refraction); | |
| 50 | ~GouraudShader(); | |
| 51 | ||
| 52 | virtual vec4 vertex(int iface, int nthvert, ModelInfo& model); | |
| 53 | virtual bool fragment(vec3& bc, vec4 &color, vec3& pos, vec3& normal, int iface); | |
| 54 | vec3 specular(vec3 uv) { | |
| 55 | return(has_specular_texture ? material.specular_intensity * trivalue(uv.x,uv.y,specular_texture, nx_st, ny_st, nn_st) : material.specular_intensity * material.specular); | |
| 56 | } | |
| 57 | vec4 emissive(vec3 uv) { | |
| 58 | return(has_emissive_texture ? material.emission_intensity * | |
| 59 | trivalue(uv.x,uv.y,emissive_texture, nx_et, ny_et, nn_et) : vec4(0.0f)); | |
| 60 | } | |
| 61 | vec3 normal_uv(vec3 uv) { | |
| 62 | return(trivalue(uv.x, uv.y, normal_texture, nx_nt, ny_nt, nn_nt)*(Float)2 - (Float)1); | |
| 63 | } | |
| 64 | vec4 diffuse(vec3 uv) { | |
| 65 | return(has_texture ? vec4(material.diffuse_intensity,material.diffuse_intensity,material.diffuse_intensity,material.dissolve) * trivalue(uv.x,uv.y,texture, nx_t, ny_t, nn_t) : vec4(material.diffuse * material.diffuse_intensity,material.dissolve)); | |
| 66 | } | |
| 67 | vec3 ambient(vec3 uv) { | |
| 68 | return(material.has_ambient_texture ? | |
| 69 | material.ambient * material.ambient_intensity * vec3(trivalue(uv.x,uv.y,ambient_texture, nx_a, ny_a, nn_a)) : | |
| 70 | vec4(material.ambient * material.ambient_intensity,0.0f)); | |
| 71 | } | |
| 72 | ! | vec4 reflection(vec3 norm) { |
| 73 | ! | norm = glm::normalize(norm); |
| 74 | vec2 uv; | |
| 75 | ! | get_sphere_uv(norm, uv); |
| 76 | ! | uv.x = 1 - uv.x; |
| 77 | ! | uv.x += 0.25; |
| 78 | ! | return(trivalue(uv.x, uv.y, reflection_map)); |
| 79 | } | |
| 80 | ! | int get_culling() { |
| 81 | ! | return(material.cull_type); |
| 82 | } | |
| 83 | ! | bool is_translucent() { |
| 84 | ! | return(material.translucent); |
| 85 | } | |
| 86 | ||
| 87 | Mat Model; | |
| 88 | Mat Projection; | |
| 89 | Mat View; | |
| 90 | Mat MVP; | |
| 91 | Mat vp; | |
| 92 | Mat uniform_Mshadow; | |
| 93 | Mat uniform_M; // Projection*ModelView | |
| 94 | Mat uniform_MIT; // (Projection*ModelView).invert_transpose() | |
| 95 | Mat uniform_M_inv; | |
| 96 | Mat uniform_MIT_inv; | |
| 97 | vec4 viewport; | |
| 98 | vec3 light_dir; | |
| 99 | vec3 l; | |
| 100 | ||
| 101 | bool has_shadow_map; | |
| 102 | Float shadow_map_bias; | |
| 103 | material_info material; | |
| 104 | ||
| 105 | int nx_t, ny_t, nn_t, nx_a, ny_a, nn_a, nx_nt, ny_nt, nn_nt, nx_st, ny_st, nn_st, nx_et, ny_et, nn_et; | |
| 106 | float* texture; | |
| 107 | float* ambient_texture; | |
| 108 | float* normal_texture; | |
| 109 | float* specular_texture; | |
| 110 | float* emissive_texture; | |
| 111 | ||
| 112 | bool has_texture, has_normal_texture, has_specular_texture, has_emissive_texture; | |
| 113 | bool has_normals; | |
| 114 | std::vector<Light>& plights; | |
| 115 | ||
| 116 | std::vector<DirectionalLight> directional_lights; | |
| 117 | std::vector<rayimage>& shadowbuffers; | |
| 118 | std::vector<rayimage>& transparency_buffers; | |
| 119 | ||
| 120 | std::vector<vec3>& vec_varying_intensity; | |
| 121 | std::vector<std::vector<vec3> >& vec_varying_uv; | |
| 122 | std::vector<std::vector<vec4> >& vec_varying_tri; | |
| 123 | std::vector<std::vector<vec3> >& vec_varying_pos; | |
| 124 | std::vector<std::vector<vec3> >& vec_varying_world_nrm; | |
| 125 | ||
| 126 | reflection_map_info reflection_map; | |
| 127 | bool has_reflection; | |
| 128 | bool has_refraction; | |
| 129 | ||
| 130 | }; | |
| 131 | ||
| 132 | ||
| 133 | class ColorShader : public IShader { | |
| 134 | public: | |
| 135 | ColorShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, | |
| 136 | material_info mat_info, | |
| 137 | std::vector<vec3>& vec_varying_intensity, | |
| 138 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 139 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 140 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 141 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 142 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 143 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 144 | reflection_map_info reflection_map, bool has_reflection, bool has_refraction); | |
| 145 | ~ColorShader(); | |
| 146 | ||
| 147 | virtual vec4 vertex(int iface, int nthvert, ModelInfo& model); | |
| 148 | virtual bool fragment(vec3& bc,vec4 &color, vec3& pos, vec3& normal, int iface); | |
| 149 | vec3 specular(vec3 uv) { | |
| 150 | return(has_specular_texture ? material.specular_intensity * trivalue(uv.x,uv.y,specular_texture, nx_st, ny_st, nn_st) : material.specular_intensity * material.specular); | |
| 151 | } | |
| 152 | ! | vec4 emissive(vec3 uv) { |
| 153 | ! | return(has_emissive_texture ? material.emission_intensity * |
| 154 | ! | trivalue(uv.x,uv.y,emissive_texture, nx_et, ny_et, nn_et) : vec4(0.0f)); |
| 155 | } | |
| 156 | vec3 normal_uv(vec3 uv) { | |
| 157 | return(trivalue(uv.x, uv.y, normal_texture, nx_nt, ny_nt, nn_nt)*(Float)2 - (Float)1); | |
| 158 | } | |
| 159 | ! | vec4 diffuse(vec3 uv) { |
| 160 | ! | return(has_texture ? |
| 161 | ! | material.diffuse_intensity * vec4(1.0,1.0,1.0, material.dissolve) * trivalue(uv.x,uv.y,texture, nx_t, ny_t, nn_t) : |
| 162 | ! | vec4(material.diffuse * material.diffuse_intensity, material.dissolve)); |
| 163 | } | |
| 164 | ! | vec4 ambient(vec3 uv) { |
| 165 | ! | return(material.has_ambient_texture ? |
| 166 | ! | vec4(material.ambient * material.ambient_intensity,0.0f) * trivalue(uv.x,uv.y,ambient_texture, nx_a, ny_a, nn_a) : |
| 167 | ! | vec4(material.ambient * material.ambient_intensity,0.0f)); |
| 168 | } | |
| 169 | ! | vec4 reflection(vec3 norm) { |
| 170 | ! | norm = glm::normalize(norm); |
| 171 | vec2 uv; | |
| 172 | ! | get_sphere_uv(norm, uv); |
| 173 | ! | uv.x = 1 - uv.x; |
| 174 | ! | uv.x += 0.25; |
| 175 | ! | return(trivalue(uv.x, uv.y, reflection_map)); |
| 176 | } | |
| 177 | ! | int get_culling() { |
| 178 | ! | return(material.cull_type); |
| 179 | } | |
| 180 | ! | bool is_translucent() { |
| 181 | ! | return(material.translucent); |
| 182 | } | |
| 183 | ||
| 184 | Mat Model; | |
| 185 | Mat Projection; | |
| 186 | Mat View; | |
| 187 | Mat MVP; | |
| 188 | Mat vp; | |
| 189 | Mat uniform_M; | |
| 190 | Mat uniform_MIT; | |
| 191 | Mat uniform_M_inv; | |
| 192 | Mat uniform_MIT_inv; | |
| 193 | vec4 viewport; | |
| 194 | ||
| 195 | material_info material; | |
| 196 | ||
| 197 | int nx_t, ny_t, nn_t, nx_a, ny_a, nn_a, nx_nt, ny_nt, nn_nt, nx_st, ny_st, nn_st, nx_et, ny_et, nn_et; | |
| 198 | float* texture; | |
| 199 | float* ambient_texture; | |
| 200 | float* normal_texture; | |
| 201 | float* specular_texture; | |
| 202 | float* emissive_texture; | |
| 203 | ||
| 204 | bool has_texture, has_normal_texture, has_specular_texture, has_emissive_texture; | |
| 205 | ||
| 206 | std::vector<std::vector<vec3> >& vec_varying_uv; | |
| 207 | std::vector<std::vector<vec4> >& vec_varying_tri; | |
| 208 | std::vector<std::vector<vec3> >& vec_varying_pos; | |
| 209 | std::vector<std::vector<vec3> >& vec_varying_world_nrm; | |
| 210 | ||
| 211 | reflection_map_info reflection_map; | |
| 212 | bool has_reflection; | |
| 213 | bool has_refraction; | |
| 214 | ||
| 215 | }; | |
| 216 | ||
| 217 | class DiffuseShader : public IShader { | |
| 218 | public: | |
| 219 | DiffuseShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, | |
| 220 | bool has_shadow_map, Float shadow_map_bias, | |
| 221 | material_info mat_info, std::vector<Light>& point_lights, | |
| 222 | std::vector<DirectionalLight> directional_lights, | |
| 223 | std::vector<rayimage>& shadowbuffers, | |
| 224 | std::vector<rayimage>& transparency_buffers, | |
| 225 | std::vector<vec3>& vec_varying_intensity, | |
| 226 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 227 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 228 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 229 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 230 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 231 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 232 | reflection_map_info reflection_map, bool has_reflection, bool has_refraction, | |
| 233 | bool two_sided); | |
| 234 | ~DiffuseShader(); | |
| 235 | ||
| 236 | virtual vec4 vertex(int iface, int nthvert, ModelInfo& model); | |
| 237 | virtual bool fragment(vec3& bc,vec4 &color, vec3& pos, vec3& normal, int iface); | |
| 238 | vec3 specular(vec3 uv) { | |
| 239 | return(has_specular_texture ? material.specular_intensity * trivalue(uv.x,uv.y,specular_texture, nx_st, ny_st, nn_st) : material.specular_intensity * material.specular); | |
| 240 | } | |
| 241 | 666476x | vec4 emissive(vec3 uv) { |
| 242 | 666476x | return(has_emissive_texture ? material.emission_intensity * |
| 243 | 1332952x | trivalue(uv.x,uv.y,emissive_texture, nx_et, ny_et, nn_et) : vec4(0.0f)); |
| 244 | } | |
| 245 | vec3 normal_uv(vec3 uv) { | |
| 246 | return(trivalue(uv.x, uv.y, normal_texture, nx_nt, ny_nt, nn_nt)*(Float)2 - (Float)1); | |
| 247 | } | |
| 248 | 666476x | vec4 diffuse(vec3 uv) { |
| 249 | 666476x | return(has_texture ? |
| 250 | 24503x | vec4(material.diffuse * material.diffuse_intensity,material.dissolve) * trivalue(uv.x,uv.y,texture, nx_t, ny_t, nn_t) : |
| 251 | 666476x | vec4(material.diffuse * material.diffuse_intensity,material.dissolve)); |
| 252 | } | |
| 253 | 666476x | vec4 ambient(vec3 uv) { |
| 254 | 666476x | return(material.has_ambient_texture ? |
| 255 | ! | vec4(material.ambient * material.ambient_intensity,0.0f) * trivalue(uv.x,uv.y,ambient_texture, nx_a, ny_a, nn_a) : |
| 256 | 666476x | vec4(material.ambient * material.ambient_intensity,0.0f)); |
| 257 | } | |
| 258 | ! | vec4 reflection(vec3 norm) { |
| 259 | ! | norm = glm::normalize(norm); |
| 260 | vec2 uv; | |
| 261 | ! | get_sphere_uv(norm, uv); |
| 262 | ! | uv.x = 1 - uv.x; |
| 263 | ! | uv.x += 0.25; |
| 264 | ! | return(trivalue(uv.x, uv.y, reflection_map)); |
| 265 | } | |
| 266 | 290524x | int get_culling() { |
| 267 | 290524x | return(material.cull_type); |
| 268 | } | |
| 269 | 666476x | bool is_translucent() { |
| 270 | 666476x | return(material.translucent); |
| 271 | } | |
| 272 | ||
| 273 | Mat Model; | |
| 274 | Mat Projection; | |
| 275 | Mat View; | |
| 276 | Mat MVP; | |
| 277 | Mat vp; | |
| 278 | Mat uniform_Mshadow; | |
| 279 | Mat uniform_M; | |
| 280 | Mat uniform_MIT; | |
| 281 | Mat uniform_M_inv; | |
| 282 | Mat uniform_MIT_inv; | |
| 283 | ||
| 284 | vec4 viewport; | |
| 285 | ||
| 286 | bool has_shadow_map; | |
| 287 | Float shadow_map_bias; | |
| 288 | material_info material; | |
| 289 | ||
| 290 | int nx_t, ny_t, nn_t, nx_a, ny_a, nn_a, nx_nt, ny_nt, nn_nt, nx_st, ny_st, nn_st, nx_et, ny_et, nn_et; | |
| 291 | float* texture; | |
| 292 | float* ambient_texture; | |
| 293 | float* normal_texture; | |
| 294 | float* specular_texture; | |
| 295 | float* emissive_texture; | |
| 296 | ||
| 297 | bool has_texture, has_normal_texture, has_specular_texture, has_emissive_texture; | |
| 298 | bool has_normals; | |
| 299 | ||
| 300 | std::vector<Light>& plights; | |
| 301 | std::vector<DirectionalLight> directional_lights; | |
| 302 | std::vector<rayimage>& shadowbuffers; | |
| 303 | std::vector<rayimage>& transparency_buffers; | |
| 304 | ||
| 305 | std::vector<vec3>& vec_varying_intensity; | |
| 306 | std::vector<std::vector<vec3> >& vec_varying_uv; | |
| 307 | std::vector<std::vector<vec4> >& vec_varying_tri; | |
| 308 | std::vector<std::vector<vec3> >& vec_varying_pos; | |
| 309 | std::vector<std::vector<vec3> >& vec_varying_world_nrm; | |
| 310 | ||
| 311 | ||
| 312 | reflection_map_info reflection_map; | |
| 313 | bool has_reflection; | |
| 314 | bool has_refraction; | |
| 315 | bool two_sided; | |
| 316 | }; | |
| 317 | ||
| 318 | ||
| 319 | class OrenNayerShader : public IShader { | |
| 320 | public: | |
| 321 | OrenNayerShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, | |
| 322 | bool has_shadow_map, Float shadow_map_bias, | |
| 323 | material_info mat_info, std::vector<Light>& point_lights, | |
| 324 | std::vector<DirectionalLight> directional_lights, | |
| 325 | std::vector<rayimage>& shadowbuffers, | |
| 326 | std::vector<rayimage>& transparency_buffers, | |
| 327 | std::vector<vec3>& vec_varying_intensity, | |
| 328 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 329 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 330 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 331 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 332 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 333 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 334 | reflection_map_info reflection_map, bool has_reflection, bool has_refraction, | |
| 335 | bool two_sided); | |
| 336 | ~OrenNayerShader(); | |
| 337 | ||
| 338 | virtual vec4 vertex(int iface, int nthvert, ModelInfo& model); | |
| 339 | virtual bool fragment(vec3& bc,vec4 &color, vec3& pos, vec3& normal, int iface); | |
| 340 | vec3 specular(vec3 uv) { | |
| 341 | return(has_specular_texture ? material.specular_intensity * trivalue(uv.x,uv.y,specular_texture, nx_st, ny_st, nn_st) : material.specular_intensity * material.specular); | |
| 342 | } | |
| 343 | ! | vec4 emissive(vec3 uv) { |
| 344 | ! | return(has_emissive_texture ? material.emission_intensity * |
| 345 | ! | trivalue(uv.x,uv.y,emissive_texture, nx_et, ny_et, nn_et) : vec4(0.0f)); |
| 346 | } | |
| 347 | vec3 normal_uv(vec3 uv) { | |
| 348 | return(trivalue(uv.x, uv.y, normal_texture, nx_nt, ny_nt, nn_nt)*(Float)2 - (Float)1); | |
| 349 | } | |
| 350 | ! | vec4 diffuse(vec3 uv) { |
| 351 | ! | return(has_texture ? |
| 352 | ! | vec4(material.diffuse * material.diffuse_intensity,material.dissolve) * trivalue(uv.x,uv.y,texture, nx_t, ny_t, nn_t) : |
| 353 | ! | vec4(material.diffuse * material.diffuse_intensity,material.dissolve)); |
| 354 | } | |
| 355 | ! | vec4 ambient(vec3 uv) { |
| 356 | ! | return(material.has_ambient_texture ? |
| 357 | ! | vec4(material.ambient * material.ambient_intensity,0.0f) * trivalue(uv.x,uv.y,ambient_texture, nx_a, ny_a, nn_a) : |
| 358 | ! | vec4(material.ambient * material.ambient_intensity,0.0f)); |
| 359 | } | |
| 360 | ! | vec4 reflection(vec3 norm) { |
| 361 | ! | norm = glm::normalize(norm); |
| 362 | vec2 uv; | |
| 363 | ! | get_sphere_uv(norm, uv); |
| 364 | ! | uv.x = 1 - uv.x; |
| 365 | ! | uv.x += 0.25; |
| 366 | ! | return(trivalue(uv.x, uv.y, reflection_map)); |
| 367 | } | |
| 368 | ! | int get_culling() { |
| 369 | ! | return(material.cull_type); |
| 370 | } | |
| 371 | ! | bool is_translucent() { |
| 372 | ! | return(material.translucent); |
| 373 | } | |
| 374 | ||
| 375 | Mat Model; | |
| 376 | Mat Projection; | |
| 377 | Mat View; | |
| 378 | Mat MVP; | |
| 379 | Mat vp; | |
| 380 | Mat uniform_Mshadow; | |
| 381 | Mat uniform_M; | |
| 382 | Mat uniform_MIT; | |
| 383 | Mat uniform_M_inv; | |
| 384 | Mat uniform_MIT_inv; | |
| 385 | ||
| 386 | vec4 viewport; | |
| 387 | ||
| 388 | bool has_shadow_map; | |
| 389 | Float shadow_map_bias; | |
| 390 | material_info material; | |
| 391 | ||
| 392 | int nx_t, ny_t, nn_t, nx_a, ny_a, nn_a, nx_nt, ny_nt, nn_nt, nx_st, ny_st, nn_st, nx_et, ny_et, nn_et; | |
| 393 | float* texture; | |
| 394 | float* ambient_texture; | |
| 395 | float* normal_texture; | |
| 396 | float* specular_texture; | |
| 397 | float* emissive_texture; | |
| 398 | ||
| 399 | bool has_texture, has_normal_texture, has_specular_texture, has_emissive_texture; | |
| 400 | bool has_normals; | |
| 401 | ||
| 402 | std::vector<Light>& plights; | |
| 403 | std::vector<DirectionalLight> directional_lights; | |
| 404 | std::vector<rayimage>& shadowbuffers; | |
| 405 | std::vector<rayimage>& transparency_buffers; | |
| 406 | ||
| 407 | std::vector<vec3>& vec_varying_intensity; | |
| 408 | std::vector<std::vector<vec3> >& vec_varying_uv; | |
| 409 | std::vector<std::vector<vec4> >& vec_varying_tri; | |
| 410 | std::vector<std::vector<vec3> >& vec_varying_pos; | |
| 411 | std::vector<std::vector<vec3> >& vec_varying_world_nrm; | |
| 412 | ||
| 413 | ||
| 414 | reflection_map_info reflection_map; | |
| 415 | bool has_reflection; | |
| 416 | bool has_refraction; | |
| 417 | bool two_sided; | |
| 418 | Float A, B; | |
| 419 | }; | |
| 420 | ||
| 421 | class DiffuseNormalShader : public IShader { | |
| 422 | public: | |
| 423 | DiffuseNormalShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, | |
| 424 | bool has_shadow_map, Float shadow_map_bias, | |
| 425 | material_info mat_info, std::vector<Light>& point_lights, | |
| 426 | std::vector<DirectionalLight> directional_lights, | |
| 427 | std::vector<rayimage>& shadowbuffers, | |
| 428 | std::vector<rayimage>& transparency_buffers, | |
| 429 | std::vector<vec3>& vec_varying_intensity, | |
| 430 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 431 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 432 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 433 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 434 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 435 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 436 | reflection_map_info reflection_map, bool has_reflection, bool has_refraction); | |
| 437 | ~DiffuseNormalShader(); | |
| 438 | virtual vec4 vertex(int iface, int nthvert, ModelInfo& model); | |
| 439 | virtual bool fragment(vec3& bc,vec4 &color, vec3& pos, vec3& normal, int iface); | |
| 440 | vec3 specular(vec3 uv) { | |
| 441 | return(has_specular_texture ? material.specular_intensity * trivalue(uv.x,uv.y,specular_texture, nx_st, ny_st, nn_st) : material.specular_intensity * material.specular); | |
| 442 | } | |
| 443 | ! | vec4 emissive(vec3 uv) { |
| 444 | ! | return(has_emissive_texture ? material.emission_intensity * |
| 445 | ! | trivalue(uv.x,uv.y,emissive_texture, nx_et, ny_et, nn_et) : vec4(0.0f)); |
| 446 | } | |
| 447 | ! | vec3 normal_uv(vec3 uv) { |
| 448 | ! | return(trivalue(uv.x, uv.y, normal_texture, nx_nt, ny_nt, nn_nt)*(Float)2 - (Float)1); |
| 449 | } | |
| 450 | ! | vec4 diffuse(vec3 uv) { |
| 451 | ! | return(has_texture ? vec4(material.diffuse * material.diffuse_intensity,material.dissolve) * trivalue(uv.x,uv.y,texture, nx_t, ny_t, nn_t) : |
| 452 | ! | vec4(material.diffuse * material.diffuse_intensity,material.dissolve)); |
| 453 | } | |
| 454 | ! | vec4 ambient(vec3 uv) { |
| 455 | ! | return(material.has_ambient_texture ? |
| 456 | ! | vec4(material.ambient * material.ambient_intensity,0.0f) * trivalue(uv.x,uv.y,ambient_texture, nx_a, ny_a, nn_a) : |
| 457 | ! | vec4(material.ambient * material.ambient_intensity,0.0f)); |
| 458 | } | |
| 459 | ! | vec4 reflection(vec3 norm) { |
| 460 | ! | norm = glm::normalize(norm); |
| 461 | vec2 uv; | |
| 462 | ! | get_sphere_uv(norm, uv); |
| 463 | ! | uv.x = 1 - uv.x; |
| 464 | ! | uv.x += 0.25; |
| 465 | ! | return(trivalue(uv.x, uv.y, reflection_map)); |
| 466 | } | |
| 467 | ! | int get_culling() { |
| 468 | ! | return(material.cull_type); |
| 469 | } | |
| 470 | ! | bool is_translucent() { |
| 471 | ! | return(material.translucent); |
| 472 | } | |
| 473 | Mat Model; | |
| 474 | Mat Projection; | |
| 475 | Mat View; | |
| 476 | Mat MVP; | |
| 477 | Mat vp; | |
| 478 | Mat uniform_Mshadow; | |
| 479 | Mat uniform_M; // Projection*ModelView | |
| 480 | Mat uniform_MIT; // (Projection*ModelView).invert_transpose() | |
| 481 | Mat uniform_M_inv; | |
| 482 | Mat uniform_MIT_inv; | |
| 483 | vec4 viewport; | |
| 484 | ||
| 485 | bool has_shadow_map; | |
| 486 | Float shadow_map_bias; | |
| 487 | material_info material; | |
| 488 | ||
| 489 | ||
| 490 | int nx_t, ny_t, nn_t, nx_a, ny_a, nn_a, nx_nt, ny_nt, nn_nt, nx_st, ny_st, nn_st, nx_et, ny_et, nn_et; | |
| 491 | float* texture; | |
| 492 | float* ambient_texture; | |
| 493 | float* normal_texture; | |
| 494 | float* specular_texture; | |
| 495 | float* emissive_texture; | |
| 496 | ||
| 497 | bool has_texture, has_normal_texture, has_specular_texture, has_emissive_texture; | |
| 498 | bool has_normals; | |
| 499 | ||
| 500 | std::vector<Light>& plights; | |
| 501 | std::vector<DirectionalLight> directional_lights; | |
| 502 | std::vector<rayimage>& shadowbuffers; | |
| 503 | std::vector<rayimage>& transparency_buffers; | |
| 504 | ||
| 505 | std::vector<std::vector<vec3> >& vec_varying_uv; | |
| 506 | std::vector<std::vector<vec4> >& vec_varying_tri; | |
| 507 | std::vector<std::vector<vec3> >& vec_varying_pos; | |
| 508 | std::vector<std::vector<vec3> >& vec_varying_world_nrm; | |
| 509 | ||
| 510 | ||
| 511 | reflection_map_info reflection_map; | |
| 512 | bool has_reflection; | |
| 513 | bool has_refraction; | |
| 514 | ||
| 515 | }; | |
| 516 | ||
| 517 | class DiffuseShaderTangent : public IShader { | |
| 518 | public: | |
| 519 | DiffuseShaderTangent(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, | |
| 520 | ||
| 521 | bool has_shadow_map, Float shadow_map_bias, | |
| 522 | material_info mat_info, std::vector<Light>& point_lights, | |
| 523 | std::vector<DirectionalLight> directional_lights, | |
| 524 | std::vector<rayimage>& shadowbuffers, | |
| 525 | std::vector<rayimage>& transparency_buffers, | |
| 526 | std::vector<vec3>& vec_varying_intensity, | |
| 527 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 528 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 529 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 530 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 531 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 532 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 533 | reflection_map_info reflection_map, bool has_reflection, bool has_refraction); | |
| 534 | ~DiffuseShaderTangent(); | |
| 535 | vec3 specular(vec3 uv) { | |
| 536 | return(has_specular_texture ? material.specular_intensity * trivalue(uv.x,uv.y,specular_texture, nx_st, ny_st, nn_st) : material.specular_intensity * material.specular); | |
| 537 | } | |
| 538 | ! | vec4 emissive(vec3 uv) { |
| 539 | ! | return(has_emissive_texture ? material.emission_intensity * |
| 540 | ! | trivalue(uv.x,uv.y,emissive_texture, nx_et, ny_et, nn_et) : vec4(0.0f)); |
| 541 | } | |
| 542 | ! | vec3 normal_uv(vec3 uv) { |
| 543 | ! | return(trivalue(uv.x, uv.y, normal_texture, nx_nt, ny_nt, nn_nt)*(Float)2 - (Float)1); |
| 544 | } | |
| 545 | ! | vec4 diffuse(vec3 uv) { |
| 546 | ! | return(has_texture ? vec4(material.diffuse * material.diffuse_intensity,material.dissolve) * trivalue(uv.x,uv.y,texture, nx_t, ny_t, nn_t) : |
| 547 | ! | vec4(material.diffuse * material.diffuse_intensity,material.dissolve)); |
| 548 | } | |
| 549 | ! | vec4 ambient(vec3 uv) { |
| 550 | ! | return(material.has_ambient_texture ? |
| 551 | ! | vec4(material.ambient * material.ambient_intensity,0.0f) * trivalue(uv.x,uv.y,ambient_texture, nx_a, ny_a, nn_a) : |
| 552 | ! | vec4(material.ambient * material.ambient_intensity,0.0f)); |
| 553 | } | |
| 554 | ! | vec4 reflection(vec3 norm) { |
| 555 | ! | norm = glm::normalize(norm); |
| 556 | vec2 uv; | |
| 557 | ! | get_sphere_uv(norm, uv); |
| 558 | ! | uv.x = 1 - uv.x; |
| 559 | ! | uv.x += 0.25; |
| 560 | ! | return(trivalue(uv.x, uv.y, reflection_map)); |
| 561 | } | |
| 562 | ! | int get_culling() { |
| 563 | ! | return(material.cull_type); |
| 564 | } | |
| 565 | ! | bool is_translucent() { |
| 566 | ! | return(material.translucent); |
| 567 | } | |
| 568 | virtual vec4 vertex(int iface, int nthvert, ModelInfo& model); | |
| 569 | virtual bool fragment(vec3& bc,vec4 &color, vec3& pos, vec3& normal, int iface); | |
| 570 | ||
| 571 | Mat Model; | |
| 572 | Mat Projection; | |
| 573 | Mat View; | |
| 574 | Mat MVP; | |
| 575 | Mat vp; | |
| 576 | Mat uniform_Mshadow; | |
| 577 | vec4 viewport; | |
| 578 | ||
| 579 | ||
| 580 | Mat uniform_M; // Projection*ModelView | |
| 581 | Mat uniform_MIT; // (Projection*ModelView).invert_transpose() | |
| 582 | Mat uniform_M_inv; | |
| 583 | Mat uniform_MIT_inv; | |
| 584 | ||
| 585 | bool has_shadow_map; | |
| 586 | Float shadow_map_bias; | |
| 587 | material_info material; | |
| 588 | ||
| 589 | int nx_t, ny_t, nn_t, nx_a, ny_a, nn_a, nx_nt, ny_nt, nn_nt, nx_st, ny_st, nn_st, nx_et, ny_et, nn_et; | |
| 590 | float* texture; | |
| 591 | float* ambient_texture; | |
| 592 | float* normal_texture; | |
| 593 | float* specular_texture; | |
| 594 | float* emissive_texture; | |
| 595 | ||
| 596 | bool has_texture, has_normal_texture, has_specular_texture, has_emissive_texture; | |
| 597 | bool has_normals; | |
| 598 | ||
| 599 | std::vector<Light>& plights; | |
| 600 | std::vector<DirectionalLight> directional_lights; | |
| 601 | std::vector<rayimage>& shadowbuffers; | |
| 602 | std::vector<rayimage>& transparency_buffers; | |
| 603 | ||
| 604 | std::vector<vec3>& vec_varying_intensity; | |
| 605 | std::vector<std::vector<vec3> >& vec_varying_uv; | |
| 606 | std::vector<std::vector<vec4> >& vec_varying_tri; | |
| 607 | std::vector<std::vector<vec3> >& vec_varying_pos; | |
| 608 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri; | |
| 609 | std::vector<std::vector<vec3> >& vec_varying_world_nrm; | |
| 610 | std::vector<std::vector<vec3> >& vec_varying_nrm; | |
| 611 | ||
| 612 | ||
| 613 | reflection_map_info reflection_map; | |
| 614 | bool has_reflection; | |
| 615 | bool has_refraction; | |
| 616 | ||
| 617 | }; | |
| 618 | ||
| 619 | class PhongShader : public IShader { | |
| 620 | public: | |
| 621 | PhongShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, | |
| 622 | bool has_shadow_map, Float shadow_map_bias, | |
| 623 | material_info mat_info, std::vector<Light>& point_lights, | |
| 624 | std::vector<DirectionalLight> directional_lights, | |
| 625 | std::vector<rayimage>& shadowbuffers, | |
| 626 | std::vector<rayimage>& transparency_buffers, | |
| 627 | std::vector<vec3>& vec_varying_intensity, | |
| 628 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 629 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 630 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 631 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 632 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 633 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 634 | reflection_map_info reflection_map, bool has_reflection, bool has_refraction); | |
| 635 | ~PhongShader(); | |
| 636 | ||
| 637 | virtual vec4 vertex(int iface, int nthvert, ModelInfo& model); | |
| 638 | virtual bool fragment(vec3& bc,vec4 &color, vec3& pos, vec3& normal, int iface); | |
| 639 | ! | vec3 specular(vec3 uv) { |
| 640 | ! | return(has_specular_texture ? material.specular_intensity * trivalue(uv.x,uv.y,specular_texture, nx_st, ny_st, nn_st) : |
| 641 | ! | material.specular_intensity * material.specular); |
| 642 | } | |
| 643 | ! | vec4 emissive(vec3 uv) { |
| 644 | ! | return(has_emissive_texture ? material.emission_intensity * |
| 645 | ! | trivalue(uv.x,uv.y,emissive_texture, nx_et, ny_et, nn_et) : vec4(0.0f)); |
| 646 | } | |
| 647 | vec3 normal_uv(vec3 uv) { | |
| 648 | return(trivalue(uv.x, uv.y, normal_texture, nx_nt, ny_nt, nn_nt)*(Float)2 - (Float)1); | |
| 649 | } | |
| 650 | ! | vec4 diffuse(vec3 uv) { |
| 651 | ! | return(has_texture ? vec4(material.diffuse * material.diffuse_intensity,material.dissolve) * trivalue(uv.x,uv.y,texture, nx_t, ny_t, nn_t) : |
| 652 | ! | vec4(material.diffuse * material.diffuse_intensity,material.dissolve)); |
| 653 | } | |
| 654 | ! | vec4 ambient(vec3 uv) { |
| 655 | ! | return(material.has_ambient_texture ? |
| 656 | ! | vec4(material.ambient * material.ambient_intensity,0.0f) * trivalue(uv.x,uv.y,ambient_texture, nx_a, ny_a, nn_a) : |
| 657 | ! | vec4(material.ambient * material.ambient_intensity,0.0f)); |
| 658 | } | |
| 659 | ! | vec4 reflection(vec3 norm) { |
| 660 | ! | norm = glm::normalize(norm); |
| 661 | vec2 uv; | |
| 662 | ! | get_sphere_uv(norm, uv); |
| 663 | ! | uv.x = 1 - uv.x; |
| 664 | ! | uv.x += 0.25; |
| 665 | ! | return(trivalue(uv.x, uv.y, reflection_map)); |
| 666 | } | |
| 667 | ! | int get_culling() { |
| 668 | ! | return(material.cull_type); |
| 669 | } | |
| 670 | ! | bool is_translucent() { |
| 671 | ! | return(material.translucent); |
| 672 | } | |
| 673 | Mat Model; | |
| 674 | Mat Projection; | |
| 675 | Mat View; | |
| 676 | Mat MVP; | |
| 677 | Mat vp; | |
| 678 | Mat uniform_Mshadow; | |
| 679 | vec4 viewport; | |
| 680 | ||
| 681 | Mat uniform_M; // Projection*ModelView | |
| 682 | Mat uniform_MIT; // (Projection*ModelView).invert_transpose() | |
| 683 | Mat uniform_M_inv; | |
| 684 | Mat uniform_MIT_inv; | |
| 685 | ||
| 686 | bool has_shadow_map; | |
| 687 | Float shadow_map_bias; | |
| 688 | material_info material; | |
| 689 | ||
| 690 | int nx_t, ny_t, nn_t, nx_a, ny_a, nn_a, nx_nt, ny_nt, nn_nt, nx_st, ny_st, nn_st, nx_et, ny_et, nn_et; | |
| 691 | float* texture; | |
| 692 | float* ambient_texture; | |
| 693 | float* normal_texture; | |
| 694 | float* specular_texture; | |
| 695 | float* emissive_texture; | |
| 696 | ||
| 697 | bool has_texture, has_normal_texture, has_specular_texture, has_emissive_texture; | |
| 698 | bool has_normals; | |
| 699 | ||
| 700 | std::vector<Light>& plights; | |
| 701 | std::vector<DirectionalLight> directional_lights; | |
| 702 | std::vector<rayimage>& shadowbuffers; | |
| 703 | std::vector<rayimage>& transparency_buffers; | |
| 704 | ||
| 705 | std::vector<vec3>& vec_varying_intensity; | |
| 706 | std::vector<std::vector<vec3> >& vec_varying_uv; | |
| 707 | std::vector<std::vector<vec4> >& vec_varying_tri; | |
| 708 | std::vector<std::vector<vec3> >& vec_varying_nrm; | |
| 709 | std::vector<std::vector<vec3> >& vec_varying_pos; | |
| 710 | std::vector<std::vector<vec3> >& vec_varying_world_nrm; | |
| 711 | ||
| 712 | ||
| 713 | reflection_map_info reflection_map; | |
| 714 | bool has_reflection; | |
| 715 | bool has_refraction; | |
| 716 | ||
| 717 | ||
| 718 | }; | |
| 719 | ||
| 720 | class PhongNormalShader : public IShader { | |
| 721 | public: | |
| 722 | PhongNormalShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, | |
| 723 | ||
| 724 | bool has_shadow_map, Float shadow_map_bias, | |
| 725 | material_info mat_info, std::vector<Light>& point_lights, | |
| 726 | std::vector<DirectionalLight> directional_lights, | |
| 727 | std::vector<rayimage>& shadowbuffers, | |
| 728 | std::vector<rayimage>& transparency_buffers, | |
| 729 | std::vector<vec3>& vec_varying_intensity, | |
| 730 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 731 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 732 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 733 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 734 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 735 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 736 | reflection_map_info reflection_map, bool has_reflection, bool has_refraction); | |
| 737 | ~PhongNormalShader(); | |
| 738 | ||
| 739 | virtual vec4 vertex(int iface, int nthvert, ModelInfo& model); | |
| 740 | virtual bool fragment(vec3& bc,vec4 &color, vec3& pos, vec3& normal, int iface); | |
| 741 | ! | vec3 specular(vec3 uv) { |
| 742 | ! | return(has_specular_texture ? material.specular_intensity * trivalue(uv.x,uv.y,specular_texture, nx_st, ny_st, nn_st) : material.specular_intensity * material.specular); |
| 743 | } | |
| 744 | ! | vec4 emissive(vec3 uv) { |
| 745 | ! | return(has_emissive_texture ? material.emission_intensity * |
| 746 | ! | trivalue(uv.x,uv.y,emissive_texture, nx_et, ny_et, nn_et) : vec4(0.0f)); |
| 747 | } | |
| 748 | ! | vec3 normal_uv(vec3 uv) { |
| 749 | ! | return(trivalue(uv.x, uv.y, normal_texture, nx_nt, ny_nt, nn_nt)*(Float)2 - (Float)1); |
| 750 | } | |
| 751 | ! | vec4 diffuse(vec3 uv) { |
| 752 | ! | return(has_texture ? vec4(material.diffuse * material.diffuse_intensity,material.dissolve) * trivalue(uv.x,uv.y,texture, nx_t, ny_t, nn_t) : |
| 753 | ! | vec4(material.diffuse * material.diffuse_intensity,material.dissolve)); |
| 754 | } | |
| 755 | vec4 ambient(vec3 uv) { | |
| 756 | return(material.has_ambient_texture ? | |
| 757 | vec4(material.ambient * material.ambient_intensity,0.0f) * trivalue(uv.x,uv.y,ambient_texture, nx_a, ny_a, nn_a) : | |
| 758 | vec4(material.ambient * material.ambient_intensity,0.0f)); | |
| 759 | } | |
| 760 | ! | vec4 reflection(vec3 norm) { |
| 761 | ! | norm = glm::normalize(norm); |
| 762 | vec2 uv; | |
| 763 | ! | get_sphere_uv(norm, uv); |
| 764 | ! | uv.x = 1 - uv.x; |
| 765 | ! | uv.x += 0.25; |
| 766 | ! | return(trivalue(uv.x, uv.y, reflection_map)); |
| 767 | } | |
| 768 | ! | int get_culling() { |
| 769 | ! | return(material.cull_type); |
| 770 | } | |
| 771 | ! | bool is_translucent() { |
| 772 | ! | return(material.translucent); |
| 773 | } | |
| 774 | Mat Model; | |
| 775 | Mat Projection; | |
| 776 | Mat View; | |
| 777 | Mat MVP; | |
| 778 | Mat vp; | |
| 779 | Mat uniform_Mshadow; | |
| 780 | Mat uniform_M; // Projection*ModelView | |
| 781 | Mat uniform_MIT; // (Projection*ModelView).invert_transpose() | |
| 782 | Mat uniform_M_inv; | |
| 783 | Mat uniform_MIT_inv; | |
| 784 | vec4 viewport; | |
| 785 | ||
| 786 | bool has_shadow_map; | |
| 787 | Float shadow_map_bias; | |
| 788 | material_info material; | |
| 789 | ||
| 790 | int nx_t, ny_t, nn_t, nx_a, ny_a, nn_a, nx_nt, ny_nt, nn_nt, nx_st, ny_st, nn_st, nx_et, ny_et, nn_et; | |
| 791 | float* texture; | |
| 792 | float* ambient_texture; | |
| 793 | float* normal_texture; | |
| 794 | float* specular_texture; | |
| 795 | float* emissive_texture; | |
| 796 | ||
| 797 | bool has_texture, has_normal_texture, has_specular_texture, has_emissive_texture; | |
| 798 | bool has_normals; | |
| 799 | ||
| 800 | std::vector<Light>& plights; | |
| 801 | std::vector<DirectionalLight> directional_lights; | |
| 802 | std::vector<rayimage>& shadowbuffers; | |
| 803 | std::vector<rayimage>& transparency_buffers; | |
| 804 | ||
| 805 | std::vector<std::vector<vec3> >& vec_varying_uv; | |
| 806 | std::vector<std::vector<vec4> >& vec_varying_tri; | |
| 807 | std::vector<std::vector<vec3> >& vec_varying_pos; | |
| 808 | std::vector<std::vector<vec3> >& vec_varying_world_nrm; | |
| 809 | ||
| 810 | ||
| 811 | reflection_map_info reflection_map; | |
| 812 | bool has_reflection; | |
| 813 | bool has_refraction; | |
| 814 | ||
| 815 | ||
| 816 | }; | |
| 817 | ||
| 818 | class PhongShaderTangent : public IShader { | |
| 819 | public: | |
| 820 | PhongShaderTangent(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, | |
| 821 | ||
| 822 | bool has_shadow_map, Float shadow_map_bias, | |
| 823 | material_info mat_info, std::vector<Light>& point_lights, | |
| 824 | std::vector<DirectionalLight> directional_lights, | |
| 825 | std::vector<rayimage>& shadowbuffers, | |
| 826 | std::vector<rayimage>& transparency_buffers, | |
| 827 | std::vector<vec3>& vec_varying_intensity, | |
| 828 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 829 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 830 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 831 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 832 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 833 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 834 | reflection_map_info reflection_map, bool has_reflection, bool has_refraction); | |
| 835 | ~PhongShaderTangent(); | |
| 836 | ||
| 837 | virtual vec4 vertex(int iface, int nthvert, ModelInfo& model); | |
| 838 | virtual bool fragment(vec3& bc,vec4 &color, vec3& pos, vec3& normal, int iface); | |
| 839 | ! | vec3 specular(vec3 uv) { |
| 840 | ! | return(has_specular_texture ? material.specular_intensity * trivalue(uv.x,uv.y,specular_texture, nx_st, ny_st, nn_st) : |
| 841 | ! | material.specular_intensity * material.specular); |
| 842 | } | |
| 843 | ! | vec4 emissive(vec3 uv) { |
| 844 | ! | return(has_emissive_texture ? material.emission_intensity * |
| 845 | ! | trivalue(uv.x,uv.y,emissive_texture, nx_et, ny_et, nn_et) : vec4(0.0f)); |
| 846 | } | |
| 847 | ! | vec3 normal_uv(vec3 uv) { |
| 848 | ! | return(trivalue(uv.x, uv.y, normal_texture, nx_nt, ny_nt, nn_nt)*(Float)2 - (Float)1); |
| 849 | } | |
| 850 | ! | vec4 diffuse(vec3 uv) { |
| 851 | ! | return(has_texture ? vec4(material.diffuse * material.diffuse_intensity,material.dissolve) * trivalue(uv.x,uv.y,texture, nx_t, ny_t, nn_t) : |
| 852 | ! | vec4(material.diffuse * material.diffuse_intensity,material.dissolve)); |
| 853 | } | |
| 854 | ! | vec4 ambient(vec3 uv) { |
| 855 | ! | return(material.has_ambient_texture ? |
| 856 | ! | vec4(material.ambient * material.ambient_intensity,0.0f) * trivalue(uv.x,uv.y,ambient_texture, nx_a, ny_a, nn_a) : |
| 857 | ! | vec4(material.ambient * material.ambient_intensity,0.0f)); |
| 858 | } | |
| 859 | ! | vec4 reflection(vec3 norm) { |
| 860 | ! | norm = glm::normalize(norm); |
| 861 | vec2 uv; | |
| 862 | ! | get_sphere_uv(norm, uv); |
| 863 | ! | uv.x = 1 - uv.x; |
| 864 | ! | uv.x += 0.25; |
| 865 | ! | return(trivalue(uv.x, uv.y, reflection_map)); |
| 866 | } | |
| 867 | ! | int get_culling() { |
| 868 | ! | return(material.cull_type); |
| 869 | } | |
| 870 | ! | bool is_translucent() { |
| 871 | ! | return(material.translucent); |
| 872 | } | |
| 873 | Mat Model; | |
| 874 | Mat Projection; | |
| 875 | Mat View; | |
| 876 | Mat MVP; | |
| 877 | Mat vp; | |
| 878 | Mat uniform_Mshadow; | |
| 879 | vec4 viewport; | |
| 880 | ||
| 881 | Mat uniform_M; // Projection*ModelView | |
| 882 | Mat uniform_MIT; // (Projection*ModelView).invert_transpose() | |
| 883 | Mat uniform_M_inv; | |
| 884 | Mat uniform_MIT_inv; | |
| 885 | ||
| 886 | bool has_shadow_map; | |
| 887 | Float shadow_map_bias; | |
| 888 | material_info material; | |
| 889 | ||
| 890 | int nx_t, ny_t, nn_t, nx_a, ny_a, nn_a, nx_nt, ny_nt, nn_nt, nx_st, ny_st, nn_st, nx_et, ny_et, nn_et; | |
| 891 | float* texture; | |
| 892 | float* ambient_texture; | |
| 893 | float* normal_texture; | |
| 894 | float* specular_texture; | |
| 895 | float* emissive_texture; | |
| 896 | ||
| 897 | bool has_texture, has_normal_texture, has_specular_texture, has_emissive_texture; | |
| 898 | bool has_normals; | |
| 899 | ||
| 900 | std::vector<Light>& plights; | |
| 901 | std::vector<DirectionalLight> directional_lights; | |
| 902 | std::vector<rayimage>& shadowbuffers; | |
| 903 | std::vector<rayimage>& transparency_buffers; | |
| 904 | ||
| 905 | std::vector<std::vector<vec3> >& vec_varying_uv; | |
| 906 | std::vector<std::vector<vec4> >& vec_varying_tri; | |
| 907 | std::vector<std::vector<vec3> >& vec_varying_pos; | |
| 908 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri; | |
| 909 | std::vector<std::vector<vec3> >& vec_varying_world_nrm; | |
| 910 | std::vector<std::vector<vec3> >& vec_varying_nrm; | |
| 911 | ||
| 912 | ||
| 913 | reflection_map_info reflection_map; | |
| 914 | bool has_reflection; | |
| 915 | bool has_refraction; | |
| 916 | ||
| 917 | }; | |
| 918 | ||
| 919 | // | |
| 920 | //Simple shader just for shadow maps | |
| 921 | // | |
| 922 | ||
| 923 | class DepthShader : public IShader { | |
| 924 | public: | |
| 925 | DepthShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, | |
| 926 | material_info mat_info, int mat_ind, | |
| 927 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 928 | std::vector<std::vector<vec4> >& vec_varying_tri | |
| 929 | ); | |
| 930 | ~DepthShader(); | |
| 931 | ||
| 932 | virtual vec4 vertex(int iface, int nthvert, ModelInfo& model); | |
| 933 | virtual bool fragment(vec3& bc,vec4 &color, vec3& pos, vec3& normal, int iface); | |
| 934 | 166395x | vec4 diffuse(vec3 uv) { |
| 935 | 166395x | return(has_texture ? vec4(material.diffuse * material.diffuse_intensity,material.dissolve) * trivalue(uv.x,uv.y,texture, nx_t, ny_t, nn_t) : |
| 936 | 166395x | vec4(material.diffuse * material.diffuse_intensity,material.dissolve)); |
| 937 | } | |
| 938 | 79328x | int get_culling() { |
| 939 | 79328x | return(material.cull_type); |
| 940 | } | |
| 941 | 166395x | bool is_translucent() { |
| 942 | 166395x | return(material.translucent); |
| 943 | } | |
| 944 | ||
| 945 | Mat Model; | |
| 946 | Mat Projection; | |
| 947 | Mat View; | |
| 948 | Mat MVP; | |
| 949 | Mat vp; | |
| 950 | vec4 viewport; | |
| 951 | ||
| 952 | int nx_t, ny_t, nn_t; | |
| 953 | float* texture; | |
| 954 | ||
| 955 | material_info material; | |
| 956 | ||
| 957 | Float shadow_map_bias; | |
| 958 | bool has_texture; | |
| 959 | ||
| 960 | std::vector<std::vector<vec3> >& vec_varying_uv; | |
| 961 | std::vector<std::vector<vec4> >& vec_varying_tri; | |
| 962 | ||
| 963 | ||
| 964 | }; | |
| 965 | ||
| 966 | ||
| 967 | class ToonShader : public IShader { | |
| 968 | public: | |
| 969 | ToonShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, | |
| 970 | bool has_shadow_map, Float shadow_map_bias, | |
| 971 | material_info mat_info, std::vector<Light>& point_lights, | |
| 972 | std::vector<DirectionalLight> directional_lights, | |
| 973 | std::vector<rayimage>& shadowbuffers, | |
| 974 | std::vector<rayimage>& transparency_buffers, | |
| 975 | std::vector<vec3>& vec_varying_intensity, | |
| 976 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 977 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 978 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 979 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 980 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 981 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 982 | reflection_map_info reflection_map, bool has_reflection, bool has_refraction); | |
| 983 | ~ToonShader(); | |
| 984 | ||
| 985 | virtual vec4 vertex(int iface, int nthvert, ModelInfo& model); | |
| 986 | virtual bool fragment(vec3& bc,vec4 &color, vec3& pos, vec3& normal, int iface); | |
| 987 | vec3 specular(vec3 uv) { | |
| 988 | return(has_specular_texture ? material.specular_intensity * trivalue(uv.x,uv.y,specular_texture, nx_st, ny_st, nn_st) : material.specular_intensity * material.specular); | |
| 989 | } | |
| 990 | ! | vec4 emissive(vec3 uv) { |
| 991 | ! | return(has_emissive_texture ? material.emission_intensity * |
| 992 | ! | trivalue(uv.x,uv.y,emissive_texture, nx_et, ny_et, nn_et) : vec4(0.0f)); |
| 993 | } | |
| 994 | vec3 normal_uv(vec3 uv) { | |
| 995 | return(trivalue(uv.x, uv.y, normal_texture, nx_nt, ny_nt, nn_nt)*(Float)2 - (Float)1); | |
| 996 | } | |
| 997 | ! | vec4 diffuse(vec3 uv) { |
| 998 | ! | return(has_texture ? |
| 999 | ! | vec4(material.diffuse * material.diffuse_intensity,material.dissolve) * trivalue(uv.x,uv.y,texture, nx_t, ny_t, nn_t) : |
| 1000 | ! | vec4(material.diffuse * material.diffuse_intensity,material.dissolve)); |
| 1001 | } | |
| 1002 | ! | vec4 ambient(vec3 uv) { |
| 1003 | ! | return(material.has_ambient_texture ? |
| 1004 | ! | vec4(material.ambient * material.ambient_intensity,0.0f) * trivalue(uv.x,uv.y,ambient_texture, nx_a, ny_a, nn_a) : |
| 1005 | ! | vec4(material.ambient * material.ambient_intensity,0.0f)); |
| 1006 | } | |
| 1007 | vec4 reflection(vec3 norm) { | |
| 1008 | norm = glm::normalize(norm); | |
| 1009 | vec2 uv; | |
| 1010 | get_sphere_uv(norm, uv); | |
| 1011 | uv.x = 1 - uv.x; | |
| 1012 | uv.x += 0.25; | |
| 1013 | return(trivalue(uv.x, uv.y, reflection_map)); | |
| 1014 | } | |
| 1015 | ! | int get_culling() { |
| 1016 | ! | return(material.cull_type); |
| 1017 | } | |
| 1018 | ! | bool is_translucent() { |
| 1019 | ! | return(material.translucent); |
| 1020 | } | |
| 1021 | ||
| 1022 | Mat Model; | |
| 1023 | Mat Projection; | |
| 1024 | Mat View; | |
| 1025 | Mat MVP; | |
| 1026 | Mat vp; | |
| 1027 | Mat uniform_Mshadow; | |
| 1028 | Mat uniform_M; | |
| 1029 | Mat uniform_MIT; | |
| 1030 | Mat uniform_M_inv; | |
| 1031 | Mat uniform_MIT_inv; | |
| 1032 | vec4 viewport; | |
| 1033 | ||
| 1034 | bool has_shadow_map; | |
| 1035 | Float shadow_map_bias; | |
| 1036 | material_info material; | |
| 1037 | ||
| 1038 | int nx_t, ny_t, nn_t, nx_a, ny_a, nn_a, nx_nt, ny_nt, nn_nt, nx_st, ny_st, nn_st, nx_et, ny_et, nn_et; | |
| 1039 | float* texture; | |
| 1040 | float* ambient_texture; | |
| 1041 | float* normal_texture; | |
| 1042 | float* specular_texture; | |
| 1043 | float* emissive_texture; | |
| 1044 | ||
| 1045 | bool has_texture, has_normal_texture, has_specular_texture, has_emissive_texture; | |
| 1046 | bool has_normals; | |
| 1047 | ||
| 1048 | std::vector<Light>& plights; | |
| 1049 | std::vector<DirectionalLight> directional_lights; | |
| 1050 | std::vector<rayimage>& shadowbuffers; | |
| 1051 | std::vector<rayimage>& transparency_buffers; | |
| 1052 | ||
| 1053 | std::vector<vec3>& vec_varying_intensity; | |
| 1054 | std::vector<std::vector<vec3> >& vec_varying_uv; | |
| 1055 | std::vector<std::vector<vec4> >& vec_varying_tri; | |
| 1056 | std::vector<std::vector<vec3> >& vec_varying_pos; | |
| 1057 | std::vector<std::vector<vec3> >& vec_varying_world_nrm; | |
| 1058 | ||
| 1059 | ||
| 1060 | reflection_map_info reflection_map; | |
| 1061 | bool has_reflection; | |
| 1062 | bool has_refraction; | |
| 1063 | ||
| 1064 | }; | |
| 1065 | ||
| 1066 | class ToonShaderPhong : public IShader { | |
| 1067 | public: | |
| 1068 | ToonShaderPhong(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, | |
| 1069 | bool has_shadow_map, Float shadow_map_bias, | |
| 1070 | material_info mat_info, std::vector<Light>& point_lights, | |
| 1071 | std::vector<DirectionalLight> directional_lights, | |
| 1072 | std::vector<rayimage>& shadowbuffers, | |
| 1073 | std::vector<rayimage>& transparency_buffers, | |
| 1074 | std::vector<vec3>& vec_varying_intensity, | |
| 1075 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 1076 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 1077 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 1078 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 1079 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 1080 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 1081 | reflection_map_info reflection_map, bool has_reflection, bool has_refraction); | |
| 1082 | ~ToonShaderPhong(); | |
| 1083 | ||
| 1084 | virtual vec4 vertex(int iface, int nthvert, ModelInfo& model); | |
| 1085 | virtual bool fragment(vec3& bc,vec4 &color, vec3& pos, vec3& normal, int iface); | |
| 1086 | ! | vec3 specular(vec3 uv) { |
| 1087 | ! | return(has_specular_texture ? material.specular_intensity * trivalue(uv.x,uv.y,specular_texture, nx_st, ny_st, nn_st) : material.specular_intensity * material.specular); |
| 1088 | } | |
| 1089 | ! | vec4 emissive(vec3 uv) { |
| 1090 | ! | return(has_emissive_texture ? material.emission_intensity * |
| 1091 | ! | trivalue(uv.x,uv.y,emissive_texture, nx_et, ny_et, nn_et) : vec4(0.0f)); |
| 1092 | } | |
| 1093 | vec3 normal_uv(vec3 uv) { | |
| 1094 | return(trivalue(uv.x, uv.y, normal_texture, nx_nt, ny_nt, nn_nt)*(Float)2 - (Float)1); | |
| 1095 | } | |
| 1096 | ! | vec4 diffuse(vec3 uv) { |
| 1097 | ! | return(has_texture ? |
| 1098 | ! | vec4(material.diffuse * material.diffuse_intensity,material.dissolve) * trivalue(uv.x,uv.y,texture, nx_t, ny_t, nn_t) : |
| 1099 | ! | vec4(material.diffuse * material.diffuse_intensity,material.dissolve)); |
| 1100 | } | |
| 1101 | ! | vec4 ambient(vec3 uv) { |
| 1102 | ! | return(material.has_ambient_texture ? |
| 1103 | ! | vec4(material.ambient * material.ambient_intensity,0.0f) * trivalue(uv.x,uv.y,ambient_texture, nx_a, ny_a, nn_a) : |
| 1104 | ! | vec4(material.ambient * material.ambient_intensity,0.0f)); |
| 1105 | } | |
| 1106 | vec4 reflection(vec3 norm) { | |
| 1107 | norm = glm::normalize(norm); | |
| 1108 | vec2 uv; | |
| 1109 | get_sphere_uv(norm, uv); | |
| 1110 | uv.x = 1 - uv.x; | |
| 1111 | uv.x += 0.25; | |
| 1112 | return(trivalue(uv.x, uv.y, reflection_map)); | |
| 1113 | } | |
| 1114 | ! | int get_culling() { |
| 1115 | ! | return(material.cull_type); |
| 1116 | } | |
| 1117 | ! | bool is_translucent() { |
| 1118 | ! | return(material.translucent); |
| 1119 | } | |
| 1120 | ||
| 1121 | Mat Model; | |
| 1122 | Mat Projection; | |
| 1123 | Mat View; | |
| 1124 | Mat MVP; | |
| 1125 | Mat vp; | |
| 1126 | Mat uniform_Mshadow; | |
| 1127 | Mat uniform_M; | |
| 1128 | Mat uniform_MIT; | |
| 1129 | Mat uniform_M_inv; | |
| 1130 | Mat uniform_MIT_inv; | |
| 1131 | vec4 viewport; | |
| 1132 | ||
| 1133 | bool has_shadow_map; | |
| 1134 | Float shadow_map_bias; | |
| 1135 | material_info material; | |
| 1136 | ||
| 1137 | int nx_t, ny_t, nn_t, nx_a, ny_a, nn_a, nx_nt, ny_nt, nn_nt, nx_st, ny_st, nn_st, nx_et, ny_et, nn_et; | |
| 1138 | float* texture; | |
| 1139 | float* ambient_texture; | |
| 1140 | float* normal_texture; | |
| 1141 | float* specular_texture; | |
| 1142 | float* emissive_texture; | |
| 1143 | ||
| 1144 | bool has_texture, has_normal_texture, has_specular_texture, has_emissive_texture; | |
| 1145 | bool has_normals; | |
| 1146 | ||
| 1147 | std::vector<Light>& plights; | |
| 1148 | std::vector<DirectionalLight> directional_lights; | |
| 1149 | std::vector<rayimage>& shadowbuffers; | |
| 1150 | std::vector<rayimage>& transparency_buffers; | |
| 1151 | ||
| 1152 | std::vector<vec3>& vec_varying_intensity; | |
| 1153 | std::vector<std::vector<vec3> >& vec_varying_uv; | |
| 1154 | std::vector<std::vector<vec4> >& vec_varying_tri; | |
| 1155 | std::vector<std::vector<vec3> >& vec_varying_pos; | |
| 1156 | std::vector<std::vector<vec3> >& vec_varying_world_nrm; | |
| 1157 | ||
| 1158 | ||
| 1159 | reflection_map_info reflection_map; | |
| 1160 | bool has_reflection; | |
| 1161 | bool has_refraction; | |
| 1162 | ||
| 1163 | }; | |
| 1164 | ||
| 1165 | ||
| 1166 | ||
| 1167 | #endif |
| 1 | #ifndef RAYIMAGEH | |
| 2 | #define RAYIMAGEH | |
| 3 | ||
| 4 | #include "glm.hpp" | |
| 5 | #include "Rcpp.h" | |
| 6 | #include "defines.h" | |
| 7 | ||
| 8 | ||
| 9 | // typedef glm::vec4 vec4; | |
| 10 | // typedef vec3 vec3; | |
| 11 | // typedef glm::vec2 vec2; | |
| 12 | // typedef glm::dmat4x4 Mat; | |
| 13 | ||
| 14 | vec4 trivalue(Float uu, Float vv, float* data, | |
| 15 | int nx, int ny, int channels); | |
| 16 | ||
| 17 | vec4 trivalue(Float uu, Float vv, reflection_map_info ref); | |
| 18 | ||
| 19 | class rayimage { | |
| 20 | public: | |
| 21 | 15x | rayimage(Rcpp::NumericMatrix &r_, Rcpp::NumericMatrix &g_, Rcpp::NumericMatrix &b_, |
| 22 | 15x | int nx, int ny, Float shadow_map_intensity = 0.0f) : r(r_), g(g_), b(b_), nx(nx), ny(ny), |
| 23 | 15x | shadow_map_intensity(shadow_map_intensity) {}; |
| 24 | 10x | rayimage(Rcpp::NumericMatrix &r_, Rcpp::NumericMatrix &g_, Rcpp::NumericMatrix &b_, Rcpp::NumericMatrix &a_, |
| 25 | 10x | int nx, int ny, Float shadow_map_intensity = 0.0f) : r(r_), g(g_), b(b_), a(a_), nx(nx), ny(ny), |
| 26 | 10x | shadow_map_intensity(shadow_map_intensity) {}; |
| 27 | 15x | rayimage(Rcpp::NumericMatrix &mat, |
| 28 | 15x | int nx, int ny, Float shadow_map_intensity = 0.0f) : r(mat), g(mat), b(mat), a(mat), nx(nx), ny(ny), |
| 29 | 15x | shadow_map_intensity(shadow_map_intensity) {}; |
| 30 | 2165823x | void set_color(int i, int j, vec3 col) { |
| 31 | 2165823x | r(i,j) = col.r; |
| 32 | 2165823x | g(i,j) = col.g; |
| 33 | 2165823x | b(i,j) = col.b; |
| 34 | } | |
| 35 | 666476x | void set_color(int i, int j, vec4 col) { |
| 36 | 666476x | r(i,j) = col.r; |
| 37 | 666476x | g(i,j) = col.g; |
| 38 | 666476x | b(i,j) = col.b; |
| 39 | 666476x | a(i,j) = col.w; |
| 40 | } | |
| 41 | 644096x | vec3 get_color(int i, int j) { |
| 42 | 644096x | return(vec3(r(i,j),g(i,j),b(i,j))); |
| 43 | } | |
| 44 | ! | vec4 get_color_a(int i, int j) { |
| 45 | ! | return(vec4(r(i,j),g(i,j),b(i,j),a(i,j))); |
| 46 | } | |
| 47 | 16638475x | vec3 get_color_bounded(int i, int j) { |
| 48 | 16638475x | i = i > nx-1 ? nx-1 : i; |
| 49 | 16638475x | j = j > ny-1 ? ny-1 : j; |
| 50 | 16638475x | i = i < 0 ? 0 : i; |
| 51 | 16638475x | j = j < 0 ? 0 : j; |
| 52 | 16638475x | return(vec3(r(i,j),g(i,j),b(i,j))); |
| 53 | } | |
| 54 | 16638475x | vec4 get_color_bounded_a(int i, int j) { |
| 55 | 16638475x | i = i > nx-1 ? nx-1 : i; |
| 56 | 16638475x | j = j > ny-1 ? ny-1 : j; |
| 57 | 16638475x | i = i < 0 ? 0 : i; |
| 58 | 16638475x | j = j < 0 ? 0 : j; |
| 59 | 16638475x | return(vec4(r(i,j),g(i,j),b(i,j),a(i,j))); |
| 60 | } | |
| 61 | 665539x | int width() { |
| 62 | 665539x | return(nx); |
| 63 | } | |
| 64 | 746051x | int height() { |
| 65 | 746051x | return(ny); |
| 66 | } | |
| 67 | 7680x | Float get_shadow_intensity() { |
| 68 | 7680x | return(shadow_map_intensity); |
| 69 | } | |
| 70 | private: | |
| 71 | Rcpp::NumericMatrix r; | |
| 72 | Rcpp::NumericMatrix g; | |
| 73 | Rcpp::NumericMatrix b; | |
| 74 | Rcpp::NumericMatrix a; | |
| 75 | ||
| 76 | int nx, ny; | |
| 77 | Float shadow_map_intensity; | |
| 78 | }; | |
| 79 | ||
| 80 | ||
| 81 | #endif |
| 1 | #include "light.h" | |
| 2 | ||
| 3 | ! | vec3 Light::CalcPointLightAtten(vec3 fragPos) { |
| 4 | ! | Float distance = length(position - fragPos); |
| 5 | ! | Float attenuation = 1.0 / (constant + linear * distance + |
| 6 | ! | quadratic * (distance * distance)); |
| 7 | ! | return (attenuation * color); |
| 8 | } | |
| 9 | ||
| 10 | ! | vec3 Light::CalcLightDir(vec3 fragPos) { |
| 11 | ! | return (normalize(position - fragPos)); |
| 12 | } |
| 1 | #include "line.h" | |
| 2 | ||
| 3 | ! | void aa_line(std::vector<vec3>& line_mat_start, |
| 4 | std::vector<vec3>& line_mat_end, | |
| 5 | std::vector<vec3>& line_color, | |
| 6 | Rcpp::NumericMatrix &zbuffer, | |
| 7 | std::vector<std::map<Float, alpha_info> >& alpha_depths, | |
| 8 | Float alpha_line, Float line_offset) { | |
| 9 | ! | auto ipart = [](Float x) -> int {return int(std::floor(x));}; |
| 10 | // auto round = [](Float x) -> Float {return std::round(x);}; | |
| 11 | ! | auto fpart = [](Float x) -> Float {return x - std::floor(x);}; |
| 12 | ! | auto rfpart = [=](Float x) -> Float {return 1 - fpart(x);}; |
| 13 | ||
| 14 | Float x0, y0, z0, x1, y1, z1; | |
| 15 | ! | int nx = zbuffer.nrow(); |
| 16 | ! | int ny = zbuffer.ncol(); |
| 17 | ||
| 18 | ! | for(unsigned int ii = 0; ii < line_mat_start.size(); ii++) { |
| 19 | ! | x0 = line_mat_start[ii].x; |
| 20 | ! | x1 = line_mat_end[ii].x; |
| 21 | ! | y0 = line_mat_start[ii].y; |
| 22 | ! | y1 = line_mat_end[ii].y; |
| 23 | //Perspective correct interpolation | |
| 24 | ! | z0 = 1.0f/line_mat_start[ii].z; |
| 25 | ! | z1 = 1.0f/line_mat_end[ii].z; |
| 26 | ||
| 27 | ! | const bool steep = std::fabs(y1 - y0) > std::fabs(x1 - x0); |
| 28 | ! | if (steep) { |
| 29 | ! | std::swap(x0,y0); |
| 30 | ! | std::swap(x1,y1); |
| 31 | } | |
| 32 | ! | if (x0 > x1) { |
| 33 | ! | std::swap(x0,x1); |
| 34 | ! | std::swap(y0,y1); |
| 35 | ! | std::swap(z0,z1); |
| 36 | } | |
| 37 | ||
| 38 | ! | const Float dx = x1 - x0; |
| 39 | ! | const Float dy = y1 - y0; |
| 40 | ! | const Float gradient = (dx == 0) ? 1 : dy/dx; |
| 41 | ||
| 42 | ! | Float offset = line_offset; |
| 43 | //zbuffer | |
| 44 | ! | Float dz = z1-z0; |
| 45 | ! | Float zcurrent = z0; |
| 46 | Float z; | |
| 47 | int xpx11; | |
| 48 | Float intery; | |
| 49 | { | |
| 50 | ! | const Float xend = floor(x0); |
| 51 | ! | const Float yend = y0 + gradient * (xend - x0); |
| 52 | // const Float xgap = rfpart(x0 + 0.5); | |
| 53 | ! | xpx11 = xend; |
| 54 | ! | const int ypx11 = ipart(yend); |
| 55 | ! | if (steep) { |
| 56 | ! | if(ypx11 < nx && ypx11 >= 0 && xpx11 < ny && xpx11 >= 0) { |
| 57 | ! | z = 1.0f/z0+offset; |
| 58 | alpha_info tmp_data; | |
| 59 | // tmp_data.color = vec4(line_color[ii], rfpart(yend) * xgap* alpha_line); | |
| 60 | // tmp_data.color = vec4(line_color[ii], 1); | |
| 61 | ||
| 62 | ! | tmp_data.normal = vec3(0.); |
| 63 | ! | tmp_data.position = vec3(0.); |
| 64 | ! | tmp_data.uv = vec3(0.); |
| 65 | // alpha_depths[xpx11 + nx * ypx11][z] = tmp_data; | |
| 66 | ||
| 67 | ! | if(xpx11 + 1 < nx) { |
| 68 | alpha_info tmp_data2; | |
| 69 | // tmp_data2.color = vec4(line_color[ii],fpart(yend) * xgap * alpha_line); | |
| 70 | // tmp_data2.color = vec4(line_color[ii],1); | |
| 71 | ||
| 72 | ! | tmp_data2.normal = vec3(0.); |
| 73 | ! | tmp_data2.position = vec3(0.); |
| 74 | ! | tmp_data2.uv = vec3(0.); |
| 75 | // alpha_depths[xpx11 + 1 + nx * ypx11][z] = tmp_data2; | |
| 76 | } | |
| 77 | } | |
| 78 | } else { | |
| 79 | ! | if(xpx11 < nx && xpx11 >= 0 && ypx11 < ny && ypx11 >= 0) { |
| 80 | ! | z = 1.0f/z0+offset; |
| 81 | alpha_info tmp_data; | |
| 82 | // tmp_data.color = vec4(line_color[ii], rfpart(yend) * xgap * alpha_line); | |
| 83 | // tmp_data.color = vec4(line_color[ii], 1); | |
| 84 | ||
| 85 | ! | tmp_data.normal = vec3(0.); |
| 86 | ! | tmp_data.position = vec3(0.); |
| 87 | ! | tmp_data.uv = vec3(0.); |
| 88 | // alpha_depths[ypx11 + ny * xpx11][z] = tmp_data; | |
| 89 | ! | if(ypx11 + 1 < ny) { |
| 90 | alpha_info tmp_data2; | |
| 91 | // tmp_data2.color = vec4(line_color[ii],fpart(yend) * xgap * alpha_line); | |
| 92 | // tmp_data2.color = vec4(line_color[ii],1); | |
| 93 | ||
| 94 | ! | tmp_data2.normal = vec3(0.); |
| 95 | ! | tmp_data2.position = vec3(0.); |
| 96 | ! | tmp_data2.uv = vec3(0.); |
| 97 | // alpha_depths[(ypx11 + 1) + ny * xpx11][z] = tmp_data2; | |
| 98 | } | |
| 99 | } | |
| 100 | } | |
| 101 | ! | intery = yend + gradient; |
| 102 | } | |
| 103 | ||
| 104 | int xpx12; | |
| 105 | { | |
| 106 | ! | const Float xend = floor(x1); |
| 107 | ! | const Float yend = y1 + gradient * (xend - x1); |
| 108 | // const Float xgap = rfpart(x1 + 0.5); | |
| 109 | ! | xpx12 = xend; |
| 110 | ! | const int ypx12 = ipart(yend); |
| 111 | ! | if (steep) { |
| 112 | ! | if(ypx12 < nx && ypx12 >= 0 && xpx12 < ny && xpx12 >= 0) { |
| 113 | ! | z = 1.0f/z1+offset; |
| 114 | alpha_info tmp_data; | |
| 115 | // tmp_data.color = vec4(line_color[ii], rfpart(yend) * xgap* alpha_line); | |
| 116 | // tmp_data.color = vec4(line_color[ii], 1); | |
| 117 | ||
| 118 | ! | tmp_data.normal = vec3(0.); |
| 119 | ! | tmp_data.position = vec3(0.); |
| 120 | ! | tmp_data.uv = vec3(0.); |
| 121 | // alpha_depths[xpx12 + nx * ypx12][z] = tmp_data; | |
| 122 | ||
| 123 | ! | if(xpx12 + 1 < nx) { |
| 124 | alpha_info tmp_data2; | |
| 125 | // tmp_data2.color = vec4(line_color[ii],fpart(yend) * xgap* alpha_line); | |
| 126 | // tmp_data2.color = vec4(line_color[ii],1); | |
| 127 | ||
| 128 | ! | tmp_data2.normal = vec3(0.); |
| 129 | ! | tmp_data2.position = vec3(0.); |
| 130 | ! | tmp_data2.uv = vec3(0.); |
| 131 | // alpha_depths[xpx12 + 1 + nx * ypx12][z] = tmp_data2; | |
| 132 | } | |
| 133 | } | |
| 134 | } else { | |
| 135 | ! | if(xpx12 < nx && xpx12 >= 0 && ypx12 < ny && ypx12 >= 0) { |
| 136 | ! | z = 1.0f/z1+offset; |
| 137 | alpha_info tmp_data; | |
| 138 | // tmp_data.color = vec4(line_color[ii], rfpart(yend) * xgap * alpha_line); | |
| 139 | // tmp_data.color = vec4(line_color[ii], 1); | |
| 140 | ||
| 141 | ! | tmp_data.normal = vec3(0.); |
| 142 | ! | tmp_data.position = vec3(0.); |
| 143 | ! | tmp_data.uv = vec3(0.); |
| 144 | // alpha_depths[ypx12 + ny * xpx12][z] = tmp_data; | |
| 145 | ! | if(ypx12 + 1 < ny) { |
| 146 | alpha_info tmp_data2; | |
| 147 | // tmp_data2.color = vec4(line_color[ii],fpart(yend) * xgap * alpha_line); | |
| 148 | // tmp_data2.color = vec4(line_color[ii],1); | |
| 149 | ||
| 150 | ! | tmp_data2.normal = vec3(0.); |
| 151 | ! | tmp_data2.position = vec3(0.); |
| 152 | ! | tmp_data2.uv = vec3(0.); |
| 153 | // alpha_depths[(ypx12 + 1) + ny * xpx12][z] = tmp_data2; | |
| 154 | } | |
| 155 | } | |
| 156 | } | |
| 157 | } | |
| 158 | ! | Float intery0 = intery; |
| 159 | ||
| 160 | int iy; | |
| 161 | ! | Float zsteps = xpx12-(xpx11); |
| 162 | ! | Float zstep = dz/zsteps; |
| 163 | ! | Float counter = 0; |
| 164 | ||
| 165 | ! | if (steep) { |
| 166 | ! | for (int x = xpx11 ; x < xpx12 ; x++) { |
| 167 | ! | iy = ipart(intery)-1; |
| 168 | ! | if(iy < nx && iy >= 0 && x < ny && x >= 0) { |
| 169 | ! | z = 1.0f/zcurrent+offset; |
| 170 | alpha_info tmp_data; | |
| 171 | ! | tmp_data.color = vec4(line_color[ii], rfpart(intery) * alpha_line); |
| 172 | ! | tmp_data.normal = vec3(0.); |
| 173 | ! | tmp_data.position = vec3(0.); |
| 174 | ! | tmp_data.uv = vec3(0.); |
| 175 | ! | alpha_depths[x + ny * iy][z] = tmp_data; |
| 176 | ||
| 177 | ! | if(iy + 1 < nx) { |
| 178 | alpha_info tmp_data2; | |
| 179 | ! | tmp_data2.color = vec4(line_color[ii],fpart(intery) * alpha_line); |
| 180 | ! | tmp_data2.normal = vec3(0.); |
| 181 | ! | tmp_data2.position = vec3(0.); |
| 182 | ! | tmp_data2.uv = vec3(0.); |
| 183 | ! | alpha_depths[x + ny * (iy+1)][z] = tmp_data2; |
| 184 | } | |
| 185 | } | |
| 186 | ! | counter++; |
| 187 | ! | zcurrent = z0 + counter * zstep; |
| 188 | ! | intery = intery0 + counter * gradient; |
| 189 | } | |
| 190 | } else { | |
| 191 | ! | for (int x = xpx11 ; x < xpx12 ; x++) { |
| 192 | ! | iy = ipart(intery)-1; |
| 193 | ! | if(x < nx && x >= 0 && iy < ny && iy >= 0) { |
| 194 | ! | z = 1.0f/zcurrent+offset; |
| 195 | alpha_info tmp_data; | |
| 196 | ! | tmp_data.color = vec4(line_color[ii], rfpart(intery) * alpha_line); |
| 197 | ! | tmp_data.normal = vec3(0.); |
| 198 | ! | tmp_data.position = vec3(0.); |
| 199 | ! | tmp_data.uv = vec3(0.); |
| 200 | ! | alpha_depths[iy + ny * x][z] = tmp_data; |
| 201 | ! | if(iy + 1 < ny) { |
| 202 | alpha_info tmp_data2; | |
| 203 | ! | tmp_data2.color = vec4(line_color[ii],fpart(intery) * alpha_line); |
| 204 | ! | tmp_data2.normal = vec3(0.); |
| 205 | ! | tmp_data2.position = vec3(0.); |
| 206 | ! | tmp_data2.uv = vec3(0.); |
| 207 | ! | alpha_depths[(iy + 1) + ny * x][z] = tmp_data2; |
| 208 | } | |
| 209 | } | |
| 210 | ! | counter++; |
| 211 | ! | zcurrent = z0 + counter * zstep; |
| 212 | ! | intery = intery0 + counter * gradient; |
| 213 | } | |
| 214 | } | |
| 215 | } | |
| 216 | } | |
| 217 | ||
| 218 | //This takes NDC values | |
| 219 | ! | void noaa_line(std::vector<vec3>& line_mat_start, |
| 220 | std::vector<vec3>& line_mat_end, | |
| 221 | std::vector<vec3>& line_color, | |
| 222 | Rcpp::NumericMatrix &zbuffer, | |
| 223 | std::vector<std::map<Float, alpha_info> >& alpha_depths, | |
| 224 | Float alpha_line, Float line_offset) { | |
| 225 | int x0, y0, x1, y1; | |
| 226 | Float z0, z1; | |
| 227 | ! | int nx = zbuffer.nrow(); |
| 228 | ! | int ny = zbuffer.ncol(); |
| 229 | ! | Float offset = line_offset; |
| 230 | ||
| 231 | ! | for(unsigned int ii = 0; ii < line_mat_start.size(); ii += 1) { |
| 232 | ! | x0 = line_mat_start[ii].x; |
| 233 | ! | x1 = line_mat_end[ii].x; |
| 234 | ! | y0 = line_mat_start[ii].y; |
| 235 | ! | y1 = line_mat_end[ii].y; |
| 236 | //Perspective correct interpolation | |
| 237 | ! | z0 = 1.0f/line_mat_start[ii].z; |
| 238 | ! | z1 = 1.0f/line_mat_end[ii].z; |
| 239 | ||
| 240 | ! | bool steep = false; |
| 241 | ! | if (std::abs(x0-x1)<std::abs(y0-y1)) { |
| 242 | ! | std::swap(x0, y0); |
| 243 | ! | std::swap(x1, y1); |
| 244 | ||
| 245 | ! | steep = true; |
| 246 | } | |
| 247 | ! | if (x0>x1) { |
| 248 | ! | std::swap(x0, x1); |
| 249 | ! | std::swap(y0, y1); |
| 250 | ! | std::swap(z0, z1); |
| 251 | } | |
| 252 | ! | int dx = x1-x0; |
| 253 | ! | int dy = y1-y0; |
| 254 | ! | Float dz = z1-z0; |
| 255 | ! | Float zcurrent = z0; |
| 256 | ||
| 257 | ! | int derror2 = std::abs(dy)*2; |
| 258 | ! | int error2 = 0; |
| 259 | ! | int y = y0; |
| 260 | ! | Float zsteps = 0; |
| 261 | ! | for (int x=x0; x<=x1; x++) { |
| 262 | ! | error2 += derror2; |
| 263 | ! | if (error2 > dx) { |
| 264 | ! | y += (y1>y0?1:-1); |
| 265 | ! | error2 -= dx*2; |
| 266 | } | |
| 267 | ! | zsteps++; |
| 268 | } | |
| 269 | ! | Float zstep = dz/zsteps; |
| 270 | Float z; | |
| 271 | ! | derror2 = std::abs(dy)*2; |
| 272 | ! | error2 = 0; |
| 273 | ! | y = y0; |
| 274 | ! | Float counter = 0; |
| 275 | ! | for (int x=x0; x<=x1; x++) { |
| 276 | ! | if (steep) { |
| 277 | ! | if(y < nx && y >= 0 && x < ny && x >= 0) { |
| 278 | ! | z = 1.0f/zcurrent + offset; |
| 279 | alpha_info tmp_data; | |
| 280 | ! | tmp_data.color = vec4(line_color[ii],1.0f * alpha_line); |
| 281 | ! | tmp_data.normal = vec3(0.); |
| 282 | ! | tmp_data.position = vec3(0.); |
| 283 | ! | tmp_data.uv = vec3(0.); |
| 284 | ! | alpha_depths[x + nx * y][z] = tmp_data; |
| 285 | } | |
| 286 | } else { | |
| 287 | ! | if(y < ny && y >= 0 && x < nx && x >= 0) { |
| 288 | ! | z = 1.0f/zcurrent + offset; |
| 289 | alpha_info tmp_data; | |
| 290 | ! | tmp_data.color = vec4(line_color[ii],1.0f * alpha_line); |
| 291 | ! | tmp_data.normal = vec3(0.); |
| 292 | ! | tmp_data.position = vec3(0.); |
| 293 | ! | tmp_data.uv = vec3(0.); |
| 294 | ! | alpha_depths[y + ny * x][z] = tmp_data; |
| 295 | } | |
| 296 | } | |
| 297 | ! | error2 += derror2; |
| 298 | ! | if (error2 > dx) { |
| 299 | ! | y += (y1>y0?1:-1); |
| 300 | ! | error2 -= dx*2; |
| 301 | } | |
| 302 | ! | counter++; |
| 303 | ! | zcurrent = z0 + counter*zstep; |
| 304 | } | |
| 305 | } | |
| 306 | } |
| 1 | #include <Rcpp.h> | |
| 2 | using namespace Rcpp; | |
| 3 | ||
| 4 | #define TINYOBJLOADER_IMPLEMENTATION | |
| 5 | #define TINYOBJLOADER_USE_MAPBOX_EARCUT | |
| 6 | #include "tinyobj/tiny_obj_loader.h" | |
| 7 | ||
| 8 | template <typename T> | |
| 9 | 180x | inline void set_item_impl( List& target, int i, const T& obj, CharacterVector& names, traits::true_type ){ |
| 10 | 180x | target[i] = obj.object ; |
| 11 | 180x | names[i] = obj.name ; |
| 12 | } | |
| 13 | ||
| 14 | template <typename T> | |
| 15 | inline void set_item_impl( List& target, int i, const T& obj, CharacterVector&, traits::false_type ){ | |
| 16 | target[i] = obj ; | |
| 17 | } | |
| 18 | ||
| 19 | template <typename T> | |
| 20 | 180x | inline void set_item( List& target, int i, const T& obj, CharacterVector& names){ |
| 21 | 180x | set_item_impl( target, i, obj, names, typename traits::is_named<T>::type() ) ; |
| 22 | } | |
| 23 | ||
| 24 | // [[Rcpp::export]] | |
| 25 | 37x | List load_obj(std::string inputfile, std::string basedir) { |
| 26 | 37x | tinyobj::ObjReader reader; |
| 27 | 37x | tinyobj::ObjReaderConfig reader_config; |
| 28 | 37x | reader_config.mtl_search_path = basedir; // Path to material files |
| 29 | 37x | reader_config.triangulate = true; |
| 30 | ||
| 31 | 37x | if (!reader.ParseFromFile(inputfile, reader_config)) { |
| 32 | ! | if (!reader.Error().empty()) { |
| 33 | ! | Rcpp::Rcout << "TinyObjReader: " << reader.Error(); |
| 34 | } | |
| 35 | ! | stop("Stopping..."); |
| 36 | } | |
| 37 | ||
| 38 | 37x | if (!reader.Warning().empty()) { |
| 39 | ! | Rcpp::Rcout << "TinyObjReader: " << reader.Warning(); |
| 40 | } | |
| 41 | ||
| 42 | 37x | auto& attrib = reader.GetAttrib(); |
| 43 | 37x | auto& shapes = reader.GetShapes(); |
| 44 | 37x | auto& materials = reader.GetMaterials(); |
| 45 | ||
| 46 | ||
| 47 | 37x | if((attrib.vertices.size() % 3) !=0) { |
| 48 | ! | throw std::runtime_error("Number of vertices is not a multiple of 3"); |
| 49 | } | |
| 50 | ||
| 51 | 37x | List shape_list; |
| 52 | 37x | List material_list; |
| 53 | 74x | for (size_t s = 0; s < shapes.size(); s++) { |
| 54 | 37x | tinyobj::mesh_t m = shapes[s].mesh; |
| 55 | ||
| 56 | 37x | const size_t n_faces = m.material_ids.size(); |
| 57 | 37x | const size_t nv_face = m.indices.size() / n_faces; |
| 58 | 37x | if(n_faces == 0 || nv_face == 0) { |
| 59 | ! | continue; |
| 60 | } | |
| 61 | ||
| 62 | List single_shape = List::create( | |
| 63 | 74x | Named("indices") = R_NilValue, |
| 64 | 74x | Named("tex_indices") = R_NilValue, |
| 65 | 74x | Named("norm_indices") = R_NilValue, |
| 66 | 74x | Named("material_ids") = R_NilValue, |
| 67 | 74x | Named("has_vertex_tex") = R_NilValue, |
| 68 | 74x | Named("has_vertex_normals") = R_NilValue |
| 69 | ); | |
| 70 | 37x | std::vector<float> verts; |
| 71 | 37x | std::vector<float> norms; |
| 72 | 37x | std::vector<float> texs; |
| 73 | 37x | std::vector<int> mats; |
| 74 | ||
| 75 | 7341x | for (size_t f = 0; f < m.num_face_vertices.size(); f++) { |
| 76 | 7304x | mats.push_back(m.material_ids[f]); |
| 77 | } | |
| 78 | 37x | std::vector<int> inds; |
| 79 | 21949x | for(unsigned int j = 0; j < m.indices.size(); j++) { |
| 80 | 21912x | inds.push_back(m.indices[j].vertex_index); |
| 81 | } | |
| 82 | 37x | std::vector<int> tex_inds; |
| 83 | 21949x | for(unsigned int j = 0; j < m.indices.size(); j++) { |
| 84 | 21912x | tex_inds.push_back(m.indices[j].texcoord_index); |
| 85 | } | |
| 86 | 37x | std::vector<int> norm_inds; |
| 87 | 21949x | for(unsigned int j = 0; j < m.indices.size(); j++) { |
| 88 | 21912x | norm_inds.push_back(m.indices[j].normal_index); |
| 89 | } | |
| 90 | ||
| 91 | 111x | single_shape["indices"] = Rcpp::transpose(IntegerMatrix(nv_face, inds.size()/nv_face, inds.begin() )); |
| 92 | 111x | single_shape["tex_indices"] = Rcpp::transpose(IntegerMatrix(nv_face, tex_inds.size()/nv_face, tex_inds.begin() )); |
| 93 | 111x | single_shape["norm_indices"] = Rcpp::transpose(IntegerMatrix(nv_face, norm_inds.size()/nv_face, norm_inds.begin() )); |
| 94 | 111x | single_shape["material_ids"] = Rcpp::transpose(IntegerMatrix(1L, mats.size(), mats.begin())); |
| 95 | 111x | single_shape["has_vertex_tex"] = LogicalVector(inds.size()/nv_face,inds.size() == tex_inds.size()); |
| 96 | 111x | single_shape["has_vertex_normals"] = LogicalVector(inds.size()/nv_face,inds.size() == norm_inds.size()); |
| 97 | ||
| 98 | 37x | shape_list.push_back(single_shape); |
| 99 | } | |
| 100 | //This needs to be updated when more defaults are added to each texture | |
| 101 | 37x | const int num_items = 30; |
| 102 | 43x | for(unsigned int i=0; i < materials.size(); i++) { |
| 103 | 6x | tinyobj::material_t m = materials[i]; |
| 104 | 6x | int culltype = m.dissolve < 1.0 ? 3 : 1; //no culling if at all transparent |
| 105 | 6x | List out(num_items); |
| 106 | 6x | CharacterVector names(num_items) ; |
| 107 | 6x | int item = 0; |
| 108 | 18x | set_item( out, item++ , _["ambient"] = NumericVector::create(m.ambient[0], m.ambient[1], m.ambient[2]), names) ; |
| 109 | 18x | set_item( out, item++ , _["diffuse"] = NumericVector::create(m.diffuse[0], m.diffuse[1], m.diffuse[2]), names) ; |
| 110 | 18x | set_item( out, item++ , _["specular"] = NumericVector::create(m.specular[0], m.specular[1], m.specular[2]), names) ; |
| 111 | 18x | set_item( out, item++ , _["transmittance"] = NumericVector::create(m.transmittance[0], m.transmittance[1], m.transmittance[2]), names) ; |
| 112 | 18x | set_item( out, item++ , _["emission"] = NumericVector::create(m.emission[0], m.emission[1], m.emission[2]), names) ; |
| 113 | 12x | set_item( out, item++ , _["shininess"] = m.shininess, names) ; |
| 114 | 12x | set_item( out, item++ , _["ior"] = m.ior, names) ; |
| 115 | 12x | set_item( out, item++ , _["dissolve"] = m.dissolve, names) ; |
| 116 | 12x | set_item( out, item++ , _["illum"] = m.illum, names) ; |
| 117 | 12x | set_item( out, item++ , _["ambient_texname"] = m.ambient_texname , names) ; |
| 118 | 12x | set_item( out, item++ , _["diffuse_texname"] = m.diffuse_texname , names) ; |
| 119 | 12x | set_item( out, item++ , _["emissive_texname"] = m.emissive_texname, names) ; |
| 120 | 12x | set_item( out, item++ , _["specular_texname"] = m.specular_texname, names) ; |
| 121 | 12x | set_item( out, item++ , _["normal_texname"] = m.normal_texname , names) ; |
| 122 | 6x | set_item( out, item++ , _["bump_texname"] = m.bump_texname , names) ; |
| 123 | 12x | set_item( out, item++ , _["diffuse_intensity"] = 1.0 , names) ; |
| 124 | 12x | set_item( out, item++ , _["emission_intensity"] = 0.0, names) ; |
| 125 | 12x | set_item( out, item++ , _["specular_intensity"] = 0.0, names) ; |
| 126 | 18x | set_item( out, item++ , _["ambient_intensity"] = 0.0, names) ; |
| 127 | 12x | set_item( out, item++ , _["bump_intensity"] = m.bump_texopt.bump_multiplier, names) ; |
| 128 | 12x | set_item( out, item++ , _["culling"] = culltype, names) ; |
| 129 | 6x | set_item( out, item++ , _["type"] = "diffuse", names) ; |
| 130 | 12x | set_item( out, item++ , _["translucent"] = true, names) ; |
| 131 | 12x | set_item( out, item++ , _["toon_levels"] = 5, names) ; |
| 132 | 12x | set_item( out, item++ , _["toon_outline_width"] = 0.05, names) ; |
| 133 | 18x | set_item( out, item++ , _["toon_outline_color"] = NumericVector::create(0,0,0), names) ; |
| 134 | 12x | set_item( out, item++ , _["reflection_intensity"] = 1.0, names) ; |
| 135 | 12x | set_item( out, item++ , _["reflection_sharpness"] = 1.0, names) ; |
| 136 | 12x | set_item( out, item++ , _["two_sided"] = false, names) ; |
| 137 | 12x | set_item( out, item++ , _["sigma"] = 0.0, names) ; |
| 138 | ||
| 139 | 6x | if(item != num_items) { |
| 140 | ! | throw std::runtime_error("Number of items is not equal to specified material length."); |
| 141 | } | |
| 142 | 6x | out.names() = names ; |
| 143 | 6x | material_list.push_back(out); |
| 144 | } | |
| 145 | List return_val = List::create( | |
| 146 | 74x | Named("shapes") = R_NilValue, |
| 147 | 74x | Named("vertices") = R_NilValue, |
| 148 | 74x | Named("texcoords") = R_NilValue, |
| 149 | 74x | Named("normals") = R_NilValue, |
| 150 | 111x | Named("materials") = R_NilValue |
| 151 | ); | |
| 152 | 37x | return_val["shapes"] = shape_list; |
| 153 | 111x | return_val["vertices"] = List::create(Rcpp::transpose(NumericMatrix(3L, attrib.vertices.size()/3L, attrib.vertices.begin()))); |
| 154 | 111x | return_val["texcoords"] = List::create(Rcpp::transpose(NumericMatrix(2L, attrib.texcoords.size()/2L, attrib.texcoords.begin()))); |
| 155 | 111x | return_val["normals"] = List::create(Rcpp::transpose(NumericMatrix(3L, attrib.normals.size()/3L, attrib.normals.begin()))); |
| 156 | 111x | return_val["materials"] = List::create(material_list); |
| 157 | ||
| 158 | 37x | return return_val; |
| 159 | } |
| 1 | /* | |
| 2 | The MIT License (MIT) | |
| 3 | ||
| 4 | Copyright (c) 2012-Present, Syoyo Fujita and many contributors. | |
| 5 | ||
| 6 | Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 7 | of this software and associated documentation files (the "Software"), to deal | |
| 8 | in the Software without restriction, including without limitation the rights | |
| 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 10 | copies of the Software, and to permit persons to whom the Software is | |
| 11 | furnished to do so, subject to the following conditions: | |
| 12 | ||
| 13 | The above copyright notice and this permission notice shall be included in | |
| 14 | all copies or substantial portions of the Software. | |
| 15 | ||
| 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
| 22 | THE SOFTWARE. | |
| 23 | */ | |
| 24 | ||
| 25 | // | |
| 26 | // version 2.0.0 : Add new object oriented API. 1.x API is still provided. | |
| 27 | // * Support line primitive. | |
| 28 | // * Support points primitive. | |
| 29 | // * Support multiple search path for .mtl(v1 API). | |
| 30 | // * Support vertex weight `vw`(as an tinyobj extension) | |
| 31 | // * Support escaped whitespece in mtllib | |
| 32 | // * Add robust triangulation using Mapbox earcut(TINYOBJLOADER_USE_MAPBOX_EARCUT). | |
| 33 | // version 1.4.0 : Modifed ParseTextureNameAndOption API | |
| 34 | // version 1.3.1 : Make ParseTextureNameAndOption API public | |
| 35 | // version 1.3.0 : Separate warning and error message(breaking API of LoadObj) | |
| 36 | // version 1.2.3 : Added color space extension('-colorspace') to tex opts. | |
| 37 | // version 1.2.2 : Parse multiple group names. | |
| 38 | // version 1.2.1 : Added initial support for line('l') primitive(PR #178) | |
| 39 | // version 1.2.0 : Hardened implementation(#175) | |
| 40 | // version 1.1.1 : Support smoothing groups(#162) | |
| 41 | // version 1.1.0 : Support parsing vertex color(#144) | |
| 42 | // version 1.0.8 : Fix parsing `g` tag just after `usemtl`(#138) | |
| 43 | // version 1.0.7 : Support multiple tex options(#126) | |
| 44 | // version 1.0.6 : Add TINYOBJLOADER_USE_DOUBLE option(#124) | |
| 45 | // version 1.0.5 : Ignore `Tr` when `d` exists in MTL(#43) | |
| 46 | // version 1.0.4 : Support multiple filenames for 'mtllib'(#112) | |
| 47 | // version 1.0.3 : Support parsing texture options(#85) | |
| 48 | // version 1.0.2 : Improve parsing speed by about a factor of 2 for large | |
| 49 | // files(#105) | |
| 50 | // version 1.0.1 : Fixes a shape is lost if obj ends with a 'usemtl'(#104) | |
| 51 | // version 1.0.0 : Change data structure. Change license from BSD to MIT. | |
| 52 | // | |
| 53 | ||
| 54 | // | |
| 55 | // Use this in *one* .cc | |
| 56 | // #define TINYOBJLOADER_IMPLEMENTATION | |
| 57 | // #include "tiny_obj_loader.h" | |
| 58 | // | |
| 59 | ||
| 60 | #ifndef TINY_OBJ_LOADER_H_ | |
| 61 | #define TINY_OBJ_LOADER_H_ | |
| 62 | ||
| 63 | #include <map> | |
| 64 | #include <string> | |
| 65 | #include <vector> | |
| 66 | ||
| 67 | namespace tinyobj { | |
| 68 | ||
| 69 | // TODO(syoyo): Better C++11 detection for older compiler | |
| 70 | #if __cplusplus > 199711L | |
| 71 | #define TINYOBJ_OVERRIDE override | |
| 72 | #else | |
| 73 | #define TINYOBJ_OVERRIDE | |
| 74 | #endif | |
| 75 | ||
| 76 | ||
| 77 | // https://en.wikipedia.org/wiki/Wavefront_.obj_file says ... | |
| 78 | // | |
| 79 | // -blendu on | off # set horizontal texture blending | |
| 80 | // (default on) | |
| 81 | // -blendv on | off # set vertical texture blending | |
| 82 | // (default on) | |
| 83 | // -boost real_value # boost mip-map sharpness | |
| 84 | // -mm base_value gain_value # modify texture map values (default | |
| 85 | // 0 1) | |
| 86 | // # base_value = brightness, | |
| 87 | // gain_value = contrast | |
| 88 | // -o u [v [w]] # Origin offset (default | |
| 89 | // 0 0 0) | |
| 90 | // -s u [v [w]] # Scale (default | |
| 91 | // 1 1 1) | |
| 92 | // -t u [v [w]] # Turbulence (default | |
| 93 | // 0 0 0) | |
| 94 | // -texres resolution # texture resolution to create | |
| 95 | // -clamp on | off # only render texels in the clamped | |
| 96 | // 0-1 range (default off) | |
| 97 | // # When unclamped, textures are | |
| 98 | // repeated across a surface, | |
| 99 | // # when clamped, only texels which | |
| 100 | // fall within the 0-1 | |
| 101 | // # range are rendered. | |
| 102 | // -bm mult_value # bump multiplier (for bump maps | |
| 103 | // only) | |
| 104 | // | |
| 105 | // -imfchan r | g | b | m | l | z # specifies which channel of the file | |
| 106 | // is used to | |
| 107 | // # create a scalar or bump texture. | |
| 108 | // r:red, g:green, | |
| 109 | // # b:blue, m:matte, l:luminance, | |
| 110 | // z:z-depth.. | |
| 111 | // # (the default for bump is 'l' and | |
| 112 | // for decal is 'm') | |
| 113 | // bump -imfchan r bumpmap.tga # says to use the red channel of | |
| 114 | // bumpmap.tga as the bumpmap | |
| 115 | // | |
| 116 | // For reflection maps... | |
| 117 | // | |
| 118 | // -type sphere # specifies a sphere for a "refl" | |
| 119 | // reflection map | |
| 120 | // -type cube_top | cube_bottom | # when using a cube map, the texture | |
| 121 | // file for each | |
| 122 | // cube_front | cube_back | # side of the cube is specified | |
| 123 | // separately | |
| 124 | // cube_left | cube_right | |
| 125 | // | |
| 126 | // TinyObjLoader extension. | |
| 127 | // | |
| 128 | // -colorspace SPACE # Color space of the texture. e.g. | |
| 129 | // 'sRGB` or 'linear' | |
| 130 | // | |
| 131 | ||
| 132 | #ifdef TINYOBJLOADER_USE_DOUBLE | |
| 133 | typedef double real_t; | |
| 134 | #else | |
| 135 | typedef float real_t; | |
| 136 | #endif | |
| 137 | ||
| 138 | typedef enum { | |
| 139 | TEXTURE_TYPE_NONE, // default | |
| 140 | TEXTURE_TYPE_SPHERE, | |
| 141 | TEXTURE_TYPE_CUBE_TOP, | |
| 142 | TEXTURE_TYPE_CUBE_BOTTOM, | |
| 143 | TEXTURE_TYPE_CUBE_FRONT, | |
| 144 | TEXTURE_TYPE_CUBE_BACK, | |
| 145 | TEXTURE_TYPE_CUBE_LEFT, | |
| 146 | TEXTURE_TYPE_CUBE_RIGHT | |
| 147 | } texture_type_t; | |
| 148 | ||
| 149 | struct texture_option_t { | |
| 150 | texture_type_t type; // -type (default TEXTURE_TYPE_NONE) | |
| 151 | real_t sharpness; // -boost (default 1.0?) | |
| 152 | real_t brightness; // base_value in -mm option (default 0) | |
| 153 | real_t contrast; // gain_value in -mm option (default 1) | |
| 154 | real_t origin_offset[3]; // -o u [v [w]] (default 0 0 0) | |
| 155 | real_t scale[3]; // -s u [v [w]] (default 1 1 1) | |
| 156 | real_t turbulence[3]; // -t u [v [w]] (default 0 0 0) | |
| 157 | int texture_resolution; // -texres resolution (No default value in the spec. | |
| 158 | // We'll use -1) | |
| 159 | bool clamp; // -clamp (default false) | |
| 160 | char imfchan; // -imfchan (the default for bump is 'l' and for decal is 'm') | |
| 161 | bool blendu; // -blendu (default on) | |
| 162 | bool blendv; // -blendv (default on) | |
| 163 | real_t bump_multiplier; // -bm (for bump maps only, default 1.0) | |
| 164 | ||
| 165 | // extension | |
| 166 | std::string colorspace; // Explicitly specify color space of stored texel | |
| 167 | // value. Usually `sRGB` or `linear` (default empty). | |
| 168 | }; | |
| 169 | ||
| 170 | struct material_t { | |
| 171 | std::string name; | |
| 172 | ||
| 173 | real_t ambient[3]; | |
| 174 | real_t diffuse[3]; | |
| 175 | real_t specular[3]; | |
| 176 | real_t transmittance[3]; | |
| 177 | real_t emission[3]; | |
| 178 | real_t shininess; | |
| 179 | real_t ior; // index of refraction | |
| 180 | real_t dissolve; // 1 == opaque; 0 == fully transparent | |
| 181 | // illumination model (see http://www.fileformat.info/format/material/) | |
| 182 | int illum; | |
| 183 | ||
| 184 | int dummy; // Suppress padding warning. | |
| 185 | ||
| 186 | std::string ambient_texname; // map_Ka | |
| 187 | std::string diffuse_texname; // map_Kd | |
| 188 | std::string specular_texname; // map_Ks | |
| 189 | std::string specular_highlight_texname; // map_Ns | |
| 190 | std::string bump_texname; // map_bump, map_Bump, bump | |
| 191 | std::string displacement_texname; // disp | |
| 192 | std::string alpha_texname; // map_d | |
| 193 | std::string reflection_texname; // refl | |
| 194 | ||
| 195 | texture_option_t ambient_texopt; | |
| 196 | texture_option_t diffuse_texopt; | |
| 197 | texture_option_t specular_texopt; | |
| 198 | texture_option_t specular_highlight_texopt; | |
| 199 | texture_option_t bump_texopt; | |
| 200 | texture_option_t displacement_texopt; | |
| 201 | texture_option_t alpha_texopt; | |
| 202 | texture_option_t reflection_texopt; | |
| 203 | ||
| 204 | // PBR extension | |
| 205 | // http://exocortex.com/blog/extending_wavefront_mtl_to_support_pbr | |
| 206 | real_t roughness; // [0, 1] default 0 | |
| 207 | real_t metallic; // [0, 1] default 0 | |
| 208 | real_t sheen; // [0, 1] default 0 | |
| 209 | real_t clearcoat_thickness; // [0, 1] default 0 | |
| 210 | real_t clearcoat_roughness; // [0, 1] default 0 | |
| 211 | real_t anisotropy; // aniso. [0, 1] default 0 | |
| 212 | real_t anisotropy_rotation; // anisor. [0, 1] default 0 | |
| 213 | real_t pad0; | |
| 214 | std::string roughness_texname; // map_Pr | |
| 215 | std::string metallic_texname; // map_Pm | |
| 216 | std::string sheen_texname; // map_Ps | |
| 217 | std::string emissive_texname; // map_Ke | |
| 218 | std::string normal_texname; // norm. For normal mapping. | |
| 219 | ||
| 220 | texture_option_t roughness_texopt; | |
| 221 | texture_option_t metallic_texopt; | |
| 222 | texture_option_t sheen_texopt; | |
| 223 | texture_option_t emissive_texopt; | |
| 224 | texture_option_t normal_texopt; | |
| 225 | ||
| 226 | int pad2; | |
| 227 | ||
| 228 | std::map<std::string, std::string> unknown_parameter; | |
| 229 | ||
| 230 | #ifdef TINY_OBJ_LOADER_PYTHON_BINDING | |
| 231 | // For pybind11 | |
| 232 | std::array<double, 3> GetDiffuse() { | |
| 233 | std::array<double, 3> values; | |
| 234 | values[0] = double(diffuse[0]); | |
| 235 | values[1] = double(diffuse[1]); | |
| 236 | values[2] = double(diffuse[2]); | |
| 237 | ||
| 238 | return values; | |
| 239 | } | |
| 240 | ||
| 241 | std::array<double, 3> GetSpecular() { | |
| 242 | std::array<double, 3> values; | |
| 243 | values[0] = double(specular[0]); | |
| 244 | values[1] = double(specular[1]); | |
| 245 | values[2] = double(specular[2]); | |
| 246 | ||
| 247 | return values; | |
| 248 | } | |
| 249 | ||
| 250 | std::array<double, 3> GetTransmittance() { | |
| 251 | std::array<double, 3> values; | |
| 252 | values[0] = double(transmittance[0]); | |
| 253 | values[1] = double(transmittance[1]); | |
| 254 | values[2] = double(transmittance[2]); | |
| 255 | ||
| 256 | return values; | |
| 257 | } | |
| 258 | ||
| 259 | std::array<double, 3> GetEmission() { | |
| 260 | std::array<double, 3> values; | |
| 261 | values[0] = double(emission[0]); | |
| 262 | values[1] = double(emission[1]); | |
| 263 | values[2] = double(emission[2]); | |
| 264 | ||
| 265 | return values; | |
| 266 | } | |
| 267 | ||
| 268 | std::array<double, 3> GetAmbient() { | |
| 269 | std::array<double, 3> values; | |
| 270 | values[0] = double(ambient[0]); | |
| 271 | values[1] = double(ambient[1]); | |
| 272 | values[2] = double(ambient[2]); | |
| 273 | ||
| 274 | return values; | |
| 275 | } | |
| 276 | ||
| 277 | void SetDiffuse(std::array<double, 3> &a) { | |
| 278 | diffuse[0] = real_t(a[0]); | |
| 279 | diffuse[1] = real_t(a[1]); | |
| 280 | diffuse[2] = real_t(a[2]); | |
| 281 | } | |
| 282 | ||
| 283 | void SetAmbient(std::array<double, 3> &a) { | |
| 284 | ambient[0] = real_t(a[0]); | |
| 285 | ambient[1] = real_t(a[1]); | |
| 286 | ambient[2] = real_t(a[2]); | |
| 287 | } | |
| 288 | ||
| 289 | void SetSpecular(std::array<double, 3> &a) { | |
| 290 | specular[0] = real_t(a[0]); | |
| 291 | specular[1] = real_t(a[1]); | |
| 292 | specular[2] = real_t(a[2]); | |
| 293 | } | |
| 294 | ||
| 295 | void SetTransmittance(std::array<double, 3> &a) { | |
| 296 | transmittance[0] = real_t(a[0]); | |
| 297 | transmittance[1] = real_t(a[1]); | |
| 298 | transmittance[2] = real_t(a[2]); | |
| 299 | } | |
| 300 | ||
| 301 | std::string GetCustomParameter(const std::string &key) { | |
| 302 | std::map<std::string, std::string>::const_iterator it = | |
| 303 | unknown_parameter.find(key); | |
| 304 | ||
| 305 | if (it != unknown_parameter.end()) { | |
| 306 | return it->second; | |
| 307 | } | |
| 308 | return std::string(); | |
| 309 | } | |
| 310 | ||
| 311 | #endif | |
| 312 | }; | |
| 313 | ||
| 314 | struct tag_t { | |
| 315 | std::string name; | |
| 316 | ||
| 317 | std::vector<int> intValues; | |
| 318 | std::vector<real_t> floatValues; | |
| 319 | std::vector<std::string> stringValues; | |
| 320 | }; | |
| 321 | ||
| 322 | struct joint_and_weight_t { | |
| 323 | int joint_id; | |
| 324 | real_t weight; | |
| 325 | }; | |
| 326 | ||
| 327 | struct skin_weight_t { | |
| 328 | int vertex_id; // Corresponding vertex index in `attrib_t::vertices`. | |
| 329 | // Compared to `index_t`, this index must be positive and | |
| 330 | // start with 0(does not allow relative indexing) | |
| 331 | std::vector<joint_and_weight_t> weightValues; | |
| 332 | }; | |
| 333 | ||
| 334 | // Index struct to support different indices for vtx/normal/texcoord. | |
| 335 | // -1 means not used. | |
| 336 | struct index_t { | |
| 337 | int vertex_index; | |
| 338 | int normal_index; | |
| 339 | int texcoord_index; | |
| 340 | }; | |
| 341 | ||
| 342 | struct mesh_t { | |
| 343 | std::vector<index_t> indices; | |
| 344 | std::vector<unsigned char> | |
| 345 | num_face_vertices; // The number of vertices per | |
| 346 | // face. 3 = triangle, 4 = quad, | |
| 347 | // ... Up to 255 vertices per face. | |
| 348 | std::vector<int> material_ids; // per-face material ID | |
| 349 | std::vector<unsigned int> smoothing_group_ids; // per-face smoothing group | |
| 350 | // ID(0 = off. positive value | |
| 351 | // = group id) | |
| 352 | std::vector<tag_t> tags; // SubD tag | |
| 353 | }; | |
| 354 | ||
| 355 | // struct path_t { | |
| 356 | // std::vector<int> indices; // pairs of indices for lines | |
| 357 | //}; | |
| 358 | ||
| 359 | struct lines_t { | |
| 360 | // Linear flattened indices. | |
| 361 | std::vector<index_t> indices; // indices for vertices(poly lines) | |
| 362 | std::vector<int> num_line_vertices; // The number of vertices per line. | |
| 363 | }; | |
| 364 | ||
| 365 | struct points_t { | |
| 366 | std::vector<index_t> indices; // indices for points | |
| 367 | }; | |
| 368 | ||
| 369 | struct shape_t { | |
| 370 | std::string name; | |
| 371 | mesh_t mesh; | |
| 372 | lines_t lines; | |
| 373 | points_t points; | |
| 374 | }; | |
| 375 | ||
| 376 | // Vertex attributes | |
| 377 | struct attrib_t { | |
| 378 | std::vector<real_t> vertices; // 'v'(xyz) | |
| 379 | ||
| 380 | // For backward compatibility, we store vertex weight in separate array. | |
| 381 | std::vector<real_t> vertex_weights; // 'v'(w) | |
| 382 | std::vector<real_t> normals; // 'vn' | |
| 383 | std::vector<real_t> texcoords; // 'vt'(uv) | |
| 384 | ||
| 385 | // For backward compatibility, we store texture coordinate 'w' in separate | |
| 386 | // array. | |
| 387 | std::vector<real_t> texcoord_ws; // 'vt'(w) | |
| 388 | std::vector<real_t> colors; // extension: vertex colors | |
| 389 | ||
| 390 | // | |
| 391 | // TinyObj extension. | |
| 392 | // | |
| 393 | ||
| 394 | // NOTE(syoyo): array index is based on the appearance order. | |
| 395 | // To get a corresponding skin weight for a specific vertex id `vid`, | |
| 396 | // Need to reconstruct a look up table: `skin_weight_t::vertex_id` == `vid` | |
| 397 | // (e.g. using std::map, std::unordered_map) | |
| 398 | std::vector<skin_weight_t> skin_weights; | |
| 399 | ||
| 400 | 37x | attrib_t() {} |
| 401 | ||
| 402 | // | |
| 403 | // For pybind11 | |
| 404 | // | |
| 405 | const std::vector<real_t> &GetVertices() const { return vertices; } | |
| 406 | ||
| 407 | const std::vector<real_t> &GetVertexWeights() const { return vertex_weights; } | |
| 408 | }; | |
| 409 | ||
| 410 | struct callback_t { | |
| 411 | // W is optional and set to 1 if there is no `w` item in `v` line | |
| 412 | void (*vertex_cb)(void *user_data, real_t x, real_t y, real_t z, real_t w); | |
| 413 | void (*normal_cb)(void *user_data, real_t x, real_t y, real_t z); | |
| 414 | ||
| 415 | // y and z are optional and set to 0 if there is no `y` and/or `z` item(s) in | |
| 416 | // `vt` line. | |
| 417 | void (*texcoord_cb)(void *user_data, real_t x, real_t y, real_t z); | |
| 418 | ||
| 419 | // called per 'f' line. num_indices is the number of face indices(e.g. 3 for | |
| 420 | // triangle, 4 for quad) | |
| 421 | // 0 will be passed for undefined index in index_t members. | |
| 422 | void (*index_cb)(void *user_data, index_t *indices, int num_indices); | |
| 423 | // `name` material name, `material_id` = the array index of material_t[]. -1 | |
| 424 | // if | |
| 425 | // a material not found in .mtl | |
| 426 | void (*usemtl_cb)(void *user_data, const char *name, int material_id); | |
| 427 | // `materials` = parsed material data. | |
| 428 | void (*mtllib_cb)(void *user_data, const material_t *materials, | |
| 429 | int num_materials); | |
| 430 | // There may be multiple group names | |
| 431 | void (*group_cb)(void *user_data, const char **names, int num_names); | |
| 432 | void (*object_cb)(void *user_data, const char *name); | |
| 433 | ||
| 434 | callback_t() | |
| 435 | : vertex_cb(NULL), | |
| 436 | normal_cb(NULL), | |
| 437 | texcoord_cb(NULL), | |
| 438 | index_cb(NULL), | |
| 439 | usemtl_cb(NULL), | |
| 440 | mtllib_cb(NULL), | |
| 441 | group_cb(NULL), | |
| 442 | object_cb(NULL) {} | |
| 443 | }; | |
| 444 | ||
| 445 | class MaterialReader { | |
| 446 | public: | |
| 447 | 37x | MaterialReader() {} |
| 448 | virtual ~MaterialReader(); | |
| 449 | ||
| 450 | virtual bool operator()(const std::string &matId, | |
| 451 | std::vector<material_t> *materials, | |
| 452 | std::map<std::string, int> *matMap, std::string *warn, | |
| 453 | std::string *err) = 0; | |
| 454 | }; | |
| 455 | ||
| 456 | /// | |
| 457 | /// Read .mtl from a file. | |
| 458 | /// | |
| 459 | class MaterialFileReader : public MaterialReader { | |
| 460 | public: | |
| 461 | // Path could contain separator(';' in Windows, ':' in Posix) | |
| 462 | 37x | explicit MaterialFileReader(const std::string &mtl_basedir) |
| 463 | 37x | : m_mtlBaseDir(mtl_basedir) {} |
| 464 | 37x | virtual ~MaterialFileReader() TINYOBJ_OVERRIDE {} |
| 465 | virtual bool operator()(const std::string &matId, | |
| 466 | std::vector<material_t> *materials, | |
| 467 | std::map<std::string, int> *matMap, std::string *warn, | |
| 468 | std::string *err) TINYOBJ_OVERRIDE; | |
| 469 | ||
| 470 | private: | |
| 471 | std::string m_mtlBaseDir; | |
| 472 | }; | |
| 473 | ||
| 474 | /// | |
| 475 | /// Read .mtl from a stream. | |
| 476 | /// | |
| 477 | class MaterialStreamReader : public MaterialReader { | |
| 478 | public: | |
| 479 | ! | explicit MaterialStreamReader(std::istream &inStream) |
| 480 | ! | : m_inStream(inStream) {} |
| 481 | ! | virtual ~MaterialStreamReader() TINYOBJ_OVERRIDE {} |
| 482 | virtual bool operator()(const std::string &matId, | |
| 483 | std::vector<material_t> *materials, | |
| 484 | std::map<std::string, int> *matMap, std::string *warn, | |
| 485 | std::string *err) TINYOBJ_OVERRIDE; | |
| 486 | ||
| 487 | private: | |
| 488 | std::istream &m_inStream; | |
| 489 | }; | |
| 490 | ||
| 491 | // v2 API | |
| 492 | struct ObjReaderConfig { | |
| 493 | bool triangulate; // triangulate polygon? | |
| 494 | ||
| 495 | // Currently not used. | |
| 496 | // "simple" or empty: Create triangle fan | |
| 497 | // "earcut": Use the algorithm based on Ear clipping | |
| 498 | std::string triangulation_method; | |
| 499 | ||
| 500 | /// Parse vertex color. | |
| 501 | /// If vertex color is not present, its filled with default value. | |
| 502 | /// false = no vertex color | |
| 503 | /// This will increase memory of parsed .obj | |
| 504 | bool vertex_color; | |
| 505 | ||
| 506 | /// | |
| 507 | /// Search path to .mtl file. | |
| 508 | /// Default = "" = search from the same directory of .obj file. | |
| 509 | /// Valid only when loading .obj from a file. | |
| 510 | /// | |
| 511 | std::string mtl_search_path; | |
| 512 | ||
| 513 | 37x | ObjReaderConfig() |
| 514 | 111x | : triangulate(true), triangulation_method("simple"), vertex_color(true) {} |
| 515 | }; | |
| 516 | ||
| 517 | /// | |
| 518 | /// Wavefront .obj reader class(v2 API) | |
| 519 | /// | |
| 520 | class ObjReader { | |
| 521 | public: | |
| 522 | 37x | ObjReader() : valid_(false) {} |
| 523 | ||
| 524 | /// | |
| 525 | /// Load .obj and .mtl from a file. | |
| 526 | /// | |
| 527 | /// @param[in] filename wavefront .obj filename | |
| 528 | /// @param[in] config Reader configuration | |
| 529 | /// | |
| 530 | bool ParseFromFile(const std::string &filename, | |
| 531 | const ObjReaderConfig &config = ObjReaderConfig()); | |
| 532 | ||
| 533 | /// | |
| 534 | /// Parse .obj from a text string. | |
| 535 | /// Need to supply .mtl text string by `mtl_text`. | |
| 536 | /// This function ignores `mtllib` line in .obj text. | |
| 537 | /// | |
| 538 | /// @param[in] obj_text wavefront .obj filename | |
| 539 | /// @param[in] mtl_text wavefront .mtl filename | |
| 540 | /// @param[in] config Reader configuration | |
| 541 | /// | |
| 542 | bool ParseFromString(const std::string &obj_text, const std::string &mtl_text, | |
| 543 | const ObjReaderConfig &config = ObjReaderConfig()); | |
| 544 | ||
| 545 | /// | |
| 546 | /// .obj was loaded or parsed correctly. | |
| 547 | /// | |
| 548 | bool Valid() const { return valid_; } | |
| 549 | ||
| 550 | 37x | const attrib_t &GetAttrib() const { return attrib_; } |
| 551 | ||
| 552 | 37x | std::vector<shape_t> &GetShapes() { return shapes_; } |
| 553 | ||
| 554 | 37x | std::vector<material_t> &GetMaterials() { return materials_; } |
| 555 | ||
| 556 | /// | |
| 557 | /// Warning message(may be filled after `Load` or `Parse`) | |
| 558 | /// | |
| 559 | 37x | const std::string &Warning() const { return warning_; } |
| 560 | ||
| 561 | /// | |
| 562 | /// Error message(filled when `Load` or `Parse` failed) | |
| 563 | /// | |
| 564 | ! | const std::string &Error() const { return error_; } |
| 565 | ||
| 566 | private: | |
| 567 | bool valid_; | |
| 568 | ||
| 569 | attrib_t attrib_; | |
| 570 | std::vector<shape_t> shapes_; | |
| 571 | std::vector<material_t> materials_; | |
| 572 | ||
| 573 | std::string warning_; | |
| 574 | std::string error_; | |
| 575 | }; | |
| 576 | ||
| 577 | /// ==>>========= Legacy v1 API ============================================= | |
| 578 | ||
| 579 | /// Loads .obj from a file. | |
| 580 | /// 'attrib', 'shapes' and 'materials' will be filled with parsed shape data | |
| 581 | /// 'shapes' will be filled with parsed shape data | |
| 582 | /// Returns true when loading .obj become success. | |
| 583 | /// Returns warning message into `warn`, and error message into `err` | |
| 584 | /// 'mtl_basedir' is optional, and used for base directory for .mtl file. | |
| 585 | /// In default(`NULL'), .mtl file is searched from an application's working | |
| 586 | /// directory. | |
| 587 | /// 'triangulate' is optional, and used whether triangulate polygon face in .obj | |
| 588 | /// or not. | |
| 589 | /// Option 'default_vcols_fallback' specifies whether vertex colors should | |
| 590 | /// always be defined, even if no colors are given (fallback to white). | |
| 591 | bool LoadObj(attrib_t *attrib, std::vector<shape_t> *shapes, | |
| 592 | std::vector<material_t> *materials, std::string *warn, | |
| 593 | std::string *err, const char *filename, | |
| 594 | const char *mtl_basedir = NULL, bool triangulate = true, | |
| 595 | bool default_vcols_fallback = true); | |
| 596 | ||
| 597 | /// Loads .obj from a file with custom user callback. | |
| 598 | /// .mtl is loaded as usual and parsed material_t data will be passed to | |
| 599 | /// `callback.mtllib_cb`. | |
| 600 | /// Returns true when loading .obj/.mtl become success. | |
| 601 | /// Returns warning message into `warn`, and error message into `err` | |
| 602 | /// See `examples/callback_api/` for how to use this function. | |
| 603 | bool LoadObjWithCallback(std::istream &inStream, const callback_t &callback, | |
| 604 | void *user_data = NULL, | |
| 605 | MaterialReader *readMatFn = NULL, | |
| 606 | std::string *warn = NULL, std::string *err = NULL); | |
| 607 | ||
| 608 | /// Loads object from a std::istream, uses `readMatFn` to retrieve | |
| 609 | /// std::istream for materials. | |
| 610 | /// Returns true when loading .obj become success. | |
| 611 | /// Returns warning and error message into `err` | |
| 612 | bool LoadObj(attrib_t *attrib, std::vector<shape_t> *shapes, | |
| 613 | std::vector<material_t> *materials, std::string *warn, | |
| 614 | std::string *err, std::istream *inStream, | |
| 615 | MaterialReader *readMatFn = NULL, bool triangulate = true, | |
| 616 | bool default_vcols_fallback = true); | |
| 617 | ||
| 618 | /// Loads materials into std::map | |
| 619 | void LoadMtl(std::map<std::string, int> *material_map, | |
| 620 | std::vector<material_t> *materials, std::istream *inStream, | |
| 621 | std::string *warning, std::string *err); | |
| 622 | ||
| 623 | /// | |
| 624 | /// Parse texture name and texture option for custom texture parameter through | |
| 625 | /// material::unknown_parameter | |
| 626 | /// | |
| 627 | /// @param[out] texname Parsed texture name | |
| 628 | /// @param[out] texopt Parsed texopt | |
| 629 | /// @param[in] linebuf Input string | |
| 630 | /// | |
| 631 | bool ParseTextureNameAndOption(std::string *texname, texture_option_t *texopt, | |
| 632 | const char *linebuf); | |
| 633 | ||
| 634 | /// =<<========== Legacy v1 API ============================================= | |
| 635 | ||
| 636 | } // namespace tinyobj | |
| 637 | ||
| 638 | #endif // TINY_OBJ_LOADER_H_ | |
| 639 | ||
| 640 | #ifdef TINYOBJLOADER_IMPLEMENTATION | |
| 641 | #include <cassert> | |
| 642 | #include <cctype> | |
| 643 | #include <cmath> | |
| 644 | #include <cstddef> | |
| 645 | #include <cstdlib> | |
| 646 | #include <cstring> | |
| 647 | #include <fstream> | |
| 648 | #include <limits> | |
| 649 | #include <set> | |
| 650 | #include <sstream> | |
| 651 | #include <utility> | |
| 652 | ||
| 653 | #ifdef TINYOBJLOADER_USE_MAPBOX_EARCUT | |
| 654 | ||
| 655 | #ifdef TINYOBJLOADER_DONOT_INCLUDE_MAPBOX_EARCUT | |
| 656 | // Assume earcut.hpp is included outside of tiny_obj_loader.h | |
| 657 | #else | |
| 658 | ||
| 659 | #include <array> | |
| 660 | #include "earcut.h" | |
| 661 | ||
| 662 | #endif | |
| 663 | ||
| 664 | #endif // TINYOBJLOADER_USE_MAPBOX_EARCUT | |
| 665 | ||
| 666 | namespace tinyobj { | |
| 667 | ||
| 668 | 37x | MaterialReader::~MaterialReader() {} |
| 669 | ||
| 670 | struct vertex_index_t { | |
| 671 | int v_idx, vt_idx, vn_idx; | |
| 672 | 19938x | vertex_index_t() : v_idx(-1), vt_idx(-1), vn_idx(-1) {} |
| 673 | 19938x | explicit vertex_index_t(int idx) : v_idx(idx), vt_idx(idx), vn_idx(idx) {} |
| 674 | vertex_index_t(int vidx, int vtidx, int vnidx) | |
| 675 | : v_idx(vidx), vt_idx(vtidx), vn_idx(vnidx) {} | |
| 676 | }; | |
| 677 | ||
| 678 | // Internal data structure for face representation | |
| 679 | // index + smoothing group. | |
| 680 | struct face_t { | |
| 681 | unsigned int | |
| 682 | smoothing_group_id; // smoothing group id. 0 = smoothing groupd is off. | |
| 683 | int pad_; | |
| 684 | std::vector<vertex_index_t> vertex_indices; // face vertex indices. | |
| 685 | ||
| 686 | 6315x | face_t() : smoothing_group_id(0), pad_(0) {} |
| 687 | }; | |
| 688 | ||
| 689 | // Internal data structure for line representation | |
| 690 | struct __line_t { | |
| 691 | // l v1/vt1 v2/vt2 ... | |
| 692 | // In the specification, line primitrive does not have normal index, but | |
| 693 | // TinyObjLoader allow it | |
| 694 | std::vector<vertex_index_t> vertex_indices; | |
| 695 | }; | |
| 696 | ||
| 697 | // Internal data structure for points representation | |
| 698 | struct __points_t { | |
| 699 | // p v1 v2 ... | |
| 700 | // In the specification, point primitrive does not have normal index and | |
| 701 | // texture coord index, but TinyObjLoader allow it. | |
| 702 | std::vector<vertex_index_t> vertex_indices; | |
| 703 | }; | |
| 704 | ||
| 705 | struct tag_sizes { | |
| 706 | ! | tag_sizes() : num_ints(0), num_reals(0), num_strings(0) {} |
| 707 | int num_ints; | |
| 708 | int num_reals; | |
| 709 | int num_strings; | |
| 710 | }; | |
| 711 | ||
| 712 | struct obj_shape { | |
| 713 | std::vector<real_t> v; | |
| 714 | std::vector<real_t> vn; | |
| 715 | std::vector<real_t> vt; | |
| 716 | }; | |
| 717 | ||
| 718 | // | |
| 719 | // Manages group of primitives(face, line, points, ...) | |
| 720 | struct PrimGroup { | |
| 721 | std::vector<face_t> faceGroup; | |
| 722 | std::vector<__line_t> lineGroup; | |
| 723 | std::vector<__points_t> pointsGroup; | |
| 724 | ||
| 725 | 73x | void clear() { |
| 726 | 73x | faceGroup.clear(); |
| 727 | 73x | lineGroup.clear(); |
| 728 | 73x | pointsGroup.clear(); |
| 729 | } | |
| 730 | ||
| 731 | 79x | bool IsEmpty() const { |
| 732 | 79x | return faceGroup.empty() && lineGroup.empty() && pointsGroup.empty(); |
| 733 | } | |
| 734 | ||
| 735 | // TODO(syoyo): bspline, surface, ... | |
| 736 | }; | |
| 737 | ||
| 738 | // See | |
| 739 | // http://stackoverflow.com/questions/6089231/getting-std-ifstream-to-handle-lf-cr-and-crlf | |
| 740 | 18119x | static std::istream &safeGetline(std::istream &is, std::string &t) { |
| 741 | 18119x | t.clear(); |
| 742 | ||
| 743 | // The characters in the stream are read one-by-one using a std::streambuf. | |
| 744 | // That is faster than reading them one-by-one using the std::istream. | |
| 745 | // Code that uses streambuf this way must be guarded by a sentry object. | |
| 746 | // The sentry object performs various tasks, | |
| 747 | // such as thread synchronization and updating the stream state. | |
| 748 | ||
| 749 | 18119x | std::istream::sentry se(is, true); |
| 750 | 18119x | std::streambuf *sb = is.rdbuf(); |
| 751 | ||
| 752 | 18119x | if (se) { |
| 753 | for (;;) { | |
| 754 | 517275x | int c = sb->sbumpc(); |
| 755 | 517275x | switch (c) { |
| 756 | 18119x | case '\n': |
| 757 | 18119x | return is; |
| 758 | ! | case '\r': |
| 759 | ! | if (sb->sgetc() == '\n') sb->sbumpc(); |
| 760 | ! | return is; |
| 761 | ! | case EOF: |
| 762 | // Also handle the case when the last line has no line ending | |
| 763 | ! | if (t.empty()) is.setstate(std::ios::eofbit); |
| 764 | ! | return is; |
| 765 | 499156x | default: |
| 766 | 499156x | t += static_cast<char>(c); |
| 767 | } | |
| 768 | } | |
| 769 | } | |
| 770 | ||
| 771 | ! | return is; |
| 772 | } | |
| 773 | ||
| 774 | #define IS_SPACE(x) (((x) == ' ') || ((x) == '\t')) | |
| 775 | #define IS_DIGIT(x) \ | |
| 776 | (static_cast<unsigned int>((x) - '0') < static_cast<unsigned int>(10)) | |
| 777 | #define IS_NEW_LINE(x) (((x) == '\r') || ((x) == '\n') || ((x) == '\0')) | |
| 778 | ||
| 779 | // Make index zero-base, and also support relative index. | |
| 780 | 54240x | static inline bool fixIndex(int idx, int n, int *ret) { |
| 781 | 54240x | if (!ret) { |
| 782 | ! | return false; |
| 783 | } | |
| 784 | ||
| 785 | 54240x | if (idx > 0) { |
| 786 | 54240x | (*ret) = idx - 1; |
| 787 | 54240x | return true; |
| 788 | } | |
| 789 | ||
| 790 | ! | if (idx == 0) { |
| 791 | // zero is not allowed according to the spec. | |
| 792 | ! | return false; |
| 793 | } | |
| 794 | ||
| 795 | ! | if (idx < 0) { |
| 796 | ! | (*ret) = n + idx; // negative value = relative |
| 797 | ! | return true; |
| 798 | } | |
| 799 | ||
| 800 | ! | return false; // never reach here. |
| 801 | } | |
| 802 | ||
| 803 | 12x | static inline std::string parseString(const char **token) { |
| 804 | 12x | std::string s; |
| 805 | 12x | (*token) += strspn((*token), " \t"); |
| 806 | 12x | size_t e = strcspn((*token), " \t\r"); |
| 807 | 12x | s = std::string((*token), &(*token)[e]); |
| 808 | 12x | (*token) += e; |
| 809 | 12x | return s; |
| 810 | } | |
| 811 | ||
| 812 | 32x | static inline int parseInt(const char **token) { |
| 813 | 32x | (*token) += strspn((*token), " \t"); |
| 814 | 32x | int i = atoi((*token)); |
| 815 | 32x | (*token) += strcspn((*token), " \t\r"); |
| 816 | 32x | return i; |
| 817 | } | |
| 818 | ||
| 819 | // Tries to parse a floating point number located at s. | |
| 820 | // | |
| 821 | // s_end should be a location in the string where reading should absolutely | |
| 822 | // stop. For example at the end of the string, to prevent buffer overflows. | |
| 823 | // | |
| 824 | // Parses the following EBNF grammar: | |
| 825 | // sign = "+" | "-" ; | |
| 826 | // END = ? anything not in digit ? | |
| 827 | // digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ; | |
| 828 | // integer = [sign] , digit , {digit} ; | |
| 829 | // decimal = integer , ["." , integer] ; | |
| 830 | // float = ( decimal , END ) | ( decimal , ("E" | "e") , integer , END ) ; | |
| 831 | // | |
| 832 | // Valid strings are for example: | |
| 833 | // -0 +3.1417e+2 -0.0E-3 1.0324 -1.41 11e2 | |
| 834 | // | |
| 835 | // If the parsing is a success, result is set to the parsed value and true | |
| 836 | // is returned. | |
| 837 | // | |
| 838 | // The function is greedy and will parse until any of the following happens: | |
| 839 | // - a non-conforming character is encountered. | |
| 840 | // - s_end is reached. | |
| 841 | // | |
| 842 | // The following situations triggers a failure: | |
| 843 | // - s >= s_end. | |
| 844 | // - parse failure. | |
| 845 | // | |
| 846 | 36583x | static bool tryParseDouble(const char *s, const char *s_end, double *result) { |
| 847 | 36583x | if (s >= s_end) { |
| 848 | 4962x | return false; |
| 849 | } | |
| 850 | ||
| 851 | 31621x | double mantissa = 0.0; |
| 852 | // This exponent is base 2 rather than 10. | |
| 853 | // However the exponent we parse is supposed to be one of ten, | |
| 854 | // thus we must take care to convert the exponent/and or the | |
| 855 | // mantissa to a * 2^E, where a is the mantissa and E is the | |
| 856 | // exponent. | |
| 857 | // To get the final double we will use ldexp, it requires the | |
| 858 | // exponent to be in base 2. | |
| 859 | 31621x | int exponent = 0; |
| 860 | ||
| 861 | // NOTE: THESE MUST BE DECLARED HERE SINCE WE ARE NOT ALLOWED | |
| 862 | // TO JUMP OVER DEFINITIONS. | |
| 863 | 31621x | char sign = '+'; |
| 864 | 31621x | char exp_sign = '+'; |
| 865 | 31621x | char const *curr = s; |
| 866 | ||
| 867 | // How many characters were read in a loop. | |
| 868 | 31621x | int read = 0; |
| 869 | // Tells whether a loop terminated due to reaching s_end. | |
| 870 | 31621x | bool end_not_reached = false; |
| 871 | 31621x | bool leading_decimal_dots = false; |
| 872 | ||
| 873 | /* | |
| 874 | BEGIN PARSING. | |
| 875 | */ | |
| 876 | ||
| 877 | // Find out what sign we've got. | |
| 878 | 31621x | if (*curr == '+' || *curr == '-') { |
| 879 | 9907x | sign = *curr; |
| 880 | 9907x | curr++; |
| 881 | 9907x | if ((curr != s_end) && (*curr == '.')) { |
| 882 | // accept. Somethig like `.7e+2`, `-.5234` | |
| 883 | ! | leading_decimal_dots = true; |
| 884 | } | |
| 885 | 21714x | } else if (IS_DIGIT(*curr)) { /* Pass through. */ |
| 886 | ! | } else if (*curr == '.') { |
| 887 | // accept. Somethig like `.7e+2`, `-.5234` | |
| 888 | ! | leading_decimal_dots = true; |
| 889 | } else { | |
| 890 | ! | goto fail; |
| 891 | } | |
| 892 | ||
| 893 | // Read the integer part. | |
| 894 | 31621x | end_not_reached = (curr != s_end); |
| 895 | 31621x | if (!leading_decimal_dots) { |
| 896 | 63247x | while (end_not_reached && IS_DIGIT(*curr)) { |
| 897 | 31626x | mantissa *= 10; |
| 898 | 31626x | mantissa += static_cast<int>(*curr - 0x30); |
| 899 | 31626x | curr++; |
| 900 | 31626x | read++; |
| 901 | 31626x | end_not_reached = (curr != s_end); |
| 902 | } | |
| 903 | ||
| 904 | // We must make sure we actually got something. | |
| 905 | 31621x | if (read == 0) goto fail; |
| 906 | } | |
| 907 | ||
| 908 | // We allow numbers of form "#", "###" etc. | |
| 909 | 31621x | if (!end_not_reached) goto assemble; |
| 910 | ||
| 911 | // Read the decimal part. | |
| 912 | 31609x | if (*curr == '.') { |
| 913 | 31609x | curr++; |
| 914 | 31609x | read = 1; |
| 915 | 31609x | end_not_reached = (curr != s_end); |
| 916 | 206594x | while (end_not_reached && IS_DIGIT(*curr)) { |
| 917 | static const double pow_lut[] = { | |
| 918 | 1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001, | |
| 919 | }; | |
| 920 | 174985x | const int lut_entries = sizeof pow_lut / sizeof pow_lut[0]; |
| 921 | ||
| 922 | // NOTE: Don't use powf here, it will absolutely murder precision. | |
| 923 | 349970x | mantissa += static_cast<int>(*curr - 0x30) * |
| 924 | 174985x | (read < lut_entries ? pow_lut[read] : std::pow(10.0, -read)); |
| 925 | 174985x | read++; |
| 926 | 174985x | curr++; |
| 927 | 174985x | end_not_reached = (curr != s_end); |
| 928 | } | |
| 929 | ! | } else if (*curr == 'e' || *curr == 'E') { |
| 930 | } else { | |
| 931 | ! | goto assemble; |
| 932 | } | |
| 933 | ||
| 934 | 31609x | if (!end_not_reached) goto assemble; |
| 935 | ||
| 936 | // Read the exponent part. | |
| 937 | 4x | if (*curr == 'e' || *curr == 'E') { |
| 938 | 4x | curr++; |
| 939 | // Figure out if a sign is present and if it is. | |
| 940 | 4x | end_not_reached = (curr != s_end); |
| 941 | 4x | if (end_not_reached && (*curr == '+' || *curr == '-')) { |
| 942 | 4x | exp_sign = *curr; |
| 943 | 4x | curr++; |
| 944 | ! | } else if (IS_DIGIT(*curr)) { /* Pass through. */ |
| 945 | } else { | |
| 946 | // Empty E is not allowed. | |
| 947 | ! | goto fail; |
| 948 | } | |
| 949 | ||
| 950 | 4x | read = 0; |
| 951 | 4x | end_not_reached = (curr != s_end); |
| 952 | 12x | while (end_not_reached && IS_DIGIT(*curr)) { |
| 953 | // To avoid annoying MSVC's min/max macro definiton, | |
| 954 | // Use hardcoded int max value | |
| 955 | 8x | if (exponent > (2147483647/10)) { // 2147483647 = std::numeric_limits<int>::max() |
| 956 | // Integer overflow | |
| 957 | ! | goto fail; |
| 958 | } | |
| 959 | 8x | exponent *= 10; |
| 960 | 8x | exponent += static_cast<int>(*curr - 0x30); |
| 961 | 8x | curr++; |
| 962 | 8x | read++; |
| 963 | 8x | end_not_reached = (curr != s_end); |
| 964 | } | |
| 965 | 4x | exponent *= (exp_sign == '+' ? 1 : -1); |
| 966 | 4x | if (read == 0) goto fail; |
| 967 | } | |
| 968 | ||
| 969 | 4x | assemble: |
| 970 | 31621x | *result = (sign == '+' ? 1 : -1) * |
| 971 | 31621x | (exponent ? std::ldexp(mantissa * std::pow(5.0, exponent), exponent) |
| 972 | : mantissa); | |
| 973 | 31621x | return true; |
| 974 | ! | fail: |
| 975 | ! | return false; |
| 976 | } | |
| 977 | ||
| 978 | 31621x | static inline real_t parseReal(const char **token, double default_value = 0.0) { |
| 979 | 31621x | (*token) += strspn((*token), " \t"); |
| 980 | 31621x | const char *end = (*token) + strcspn((*token), " \t\r"); |
| 981 | 31621x | double val = default_value; |
| 982 | 31621x | tryParseDouble((*token), end, &val); |
| 983 | 31621x | real_t f = static_cast<real_t>(val); |
| 984 | 31621x | (*token) = end; |
| 985 | 31621x | return f; |
| 986 | } | |
| 987 | ||
| 988 | 4962x | static inline bool parseReal(const char **token, real_t *out) { |
| 989 | 4962x | (*token) += strspn((*token), " \t"); |
| 990 | 4962x | const char *end = (*token) + strcspn((*token), " \t\r"); |
| 991 | double val; | |
| 992 | 4962x | bool ret = tryParseDouble((*token), end, &val); |
| 993 | 4962x | if (ret) { |
| 994 | ! | real_t f = static_cast<real_t>(val); |
| 995 | ! | (*out) = f; |
| 996 | } | |
| 997 | 4962x | (*token) = end; |
| 998 | 4962x | return ret; |
| 999 | } | |
| 1000 | ||
| 1001 | 3361x | static inline void parseReal2(real_t *x, real_t *y, const char **token, |
| 1002 | const double default_x = 0.0, | |
| 1003 | const double default_y = 0.0) { | |
| 1004 | 3361x | (*x) = parseReal(token, default_x); |
| 1005 | 3361x | (*y) = parseReal(token, default_y); |
| 1006 | } | |
| 1007 | ||
| 1008 | 3336x | static inline void parseReal3(real_t *x, real_t *y, real_t *z, |
| 1009 | const char **token, const double default_x = 0.0, | |
| 1010 | const double default_y = 0.0, | |
| 1011 | const double default_z = 0.0) { | |
| 1012 | 3336x | (*x) = parseReal(token, default_x); |
| 1013 | 3336x | (*y) = parseReal(token, default_y); |
| 1014 | 3336x | (*z) = parseReal(token, default_z); |
| 1015 | } | |
| 1016 | ||
| 1017 | ! | static inline void parseV(real_t *x, real_t *y, real_t *z, real_t *w, |
| 1018 | const char **token, const double default_x = 0.0, | |
| 1019 | const double default_y = 0.0, | |
| 1020 | const double default_z = 0.0, | |
| 1021 | const double default_w = 1.0) { | |
| 1022 | ! | (*x) = parseReal(token, default_x); |
| 1023 | ! | (*y) = parseReal(token, default_y); |
| 1024 | ! | (*z) = parseReal(token, default_z); |
| 1025 | ! | (*w) = parseReal(token, default_w); |
| 1026 | } | |
| 1027 | ||
| 1028 | // Extension: parse vertex with colors(6 items) | |
| 1029 | 4962x | static inline bool parseVertexWithColor(real_t *x, real_t *y, real_t *z, |
| 1030 | real_t *r, real_t *g, real_t *b, | |
| 1031 | const char **token, | |
| 1032 | const double default_x = 0.0, | |
| 1033 | const double default_y = 0.0, | |
| 1034 | const double default_z = 0.0) { | |
| 1035 | 4962x | (*x) = parseReal(token, default_x); |
| 1036 | 4962x | (*y) = parseReal(token, default_y); |
| 1037 | 4962x | (*z) = parseReal(token, default_z); |
| 1038 | ||
| 1039 | const bool found_color = | |
| 1040 | 4962x | parseReal(token, r) && parseReal(token, g) && parseReal(token, b); |
| 1041 | ||
| 1042 | 4962x | if (!found_color) { |
| 1043 | 4962x | (*r) = (*g) = (*b) = 1.0; |
| 1044 | } | |
| 1045 | ||
| 1046 | 4962x | return found_color; |
| 1047 | } | |
| 1048 | ||
| 1049 | ! | static inline bool parseOnOff(const char **token, bool default_value = true) { |
| 1050 | ! | (*token) += strspn((*token), " \t"); |
| 1051 | ! | const char *end = (*token) + strcspn((*token), " \t\r"); |
| 1052 | ||
| 1053 | ! | bool ret = default_value; |
| 1054 | ! | if ((0 == strncmp((*token), "on", 2))) { |
| 1055 | ! | ret = true; |
| 1056 | ! | } else if ((0 == strncmp((*token), "off", 3))) { |
| 1057 | ! | ret = false; |
| 1058 | } | |
| 1059 | ||
| 1060 | ! | (*token) = end; |
| 1061 | ! | return ret; |
| 1062 | } | |
| 1063 | ||
| 1064 | ! | static inline texture_type_t parseTextureType( |
| 1065 | const char **token, texture_type_t default_value = TEXTURE_TYPE_NONE) { | |
| 1066 | ! | (*token) += strspn((*token), " \t"); |
| 1067 | ! | const char *end = (*token) + strcspn((*token), " \t\r"); |
| 1068 | ! | texture_type_t ty = default_value; |
| 1069 | ||
| 1070 | ! | if ((0 == strncmp((*token), "cube_top", strlen("cube_top")))) { |
| 1071 | ! | ty = TEXTURE_TYPE_CUBE_TOP; |
| 1072 | ! | } else if ((0 == strncmp((*token), "cube_bottom", strlen("cube_bottom")))) { |
| 1073 | ! | ty = TEXTURE_TYPE_CUBE_BOTTOM; |
| 1074 | ! | } else if ((0 == strncmp((*token), "cube_left", strlen("cube_left")))) { |
| 1075 | ! | ty = TEXTURE_TYPE_CUBE_LEFT; |
| 1076 | ! | } else if ((0 == strncmp((*token), "cube_right", strlen("cube_right")))) { |
| 1077 | ! | ty = TEXTURE_TYPE_CUBE_RIGHT; |
| 1078 | ! | } else if ((0 == strncmp((*token), "cube_front", strlen("cube_front")))) { |
| 1079 | ! | ty = TEXTURE_TYPE_CUBE_FRONT; |
| 1080 | ! | } else if ((0 == strncmp((*token), "cube_back", strlen("cube_back")))) { |
| 1081 | ! | ty = TEXTURE_TYPE_CUBE_BACK; |
| 1082 | ! | } else if ((0 == strncmp((*token), "sphere", strlen("sphere")))) { |
| 1083 | ! | ty = TEXTURE_TYPE_SPHERE; |
| 1084 | } | |
| 1085 | ||
| 1086 | ! | (*token) = end; |
| 1087 | ! | return ty; |
| 1088 | } | |
| 1089 | ||
| 1090 | ! | static tag_sizes parseTagTriple(const char **token) { |
| 1091 | ! | tag_sizes ts; |
| 1092 | ||
| 1093 | ! | (*token) += strspn((*token), " \t"); |
| 1094 | ! | ts.num_ints = atoi((*token)); |
| 1095 | ! | (*token) += strcspn((*token), "/ \t\r"); |
| 1096 | ! | if ((*token)[0] != '/') { |
| 1097 | ! | return ts; |
| 1098 | } | |
| 1099 | ||
| 1100 | ! | (*token)++; // Skip '/' |
| 1101 | ||
| 1102 | ! | (*token) += strspn((*token), " \t"); |
| 1103 | ! | ts.num_reals = atoi((*token)); |
| 1104 | ! | (*token) += strcspn((*token), "/ \t\r"); |
| 1105 | ! | if ((*token)[0] != '/') { |
| 1106 | ! | return ts; |
| 1107 | } | |
| 1108 | ! | (*token)++; // Skip '/' |
| 1109 | ||
| 1110 | ! | ts.num_strings = parseInt(token); |
| 1111 | ||
| 1112 | ! | return ts; |
| 1113 | } | |
| 1114 | ||
| 1115 | // Parse triples with index offsets: i, i/j/k, i//k, i/j | |
| 1116 | 19938x | static bool parseTriple(const char **token, int vsize, int vnsize, int vtsize, |
| 1117 | vertex_index_t *ret) { | |
| 1118 | 19938x | if (!ret) { |
| 1119 | ! | return false; |
| 1120 | } | |
| 1121 | ||
| 1122 | 19938x | vertex_index_t vi(-1); |
| 1123 | ||
| 1124 | 19938x | if (!fixIndex(atoi((*token)), vsize, &(vi.v_idx))) { |
| 1125 | ! | return false; |
| 1126 | } | |
| 1127 | ||
| 1128 | 19938x | (*token) += strcspn((*token), "/ \t\r"); |
| 1129 | 19938x | if ((*token)[0] != '/') { |
| 1130 | 96x | (*ret) = vi; |
| 1131 | 96x | return true; |
| 1132 | } | |
| 1133 | 19842x | (*token)++; |
| 1134 | ||
| 1135 | // i//k | |
| 1136 | 19842x | if ((*token)[0] == '/') { |
| 1137 | 5076x | (*token)++; |
| 1138 | 5076x | if (!fixIndex(atoi((*token)), vnsize, &(vi.vn_idx))) { |
| 1139 | ! | return false; |
| 1140 | } | |
| 1141 | 5076x | (*token) += strcspn((*token), "/ \t\r"); |
| 1142 | 5076x | (*ret) = vi; |
| 1143 | 5076x | return true; |
| 1144 | } | |
| 1145 | ||
| 1146 | // i/j/k or i/j | |
| 1147 | 14766x | if (!fixIndex(atoi((*token)), vtsize, &(vi.vt_idx))) { |
| 1148 | ! | return false; |
| 1149 | } | |
| 1150 | ||
| 1151 | 14766x | (*token) += strcspn((*token), "/ \t\r"); |
| 1152 | 14766x | if ((*token)[0] != '/') { |
| 1153 | 306x | (*ret) = vi; |
| 1154 | 306x | return true; |
| 1155 | } | |
| 1156 | ||
| 1157 | // i/j/k | |
| 1158 | 14460x | (*token)++; // skip '/' |
| 1159 | 14460x | if (!fixIndex(atoi((*token)), vnsize, &(vi.vn_idx))) { |
| 1160 | ! | return false; |
| 1161 | } | |
| 1162 | 14460x | (*token) += strcspn((*token), "/ \t\r"); |
| 1163 | ||
| 1164 | 14460x | (*ret) = vi; |
| 1165 | ||
| 1166 | 14460x | return true; |
| 1167 | } | |
| 1168 | ||
| 1169 | // Parse raw triples: i, i/j/k, i//k, i/j | |
| 1170 | ! | static vertex_index_t parseRawTriple(const char **token) { |
| 1171 | ! | vertex_index_t vi(static_cast<int>(0)); // 0 is an invalid index in OBJ |
| 1172 | ||
| 1173 | ! | vi.v_idx = atoi((*token)); |
| 1174 | ! | (*token) += strcspn((*token), "/ \t\r"); |
| 1175 | ! | if ((*token)[0] != '/') { |
| 1176 | ! | return vi; |
| 1177 | } | |
| 1178 | ! | (*token)++; |
| 1179 | ||
| 1180 | // i//k | |
| 1181 | ! | if ((*token)[0] == '/') { |
| 1182 | ! | (*token)++; |
| 1183 | ! | vi.vn_idx = atoi((*token)); |
| 1184 | ! | (*token) += strcspn((*token), "/ \t\r"); |
| 1185 | ! | return vi; |
| 1186 | } | |
| 1187 | ||
| 1188 | // i/j/k or i/j | |
| 1189 | ! | vi.vt_idx = atoi((*token)); |
| 1190 | ! | (*token) += strcspn((*token), "/ \t\r"); |
| 1191 | ! | if ((*token)[0] != '/') { |
| 1192 | ! | return vi; |
| 1193 | } | |
| 1194 | ||
| 1195 | // i/j/k | |
| 1196 | ! | (*token)++; // skip '/' |
| 1197 | ! | vi.vn_idx = atoi((*token)); |
| 1198 | ! | (*token) += strcspn((*token), "/ \t\r"); |
| 1199 | ! | return vi; |
| 1200 | } | |
| 1201 | ||
| 1202 | 1x | bool ParseTextureNameAndOption(std::string *texname, texture_option_t *texopt, |
| 1203 | const char *linebuf) { | |
| 1204 | // @todo { write more robust lexer and parser. } | |
| 1205 | 1x | bool found_texname = false; |
| 1206 | 1x | std::string texture_name; |
| 1207 | ||
| 1208 | 1x | const char *token = linebuf; // Assume line ends with NULL |
| 1209 | ||
| 1210 | 2x | while (!IS_NEW_LINE((*token))) { |
| 1211 | 1x | token += strspn(token, " \t"); // skip space |
| 1212 | 1x | if ((0 == strncmp(token, "-blendu", 7)) && IS_SPACE((token[7]))) { |
| 1213 | ! | token += 8; |
| 1214 | ! | texopt->blendu = parseOnOff(&token, /* default */ true); |
| 1215 | 1x | } else if ((0 == strncmp(token, "-blendv", 7)) && IS_SPACE((token[7]))) { |
| 1216 | ! | token += 8; |
| 1217 | ! | texopt->blendv = parseOnOff(&token, /* default */ true); |
| 1218 | 1x | } else if ((0 == strncmp(token, "-clamp", 6)) && IS_SPACE((token[6]))) { |
| 1219 | ! | token += 7; |
| 1220 | ! | texopt->clamp = parseOnOff(&token, /* default */ true); |
| 1221 | 1x | } else if ((0 == strncmp(token, "-boost", 6)) && IS_SPACE((token[6]))) { |
| 1222 | ! | token += 7; |
| 1223 | ! | texopt->sharpness = parseReal(&token, 1.0); |
| 1224 | 1x | } else if ((0 == strncmp(token, "-bm", 3)) && IS_SPACE((token[3]))) { |
| 1225 | ! | token += 4; |
| 1226 | ! | texopt->bump_multiplier = parseReal(&token, 1.0); |
| 1227 | 1x | } else if ((0 == strncmp(token, "-o", 2)) && IS_SPACE((token[2]))) { |
| 1228 | ! | token += 3; |
| 1229 | ! | parseReal3(&(texopt->origin_offset[0]), &(texopt->origin_offset[1]), |
| 1230 | &(texopt->origin_offset[2]), &token); | |
| 1231 | 1x | } else if ((0 == strncmp(token, "-s", 2)) && IS_SPACE((token[2]))) { |
| 1232 | ! | token += 3; |
| 1233 | ! | parseReal3(&(texopt->scale[0]), &(texopt->scale[1]), &(texopt->scale[2]), |
| 1234 | &token, 1.0, 1.0, 1.0); | |
| 1235 | 1x | } else if ((0 == strncmp(token, "-t", 2)) && IS_SPACE((token[2]))) { |
| 1236 | ! | token += 3; |
| 1237 | ! | parseReal3(&(texopt->turbulence[0]), &(texopt->turbulence[1]), |
| 1238 | &(texopt->turbulence[2]), &token); | |
| 1239 | 1x | } else if ((0 == strncmp(token, "-type", 5)) && IS_SPACE((token[5]))) { |
| 1240 | ! | token += 5; |
| 1241 | ! | texopt->type = parseTextureType((&token), TEXTURE_TYPE_NONE); |
| 1242 | 1x | } else if ((0 == strncmp(token, "-texres", 7)) && IS_SPACE((token[7]))) { |
| 1243 | ! | token += 7; |
| 1244 | // TODO(syoyo): Check if arg is int type. | |
| 1245 | ! | texopt->texture_resolution = parseInt(&token); |
| 1246 | 1x | } else if ((0 == strncmp(token, "-imfchan", 8)) && IS_SPACE((token[8]))) { |
| 1247 | ! | token += 9; |
| 1248 | ! | token += strspn(token, " \t"); |
| 1249 | ! | const char *end = token + strcspn(token, " \t\r"); |
| 1250 | ! | if ((end - token) == 1) { // Assume one char for -imfchan |
| 1251 | ! | texopt->imfchan = (*token); |
| 1252 | } | |
| 1253 | ! | token = end; |
| 1254 | 1x | } else if ((0 == strncmp(token, "-mm", 3)) && IS_SPACE((token[3]))) { |
| 1255 | ! | token += 4; |
| 1256 | ! | parseReal2(&(texopt->brightness), &(texopt->contrast), &token, 0.0, 1.0); |
| 1257 | 1x | } else if ((0 == strncmp(token, "-colorspace", 11)) && |
| 1258 | ! | IS_SPACE((token[11]))) { |
| 1259 | ! | token += 12; |
| 1260 | ! | texopt->colorspace = parseString(&token); |
| 1261 | } else { | |
| 1262 | // Assume texture filename | |
| 1263 | #if 0 | |
| 1264 | size_t len = strcspn(token, " \t\r"); // untile next space | |
| 1265 | texture_name = std::string(token, token + len); | |
| 1266 | token += len; | |
| 1267 | ||
| 1268 | token += strspn(token, " \t"); // skip space | |
| 1269 | #else | |
| 1270 | // Read filename until line end to parse filename containing whitespace | |
| 1271 | // TODO(syoyo): Support parsing texture option flag after the filename. | |
| 1272 | 1x | texture_name = std::string(token); |
| 1273 | 1x | token += texture_name.length(); |
| 1274 | #endif | |
| 1275 | ||
| 1276 | 1x | found_texname = true; |
| 1277 | } | |
| 1278 | } | |
| 1279 | ||
| 1280 | 1x | if (found_texname) { |
| 1281 | 1x | (*texname) = texture_name; |
| 1282 | 1x | return true; |
| 1283 | } else { | |
| 1284 | ! | return false; |
| 1285 | } | |
| 1286 | } | |
| 1287 | ||
| 1288 | 130x | static void InitTexOpt(texture_option_t *texopt, const bool is_bump) { |
| 1289 | 130x | if (is_bump) { |
| 1290 | 10x | texopt->imfchan = 'l'; |
| 1291 | } else { | |
| 1292 | 120x | texopt->imfchan = 'm'; |
| 1293 | } | |
| 1294 | 130x | texopt->bump_multiplier = static_cast<real_t>(1.0); |
| 1295 | 130x | texopt->clamp = false; |
| 1296 | 130x | texopt->blendu = true; |
| 1297 | 130x | texopt->blendv = true; |
| 1298 | 130x | texopt->sharpness = static_cast<real_t>(1.0); |
| 1299 | 130x | texopt->brightness = static_cast<real_t>(0.0); |
| 1300 | 130x | texopt->contrast = static_cast<real_t>(1.0); |
| 1301 | 130x | texopt->origin_offset[0] = static_cast<real_t>(0.0); |
| 1302 | 130x | texopt->origin_offset[1] = static_cast<real_t>(0.0); |
| 1303 | 130x | texopt->origin_offset[2] = static_cast<real_t>(0.0); |
| 1304 | 130x | texopt->scale[0] = static_cast<real_t>(1.0); |
| 1305 | 130x | texopt->scale[1] = static_cast<real_t>(1.0); |
| 1306 | 130x | texopt->scale[2] = static_cast<real_t>(1.0); |
| 1307 | 130x | texopt->turbulence[0] = static_cast<real_t>(0.0); |
| 1308 | 130x | texopt->turbulence[1] = static_cast<real_t>(0.0); |
| 1309 | 130x | texopt->turbulence[2] = static_cast<real_t>(0.0); |
| 1310 | 130x | texopt->texture_resolution = -1; |
| 1311 | 130x | texopt->type = TEXTURE_TYPE_NONE; |
| 1312 | } | |
| 1313 | ||
| 1314 | 10x | static void InitMaterial(material_t *material) { |
| 1315 | 10x | InitTexOpt(&material->ambient_texopt, /* is_bump */ false); |
| 1316 | 10x | InitTexOpt(&material->diffuse_texopt, /* is_bump */ false); |
| 1317 | 10x | InitTexOpt(&material->specular_texopt, /* is_bump */ false); |
| 1318 | 10x | InitTexOpt(&material->specular_highlight_texopt, /* is_bump */ false); |
| 1319 | 10x | InitTexOpt(&material->bump_texopt, /* is_bump */ true); |
| 1320 | 10x | InitTexOpt(&material->displacement_texopt, /* is_bump */ false); |
| 1321 | 10x | InitTexOpt(&material->alpha_texopt, /* is_bump */ false); |
| 1322 | 10x | InitTexOpt(&material->reflection_texopt, /* is_bump */ false); |
| 1323 | 10x | InitTexOpt(&material->roughness_texopt, /* is_bump */ false); |
| 1324 | 10x | InitTexOpt(&material->metallic_texopt, /* is_bump */ false); |
| 1325 | 10x | InitTexOpt(&material->sheen_texopt, /* is_bump */ false); |
| 1326 | 10x | InitTexOpt(&material->emissive_texopt, /* is_bump */ false); |
| 1327 | 10x | InitTexOpt(&material->normal_texopt, |
| 1328 | /* is_bump */ false); // @fixme { is_bump will be true? } | |
| 1329 | 10x | material->name = ""; |
| 1330 | 10x | material->ambient_texname = ""; |
| 1331 | 10x | material->diffuse_texname = ""; |
| 1332 | 10x | material->specular_texname = ""; |
| 1333 | 10x | material->specular_highlight_texname = ""; |
| 1334 | 10x | material->bump_texname = ""; |
| 1335 | 10x | material->displacement_texname = ""; |
| 1336 | 10x | material->reflection_texname = ""; |
| 1337 | 10x | material->alpha_texname = ""; |
| 1338 | 40x | for (int i = 0; i < 3; i++) { |
| 1339 | 30x | material->ambient[i] = static_cast<real_t>(0.0); |
| 1340 | 30x | material->diffuse[i] = static_cast<real_t>(0.0); |
| 1341 | 30x | material->specular[i] = static_cast<real_t>(0.0); |
| 1342 | 30x | material->transmittance[i] = static_cast<real_t>(0.0); |
| 1343 | 30x | material->emission[i] = static_cast<real_t>(0.0); |
| 1344 | } | |
| 1345 | 10x | material->illum = 0; |
| 1346 | 10x | material->dissolve = static_cast<real_t>(1.0); |
| 1347 | 10x | material->shininess = static_cast<real_t>(1.0); |
| 1348 | 10x | material->ior = static_cast<real_t>(1.0); |
| 1349 | ||
| 1350 | 10x | material->roughness = static_cast<real_t>(0.0); |
| 1351 | 10x | material->metallic = static_cast<real_t>(0.0); |
| 1352 | 10x | material->sheen = static_cast<real_t>(0.0); |
| 1353 | 10x | material->clearcoat_thickness = static_cast<real_t>(0.0); |
| 1354 | 10x | material->clearcoat_roughness = static_cast<real_t>(0.0); |
| 1355 | 10x | material->anisotropy_rotation = static_cast<real_t>(0.0); |
| 1356 | 10x | material->anisotropy = static_cast<real_t>(0.0); |
| 1357 | 10x | material->roughness_texname = ""; |
| 1358 | 10x | material->metallic_texname = ""; |
| 1359 | 10x | material->sheen_texname = ""; |
| 1360 | 10x | material->emissive_texname = ""; |
| 1361 | 10x | material->normal_texname = ""; |
| 1362 | ||
| 1363 | 10x | material->unknown_parameter.clear(); |
| 1364 | } | |
| 1365 | ||
| 1366 | // code from https://wrf.ecse.rpi.edu//Research/Short_Notes/pnpoly.html | |
| 1367 | template <typename T> | |
| 1368 | static int pnpoly(int nvert, T *vertx, T *verty, T testx, T testy) { | |
| 1369 | int i, j, c = 0; | |
| 1370 | for (i = 0, j = nvert - 1; i < nvert; j = i++) { | |
| 1371 | if (((verty[i] > testy) != (verty[j] > testy)) && | |
| 1372 | (testx < | |
| 1373 | (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + | |
| 1374 | vertx[i])) | |
| 1375 | c = !c; | |
| 1376 | } | |
| 1377 | return c; | |
| 1378 | } | |
| 1379 | ||
| 1380 | struct TinyObjPoint { | |
| 1381 | real_t x, y, z; | |
| 1382 | 10x | TinyObjPoint() : x(0), y(0), z(0) {} |
| 1383 | 620x | TinyObjPoint(real_t x_, real_t y_, real_t z_) : |
| 1384 | 620x | x(x_), y(y_), z(z_) {} |
| 1385 | }; | |
| 1386 | ||
| 1387 | 4x | inline TinyObjPoint cross(const TinyObjPoint &v1, const TinyObjPoint &v2) { |
| 1388 | 4x | return TinyObjPoint(v1.y * v2.z - v1.z * v2.y, |
| 1389 | 4x | v1.z * v2.x - v1.x * v2.z, |
| 1390 | 4x | v1.x * v2.y - v1.y * v2.x); |
| 1391 | } | |
| 1392 | ||
| 1393 | 306x | inline real_t dot(const TinyObjPoint &v1, const TinyObjPoint &v2) { |
| 1394 | 306x | return (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z); |
| 1395 | } | |
| 1396 | ||
| 1397 | 4x | inline real_t GetLength(TinyObjPoint &e) { |
| 1398 | 4x | return std::sqrt(e.x*e.x + e.y*e.y + e.z*e.z); |
| 1399 | } | |
| 1400 | ||
| 1401 | 2x | inline TinyObjPoint Normalize(TinyObjPoint e) { |
| 1402 | 2x | real_t inv_length = 1.0 / GetLength(e); |
| 1403 | 2x | return TinyObjPoint(e.x * inv_length, e.y * inv_length, e.z * inv_length ); |
| 1404 | } | |
| 1405 | ||
| 1406 | ||
| 1407 | 102x | inline TinyObjPoint WorldToLocal(const TinyObjPoint& a, |
| 1408 | const TinyObjPoint& u, | |
| 1409 | const TinyObjPoint& v, | |
| 1410 | const TinyObjPoint& w) { | |
| 1411 | 102x | return TinyObjPoint(dot(a,u),dot(a,v),dot(a,w)); |
| 1412 | } | |
| 1413 | ||
| 1414 | ||
| 1415 | // TODO(syoyo): refactor function. | |
| 1416 | 79x | static bool exportGroupsToShape(shape_t *shape, const PrimGroup &prim_group, |
| 1417 | const std::vector<tag_t> &tags, | |
| 1418 | const int material_id, const std::string &name, | |
| 1419 | bool triangulate, const std::vector<real_t> &v, | |
| 1420 | std::string *warn) { | |
| 1421 | 79x | if (prim_group.IsEmpty()) { |
| 1422 | 40x | return false; |
| 1423 | } | |
| 1424 | ||
| 1425 | 39x | shape->name = name; |
| 1426 | ||
| 1427 | // polygon | |
| 1428 | 39x | if (!prim_group.faceGroup.empty()) { |
| 1429 | // Flatten vertices and indices | |
| 1430 | 6354x | for (size_t i = 0; i < prim_group.faceGroup.size(); i++) { |
| 1431 | 6315x | const face_t &face = prim_group.faceGroup[i]; |
| 1432 | ||
| 1433 | 6315x | size_t npolys = face.vertex_indices.size(); |
| 1434 | ||
| 1435 | 6315x | if (npolys < 3) { |
| 1436 | // Face must have 3+ vertices. | |
| 1437 | ! | if (warn) { |
| 1438 | ! | (*warn) += "Degenerated face found\n."; |
| 1439 | } | |
| 1440 | ! | continue; |
| 1441 | } | |
| 1442 | ||
| 1443 | 6315x | if (triangulate && npolys != 3) { |
| 1444 | 899x | if (npolys == 4) { |
| 1445 | 897x | vertex_index_t i0 = face.vertex_indices[0]; |
| 1446 | 897x | vertex_index_t i1 = face.vertex_indices[1]; |
| 1447 | 897x | vertex_index_t i2 = face.vertex_indices[2]; |
| 1448 | 897x | vertex_index_t i3 = face.vertex_indices[3]; |
| 1449 | ||
| 1450 | 897x | size_t vi0 = size_t(i0.v_idx); |
| 1451 | 897x | size_t vi1 = size_t(i1.v_idx); |
| 1452 | 897x | size_t vi2 = size_t(i2.v_idx); |
| 1453 | 897x | size_t vi3 = size_t(i3.v_idx); |
| 1454 | ||
| 1455 | 2691x | if (((3 * vi0 + 2) >= v.size()) || ((3 * vi1 + 2) >= v.size()) || |
| 1456 | 2691x | ((3 * vi2 + 2) >= v.size()) || ((3 * vi3 + 2) >= v.size())) { |
| 1457 | // Invalid triangle. | |
| 1458 | // FIXME(syoyo): Is it ok to simply skip this invalid triangle? | |
| 1459 | ! | if (warn) { |
| 1460 | ! | (*warn) += "Face with invalid vertex index found.\n"; |
| 1461 | } | |
| 1462 | ! | continue; |
| 1463 | } | |
| 1464 | ||
| 1465 | 897x | real_t v0x = v[vi0 * 3 + 0]; |
| 1466 | 897x | real_t v0y = v[vi0 * 3 + 1]; |
| 1467 | 897x | real_t v0z = v[vi0 * 3 + 2]; |
| 1468 | 897x | real_t v1x = v[vi1 * 3 + 0]; |
| 1469 | 897x | real_t v1y = v[vi1 * 3 + 1]; |
| 1470 | 897x | real_t v1z = v[vi1 * 3 + 2]; |
| 1471 | 897x | real_t v2x = v[vi2 * 3 + 0]; |
| 1472 | 897x | real_t v2y = v[vi2 * 3 + 1]; |
| 1473 | 897x | real_t v2z = v[vi2 * 3 + 2]; |
| 1474 | 897x | real_t v3x = v[vi3 * 3 + 0]; |
| 1475 | 897x | real_t v3y = v[vi3 * 3 + 1]; |
| 1476 | 897x | real_t v3z = v[vi3 * 3 + 2]; |
| 1477 | ||
| 1478 | // There are two candidates to split the quad into two triangles. | |
| 1479 | // | |
| 1480 | // Choose the shortest edge. | |
| 1481 | // TODO: Is it better to determine the edge to split by calculating | |
| 1482 | // the area of each triangle? | |
| 1483 | // | |
| 1484 | // +---+ | |
| 1485 | // |\ | | |
| 1486 | // | \ | | |
| 1487 | // | \| | |
| 1488 | // +---+ | |
| 1489 | // | |
| 1490 | // +---+ | |
| 1491 | // | /| | |
| 1492 | // | / | | |
| 1493 | // |/ | | |
| 1494 | // +---+ | |
| 1495 | ||
| 1496 | 897x | real_t e02x = v2x - v0x; |
| 1497 | 897x | real_t e02y = v2y - v0y; |
| 1498 | 897x | real_t e02z = v2z - v0z; |
| 1499 | 897x | real_t e13x = v3x - v1x; |
| 1500 | 897x | real_t e13y = v3y - v1y; |
| 1501 | 897x | real_t e13z = v3z - v1z; |
| 1502 | ||
| 1503 | 897x | real_t sqr02 = e02x * e02x + e02y * e02y + e02z * e02z; |
| 1504 | 897x | real_t sqr13 = e13x * e13x + e13y * e13y + e13z * e13z; |
| 1505 | ||
| 1506 | index_t idx0, idx1, idx2, idx3; | |
| 1507 | ||
| 1508 | 897x | idx0.vertex_index = i0.v_idx; |
| 1509 | 897x | idx0.normal_index = i0.vn_idx; |
| 1510 | 897x | idx0.texcoord_index = i0.vt_idx; |
| 1511 | 897x | idx1.vertex_index = i1.v_idx; |
| 1512 | 897x | idx1.normal_index = i1.vn_idx; |
| 1513 | 897x | idx1.texcoord_index = i1.vt_idx; |
| 1514 | 897x | idx2.vertex_index = i2.v_idx; |
| 1515 | 897x | idx2.normal_index = i2.vn_idx; |
| 1516 | 897x | idx2.texcoord_index = i2.vt_idx; |
| 1517 | 897x | idx3.vertex_index = i3.v_idx; |
| 1518 | 897x | idx3.normal_index = i3.vn_idx; |
| 1519 | 897x | idx3.texcoord_index = i3.vt_idx; |
| 1520 | ||
| 1521 | 897x | if (sqr02 < sqr13) { |
| 1522 | // [0, 1, 2], [0, 2, 3] | |
| 1523 | 285x | shape->mesh.indices.push_back(idx0); |
| 1524 | 285x | shape->mesh.indices.push_back(idx1); |
| 1525 | 285x | shape->mesh.indices.push_back(idx2); |
| 1526 | ||
| 1527 | 285x | shape->mesh.indices.push_back(idx0); |
| 1528 | 285x | shape->mesh.indices.push_back(idx2); |
| 1529 | 285x | shape->mesh.indices.push_back(idx3); |
| 1530 | } else { | |
| 1531 | // [0, 1, 3], [1, 2, 3] | |
| 1532 | 612x | shape->mesh.indices.push_back(idx0); |
| 1533 | 612x | shape->mesh.indices.push_back(idx1); |
| 1534 | 612x | shape->mesh.indices.push_back(idx3); |
| 1535 | ||
| 1536 | 612x | shape->mesh.indices.push_back(idx1); |
| 1537 | 612x | shape->mesh.indices.push_back(idx2); |
| 1538 | 612x | shape->mesh.indices.push_back(idx3); |
| 1539 | } | |
| 1540 | ||
| 1541 | // Two triangle faces | |
| 1542 | 897x | shape->mesh.num_face_vertices.push_back(3); |
| 1543 | 897x | shape->mesh.num_face_vertices.push_back(3); |
| 1544 | ||
| 1545 | 897x | shape->mesh.material_ids.push_back(material_id); |
| 1546 | 897x | shape->mesh.material_ids.push_back(material_id); |
| 1547 | ||
| 1548 | 897x | shape->mesh.smoothing_group_ids.push_back(face.smoothing_group_id); |
| 1549 | 897x | shape->mesh.smoothing_group_ids.push_back(face.smoothing_group_id); |
| 1550 | ||
| 1551 | } else { | |
| 1552 | #ifdef TINYOBJLOADER_USE_MAPBOX_EARCUT | |
| 1553 | 2x | vertex_index_t i0 = face.vertex_indices[0]; |
| 1554 | 2x | vertex_index_t i0_2 = i0; |
| 1555 | ||
| 1556 | // TMW change: Find the normal axis of the polygon using Newell's method | |
| 1557 | 2x | TinyObjPoint n; |
| 1558 | 104x | for (size_t k = 0; k < npolys; ++k) { |
| 1559 | 102x | i0 = face.vertex_indices[k % npolys]; |
| 1560 | 102x | size_t vi0 = size_t(i0.v_idx); |
| 1561 | ||
| 1562 | 102x | size_t j = (k + 1) % npolys; |
| 1563 | 102x | i0_2 = face.vertex_indices[j]; |
| 1564 | 102x | size_t vi0_2 = size_t(i0_2.v_idx); |
| 1565 | ||
| 1566 | 102x | real_t v0x = v[vi0 * 3 + 0]; |
| 1567 | 102x | real_t v0y = v[vi0 * 3 + 1]; |
| 1568 | 102x | real_t v0z = v[vi0 * 3 + 2]; |
| 1569 | ||
| 1570 | 102x | real_t v0x_2 = v[vi0_2 * 3 + 0]; |
| 1571 | 102x | real_t v0y_2 = v[vi0_2 * 3 + 1]; |
| 1572 | 102x | real_t v0z_2 = v[vi0_2 * 3 + 2]; |
| 1573 | ||
| 1574 | 102x | const TinyObjPoint point1(v0x,v0y,v0z); |
| 1575 | 102x | const TinyObjPoint point2(v0x_2,v0y_2,v0z_2); |
| 1576 | ||
| 1577 | 102x | TinyObjPoint a(point1.x - point2.x, point1.y - point2.y, point1.z - point2.z); |
| 1578 | 102x | TinyObjPoint b(point1.x + point2.x, point1.y + point2.y, point1.z + point2.z); |
| 1579 | ||
| 1580 | 102x | n.x += (a.y * b.z); |
| 1581 | 102x | n.y += (a.z * b.x); |
| 1582 | 102x | n.z += (a.x * b.y); |
| 1583 | } | |
| 1584 | 2x | real_t length_n = GetLength(n); |
| 1585 | //Check if zero length normal | |
| 1586 | 2x | if(length_n <= 0) { |
| 1587 | ! | continue; |
| 1588 | } | |
| 1589 | //Negative is to flip the normal to the correct direction | |
| 1590 | 2x | real_t inv_length = -1.0f / length_n; |
| 1591 | 2x | n.x *= inv_length; |
| 1592 | 2x | n.y *= inv_length; |
| 1593 | 2x | n.z *= inv_length; |
| 1594 | ||
| 1595 | 2x | TinyObjPoint axis_w, axis_v, axis_u; |
| 1596 | 2x | axis_w = n; |
| 1597 | 2x | TinyObjPoint a; |
| 1598 | 2x | if(std::fabs(axis_w.x) > 0.9999999) { |
| 1599 | ! | a = TinyObjPoint(0,1,0); |
| 1600 | } else { | |
| 1601 | 2x | a = TinyObjPoint(1,0,0); |
| 1602 | } | |
| 1603 | 2x | axis_v = Normalize(cross(axis_w, a)); |
| 1604 | 2x | axis_u = cross(axis_w, axis_v); |
| 1605 | using Point = std::array<real_t, 2>; | |
| 1606 | ||
| 1607 | // first polyline define the main polygon. | |
| 1608 | // following polylines define holes(not used in tinyobj). | |
| 1609 | 2x | std::vector<std::vector<Point> > polygon; |
| 1610 | ||
| 1611 | 2x | std::vector<Point> polyline; |
| 1612 | ||
| 1613 | //TMW change: Find best normal and project v0x and v0y to those coordinates, instead of | |
| 1614 | //picking a plane aligned with an axis (which can flip polygons). | |
| 1615 | ||
| 1616 | // Fill polygon data(facevarying vertices). | |
| 1617 | 104x | for (size_t k = 0; k < npolys; k++) { |
| 1618 | 102x | i0 = face.vertex_indices[k]; |
| 1619 | 102x | size_t vi0 = size_t(i0.v_idx); |
| 1620 | ||
| 1621 | assert(((3 * vi0 + 2) < v.size())); | |
| 1622 | ||
| 1623 | 102x | real_t v0x = v[vi0 * 3 + 0]; |
| 1624 | 102x | real_t v0y = v[vi0 * 3 + 1]; |
| 1625 | 102x | real_t v0z = v[vi0 * 3 + 2]; |
| 1626 | ||
| 1627 | 102x | TinyObjPoint polypoint(v0x,v0y,v0z); |
| 1628 | 102x | TinyObjPoint loc = WorldToLocal(polypoint, axis_u, axis_v, axis_w); |
| 1629 | ||
| 1630 | 102x | polyline.push_back({loc.x, loc.y}); |
| 1631 | } | |
| 1632 | ||
| 1633 | 2x | polygon.push_back(polyline); |
| 1634 | 2x | std::vector<uint32_t> indices = mapbox::earcut<uint32_t>(polygon); |
| 1635 | // => result = 3 * faces, clockwise | |
| 1636 | ||
| 1637 | assert(indices.size() % 3 == 0); | |
| 1638 | ||
| 1639 | // Reconstruct vertex_index_t | |
| 1640 | 96x | for (size_t k = 0; k < indices.size() / 3; k++) { |
| 1641 | { | |
| 1642 | index_t idx0, idx1, idx2; | |
| 1643 | 94x | idx0.vertex_index = face.vertex_indices[indices[3 * k + 0]].v_idx; |
| 1644 | 94x | idx0.normal_index = |
| 1645 | 94x | face.vertex_indices[indices[3 * k + 0]].vn_idx; |
| 1646 | 94x | idx0.texcoord_index = |
| 1647 | 94x | face.vertex_indices[indices[3 * k + 0]].vt_idx; |
| 1648 | 94x | idx1.vertex_index = face.vertex_indices[indices[3 * k + 1]].v_idx; |
| 1649 | 94x | idx1.normal_index = |
| 1650 | 94x | face.vertex_indices[indices[3 * k + 1]].vn_idx; |
| 1651 | 94x | idx1.texcoord_index = |
| 1652 | 94x | face.vertex_indices[indices[3 * k + 1]].vt_idx; |
| 1653 | 94x | idx2.vertex_index = face.vertex_indices[indices[3 * k + 2]].v_idx; |
| 1654 | 94x | idx2.normal_index = |
| 1655 | 94x | face.vertex_indices[indices[3 * k + 2]].vn_idx; |
| 1656 | 94x | idx2.texcoord_index = |
| 1657 | 94x | face.vertex_indices[indices[3 * k + 2]].vt_idx; |
| 1658 | ||
| 1659 | 94x | shape->mesh.indices.push_back(idx0); |
| 1660 | 94x | shape->mesh.indices.push_back(idx1); |
| 1661 | 94x | shape->mesh.indices.push_back(idx2); |
| 1662 | ||
| 1663 | 94x | shape->mesh.num_face_vertices.push_back(3); |
| 1664 | 94x | shape->mesh.material_ids.push_back(material_id); |
| 1665 | 94x | shape->mesh.smoothing_group_ids.push_back( |
| 1666 | 94x | face.smoothing_group_id); |
| 1667 | } | |
| 1668 | } | |
| 1669 | ||
| 1670 | #else // Built-in ear clipping triangulation | |
| 1671 | vertex_index_t i0 = face.vertex_indices[0]; | |
| 1672 | vertex_index_t i1(-1); | |
| 1673 | vertex_index_t i2 = face.vertex_indices[1]; | |
| 1674 | ||
| 1675 | // find the two axes to work in | |
| 1676 | size_t axes[2] = {1, 2}; | |
| 1677 | for (size_t k = 0; k < npolys; ++k) { | |
| 1678 | i0 = face.vertex_indices[(k + 0) % npolys]; | |
| 1679 | i1 = face.vertex_indices[(k + 1) % npolys]; | |
| 1680 | i2 = face.vertex_indices[(k + 2) % npolys]; | |
| 1681 | size_t vi0 = size_t(i0.v_idx); | |
| 1682 | size_t vi1 = size_t(i1.v_idx); | |
| 1683 | size_t vi2 = size_t(i2.v_idx); | |
| 1684 | ||
| 1685 | if (((3 * vi0 + 2) >= v.size()) || ((3 * vi1 + 2) >= v.size()) || | |
| 1686 | ((3 * vi2 + 2) >= v.size())) { | |
| 1687 | // Invalid triangle. | |
| 1688 | // FIXME(syoyo): Is it ok to simply skip this invalid triangle? | |
| 1689 | continue; | |
| 1690 | } | |
| 1691 | real_t v0x = v[vi0 * 3 + 0]; | |
| 1692 | real_t v0y = v[vi0 * 3 + 1]; | |
| 1693 | real_t v0z = v[vi0 * 3 + 2]; | |
| 1694 | real_t v1x = v[vi1 * 3 + 0]; | |
| 1695 | real_t v1y = v[vi1 * 3 + 1]; | |
| 1696 | real_t v1z = v[vi1 * 3 + 2]; | |
| 1697 | real_t v2x = v[vi2 * 3 + 0]; | |
| 1698 | real_t v2y = v[vi2 * 3 + 1]; | |
| 1699 | real_t v2z = v[vi2 * 3 + 2]; | |
| 1700 | real_t e0x = v1x - v0x; | |
| 1701 | real_t e0y = v1y - v0y; | |
| 1702 | real_t e0z = v1z - v0z; | |
| 1703 | real_t e1x = v2x - v1x; | |
| 1704 | real_t e1y = v2y - v1y; | |
| 1705 | real_t e1z = v2z - v1z; | |
| 1706 | real_t cx = std::fabs(e0y * e1z - e0z * e1y); | |
| 1707 | real_t cy = std::fabs(e0z * e1x - e0x * e1z); | |
| 1708 | real_t cz = std::fabs(e0x * e1y - e0y * e1x); | |
| 1709 | const real_t epsilon = std::numeric_limits<real_t>::epsilon(); | |
| 1710 | // std::cout << "cx " << cx << ", cy " << cy << ", cz " << cz << | |
| 1711 | // "\n"; | |
| 1712 | if (cx > epsilon || cy > epsilon || cz > epsilon) { | |
| 1713 | // std::cout << "corner\n"; | |
| 1714 | // found a corner | |
| 1715 | if (cx > cy && cx > cz) { | |
| 1716 | // std::cout << "pattern0\n"; | |
| 1717 | } else { | |
| 1718 | // std::cout << "axes[0] = 0\n"; | |
| 1719 | axes[0] = 0; | |
| 1720 | if (cz > cx && cz > cy) { | |
| 1721 | // std::cout << "axes[1] = 1\n"; | |
| 1722 | axes[1] = 1; | |
| 1723 | } | |
| 1724 | } | |
| 1725 | break; | |
| 1726 | } | |
| 1727 | } | |
| 1728 | ||
| 1729 | face_t remainingFace = face; // copy | |
| 1730 | size_t guess_vert = 0; | |
| 1731 | vertex_index_t ind[3]; | |
| 1732 | real_t vx[3]; | |
| 1733 | real_t vy[3]; | |
| 1734 | ||
| 1735 | // How many iterations can we do without decreasing the remaining | |
| 1736 | // vertices. | |
| 1737 | size_t remainingIterations = face.vertex_indices.size(); | |
| 1738 | size_t previousRemainingVertices = | |
| 1739 | remainingFace.vertex_indices.size(); | |
| 1740 | ||
| 1741 | while (remainingFace.vertex_indices.size() > 3 && | |
| 1742 | remainingIterations > 0) { | |
| 1743 | // std::cout << "remainingIterations " << remainingIterations << | |
| 1744 | // "\n"; | |
| 1745 | ||
| 1746 | npolys = remainingFace.vertex_indices.size(); | |
| 1747 | if (guess_vert >= npolys) { | |
| 1748 | guess_vert -= npolys; | |
| 1749 | } | |
| 1750 | ||
| 1751 | if (previousRemainingVertices != npolys) { | |
| 1752 | // The number of remaining vertices decreased. Reset counters. | |
| 1753 | previousRemainingVertices = npolys; | |
| 1754 | remainingIterations = npolys; | |
| 1755 | } else { | |
| 1756 | // We didn't consume a vertex on previous iteration, reduce the | |
| 1757 | // available iterations. | |
| 1758 | remainingIterations--; | |
| 1759 | } | |
| 1760 | ||
| 1761 | for (size_t k = 0; k < 3; k++) { | |
| 1762 | ind[k] = remainingFace.vertex_indices[(guess_vert + k) % npolys]; | |
| 1763 | size_t vi = size_t(ind[k].v_idx); | |
| 1764 | if (((vi * 3 + axes[0]) >= v.size()) || | |
| 1765 | ((vi * 3 + axes[1]) >= v.size())) { | |
| 1766 | // ??? | |
| 1767 | vx[k] = static_cast<real_t>(0.0); | |
| 1768 | vy[k] = static_cast<real_t>(0.0); | |
| 1769 | } else { | |
| 1770 | vx[k] = v[vi * 3 + axes[0]]; | |
| 1771 | vy[k] = v[vi * 3 + axes[1]]; | |
| 1772 | } | |
| 1773 | } | |
| 1774 | ||
| 1775 | // | |
| 1776 | // area is calculated per face | |
| 1777 | // | |
| 1778 | real_t e0x = vx[1] - vx[0]; | |
| 1779 | real_t e0y = vy[1] - vy[0]; | |
| 1780 | real_t e1x = vx[2] - vx[1]; | |
| 1781 | real_t e1y = vy[2] - vy[1]; | |
| 1782 | real_t cross = e0x * e1y - e0y * e1x; | |
| 1783 | // std::cout << "axes = " << axes[0] << ", " << axes[1] << "\n"; | |
| 1784 | // std::cout << "e0x, e0y, e1x, e1y " << e0x << ", " << e0y << ", " | |
| 1785 | // << e1x << ", " << e1y << "\n"; | |
| 1786 | ||
| 1787 | real_t area = (vx[0] * vy[1] - vy[0] * vx[1]) * static_cast<real_t>(0.5); | |
| 1788 | // std::cout << "cross " << cross << ", area " << area << "\n"; | |
| 1789 | // if an internal angle | |
| 1790 | if (cross * area < static_cast<real_t>(0.0)) { | |
| 1791 | // std::cout << "internal \n"; | |
| 1792 | guess_vert += 1; | |
| 1793 | // std::cout << "guess vert : " << guess_vert << "\n"; | |
| 1794 | continue; | |
| 1795 | } | |
| 1796 | ||
| 1797 | // check all other verts in case they are inside this triangle | |
| 1798 | bool overlap = false; | |
| 1799 | for (size_t otherVert = 3; otherVert < npolys; ++otherVert) { | |
| 1800 | size_t idx = (guess_vert + otherVert) % npolys; | |
| 1801 | ||
| 1802 | if (idx >= remainingFace.vertex_indices.size()) { | |
| 1803 | // std::cout << "???0\n"; | |
| 1804 | // ??? | |
| 1805 | continue; | |
| 1806 | } | |
| 1807 | ||
| 1808 | size_t ovi = size_t(remainingFace.vertex_indices[idx].v_idx); | |
| 1809 | ||
| 1810 | if (((ovi * 3 + axes[0]) >= v.size()) || | |
| 1811 | ((ovi * 3 + axes[1]) >= v.size())) { | |
| 1812 | // std::cout << "???1\n"; | |
| 1813 | // ??? | |
| 1814 | continue; | |
| 1815 | } | |
| 1816 | real_t tx = v[ovi * 3 + axes[0]]; | |
| 1817 | real_t ty = v[ovi * 3 + axes[1]]; | |
| 1818 | if (pnpoly(3, vx, vy, tx, ty)) { | |
| 1819 | // std::cout << "overlap\n"; | |
| 1820 | overlap = true; | |
| 1821 | break; | |
| 1822 | } | |
| 1823 | } | |
| 1824 | ||
| 1825 | if (overlap) { | |
| 1826 | // std::cout << "overlap2\n"; | |
| 1827 | guess_vert += 1; | |
| 1828 | continue; | |
| 1829 | } | |
| 1830 | ||
| 1831 | // this triangle is an ear | |
| 1832 | { | |
| 1833 | index_t idx0, idx1, idx2; | |
| 1834 | idx0.vertex_index = ind[0].v_idx; | |
| 1835 | idx0.normal_index = ind[0].vn_idx; | |
| 1836 | idx0.texcoord_index = ind[0].vt_idx; | |
| 1837 | idx1.vertex_index = ind[1].v_idx; | |
| 1838 | idx1.normal_index = ind[1].vn_idx; | |
| 1839 | idx1.texcoord_index = ind[1].vt_idx; | |
| 1840 | idx2.vertex_index = ind[2].v_idx; | |
| 1841 | idx2.normal_index = ind[2].vn_idx; | |
| 1842 | idx2.texcoord_index = ind[2].vt_idx; | |
| 1843 | ||
| 1844 | shape->mesh.indices.push_back(idx0); | |
| 1845 | shape->mesh.indices.push_back(idx1); | |
| 1846 | shape->mesh.indices.push_back(idx2); | |
| 1847 | ||
| 1848 | shape->mesh.num_face_vertices.push_back(3); | |
| 1849 | shape->mesh.material_ids.push_back(material_id); | |
| 1850 | shape->mesh.smoothing_group_ids.push_back( | |
| 1851 | face.smoothing_group_id); | |
| 1852 | } | |
| 1853 | ||
| 1854 | // remove v1 from the list | |
| 1855 | size_t removed_vert_index = (guess_vert + 1) % npolys; | |
| 1856 | while (removed_vert_index + 1 < npolys) { | |
| 1857 | remainingFace.vertex_indices[removed_vert_index] = | |
| 1858 | remainingFace.vertex_indices[removed_vert_index + 1]; | |
| 1859 | removed_vert_index += 1; | |
| 1860 | } | |
| 1861 | remainingFace.vertex_indices.pop_back(); | |
| 1862 | } | |
| 1863 | ||
| 1864 | // std::cout << "remainingFace.vi.size = " << | |
| 1865 | // remainingFace.vertex_indices.size() << "\n"; | |
| 1866 | if (remainingFace.vertex_indices.size() == 3) { | |
| 1867 | i0 = remainingFace.vertex_indices[0]; | |
| 1868 | i1 = remainingFace.vertex_indices[1]; | |
| 1869 | i2 = remainingFace.vertex_indices[2]; | |
| 1870 | { | |
| 1871 | index_t idx0, idx1, idx2; | |
| 1872 | idx0.vertex_index = i0.v_idx; | |
| 1873 | idx0.normal_index = i0.vn_idx; | |
| 1874 | idx0.texcoord_index = i0.vt_idx; | |
| 1875 | idx1.vertex_index = i1.v_idx; | |
| 1876 | idx1.normal_index = i1.vn_idx; | |
| 1877 | idx1.texcoord_index = i1.vt_idx; | |
| 1878 | idx2.vertex_index = i2.v_idx; | |
| 1879 | idx2.normal_index = i2.vn_idx; | |
| 1880 | idx2.texcoord_index = i2.vt_idx; | |
| 1881 | ||
| 1882 | shape->mesh.indices.push_back(idx0); | |
| 1883 | shape->mesh.indices.push_back(idx1); | |
| 1884 | shape->mesh.indices.push_back(idx2); | |
| 1885 | ||
| 1886 | shape->mesh.num_face_vertices.push_back(3); | |
| 1887 | shape->mesh.material_ids.push_back(material_id); | |
| 1888 | shape->mesh.smoothing_group_ids.push_back( | |
| 1889 | face.smoothing_group_id); | |
| 1890 | } | |
| 1891 | } | |
| 1892 | #endif | |
| 1893 | 2x | } // npolys |
| 1894 | } else { | |
| 1895 | 21664x | for (size_t k = 0; k < npolys; k++) { |
| 1896 | index_t idx; | |
| 1897 | 16248x | idx.vertex_index = face.vertex_indices[k].v_idx; |
| 1898 | 16248x | idx.normal_index = face.vertex_indices[k].vn_idx; |
| 1899 | 16248x | idx.texcoord_index = face.vertex_indices[k].vt_idx; |
| 1900 | 16248x | shape->mesh.indices.push_back(idx); |
| 1901 | } | |
| 1902 | ||
| 1903 | 5416x | shape->mesh.num_face_vertices.push_back( |
| 1904 | 5416x | static_cast<unsigned char>(npolys)); |
| 1905 | 5416x | shape->mesh.material_ids.push_back(material_id); // per face |
| 1906 | 5416x | shape->mesh.smoothing_group_ids.push_back( |
| 1907 | 5416x | face.smoothing_group_id); // per face |
| 1908 | } | |
| 1909 | } | |
| 1910 | ||
| 1911 | 39x | shape->mesh.tags = tags; |
| 1912 | } | |
| 1913 | ||
| 1914 | // line | |
| 1915 | 39x | if (!prim_group.lineGroup.empty()) { |
| 1916 | // Flatten indices | |
| 1917 | ! | for (size_t i = 0; i < prim_group.lineGroup.size(); i++) { |
| 1918 | ! | for (size_t j = 0; j < prim_group.lineGroup[i].vertex_indices.size(); |
| 1919 | j++) { | |
| 1920 | ! | const vertex_index_t &vi = prim_group.lineGroup[i].vertex_indices[j]; |
| 1921 | ||
| 1922 | index_t idx; | |
| 1923 | ! | idx.vertex_index = vi.v_idx; |
| 1924 | ! | idx.normal_index = vi.vn_idx; |
| 1925 | ! | idx.texcoord_index = vi.vt_idx; |
| 1926 | ||
| 1927 | ! | shape->lines.indices.push_back(idx); |
| 1928 | } | |
| 1929 | ||
| 1930 | ! | shape->lines.num_line_vertices.push_back( |
| 1931 | ! | int(prim_group.lineGroup[i].vertex_indices.size())); |
| 1932 | } | |
| 1933 | } | |
| 1934 | ||
| 1935 | // points | |
| 1936 | 39x | if (!prim_group.pointsGroup.empty()) { |
| 1937 | // Flatten & convert indices | |
| 1938 | ! | for (size_t i = 0; i < prim_group.pointsGroup.size(); i++) { |
| 1939 | ! | for (size_t j = 0; j < prim_group.pointsGroup[i].vertex_indices.size(); |
| 1940 | j++) { | |
| 1941 | ! | const vertex_index_t &vi = prim_group.pointsGroup[i].vertex_indices[j]; |
| 1942 | ||
| 1943 | index_t idx; | |
| 1944 | ! | idx.vertex_index = vi.v_idx; |
| 1945 | ! | idx.normal_index = vi.vn_idx; |
| 1946 | ! | idx.texcoord_index = vi.vt_idx; |
| 1947 | ||
| 1948 | ! | shape->points.indices.push_back(idx); |
| 1949 | } | |
| 1950 | } | |
| 1951 | } | |
| 1952 | ||
| 1953 | 39x | return true; |
| 1954 | } | |
| 1955 | ||
| 1956 | // Split a string with specified delimiter character and escape character. | |
| 1957 | // https://rosettacode.org/wiki/Tokenize_a_string_with_escaping#C.2B.2B | |
| 1958 | 4x | static void SplitString(const std::string &s, char delim, char escape, |
| 1959 | std::vector<std::string> &elems) { | |
| 1960 | 4x | std::string token; |
| 1961 | ||
| 1962 | 4x | bool escaping = false; |
| 1963 | 73x | for (size_t i = 0; i < s.size(); ++i) { |
| 1964 | 69x | char ch = s[i]; |
| 1965 | 69x | if (escaping) { |
| 1966 | ! | escaping = false; |
| 1967 | 69x | } else if (ch == escape) { |
| 1968 | ! | escaping = true; |
| 1969 | ! | continue; |
| 1970 | 69x | } else if (ch == delim) { |
| 1971 | ! | if (!token.empty()) { |
| 1972 | ! | elems.push_back(token); |
| 1973 | } | |
| 1974 | ! | token.clear(); |
| 1975 | ! | continue; |
| 1976 | } | |
| 1977 | 69x | token += ch; |
| 1978 | } | |
| 1979 | ||
| 1980 | 4x | elems.push_back(token); |
| 1981 | } | |
| 1982 | ||
| 1983 | 4x | static std::string JoinPath(const std::string &dir, |
| 1984 | const std::string &filename) { | |
| 1985 | 4x | if (dir.empty()) { |
| 1986 | ! | return filename; |
| 1987 | } else { | |
| 1988 | // check '/' | |
| 1989 | 4x | char lastChar = *dir.rbegin(); |
| 1990 | 4x | if (lastChar != '/') { |
| 1991 | ! | return dir + std::string("/") + filename; |
| 1992 | } else { | |
| 1993 | 4x | return dir + filename; |
| 1994 | } | |
| 1995 | } | |
| 1996 | } | |
| 1997 | ||
| 1998 | 4x | void LoadMtl(std::map<std::string, int> *material_map, |
| 1999 | std::vector<material_t> *materials, std::istream *inStream, | |
| 2000 | std::string *warning, std::string *err) { | |
| 2001 | (void)err; | |
| 2002 | ||
| 2003 | // Create a default material anyway. | |
| 2004 | 4x | material_t material; |
| 2005 | 4x | InitMaterial(&material); |
| 2006 | ||
| 2007 | // Issue 43. `d` wins against `Tr` since `Tr` is not in the MTL specification. | |
| 2008 | 4x | bool has_d = false; |
| 2009 | 4x | bool has_tr = false; |
| 2010 | ||
| 2011 | // has_kd is used to set a default diffuse value when map_Kd is present | |
| 2012 | // and Kd is not. | |
| 2013 | 4x | bool has_kd = false; |
| 2014 | ||
| 2015 | 4x | std::stringstream warn_ss; |
| 2016 | ||
| 2017 | 4x | size_t line_no = 0; |
| 2018 | 4x | std::string linebuf; |
| 2019 | 56x | while (inStream->peek() != -1) { |
| 2020 | 52x | safeGetline(*inStream, linebuf); |
| 2021 | 52x | line_no++; |
| 2022 | ||
| 2023 | // Trim trailing whitespace. | |
| 2024 | 52x | if (linebuf.size() > 0) { |
| 2025 | 42x | linebuf = linebuf.substr(0, linebuf.find_last_not_of(" \t") + 1); |
| 2026 | } | |
| 2027 | ||
| 2028 | // Trim newline '\r\n' or '\n' | |
| 2029 | 52x | if (linebuf.size() > 0) { |
| 2030 | 42x | if (linebuf[linebuf.size() - 1] == '\n') |
| 2031 | ! | linebuf.erase(linebuf.size() - 1); |
| 2032 | } | |
| 2033 | 52x | if (linebuf.size() > 0) { |
| 2034 | 42x | if (linebuf[linebuf.size() - 1] == '\r') |
| 2035 | ! | linebuf.erase(linebuf.size() - 1); |
| 2036 | } | |
| 2037 | ||
| 2038 | // Skip if empty line. | |
| 2039 | 52x | if (linebuf.empty()) { |
| 2040 | 47x | continue; |
| 2041 | } | |
| 2042 | ||
| 2043 | // Skip leading space. | |
| 2044 | 42x | const char *token = linebuf.c_str(); |
| 2045 | 42x | token += strspn(token, " \t"); |
| 2046 | ||
| 2047 | assert(token); | |
| 2048 | 42x | if (token[0] == '\0') continue; // empty line |
| 2049 | ||
| 2050 | 42x | if (token[0] == '#') continue; // comment line |
| 2051 | ||
| 2052 | // new mtl | |
| 2053 | 42x | if ((0 == strncmp(token, "newmtl", 6)) && IS_SPACE((token[6]))) { |
| 2054 | // flush previous material. | |
| 2055 | 6x | if (!material.name.empty()) { |
| 2056 | 2x | material_map->insert(std::pair<std::string, int>( |
| 2057 | 2x | material.name, static_cast<int>(materials->size()))); |
| 2058 | 2x | materials->push_back(material); |
| 2059 | } | |
| 2060 | ||
| 2061 | // initial temporary material | |
| 2062 | 6x | InitMaterial(&material); |
| 2063 | ||
| 2064 | 6x | has_d = false; |
| 2065 | 6x | has_tr = false; |
| 2066 | ||
| 2067 | // set new mtl name | |
| 2068 | 6x | token += 7; |
| 2069 | { | |
| 2070 | 6x | std::stringstream sstr; |
| 2071 | 6x | sstr << token; |
| 2072 | 6x | material.name = sstr.str(); |
| 2073 | } | |
| 2074 | 6x | continue; |
| 2075 | } | |
| 2076 | ||
| 2077 | // ambient | |
| 2078 | 36x | if (token[0] == 'K' && token[1] == 'a' && IS_SPACE((token[2]))) { |
| 2079 | 5x | token += 2; |
| 2080 | real_t r, g, b; | |
| 2081 | 5x | parseReal3(&r, &g, &b, &token); |
| 2082 | 5x | material.ambient[0] = r; |
| 2083 | 5x | material.ambient[1] = g; |
| 2084 | 5x | material.ambient[2] = b; |
| 2085 | 5x | continue; |
| 2086 | } | |
| 2087 | ||
| 2088 | // diffuse | |
| 2089 | 31x | if (token[0] == 'K' && token[1] == 'd' && IS_SPACE((token[2]))) { |
| 2090 | 5x | token += 2; |
| 2091 | real_t r, g, b; | |
| 2092 | 5x | parseReal3(&r, &g, &b, &token); |
| 2093 | 5x | material.diffuse[0] = r; |
| 2094 | 5x | material.diffuse[1] = g; |
| 2095 | 5x | material.diffuse[2] = b; |
| 2096 | 5x | has_kd = true; |
| 2097 | 5x | continue; |
| 2098 | } | |
| 2099 | ||
| 2100 | // specular | |
| 2101 | 26x | if (token[0] == 'K' && token[1] == 's' && IS_SPACE((token[2]))) { |
| 2102 | 5x | token += 2; |
| 2103 | real_t r, g, b; | |
| 2104 | 5x | parseReal3(&r, &g, &b, &token); |
| 2105 | 5x | material.specular[0] = r; |
| 2106 | 5x | material.specular[1] = g; |
| 2107 | 5x | material.specular[2] = b; |
| 2108 | 5x | continue; |
| 2109 | } | |
| 2110 | ||
| 2111 | // transmittance | |
| 2112 | 21x | if ((token[0] == 'K' && token[1] == 't' && IS_SPACE((token[2]))) || |
| 2113 | 21x | (token[0] == 'T' && token[1] == 'f' && IS_SPACE((token[2])))) { |
| 2114 | 5x | token += 2; |
| 2115 | real_t r, g, b; | |
| 2116 | 5x | parseReal3(&r, &g, &b, &token); |
| 2117 | 5x | material.transmittance[0] = r; |
| 2118 | 5x | material.transmittance[1] = g; |
| 2119 | 5x | material.transmittance[2] = b; |
| 2120 | 5x | continue; |
| 2121 | } | |
| 2122 | ||
| 2123 | // ior(index of refraction) | |
| 2124 | 16x | if (token[0] == 'N' && token[1] == 'i' && IS_SPACE((token[2]))) { |
| 2125 | ! | token += 2; |
| 2126 | ! | material.ior = parseReal(&token); |
| 2127 | ! | continue; |
| 2128 | } | |
| 2129 | ||
| 2130 | // emission | |
| 2131 | 16x | if (token[0] == 'K' && token[1] == 'e' && IS_SPACE(token[2])) { |
| 2132 | ! | token += 2; |
| 2133 | real_t r, g, b; | |
| 2134 | ! | parseReal3(&r, &g, &b, &token); |
| 2135 | ! | material.emission[0] = r; |
| 2136 | ! | material.emission[1] = g; |
| 2137 | ! | material.emission[2] = b; |
| 2138 | ! | continue; |
| 2139 | } | |
| 2140 | ||
| 2141 | // shininess | |
| 2142 | 16x | if (token[0] == 'N' && token[1] == 's' && IS_SPACE(token[2])) { |
| 2143 | 5x | token += 2; |
| 2144 | 5x | material.shininess = parseReal(&token); |
| 2145 | 5x | continue; |
| 2146 | } | |
| 2147 | ||
| 2148 | // illum model | |
| 2149 | 11x | if (0 == strncmp(token, "illum", 5) && IS_SPACE(token[5])) { |
| 2150 | 5x | token += 6; |
| 2151 | 5x | material.illum = parseInt(&token); |
| 2152 | 5x | continue; |
| 2153 | } | |
| 2154 | ||
| 2155 | // dissolve | |
| 2156 | 6x | if ((token[0] == 'd' && IS_SPACE(token[1]))) { |
| 2157 | ! | token += 1; |
| 2158 | ! | material.dissolve = parseReal(&token); |
| 2159 | ||
| 2160 | ! | if (has_tr) { |
| 2161 | warn_ss << "Both `d` and `Tr` parameters defined for \"" | |
| 2162 | << material.name | |
| 2163 | ! | << "\". Use the value of `d` for dissolve (line " << line_no |
| 2164 | ! | << " in .mtl.)\n"; |
| 2165 | } | |
| 2166 | ! | has_d = true; |
| 2167 | ! | continue; |
| 2168 | } | |
| 2169 | 6x | if (token[0] == 'T' && token[1] == 'r' && IS_SPACE(token[2])) { |
| 2170 | ! | token += 2; |
| 2171 | ! | if (has_d) { |
| 2172 | // `d` wins. Ignore `Tr` value. | |
| 2173 | warn_ss << "Both `d` and `Tr` parameters defined for \"" | |
| 2174 | << material.name | |
| 2175 | ! | << "\". Use the value of `d` for dissolve (line " << line_no |
| 2176 | ! | << " in .mtl.)\n"; |
| 2177 | } else { | |
| 2178 | // We invert value of Tr(assume Tr is in range [0, 1]) | |
| 2179 | // NOTE: Interpretation of Tr is application(exporter) dependent. For | |
| 2180 | // some application(e.g. 3ds max obj exporter), Tr = d(Issue 43) | |
| 2181 | ! | material.dissolve = static_cast<real_t>(1.0) - parseReal(&token); |
| 2182 | } | |
| 2183 | ! | has_tr = true; |
| 2184 | ! | continue; |
| 2185 | } | |
| 2186 | ||
| 2187 | // PBR: roughness | |
| 2188 | 6x | if (token[0] == 'P' && token[1] == 'r' && IS_SPACE(token[2])) { |
| 2189 | ! | token += 2; |
| 2190 | ! | material.roughness = parseReal(&token); |
| 2191 | ! | continue; |
| 2192 | } | |
| 2193 | ||
| 2194 | // PBR: metallic | |
| 2195 | 6x | if (token[0] == 'P' && token[1] == 'm' && IS_SPACE(token[2])) { |
| 2196 | ! | token += 2; |
| 2197 | ! | material.metallic = parseReal(&token); |
| 2198 | ! | continue; |
| 2199 | } | |
| 2200 | ||
| 2201 | // PBR: sheen | |
| 2202 | 6x | if (token[0] == 'P' && token[1] == 's' && IS_SPACE(token[2])) { |
| 2203 | ! | token += 2; |
| 2204 | ! | material.sheen = parseReal(&token); |
| 2205 | ! | continue; |
| 2206 | } | |
| 2207 | ||
| 2208 | // PBR: clearcoat thickness | |
| 2209 | 6x | if (token[0] == 'P' && token[1] == 'c' && IS_SPACE(token[2])) { |
| 2210 | ! | token += 2; |
| 2211 | ! | material.clearcoat_thickness = parseReal(&token); |
| 2212 | ! | continue; |
| 2213 | } | |
| 2214 | ||
| 2215 | // PBR: clearcoat roughness | |
| 2216 | 6x | if ((0 == strncmp(token, "Pcr", 3)) && IS_SPACE(token[3])) { |
| 2217 | ! | token += 4; |
| 2218 | ! | material.clearcoat_roughness = parseReal(&token); |
| 2219 | ! | continue; |
| 2220 | } | |
| 2221 | ||
| 2222 | // PBR: anisotropy | |
| 2223 | 6x | if ((0 == strncmp(token, "aniso", 5)) && IS_SPACE(token[5])) { |
| 2224 | ! | token += 6; |
| 2225 | ! | material.anisotropy = parseReal(&token); |
| 2226 | ! | continue; |
| 2227 | } | |
| 2228 | ||
| 2229 | // PBR: anisotropy rotation | |
| 2230 | 6x | if ((0 == strncmp(token, "anisor", 6)) && IS_SPACE(token[6])) { |
| 2231 | ! | token += 7; |
| 2232 | ! | material.anisotropy_rotation = parseReal(&token); |
| 2233 | ! | continue; |
| 2234 | } | |
| 2235 | ||
| 2236 | // ambient texture | |
| 2237 | 6x | if ((0 == strncmp(token, "map_Ka", 6)) && IS_SPACE(token[6])) { |
| 2238 | ! | token += 7; |
| 2239 | ! | ParseTextureNameAndOption(&(material.ambient_texname), |
| 2240 | &(material.ambient_texopt), token); | |
| 2241 | ! | continue; |
| 2242 | } | |
| 2243 | ||
| 2244 | // diffuse texture | |
| 2245 | 6x | if ((0 == strncmp(token, "map_Kd", 6)) && IS_SPACE(token[6])) { |
| 2246 | 1x | token += 7; |
| 2247 | 1x | ParseTextureNameAndOption(&(material.diffuse_texname), |
| 2248 | &(material.diffuse_texopt), token); | |
| 2249 | ||
| 2250 | // Set a decent diffuse default value if a diffuse texture is specified | |
| 2251 | // without a matching Kd value. | |
| 2252 | 1x | if (!has_kd) { |
| 2253 | 1x | material.diffuse[0] = static_cast<real_t>(0.6); |
| 2254 | 1x | material.diffuse[1] = static_cast<real_t>(0.6); |
| 2255 | 1x | material.diffuse[2] = static_cast<real_t>(0.6); |
| 2256 | } | |
| 2257 | ||
| 2258 | 1x | continue; |
| 2259 | } | |
| 2260 | ||
| 2261 | // specular texture | |
| 2262 | 5x | if ((0 == strncmp(token, "map_Ks", 6)) && IS_SPACE(token[6])) { |
| 2263 | ! | token += 7; |
| 2264 | ! | ParseTextureNameAndOption(&(material.specular_texname), |
| 2265 | &(material.specular_texopt), token); | |
| 2266 | ! | continue; |
| 2267 | } | |
| 2268 | ||
| 2269 | // specular highlight texture | |
| 2270 | 5x | if ((0 == strncmp(token, "map_Ns", 6)) && IS_SPACE(token[6])) { |
| 2271 | ! | token += 7; |
| 2272 | ! | ParseTextureNameAndOption(&(material.specular_highlight_texname), |
| 2273 | &(material.specular_highlight_texopt), token); | |
| 2274 | ! | continue; |
| 2275 | } | |
| 2276 | ||
| 2277 | // bump texture | |
| 2278 | 5x | if (((0 == strncmp(token, "map_bump", 8)) || |
| 2279 | 5x | (0 == strncmp(token, "map_Bump", 8))) && |
| 2280 | ! | IS_SPACE(token[8])) { |
| 2281 | ! | token += 9; |
| 2282 | ! | ParseTextureNameAndOption(&(material.bump_texname), |
| 2283 | &(material.bump_texopt), token); | |
| 2284 | ! | continue; |
| 2285 | } | |
| 2286 | ||
| 2287 | // bump texture | |
| 2288 | 5x | if ((0 == strncmp(token, "bump", 4)) && IS_SPACE(token[4])) { |
| 2289 | ! | token += 5; |
| 2290 | ! | ParseTextureNameAndOption(&(material.bump_texname), |
| 2291 | &(material.bump_texopt), token); | |
| 2292 | ! | continue; |
| 2293 | } | |
| 2294 | ||
| 2295 | // alpha texture | |
| 2296 | 5x | if ((0 == strncmp(token, "map_d", 5)) && IS_SPACE(token[5])) { |
| 2297 | ! | token += 6; |
| 2298 | ! | material.alpha_texname = token; |
| 2299 | ! | ParseTextureNameAndOption(&(material.alpha_texname), |
| 2300 | &(material.alpha_texopt), token); | |
| 2301 | ! | continue; |
| 2302 | } | |
| 2303 | ||
| 2304 | // displacement texture | |
| 2305 | 5x | if (((0 == strncmp(token, "map_disp", 8)) || |
| 2306 | 5x | (0 == strncmp(token, "map_Disp", 8))) && |
| 2307 | ! | IS_SPACE(token[8])) { |
| 2308 | ! | token += 9; |
| 2309 | ! | ParseTextureNameAndOption(&(material.displacement_texname), |
| 2310 | &(material.displacement_texopt), token); | |
| 2311 | ! | continue; |
| 2312 | } | |
| 2313 | ||
| 2314 | // displacement texture | |
| 2315 | 5x | if ((0 == strncmp(token, "disp", 4)) && IS_SPACE(token[4])) { |
| 2316 | ! | token += 5; |
| 2317 | ! | ParseTextureNameAndOption(&(material.displacement_texname), |
| 2318 | &(material.displacement_texopt), token); | |
| 2319 | ! | continue; |
| 2320 | } | |
| 2321 | ||
| 2322 | // reflection map | |
| 2323 | 5x | if ((0 == strncmp(token, "refl", 4)) && IS_SPACE(token[4])) { |
| 2324 | ! | token += 5; |
| 2325 | ! | ParseTextureNameAndOption(&(material.reflection_texname), |
| 2326 | &(material.reflection_texopt), token); | |
| 2327 | ! | continue; |
| 2328 | } | |
| 2329 | ||
| 2330 | // PBR: roughness texture | |
| 2331 | 5x | if ((0 == strncmp(token, "map_Pr", 6)) && IS_SPACE(token[6])) { |
| 2332 | ! | token += 7; |
| 2333 | ! | ParseTextureNameAndOption(&(material.roughness_texname), |
| 2334 | &(material.roughness_texopt), token); | |
| 2335 | ! | continue; |
| 2336 | } | |
| 2337 | ||
| 2338 | // PBR: metallic texture | |
| 2339 | 5x | if ((0 == strncmp(token, "map_Pm", 6)) && IS_SPACE(token[6])) { |
| 2340 | ! | token += 7; |
| 2341 | ! | ParseTextureNameAndOption(&(material.metallic_texname), |
| 2342 | &(material.metallic_texopt), token); | |
| 2343 | ! | continue; |
| 2344 | } | |
| 2345 | ||
| 2346 | // PBR: sheen texture | |
| 2347 | 5x | if ((0 == strncmp(token, "map_Ps", 6)) && IS_SPACE(token[6])) { |
| 2348 | ! | token += 7; |
| 2349 | ! | ParseTextureNameAndOption(&(material.sheen_texname), |
| 2350 | &(material.sheen_texopt), token); | |
| 2351 | ! | continue; |
| 2352 | } | |
| 2353 | ||
| 2354 | // PBR: emissive texture | |
| 2355 | 5x | if ((0 == strncmp(token, "map_Ke", 6)) && IS_SPACE(token[6])) { |
| 2356 | ! | token += 7; |
| 2357 | ! | ParseTextureNameAndOption(&(material.emissive_texname), |
| 2358 | &(material.emissive_texopt), token); | |
| 2359 | ! | continue; |
| 2360 | } | |
| 2361 | ||
| 2362 | // PBR: normal map texture | |
| 2363 | 5x | if ((0 == strncmp(token, "norm", 4)) && IS_SPACE(token[4])) { |
| 2364 | ! | token += 5; |
| 2365 | ! | ParseTextureNameAndOption(&(material.normal_texname), |
| 2366 | &(material.normal_texopt), token); | |
| 2367 | ! | continue; |
| 2368 | } | |
| 2369 | ||
| 2370 | // unknown parameter | |
| 2371 | 5x | const char *_space = strchr(token, ' '); |
| 2372 | 5x | if (!_space) { |
| 2373 | ! | _space = strchr(token, '\t'); |
| 2374 | } | |
| 2375 | 5x | if (_space) { |
| 2376 | 5x | std::ptrdiff_t len = _space - token; |
| 2377 | 10x | std::string key(token, static_cast<size_t>(len)); |
| 2378 | 5x | std::string value = _space + 1; |
| 2379 | 5x | material.unknown_parameter.insert( |
| 2380 | 10x | std::pair<std::string, std::string>(key, value)); |
| 2381 | } | |
| 2382 | } | |
| 2383 | // flush last material. | |
| 2384 | 4x | material_map->insert(std::pair<std::string, int>( |
| 2385 | 4x | material.name, static_cast<int>(materials->size()))); |
| 2386 | 4x | materials->push_back(material); |
| 2387 | ||
| 2388 | 4x | if (warning) { |
| 2389 | 4x | (*warning) = warn_ss.str(); |
| 2390 | } | |
| 2391 | } | |
| 2392 | ||
| 2393 | 4x | bool MaterialFileReader::operator()(const std::string &matId, |
| 2394 | std::vector<material_t> *materials, | |
| 2395 | std::map<std::string, int> *matMap, | |
| 2396 | std::string *warn, std::string *err) { | |
| 2397 | 4x | if (!m_mtlBaseDir.empty()) { |
| 2398 | #ifdef _WIN32 | |
| 2399 | char sep = ';'; | |
| 2400 | #else | |
| 2401 | 4x | char sep = ':'; |
| 2402 | #endif | |
| 2403 | ||
| 2404 | // https://stackoverflow.com/questions/5167625/splitting-a-c-stdstring-using-tokens-e-g | |
| 2405 | 4x | std::vector<std::string> paths; |
| 2406 | 4x | std::istringstream f(m_mtlBaseDir); |
| 2407 | ||
| 2408 | 4x | std::string s; |
| 2409 | 8x | while (getline(f, s, sep)) { |
| 2410 | 4x | paths.push_back(s); |
| 2411 | } | |
| 2412 | ||
| 2413 | 4x | for (size_t i = 0; i < paths.size(); i++) { |
| 2414 | 4x | std::string filepath = JoinPath(paths[i], matId); |
| 2415 | ||
| 2416 | 4x | std::ifstream matIStream(filepath.c_str()); |
| 2417 | 4x | if (matIStream) { |
| 2418 | 4x | LoadMtl(matMap, materials, &matIStream, warn, err); |
| 2419 | ||
| 2420 | 4x | return true; |
| 2421 | } | |
| 2422 | } | |
| 2423 | ||
| 2424 | ! | std::stringstream ss; |
| 2425 | ss << "Material file [ " << matId | |
| 2426 | ! | << " ] not found in a path : " << m_mtlBaseDir << "\n"; |
| 2427 | ! | if (warn) { |
| 2428 | ! | (*warn) += ss.str(); |
| 2429 | } | |
| 2430 | ! | return false; |
| 2431 | ||
| 2432 | } else { | |
| 2433 | ! | std::string filepath = matId; |
| 2434 | ! | std::ifstream matIStream(filepath.c_str()); |
| 2435 | ! | if (matIStream) { |
| 2436 | ! | LoadMtl(matMap, materials, &matIStream, warn, err); |
| 2437 | ||
| 2438 | ! | return true; |
| 2439 | } | |
| 2440 | ||
| 2441 | ! | std::stringstream ss; |
| 2442 | ss << "Material file [ " << filepath | |
| 2443 | ! | << " ] not found in a path : " << m_mtlBaseDir << "\n"; |
| 2444 | ! | if (warn) { |
| 2445 | ! | (*warn) += ss.str(); |
| 2446 | } | |
| 2447 | ||
| 2448 | ! | return false; |
| 2449 | } | |
| 2450 | } | |
| 2451 | ||
| 2452 | ! | bool MaterialStreamReader::operator()(const std::string &matId, |
| 2453 | std::vector<material_t> *materials, | |
| 2454 | std::map<std::string, int> *matMap, | |
| 2455 | std::string *warn, std::string *err) { | |
| 2456 | (void)err; | |
| 2457 | (void)matId; | |
| 2458 | ! | if (!m_inStream) { |
| 2459 | ! | std::stringstream ss; |
| 2460 | ! | ss << "Material stream in error state. \n"; |
| 2461 | ! | if (warn) { |
| 2462 | ! | (*warn) += ss.str(); |
| 2463 | } | |
| 2464 | ! | return false; |
| 2465 | } | |
| 2466 | ||
| 2467 | ! | LoadMtl(matMap, materials, &m_inStream, warn, err); |
| 2468 | ||
| 2469 | ! | return true; |
| 2470 | } | |
| 2471 | ||
| 2472 | 37x | bool LoadObj(attrib_t *attrib, std::vector<shape_t> *shapes, |
| 2473 | std::vector<material_t> *materials, std::string *warn, | |
| 2474 | std::string *err, const char *filename, const char *mtl_basedir, | |
| 2475 | bool triangulate, bool default_vcols_fallback) { | |
| 2476 | 37x | attrib->vertices.clear(); |
| 2477 | 37x | attrib->normals.clear(); |
| 2478 | 37x | attrib->texcoords.clear(); |
| 2479 | 37x | attrib->colors.clear(); |
| 2480 | 37x | shapes->clear(); |
| 2481 | ||
| 2482 | 37x | std::stringstream errss; |
| 2483 | ||
| 2484 | 37x | std::ifstream ifs(filename); |
| 2485 | 37x | if (!ifs) { |
| 2486 | ! | errss << "Cannot open file [" << filename << "]\n"; |
| 2487 | ! | if (err) { |
| 2488 | ! | (*err) = errss.str(); |
| 2489 | } | |
| 2490 | ! | return false; |
| 2491 | } | |
| 2492 | ||
| 2493 | 37x | std::string baseDir = mtl_basedir ? mtl_basedir : ""; |
| 2494 | 37x | if (!baseDir.empty()) { |
| 2495 | #ifndef _WIN32 | |
| 2496 | 37x | const char dirsep = '/'; |
| 2497 | #else | |
| 2498 | const char dirsep = '\\'; | |
| 2499 | #endif | |
| 2500 | 37x | if (baseDir[baseDir.length() - 1] != dirsep) baseDir += dirsep; |
| 2501 | } | |
| 2502 | 37x | MaterialFileReader matFileReader(baseDir); |
| 2503 | ||
| 2504 | 37x | return LoadObj(attrib, shapes, materials, warn, err, &ifs, &matFileReader, |
| 2505 | 37x | triangulate, default_vcols_fallback); |
| 2506 | } | |
| 2507 | ||
| 2508 | 37x | bool LoadObj(attrib_t *attrib, std::vector<shape_t> *shapes, |
| 2509 | std::vector<material_t> *materials, std::string *warn, | |
| 2510 | std::string *err, std::istream *inStream, | |
| 2511 | MaterialReader *readMatFn /*= NULL*/, bool triangulate, | |
| 2512 | bool default_vcols_fallback) { | |
| 2513 | 37x | std::stringstream errss; |
| 2514 | ||
| 2515 | 37x | std::vector<real_t> v; |
| 2516 | 37x | std::vector<real_t> vn; |
| 2517 | 37x | std::vector<real_t> vt; |
| 2518 | 37x | std::vector<real_t> vc; |
| 2519 | 37x | std::vector<skin_weight_t> vw; |
| 2520 | 37x | std::vector<tag_t> tags; |
| 2521 | 37x | PrimGroup prim_group; |
| 2522 | 37x | std::string name; |
| 2523 | ||
| 2524 | // material | |
| 2525 | 37x | std::set<std::string> material_filenames; |
| 2526 | 37x | std::map<std::string, int> material_map; |
| 2527 | 37x | int material = -1; |
| 2528 | ||
| 2529 | // smoothing group id | |
| 2530 | 37x | unsigned int current_smoothing_id = |
| 2531 | 0; // Initial value. 0 means no smoothing. | |
| 2532 | ||
| 2533 | 37x | int greatest_v_idx = -1; |
| 2534 | 37x | int greatest_vn_idx = -1; |
| 2535 | 37x | int greatest_vt_idx = -1; |
| 2536 | ||
| 2537 | 37x | shape_t shape; |
| 2538 | ||
| 2539 | 37x | bool found_all_colors = true; |
| 2540 | ||
| 2541 | 37x | size_t line_num = 0; |
| 2542 | 37x | std::string linebuf; |
| 2543 | 18104x | while (inStream->peek() != -1) { |
| 2544 | 18067x | safeGetline(*inStream, linebuf); |
| 2545 | ||
| 2546 | 18067x | line_num++; |
| 2547 | ||
| 2548 | // Trim newline '\r\n' or '\n' | |
| 2549 | 18067x | if (linebuf.size() > 0) { |
| 2550 | 18055x | if (linebuf[linebuf.size() - 1] == '\n') |
| 2551 | ! | linebuf.erase(linebuf.size() - 1); |
| 2552 | } | |
| 2553 | 18067x | if (linebuf.size() > 0) { |
| 2554 | 18055x | if (linebuf[linebuf.size() - 1] == '\r') |
| 2555 | ! | linebuf.erase(linebuf.size() - 1); |
| 2556 | } | |
| 2557 | ||
| 2558 | // Skip if empty line. | |
| 2559 | 18067x | if (linebuf.empty()) { |
| 2560 | 18067x | continue; |
| 2561 | } | |
| 2562 | ||
| 2563 | // Skip leading space. | |
| 2564 | 18055x | const char *token = linebuf.c_str(); |
| 2565 | 18055x | token += strspn(token, " \t"); |
| 2566 | ||
| 2567 | assert(token); | |
| 2568 | 18055x | if (token[0] == '\0') continue; // empty line |
| 2569 | ||
| 2570 | 18055x | if (token[0] == '#') continue; // comment line |
| 2571 | ||
| 2572 | // vertex | |
| 2573 | 18051x | if (token[0] == 'v' && IS_SPACE((token[1]))) { |
| 2574 | 4962x | token += 2; |
| 2575 | real_t x, y, z; | |
| 2576 | real_t r, g, b; | |
| 2577 | ||
| 2578 | 4962x | found_all_colors &= parseVertexWithColor(&x, &y, &z, &r, &g, &b, &token); |
| 2579 | ||
| 2580 | 4962x | v.push_back(x); |
| 2581 | 4962x | v.push_back(y); |
| 2582 | 4962x | v.push_back(z); |
| 2583 | ||
| 2584 | 4962x | if (found_all_colors || default_vcols_fallback) { |
| 2585 | 4962x | vc.push_back(r); |
| 2586 | 4962x | vc.push_back(g); |
| 2587 | 4962x | vc.push_back(b); |
| 2588 | } | |
| 2589 | ||
| 2590 | 4962x | continue; |
| 2591 | } | |
| 2592 | ||
| 2593 | // normal | |
| 2594 | 13089x | if (token[0] == 'v' && token[1] == 'n' && IS_SPACE((token[2]))) { |
| 2595 | 3316x | token += 3; |
| 2596 | real_t x, y, z; | |
| 2597 | 3316x | parseReal3(&x, &y, &z, &token); |
| 2598 | 3316x | vn.push_back(x); |
| 2599 | 3316x | vn.push_back(y); |
| 2600 | 3316x | vn.push_back(z); |
| 2601 | 3316x | continue; |
| 2602 | } | |
| 2603 | ||
| 2604 | // texcoord | |
| 2605 | 9773x | if (token[0] == 'v' && token[1] == 't' && IS_SPACE((token[2]))) { |
| 2606 | 3361x | token += 3; |
| 2607 | real_t x, y; | |
| 2608 | 3361x | parseReal2(&x, &y, &token); |
| 2609 | 3361x | vt.push_back(x); |
| 2610 | 3361x | vt.push_back(y); |
| 2611 | 3361x | continue; |
| 2612 | } | |
| 2613 | ||
| 2614 | // skin weight. tinyobj extension | |
| 2615 | 6412x | if (token[0] == 'v' && token[1] == 'w' && IS_SPACE((token[2]))) { |
| 2616 | ! | token += 3; |
| 2617 | ||
| 2618 | // vw <vid> <joint_0> <weight_0> <joint_1> <weight_1> ... | |
| 2619 | // example: | |
| 2620 | // vw 0 0 0.25 1 0.25 2 0.5 | |
| 2621 | ||
| 2622 | // TODO(syoyo): Add syntax check | |
| 2623 | ! | int vid = 0; |
| 2624 | ! | vid = parseInt(&token); |
| 2625 | ||
| 2626 | ! | skin_weight_t sw; |
| 2627 | ||
| 2628 | ! | sw.vertex_id = vid; |
| 2629 | ||
| 2630 | ! | while (!IS_NEW_LINE(token[0])) { |
| 2631 | real_t j, w; | |
| 2632 | // joint_id should not be negative, weight may be negative | |
| 2633 | // TODO(syoyo): # of elements check | |
| 2634 | ! | parseReal2(&j, &w, &token, -1.0); |
| 2635 | ||
| 2636 | ! | if (j < static_cast<real_t>(0)) { |
| 2637 | ! | if (err) { |
| 2638 | ! | std::stringstream ss; |
| 2639 | ss << "Failed parse `vw' line. joint_id is negative. " | |
| 2640 | ! | "line " |
| 2641 | ! | << line_num << ".)\n"; |
| 2642 | ! | (*err) += ss.str(); |
| 2643 | } | |
| 2644 | ! | return false; |
| 2645 | } | |
| 2646 | ||
| 2647 | joint_and_weight_t jw; | |
| 2648 | ||
| 2649 | ! | jw.joint_id = int(j); |
| 2650 | ! | jw.weight = w; |
| 2651 | ||
| 2652 | ! | sw.weightValues.push_back(jw); |
| 2653 | ||
| 2654 | ! | size_t n = strspn(token, " \t\r"); |
| 2655 | ! | token += n; |
| 2656 | } | |
| 2657 | ||
| 2658 | ! | vw.push_back(sw); |
| 2659 | } | |
| 2660 | ||
| 2661 | // line | |
| 2662 | 6412x | if (token[0] == 'l' && IS_SPACE((token[1]))) { |
| 2663 | ! | token += 2; |
| 2664 | ||
| 2665 | ! | __line_t line; |
| 2666 | ||
| 2667 | ! | while (!IS_NEW_LINE(token[0])) { |
| 2668 | ! | vertex_index_t vi; |
| 2669 | ! | if (!parseTriple(&token, static_cast<int>(v.size() / 3), |
| 2670 | ! | static_cast<int>(vn.size() / 3), |
| 2671 | ! | static_cast<int>(vt.size() / 2), &vi)) { |
| 2672 | ! | if (err) { |
| 2673 | ! | std::stringstream ss; |
| 2674 | ss << "Failed parse `l' line(e.g. zero value for vertex index. " | |
| 2675 | ! | "line " |
| 2676 | ! | << line_num << ".)\n"; |
| 2677 | ! | (*err) += ss.str(); |
| 2678 | } | |
| 2679 | ! | return false; |
| 2680 | } | |
| 2681 | ||
| 2682 | ! | line.vertex_indices.push_back(vi); |
| 2683 | ||
| 2684 | ! | size_t n = strspn(token, " \t\r"); |
| 2685 | ! | token += n; |
| 2686 | } | |
| 2687 | ||
| 2688 | ! | prim_group.lineGroup.push_back(line); |
| 2689 | ||
| 2690 | ! | continue; |
| 2691 | } | |
| 2692 | ||
| 2693 | // points | |
| 2694 | 6412x | if (token[0] == 'p' && IS_SPACE((token[1]))) { |
| 2695 | ! | token += 2; |
| 2696 | ||
| 2697 | ! | __points_t pts; |
| 2698 | ||
| 2699 | ! | while (!IS_NEW_LINE(token[0])) { |
| 2700 | ! | vertex_index_t vi; |
| 2701 | ! | if (!parseTriple(&token, static_cast<int>(v.size() / 3), |
| 2702 | ! | static_cast<int>(vn.size() / 3), |
| 2703 | ! | static_cast<int>(vt.size() / 2), &vi)) { |
| 2704 | ! | if (err) { |
| 2705 | ! | std::stringstream ss; |
| 2706 | ss << "Failed parse `p' line(e.g. zero value for vertex index. " | |
| 2707 | ! | "line " |
| 2708 | ! | << line_num << ".)\n"; |
| 2709 | ! | (*err) += ss.str(); |
| 2710 | } | |
| 2711 | ! | return false; |
| 2712 | } | |
| 2713 | ||
| 2714 | ! | pts.vertex_indices.push_back(vi); |
| 2715 | ||
| 2716 | ! | size_t n = strspn(token, " \t\r"); |
| 2717 | ! | token += n; |
| 2718 | } | |
| 2719 | ||
| 2720 | ! | prim_group.pointsGroup.push_back(pts); |
| 2721 | ||
| 2722 | ! | continue; |
| 2723 | } | |
| 2724 | ||
| 2725 | // face | |
| 2726 | 6412x | if (token[0] == 'f' && IS_SPACE((token[1]))) { |
| 2727 | 6315x | token += 2; |
| 2728 | 6315x | token += strspn(token, " \t"); |
| 2729 | ||
| 2730 | 6315x | face_t face; |
| 2731 | ||
| 2732 | 6315x | face.smoothing_group_id = current_smoothing_id; |
| 2733 | 6315x | face.vertex_indices.reserve(3); |
| 2734 | ||
| 2735 | 26253x | while (!IS_NEW_LINE(token[0])) { |
| 2736 | 19938x | vertex_index_t vi; |
| 2737 | 19938x | if (!parseTriple(&token, static_cast<int>(v.size() / 3), |
| 2738 | 19938x | static_cast<int>(vn.size() / 3), |
| 2739 | 19938x | static_cast<int>(vt.size() / 2), &vi)) { |
| 2740 | ! | if (err) { |
| 2741 | ! | std::stringstream ss; |
| 2742 | ! | ss << "Failed parse `f' line(e.g. zero value for face index. line " |
| 2743 | ! | << line_num << ".)\n"; |
| 2744 | ! | (*err) += ss.str(); |
| 2745 | } | |
| 2746 | ! | return false; |
| 2747 | } | |
| 2748 | ||
| 2749 | 19938x | greatest_v_idx = greatest_v_idx > vi.v_idx ? greatest_v_idx : vi.v_idx; |
| 2750 | 19938x | greatest_vn_idx = |
| 2751 | 19938x | greatest_vn_idx > vi.vn_idx ? greatest_vn_idx : vi.vn_idx; |
| 2752 | 19938x | greatest_vt_idx = |
| 2753 | 19938x | greatest_vt_idx > vi.vt_idx ? greatest_vt_idx : vi.vt_idx; |
| 2754 | ||
| 2755 | 19938x | face.vertex_indices.push_back(vi); |
| 2756 | 19938x | size_t n = strspn(token, " \t\r"); |
| 2757 | 19938x | token += n; |
| 2758 | } | |
| 2759 | ||
| 2760 | // replace with emplace_back + std::move on C++11 | |
| 2761 | 6315x | prim_group.faceGroup.push_back(face); |
| 2762 | ||
| 2763 | 6315x | continue; |
| 2764 | } | |
| 2765 | ||
| 2766 | // use mtl | |
| 2767 | 97x | if ((0 == strncmp(token, "usemtl", 6))) { |
| 2768 | 6x | token += 6; |
| 2769 | 6x | std::string namebuf = parseString(&token); |
| 2770 | ||
| 2771 | 6x | int newMaterialId = -1; |
| 2772 | std::map<std::string, int>::const_iterator it = | |
| 2773 | 6x | material_map.find(namebuf); |
| 2774 | 6x | if (it != material_map.end()) { |
| 2775 | 6x | newMaterialId = it->second; |
| 2776 | } else { | |
| 2777 | // { error!! material not found } | |
| 2778 | ! | if (warn) { |
| 2779 | ! | (*warn) += "material [ '" + namebuf + "' ] not found in .mtl\n"; |
| 2780 | } | |
| 2781 | } | |
| 2782 | ||
| 2783 | 6x | if (newMaterialId != material) { |
| 2784 | // Create per-face material. Thus we don't add `shape` to `shapes` at | |
| 2785 | // this time. | |
| 2786 | // just clear `faceGroup` after `exportGroupsToShape()` call. | |
| 2787 | 6x | exportGroupsToShape(&shape, prim_group, tags, material, name, |
| 2788 | triangulate, v, warn); | |
| 2789 | 6x | prim_group.faceGroup.clear(); |
| 2790 | 6x | material = newMaterialId; |
| 2791 | } | |
| 2792 | ||
| 2793 | 6x | continue; |
| 2794 | } | |
| 2795 | ||
| 2796 | // load mtl | |
| 2797 | 91x | if ((0 == strncmp(token, "mtllib", 6)) && IS_SPACE((token[6]))) { |
| 2798 | 4x | if (readMatFn) { |
| 2799 | 4x | token += 7; |
| 2800 | ||
| 2801 | 4x | std::vector<std::string> filenames; |
| 2802 | 4x | SplitString(std::string(token), ' ', '\\', filenames); |
| 2803 | ||
| 2804 | 4x | if (filenames.empty()) { |
| 2805 | ! | if (warn) { |
| 2806 | ! | std::stringstream ss; |
| 2807 | ss << "Looks like empty filename for mtllib. Use default " | |
| 2808 | ! | "material (line " |
| 2809 | ! | << line_num << ".)\n"; |
| 2810 | ||
| 2811 | ! | (*warn) += ss.str(); |
| 2812 | } | |
| 2813 | } else { | |
| 2814 | 4x | bool found = false; |
| 2815 | 4x | for (size_t s = 0; s < filenames.size(); s++) { |
| 2816 | 4x | if (material_filenames.count(filenames[s]) > 0) { |
| 2817 | ! | found = true; |
| 2818 | ! | continue; |
| 2819 | } | |
| 2820 | ||
| 2821 | 4x | std::string warn_mtl; |
| 2822 | 4x | std::string err_mtl; |
| 2823 | 8x | bool ok = (*readMatFn)(filenames[s].c_str(), materials, |
| 2824 | &material_map, &warn_mtl, &err_mtl); | |
| 2825 | 4x | if (warn && (!warn_mtl.empty())) { |
| 2826 | ! | (*warn) += warn_mtl; |
| 2827 | } | |
| 2828 | ||
| 2829 | 4x | if (err && (!err_mtl.empty())) { |
| 2830 | ! | (*err) += err_mtl; |
| 2831 | } | |
| 2832 | ||
| 2833 | 4x | if (ok) { |
| 2834 | 4x | found = true; |
| 2835 | 4x | material_filenames.insert(filenames[s]); |
| 2836 | 4x | break; |
| 2837 | } | |
| 2838 | } | |
| 2839 | ||
| 2840 | 4x | if (!found) { |
| 2841 | ! | if (warn) { |
| 2842 | (*warn) += | |
| 2843 | "Failed to load material file(s). Use default " | |
| 2844 | ! | "material.\n"; |
| 2845 | } | |
| 2846 | } | |
| 2847 | } | |
| 2848 | } | |
| 2849 | ||
| 2850 | 4x | continue; |
| 2851 | } | |
| 2852 | ||
| 2853 | // group name | |
| 2854 | 87x | if (token[0] == 'g' && IS_SPACE((token[1]))) { |
| 2855 | // flush previous face group. | |
| 2856 | 3x | bool ret = exportGroupsToShape(&shape, prim_group, tags, material, name, |
| 2857 | triangulate, v, warn); | |
| 2858 | (void)ret; // return value not used. | |
| 2859 | ||
| 2860 | 3x | if (shape.mesh.indices.size() > 0) { |
| 2861 | ! | shapes->push_back(shape); |
| 2862 | } | |
| 2863 | ||
| 2864 | 3x | shape = shape_t(); |
| 2865 | ||
| 2866 | // material = -1; | |
| 2867 | 3x | prim_group.clear(); |
| 2868 | ||
| 2869 | 3x | std::vector<std::string> names; |
| 2870 | ||
| 2871 | 9x | while (!IS_NEW_LINE(token[0])) { |
| 2872 | 6x | std::string str = parseString(&token); |
| 2873 | 6x | names.push_back(str); |
| 2874 | 6x | token += strspn(token, " \t\r"); // skip tag |
| 2875 | } | |
| 2876 | ||
| 2877 | // names[0] must be 'g' | |
| 2878 | ||
| 2879 | 3x | if (names.size() < 2) { |
| 2880 | // 'g' with empty names | |
| 2881 | ! | if (warn) { |
| 2882 | ! | std::stringstream ss; |
| 2883 | ! | ss << "Empty group name. line: " << line_num << "\n"; |
| 2884 | ! | (*warn) += ss.str(); |
| 2885 | ! | name = ""; |
| 2886 | } | |
| 2887 | } else { | |
| 2888 | 3x | std::stringstream ss; |
| 2889 | 3x | ss << names[1]; |
| 2890 | ||
| 2891 | // tinyobjloader does not support multiple groups for a primitive. | |
| 2892 | // Currently we concatinate multiple group names with a space to get | |
| 2893 | // single group name. | |
| 2894 | ||
| 2895 | 3x | for (size_t i = 2; i < names.size(); i++) { |
| 2896 | ! | ss << " " << names[i]; |
| 2897 | } | |
| 2898 | ||
| 2899 | 3x | name = ss.str(); |
| 2900 | } | |
| 2901 | ||
| 2902 | 3x | continue; |
| 2903 | } | |
| 2904 | ||
| 2905 | // object name | |
| 2906 | 84x | if (token[0] == 'o' && IS_SPACE((token[1]))) { |
| 2907 | // flush previous face group. | |
| 2908 | 33x | bool ret = exportGroupsToShape(&shape, prim_group, tags, material, name, |
| 2909 | triangulate, v, warn); | |
| 2910 | (void)ret; // return value not used. | |
| 2911 | ||
| 2912 | 66x | if (shape.mesh.indices.size() > 0 || shape.lines.indices.size() > 0 || |
| 2913 | 33x | shape.points.indices.size() > 0) { |
| 2914 | ! | shapes->push_back(shape); |
| 2915 | } | |
| 2916 | ||
| 2917 | // material = -1; | |
| 2918 | 33x | prim_group.clear(); |
| 2919 | 33x | shape = shape_t(); |
| 2920 | ||
| 2921 | // @todo { multiple object name? } | |
| 2922 | 33x | token += 2; |
| 2923 | 33x | std::stringstream ss; |
| 2924 | 33x | ss << token; |
| 2925 | 33x | name = ss.str(); |
| 2926 | ||
| 2927 | 33x | continue; |
| 2928 | } | |
| 2929 | ||
| 2930 | 51x | if (token[0] == 't' && IS_SPACE(token[1])) { |
| 2931 | ! | const int max_tag_nums = 8192; // FIXME(syoyo): Parameterize. |
| 2932 | ! | tag_t tag; |
| 2933 | ||
| 2934 | ! | token += 2; |
| 2935 | ||
| 2936 | ! | tag.name = parseString(&token); |
| 2937 | ||
| 2938 | ! | tag_sizes ts = parseTagTriple(&token); |
| 2939 | ||
| 2940 | ! | if (ts.num_ints < 0) { |
| 2941 | ! | ts.num_ints = 0; |
| 2942 | } | |
| 2943 | ! | if (ts.num_ints > max_tag_nums) { |
| 2944 | ! | ts.num_ints = max_tag_nums; |
| 2945 | } | |
| 2946 | ||
| 2947 | ! | if (ts.num_reals < 0) { |
| 2948 | ! | ts.num_reals = 0; |
| 2949 | } | |
| 2950 | ! | if (ts.num_reals > max_tag_nums) { |
| 2951 | ! | ts.num_reals = max_tag_nums; |
| 2952 | } | |
| 2953 | ||
| 2954 | ! | if (ts.num_strings < 0) { |
| 2955 | ! | ts.num_strings = 0; |
| 2956 | } | |
| 2957 | ! | if (ts.num_strings > max_tag_nums) { |
| 2958 | ! | ts.num_strings = max_tag_nums; |
| 2959 | } | |
| 2960 | ||
| 2961 | ! | tag.intValues.resize(static_cast<size_t>(ts.num_ints)); |
| 2962 | ||
| 2963 | ! | for (size_t i = 0; i < static_cast<size_t>(ts.num_ints); ++i) { |
| 2964 | ! | tag.intValues[i] = parseInt(&token); |
| 2965 | } | |
| 2966 | ||
| 2967 | ! | tag.floatValues.resize(static_cast<size_t>(ts.num_reals)); |
| 2968 | ! | for (size_t i = 0; i < static_cast<size_t>(ts.num_reals); ++i) { |
| 2969 | ! | tag.floatValues[i] = parseReal(&token); |
| 2970 | } | |
| 2971 | ||
| 2972 | ! | tag.stringValues.resize(static_cast<size_t>(ts.num_strings)); |
| 2973 | ! | for (size_t i = 0; i < static_cast<size_t>(ts.num_strings); ++i) { |
| 2974 | ! | tag.stringValues[i] = parseString(&token); |
| 2975 | } | |
| 2976 | ||
| 2977 | ! | tags.push_back(tag); |
| 2978 | ||
| 2979 | ! | continue; |
| 2980 | } | |
| 2981 | ||
| 2982 | 51x | if (token[0] == 's' && IS_SPACE(token[1])) { |
| 2983 | // smoothing group id | |
| 2984 | 51x | token += 2; |
| 2985 | ||
| 2986 | // skip space. | |
| 2987 | 51x | token += strspn(token, " \t"); // skip space |
| 2988 | ||
| 2989 | 51x | if (token[0] == '\0') { |
| 2990 | ! | continue; |
| 2991 | } | |
| 2992 | ||
| 2993 | 51x | if (token[0] == '\r' || token[1] == '\n') { |
| 2994 | ! | continue; |
| 2995 | } | |
| 2996 | ||
| 2997 | 51x | if (strlen(token) >= 3 && token[0] == 'o' && token[1] == 'f' && |
| 2998 | 24x | token[2] == 'f') { |
| 2999 | 24x | current_smoothing_id = 0; |
| 3000 | } else { | |
| 3001 | // assume number | |
| 3002 | 27x | int smGroupId = parseInt(&token); |
| 3003 | 27x | if (smGroupId < 0) { |
| 3004 | // parse error. force set to 0. | |
| 3005 | // FIXME(syoyo): Report warning. | |
| 3006 | ! | current_smoothing_id = 0; |
| 3007 | } else { | |
| 3008 | 27x | current_smoothing_id = static_cast<unsigned int>(smGroupId); |
| 3009 | } | |
| 3010 | } | |
| 3011 | ||
| 3012 | 51x | continue; |
| 3013 | 51x | } // smoothing group id |
| 3014 | ||
| 3015 | // Ignore unknown command. | |
| 3016 | } | |
| 3017 | ||
| 3018 | // not all vertices have colors, no default colors desired? -> clear colors | |
| 3019 | 37x | if (!found_all_colors && !default_vcols_fallback) { |
| 3020 | ! | vc.clear(); |
| 3021 | } | |
| 3022 | ||
| 3023 | 37x | if (greatest_v_idx >= static_cast<int>(v.size() / 3)) { |
| 3024 | ! | if (warn) { |
| 3025 | ! | std::stringstream ss; |
| 3026 | ! | ss << "Vertex indices out of bounds (line " << line_num << ".)\n\n"; |
| 3027 | ! | (*warn) += ss.str(); |
| 3028 | } | |
| 3029 | } | |
| 3030 | 37x | if (greatest_vn_idx >= static_cast<int>(vn.size() / 3)) { |
| 3031 | ! | if (warn) { |
| 3032 | ! | std::stringstream ss; |
| 3033 | ! | ss << "Vertex normal indices out of bounds (line " << line_num << ".)\n\n"; |
| 3034 | ! | (*warn) += ss.str(); |
| 3035 | } | |
| 3036 | } | |
| 3037 | 37x | if (greatest_vt_idx >= static_cast<int>(vt.size() / 2)) { |
| 3038 | ! | if (warn) { |
| 3039 | ! | std::stringstream ss; |
| 3040 | ! | ss << "Vertex texcoord indices out of bounds (line " << line_num << ".)\n\n"; |
| 3041 | ! | (*warn) += ss.str(); |
| 3042 | } | |
| 3043 | } | |
| 3044 | ||
| 3045 | 37x | bool ret = exportGroupsToShape(&shape, prim_group, tags, material, name, |
| 3046 | triangulate, v, warn); | |
| 3047 | // exportGroupsToShape return false when `usemtl` is called in the last | |
| 3048 | // line. | |
| 3049 | // we also add `shape` to `shapes` when `shape.mesh` has already some | |
| 3050 | // faces(indices) | |
| 3051 | 37x | if (ret || shape.mesh.indices |
| 3052 | ! | .size()) { // FIXME(syoyo): Support other prims(e.g. lines) |
| 3053 | 37x | shapes->push_back(shape); |
| 3054 | } | |
| 3055 | 37x | prim_group.clear(); // for safety |
| 3056 | ||
| 3057 | 37x | if (err) { |
| 3058 | 37x | (*err) += errss.str(); |
| 3059 | } | |
| 3060 | ||
| 3061 | 37x | attrib->vertices.swap(v); |
| 3062 | 37x | attrib->vertex_weights.swap(v); |
| 3063 | 37x | attrib->normals.swap(vn); |
| 3064 | 37x | attrib->texcoords.swap(vt); |
| 3065 | 37x | attrib->texcoord_ws.swap(vt); |
| 3066 | 37x | attrib->colors.swap(vc); |
| 3067 | 37x | attrib->skin_weights.swap(vw); |
| 3068 | ||
| 3069 | 37x | return true; |
| 3070 | } | |
| 3071 | ||
| 3072 | ! | bool LoadObjWithCallback(std::istream &inStream, const callback_t &callback, |
| 3073 | void *user_data /*= NULL*/, | |
| 3074 | MaterialReader *readMatFn /*= NULL*/, | |
| 3075 | std::string *warn, /* = NULL*/ | |
| 3076 | std::string *err /*= NULL*/) { | |
| 3077 | ! | std::stringstream errss; |
| 3078 | ||
| 3079 | // material | |
| 3080 | ! | std::set<std::string> material_filenames; |
| 3081 | ! | std::map<std::string, int> material_map; |
| 3082 | ! | int material_id = -1; // -1 = invalid |
| 3083 | ||
| 3084 | ! | std::vector<index_t> indices; |
| 3085 | ! | std::vector<material_t> materials; |
| 3086 | ! | std::vector<std::string> names; |
| 3087 | ! | names.reserve(2); |
| 3088 | ! | std::vector<const char *> names_out; |
| 3089 | ||
| 3090 | ! | std::string linebuf; |
| 3091 | ! | while (inStream.peek() != -1) { |
| 3092 | ! | safeGetline(inStream, linebuf); |
| 3093 | ||
| 3094 | // Trim newline '\r\n' or '\n' | |
| 3095 | ! | if (linebuf.size() > 0) { |
| 3096 | ! | if (linebuf[linebuf.size() - 1] == '\n') |
| 3097 | ! | linebuf.erase(linebuf.size() - 1); |
| 3098 | } | |
| 3099 | ! | if (linebuf.size() > 0) { |
| 3100 | ! | if (linebuf[linebuf.size() - 1] == '\r') |
| 3101 | ! | linebuf.erase(linebuf.size() - 1); |
| 3102 | } | |
| 3103 | ||
| 3104 | // Skip if empty line. | |
| 3105 | ! | if (linebuf.empty()) { |
| 3106 | ! | continue; |
| 3107 | } | |
| 3108 | ||
| 3109 | // Skip leading space. | |
| 3110 | ! | const char *token = linebuf.c_str(); |
| 3111 | ! | token += strspn(token, " \t"); |
| 3112 | ||
| 3113 | assert(token); | |
| 3114 | ! | if (token[0] == '\0') continue; // empty line |
| 3115 | ||
| 3116 | ! | if (token[0] == '#') continue; // comment line |
| 3117 | ||
| 3118 | // vertex | |
| 3119 | ! | if (token[0] == 'v' && IS_SPACE((token[1]))) { |
| 3120 | ! | token += 2; |
| 3121 | // TODO(syoyo): Support parsing vertex color extension. | |
| 3122 | real_t x, y, z, w; // w is optional. default = 1.0 | |
| 3123 | ! | parseV(&x, &y, &z, &w, &token); |
| 3124 | ! | if (callback.vertex_cb) { |
| 3125 | ! | callback.vertex_cb(user_data, x, y, z, w); |
| 3126 | } | |
| 3127 | ! | continue; |
| 3128 | } | |
| 3129 | ||
| 3130 | // normal | |
| 3131 | ! | if (token[0] == 'v' && token[1] == 'n' && IS_SPACE((token[2]))) { |
| 3132 | ! | token += 3; |
| 3133 | real_t x, y, z; | |
| 3134 | ! | parseReal3(&x, &y, &z, &token); |
| 3135 | ! | if (callback.normal_cb) { |
| 3136 | ! | callback.normal_cb(user_data, x, y, z); |
| 3137 | } | |
| 3138 | ! | continue; |
| 3139 | } | |
| 3140 | ||
| 3141 | // texcoord | |
| 3142 | ! | if (token[0] == 'v' && token[1] == 't' && IS_SPACE((token[2]))) { |
| 3143 | ! | token += 3; |
| 3144 | real_t x, y, z; // y and z are optional. default = 0.0 | |
| 3145 | ! | parseReal3(&x, &y, &z, &token); |
| 3146 | ! | if (callback.texcoord_cb) { |
| 3147 | ! | callback.texcoord_cb(user_data, x, y, z); |
| 3148 | } | |
| 3149 | ! | continue; |
| 3150 | } | |
| 3151 | ||
| 3152 | // face | |
| 3153 | ! | if (token[0] == 'f' && IS_SPACE((token[1]))) { |
| 3154 | ! | token += 2; |
| 3155 | ! | token += strspn(token, " \t"); |
| 3156 | ||
| 3157 | ! | indices.clear(); |
| 3158 | ! | while (!IS_NEW_LINE(token[0])) { |
| 3159 | ! | vertex_index_t vi = parseRawTriple(&token); |
| 3160 | ||
| 3161 | index_t idx; | |
| 3162 | ! | idx.vertex_index = vi.v_idx; |
| 3163 | ! | idx.normal_index = vi.vn_idx; |
| 3164 | ! | idx.texcoord_index = vi.vt_idx; |
| 3165 | ||
| 3166 | ! | indices.push_back(idx); |
| 3167 | ! | size_t n = strspn(token, " \t\r"); |
| 3168 | ! | token += n; |
| 3169 | } | |
| 3170 | ||
| 3171 | ! | if (callback.index_cb && indices.size() > 0) { |
| 3172 | ! | callback.index_cb(user_data, &indices.at(0), |
| 3173 | ! | static_cast<int>(indices.size())); |
| 3174 | } | |
| 3175 | ||
| 3176 | ! | continue; |
| 3177 | } | |
| 3178 | ||
| 3179 | // use mtl | |
| 3180 | ! | if ((0 == strncmp(token, "usemtl", 6)) && IS_SPACE((token[6]))) { |
| 3181 | ! | token += 7; |
| 3182 | ! | std::stringstream ss; |
| 3183 | ! | ss << token; |
| 3184 | ! | std::string namebuf = ss.str(); |
| 3185 | ||
| 3186 | ! | int newMaterialId = -1; |
| 3187 | std::map<std::string, int>::const_iterator it = | |
| 3188 | ! | material_map.find(namebuf); |
| 3189 | ! | if (it != material_map.end()) { |
| 3190 | ! | newMaterialId = it->second; |
| 3191 | } else { | |
| 3192 | // { warn!! material not found } | |
| 3193 | ! | if (warn && (!callback.usemtl_cb)) { |
| 3194 | ! | (*warn) += "material [ " + namebuf + " ] not found in .mtl\n"; |
| 3195 | } | |
| 3196 | } | |
| 3197 | ||
| 3198 | ! | if (newMaterialId != material_id) { |
| 3199 | ! | material_id = newMaterialId; |
| 3200 | } | |
| 3201 | ||
| 3202 | ! | if (callback.usemtl_cb) { |
| 3203 | ! | callback.usemtl_cb(user_data, namebuf.c_str(), material_id); |
| 3204 | } | |
| 3205 | ||
| 3206 | ! | continue; |
| 3207 | } | |
| 3208 | ||
| 3209 | // load mtl | |
| 3210 | ! | if ((0 == strncmp(token, "mtllib", 6)) && IS_SPACE((token[6]))) { |
| 3211 | ! | if (readMatFn) { |
| 3212 | ! | token += 7; |
| 3213 | ||
| 3214 | ! | std::vector<std::string> filenames; |
| 3215 | ! | SplitString(std::string(token), ' ', '\\', filenames); |
| 3216 | ||
| 3217 | ! | if (filenames.empty()) { |
| 3218 | ! | if (warn) { |
| 3219 | (*warn) += | |
| 3220 | "Looks like empty filename for mtllib. Use default " | |
| 3221 | ! | "material. \n"; |
| 3222 | } | |
| 3223 | } else { | |
| 3224 | ! | bool found = false; |
| 3225 | ! | for (size_t s = 0; s < filenames.size(); s++) { |
| 3226 | ! | if (material_filenames.count(filenames[s]) > 0) { |
| 3227 | ! | found = true; |
| 3228 | ! | continue; |
| 3229 | } | |
| 3230 | ||
| 3231 | ! | std::string warn_mtl; |
| 3232 | ! | std::string err_mtl; |
| 3233 | ! | bool ok = (*readMatFn)(filenames[s].c_str(), &materials, |
| 3234 | &material_map, &warn_mtl, &err_mtl); | |
| 3235 | ||
| 3236 | ! | if (warn && (!warn_mtl.empty())) { |
| 3237 | ! | (*warn) += warn_mtl; // This should be warn message. |
| 3238 | } | |
| 3239 | ||
| 3240 | ! | if (err && (!err_mtl.empty())) { |
| 3241 | ! | (*err) += err_mtl; |
| 3242 | } | |
| 3243 | ||
| 3244 | ! | if (ok) { |
| 3245 | ! | found = true; |
| 3246 | ! | material_filenames.insert(filenames[s]); |
| 3247 | ! | break; |
| 3248 | } | |
| 3249 | } | |
| 3250 | ||
| 3251 | ! | if (!found) { |
| 3252 | ! | if (warn) { |
| 3253 | (*warn) += | |
| 3254 | "Failed to load material file(s). Use default " | |
| 3255 | ! | "material.\n"; |
| 3256 | } | |
| 3257 | } else { | |
| 3258 | ! | if (callback.mtllib_cb) { |
| 3259 | ! | callback.mtllib_cb(user_data, &materials.at(0), |
| 3260 | ! | static_cast<int>(materials.size())); |
| 3261 | } | |
| 3262 | } | |
| 3263 | } | |
| 3264 | } | |
| 3265 | ||
| 3266 | ! | continue; |
| 3267 | } | |
| 3268 | ||
| 3269 | // group name | |
| 3270 | ! | if (token[0] == 'g' && IS_SPACE((token[1]))) { |
| 3271 | ! | names.clear(); |
| 3272 | ||
| 3273 | ! | while (!IS_NEW_LINE(token[0])) { |
| 3274 | ! | std::string str = parseString(&token); |
| 3275 | ! | names.push_back(str); |
| 3276 | ! | token += strspn(token, " \t\r"); // skip tag |
| 3277 | } | |
| 3278 | ||
| 3279 | assert(names.size() > 0); | |
| 3280 | ||
| 3281 | ! | if (callback.group_cb) { |
| 3282 | ! | if (names.size() > 1) { |
| 3283 | // create const char* array. | |
| 3284 | ! | names_out.resize(names.size() - 1); |
| 3285 | ! | for (size_t j = 0; j < names_out.size(); j++) { |
| 3286 | ! | names_out[j] = names[j + 1].c_str(); |
| 3287 | } | |
| 3288 | ! | callback.group_cb(user_data, &names_out.at(0), |
| 3289 | ! | static_cast<int>(names_out.size())); |
| 3290 | ||
| 3291 | } else { | |
| 3292 | ! | callback.group_cb(user_data, NULL, 0); |
| 3293 | } | |
| 3294 | } | |
| 3295 | ||
| 3296 | ! | continue; |
| 3297 | } | |
| 3298 | ||
| 3299 | // object name | |
| 3300 | ! | if (token[0] == 'o' && IS_SPACE((token[1]))) { |
| 3301 | // @todo { multiple object name? } | |
| 3302 | ! | token += 2; |
| 3303 | ||
| 3304 | ! | std::stringstream ss; |
| 3305 | ! | ss << token; |
| 3306 | ! | std::string object_name = ss.str(); |
| 3307 | ||
| 3308 | ! | if (callback.object_cb) { |
| 3309 | ! | callback.object_cb(user_data, object_name.c_str()); |
| 3310 | } | |
| 3311 | ||
| 3312 | ! | continue; |
| 3313 | } | |
| 3314 | ||
| 3315 | #if 0 // @todo | |
| 3316 | if (token[0] == 't' && IS_SPACE(token[1])) { | |
| 3317 | tag_t tag; | |
| 3318 | ||
| 3319 | token += 2; | |
| 3320 | std::stringstream ss; | |
| 3321 | ss << token; | |
| 3322 | tag.name = ss.str(); | |
| 3323 | ||
| 3324 | token += tag.name.size() + 1; | |
| 3325 | ||
| 3326 | tag_sizes ts = parseTagTriple(&token); | |
| 3327 | ||
| 3328 | tag.intValues.resize(static_cast<size_t>(ts.num_ints)); | |
| 3329 | ||
| 3330 | for (size_t i = 0; i < static_cast<size_t>(ts.num_ints); ++i) { | |
| 3331 | tag.intValues[i] = atoi(token); | |
| 3332 | token += strcspn(token, "/ \t\r") + 1; | |
| 3333 | } | |
| 3334 | ||
| 3335 | tag.floatValues.resize(static_cast<size_t>(ts.num_reals)); | |
| 3336 | for (size_t i = 0; i < static_cast<size_t>(ts.num_reals); ++i) { | |
| 3337 | tag.floatValues[i] = parseReal(&token); | |
| 3338 | token += strcspn(token, "/ \t\r") + 1; | |
| 3339 | } | |
| 3340 | ||
| 3341 | tag.stringValues.resize(static_cast<size_t>(ts.num_strings)); | |
| 3342 | for (size_t i = 0; i < static_cast<size_t>(ts.num_strings); ++i) { | |
| 3343 | std::stringstream ss; | |
| 3344 | ss << token; | |
| 3345 | tag.stringValues[i] = ss.str(); | |
| 3346 | token += tag.stringValues[i].size() + 1; | |
| 3347 | } | |
| 3348 | ||
| 3349 | tags.push_back(tag); | |
| 3350 | } | |
| 3351 | #endif | |
| 3352 | ||
| 3353 | // Ignore unknown command. | |
| 3354 | } | |
| 3355 | ||
| 3356 | ! | if (err) { |
| 3357 | ! | (*err) += errss.str(); |
| 3358 | } | |
| 3359 | ||
| 3360 | ! | return true; |
| 3361 | } | |
| 3362 | ||
| 3363 | 37x | bool ObjReader::ParseFromFile(const std::string &filename, |
| 3364 | const ObjReaderConfig &config) { | |
| 3365 | 37x | std::string mtl_search_path; |
| 3366 | ||
| 3367 | 37x | if (config.mtl_search_path.empty()) { |
| 3368 | // | |
| 3369 | // split at last '/'(for unixish system) or '\\'(for windows) to get | |
| 3370 | // the base directory of .obj file | |
| 3371 | // | |
| 3372 | ! | size_t pos = filename.find_last_of("/\\"); |
| 3373 | ! | if (pos != std::string::npos) { |
| 3374 | ! | mtl_search_path = filename.substr(0, pos); |
| 3375 | } | |
| 3376 | } else { | |
| 3377 | 37x | mtl_search_path = config.mtl_search_path; |
| 3378 | } | |
| 3379 | ||
| 3380 | 37x | valid_ = LoadObj(&attrib_, &shapes_, &materials_, &warning_, &error_, |
| 3381 | filename.c_str(), mtl_search_path.c_str(), | |
| 3382 | 37x | config.triangulate, config.vertex_color); |
| 3383 | ||
| 3384 | 37x | return valid_; |
| 3385 | } | |
| 3386 | ||
| 3387 | ! | bool ObjReader::ParseFromString(const std::string &obj_text, |
| 3388 | const std::string &mtl_text, | |
| 3389 | const ObjReaderConfig &config) { | |
| 3390 | ! | std::stringbuf obj_buf(obj_text); |
| 3391 | ! | std::stringbuf mtl_buf(mtl_text); |
| 3392 | ||
| 3393 | ! | std::istream obj_ifs(&obj_buf); |
| 3394 | ! | std::istream mtl_ifs(&mtl_buf); |
| 3395 | ||
| 3396 | ! | MaterialStreamReader mtl_ss(mtl_ifs); |
| 3397 | ||
| 3398 | ! | valid_ = LoadObj(&attrib_, &shapes_, &materials_, &warning_, &error_, |
| 3399 | ! | &obj_ifs, &mtl_ss, config.triangulate, config.vertex_color); |
| 3400 | ||
| 3401 | ! | return valid_; |
| 3402 | } | |
| 3403 | ||
| 3404 | } // namespace tinyobj | |
| 3405 | ||
| 3406 | #endif |
| 1 | #include <algorithm> | |
| 2 | #include <cassert> | |
| 3 | #include <cmath> | |
| 4 | #include <cstddef> | |
| 5 | #include <limits> | |
| 6 | #include <memory> | |
| 7 | #include <utility> | |
| 8 | #include <vector> | |
| 9 | ||
| 10 | namespace mapbox { | |
| 11 | ||
| 12 | namespace util { | |
| 13 | ||
| 14 | template <std::size_t I, typename T> struct nth { | |
| 15 | inline static typename std::tuple_element<I, T>::type | |
| 16 | 612x | get(const T& t) { return std::get<I>(t); }; |
| 17 | }; | |
| 18 | ||
| 19 | } | |
| 20 | ||
| 21 | namespace detail { | |
| 22 | ||
| 23 | template <typename N = uint32_t> | |
| 24 | class Earcut { | |
| 25 | public: | |
| 26 | std::vector<N> indices; | |
| 27 | std::size_t vertices = 0; | |
| 28 | ||
| 29 | template <typename Polygon> | |
| 30 | void operator()(const Polygon& points); | |
| 31 | ||
| 32 | private: | |
| 33 | struct Node { | |
| 34 | 102x | Node(N index, double x_, double y_) : i(index), x(x_), y(y_) {} |
| 35 | Node(const Node&) = delete; | |
| 36 | Node& operator=(const Node&) = delete; | |
| 37 | Node(Node&&) = delete; | |
| 38 | Node& operator=(Node&&) = delete; | |
| 39 | ||
| 40 | const N i; | |
| 41 | const double x; | |
| 42 | const double y; | |
| 43 | ||
| 44 | // previous and next vertice nodes in a polygon ring | |
| 45 | Node* prev = nullptr; | |
| 46 | Node* next = nullptr; | |
| 47 | ||
| 48 | // z-order curve value | |
| 49 | int32_t z = 0; | |
| 50 | ||
| 51 | // previous and next nodes in z-order | |
| 52 | Node* prevZ = nullptr; | |
| 53 | Node* nextZ = nullptr; | |
| 54 | ||
| 55 | // indicates whether this is a steiner point | |
| 56 | bool steiner = false; | |
| 57 | }; | |
| 58 | ||
| 59 | template <typename Ring> Node* linkedList(const Ring& points, const bool clockwise); | |
| 60 | Node* filterPoints(Node* start, Node* end = nullptr); | |
| 61 | void earcutLinked(Node* ear, int pass = 0); | |
| 62 | bool isEar(Node* ear); | |
| 63 | bool isEarHashed(Node* ear); | |
| 64 | Node* cureLocalIntersections(Node* start); | |
| 65 | void splitEarcut(Node* start); | |
| 66 | template <typename Polygon> Node* eliminateHoles(const Polygon& points, Node* outerNode); | |
| 67 | Node* eliminateHole(Node* hole, Node* outerNode); | |
| 68 | Node* findHoleBridge(Node* hole, Node* outerNode); | |
| 69 | bool sectorContainsSector(const Node* m, const Node* p); | |
| 70 | void indexCurve(Node* start); | |
| 71 | Node* sortLinked(Node* list); | |
| 72 | int32_t zOrder(const double x_, const double y_); | |
| 73 | Node* getLeftmost(Node* start); | |
| 74 | bool pointInTriangle(double ax, double ay, double bx, double by, double cx, double cy, double px, double py) const; | |
| 75 | bool isValidDiagonal(Node* a, Node* b); | |
| 76 | double area(const Node* p, const Node* q, const Node* r) const; | |
| 77 | bool equals(const Node* p1, const Node* p2); | |
| 78 | bool intersects(const Node* p1, const Node* q1, const Node* p2, const Node* q2); | |
| 79 | bool onSegment(const Node* p, const Node* q, const Node* r); | |
| 80 | int sign(double val); | |
| 81 | bool intersectsPolygon(const Node* a, const Node* b); | |
| 82 | bool locallyInside(const Node* a, const Node* b); | |
| 83 | bool middleInside(const Node* a, const Node* b); | |
| 84 | Node* splitPolygon(Node* a, Node* b); | |
| 85 | template <typename Point> Node* insertNode(std::size_t i, const Point& p, Node* last); | |
| 86 | void removeNode(Node* p); | |
| 87 | ||
| 88 | bool hashing; | |
| 89 | double minX, maxX; | |
| 90 | double minY, maxY; | |
| 91 | double inv_size = 0; | |
| 92 | ||
| 93 | template <typename T, typename Alloc = std::allocator<T>> | |
| 94 | class ObjectPool { | |
| 95 | public: | |
| 96 | 2x | ObjectPool() { } |
| 97 | ObjectPool(std::size_t blockSize_) { | |
| 98 | reset(blockSize_); | |
| 99 | } | |
| 100 | 2x | ~ObjectPool() { |
| 101 | 2x | clear(); |
| 102 | } | |
| 103 | template <typename... Args> | |
| 104 | 102x | T* construct(Args&&... args) { |
| 105 | 102x | if (currentIndex >= blockSize) { |
| 106 | 2x | currentBlock = alloc_traits::allocate(alloc, blockSize); |
| 107 | 2x | allocations.emplace_back(currentBlock); |
| 108 | 2x | currentIndex = 0; |
| 109 | } | |
| 110 | 102x | T* object = ¤tBlock[currentIndex++]; |
| 111 | 306x | alloc_traits::construct(alloc, object, std::forward<Args>(args)...); |
| 112 | 102x | return object; |
| 113 | } | |
| 114 | 6x | void reset(std::size_t newBlockSize) { |
| 115 | 14x | for (auto allocation : allocations) { |
| 116 | 2x | alloc_traits::deallocate(alloc, allocation, blockSize); |
| 117 | } | |
| 118 | 6x | allocations.clear(); |
| 119 | 6x | blockSize = std::max<std::size_t>(1, newBlockSize); |
| 120 | 6x | currentBlock = nullptr; |
| 121 | 6x | currentIndex = blockSize; |
| 122 | } | |
| 123 | 4x | void clear() { reset(blockSize); } |
| 124 | private: | |
| 125 | T* currentBlock = nullptr; | |
| 126 | std::size_t currentIndex = 1; | |
| 127 | std::size_t blockSize = 1; | |
| 128 | std::vector<T*> allocations; | |
| 129 | Alloc alloc; | |
| 130 | typedef typename std::allocator_traits<Alloc> alloc_traits; | |
| 131 | }; | |
| 132 | ObjectPool<Node> nodes; | |
| 133 | }; | |
| 134 | ||
| 135 | template <typename N> template <typename Polygon> | |
| 136 | 2x | void Earcut<N>::operator()(const Polygon& points) { |
| 137 | // reset | |
| 138 | 2x | indices.clear(); |
| 139 | 2x | vertices = 0; |
| 140 | ||
| 141 | 2x | if (points.empty()) return; |
| 142 | ||
| 143 | double x; | |
| 144 | double y; | |
| 145 | 2x | int threshold = 80; |
| 146 | 2x | std::size_t len = 0; |
| 147 | ||
| 148 | 4x | for (size_t i = 0; threshold >= 0 && i < points.size(); i++) { |
| 149 | 2x | threshold -= static_cast<int>(points[i].size()); |
| 150 | 2x | len += points[i].size(); |
| 151 | } | |
| 152 | ||
| 153 | //estimate size of nodes and indices | |
| 154 | 2x | nodes.reset(len * 3 / 2); |
| 155 | 2x | indices.reserve(len + points[0].size()); |
| 156 | ||
| 157 | 2x | Node* outerNode = linkedList(points[0], true); |
| 158 | 2x | if (!outerNode || outerNode->prev == outerNode->next) return; |
| 159 | ||
| 160 | 2x | if (points.size() > 1) outerNode = eliminateHoles(points, outerNode); |
| 161 | ||
| 162 | // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox | |
| 163 | 2x | hashing = threshold < 0; |
| 164 | 2x | if (hashing) { |
| 165 | ! | Node* p = outerNode->next; |
| 166 | ! | minX = maxX = outerNode->x; |
| 167 | ! | minY = maxY = outerNode->y; |
| 168 | do { | |
| 169 | ! | x = p->x; |
| 170 | ! | y = p->y; |
| 171 | ! | minX = std::min<double>(minX, x); |
| 172 | ! | minY = std::min<double>(minY, y); |
| 173 | ! | maxX = std::max<double>(maxX, x); |
| 174 | ! | maxY = std::max<double>(maxY, y); |
| 175 | ! | p = p->next; |
| 176 | ! | } while (p != outerNode); |
| 177 | ||
| 178 | // minX, minY and inv_size are later used to transform coords into integers for z-order calculation | |
| 179 | ! | inv_size = std::max<double>(maxX - minX, maxY - minY); |
| 180 | ! | inv_size = inv_size != .0 ? (32767. / inv_size) : .0; |
| 181 | } | |
| 182 | ||
| 183 | 2x | earcutLinked(outerNode); |
| 184 | ||
| 185 | 2x | nodes.clear(); |
| 186 | } | |
| 187 | ||
| 188 | // create a circular doubly linked list from polygon points in the specified winding order | |
| 189 | template <typename N> template <typename Ring> | |
| 190 | typename Earcut<N>::Node* | |
| 191 | 2x | Earcut<N>::linkedList(const Ring& points, const bool clockwise) { |
| 192 | using Point = typename Ring::value_type; | |
| 193 | 2x | double sum = 0; |
| 194 | 2x | const std::size_t len = points.size(); |
| 195 | std::size_t i, j; | |
| 196 | 2x | Node* last = nullptr; |
| 197 | ||
| 198 | // calculate original winding order of a polygon ring | |
| 199 | 104x | for (i = 0, j = len > 0 ? len - 1 : 0; i < len; j = i++) { |
| 200 | 102x | const auto& p1 = points[i]; |
| 201 | 102x | const auto& p2 = points[j]; |
| 202 | 102x | const double p20 = util::nth<0, Point>::get(p2); |
| 203 | 102x | const double p10 = util::nth<0, Point>::get(p1); |
| 204 | 102x | const double p11 = util::nth<1, Point>::get(p1); |
| 205 | 102x | const double p21 = util::nth<1, Point>::get(p2); |
| 206 | 102x | sum += (p20 - p10) * (p11 + p21); |
| 207 | } | |
| 208 | ||
| 209 | // link points into circular doubly-linked list in the specified winding order | |
| 210 | 2x | if (clockwise == (sum > 0)) { |
| 211 | 104x | for (i = 0; i < len; i++) last = insertNode(vertices + i, points[i], last); |
| 212 | } else { | |
| 213 | ! | for (i = len; i-- > 0;) last = insertNode(vertices + i, points[i], last); |
| 214 | } | |
| 215 | ||
| 216 | 2x | if (last && equals(last, last->next)) { |
| 217 | ! | removeNode(last); |
| 218 | ! | last = last->next; |
| 219 | } | |
| 220 | ||
| 221 | 2x | vertices += len; |
| 222 | ||
| 223 | 2x | return last; |
| 224 | } | |
| 225 | ||
| 226 | // eliminate colinear or duplicate points | |
| 227 | template <typename N> | |
| 228 | typename Earcut<N>::Node* | |
| 229 | 2x | Earcut<N>::filterPoints(Node* start, Node* end) { |
| 230 | 2x | if (!end) end = start; |
| 231 | ||
| 232 | 2x | Node* p = start; |
| 233 | bool again; | |
| 234 | do { | |
| 235 | 16x | again = false; |
| 236 | ||
| 237 | 16x | if (!p->steiner && (equals(p, p->next) || area(p->prev, p, p->next) == 0)) { |
| 238 | 4x | removeNode(p); |
| 239 | 4x | p = end = p->prev; |
| 240 | ||
| 241 | 4x | if (p == p->next) break; |
| 242 | 4x | again = true; |
| 243 | ||
| 244 | } else { | |
| 245 | 12x | p = p->next; |
| 246 | } | |
| 247 | 16x | } while (again || p != end); |
| 248 | ||
| 249 | 2x | return end; |
| 250 | } | |
| 251 | ||
| 252 | // main ear slicing loop which triangulates a polygon (given as a linked list) | |
| 253 | template <typename N> | |
| 254 | 4x | void Earcut<N>::earcutLinked(Node* ear, int pass) { |
| 255 | 4x | if (!ear) return; |
| 256 | ||
| 257 | // interlink polygon nodes in z-order | |
| 258 | 4x | if (!pass && hashing) indexCurve(ear); |
| 259 | ||
| 260 | 4x | Node* stop = ear; |
| 261 | Node* prev; | |
| 262 | Node* next; | |
| 263 | ||
| 264 | // iterate through ears, slicing them one by one | |
| 265 | 174x | while (ear->prev != ear->next) { |
| 266 | 172x | prev = ear->prev; |
| 267 | 172x | next = ear->next; |
| 268 | ||
| 269 | 172x | if (hashing ? isEarHashed(ear) : isEar(ear)) { |
| 270 | // cut off the triangle | |
| 271 | 94x | indices.emplace_back(prev->i); |
| 272 | 94x | indices.emplace_back(ear->i); |
| 273 | 94x | indices.emplace_back(next->i); |
| 274 | ||
| 275 | 94x | removeNode(ear); |
| 276 | ||
| 277 | // skipping the next vertice leads to less sliver triangles | |
| 278 | 94x | ear = next->next; |
| 279 | 94x | stop = next->next; |
| 280 | ||
| 281 | 94x | continue; |
| 282 | } | |
| 283 | ||
| 284 | 78x | ear = next; |
| 285 | ||
| 286 | // if we looped through the whole remaining polygon and can't find any more ears | |
| 287 | 78x | if (ear == stop) { |
| 288 | // try filtering points and slicing again | |
| 289 | 2x | if (!pass) earcutLinked(filterPoints(ear), 1); |
| 290 | ||
| 291 | // if this didn't work, try curing all small self-intersections locally | |
| 292 | ! | else if (pass == 1) { |
| 293 | ! | ear = cureLocalIntersections(filterPoints(ear)); |
| 294 | ! | earcutLinked(ear, 2); |
| 295 | ||
| 296 | // as a last resort, try splitting the remaining polygon into two | |
| 297 | ! | } else if (pass == 2) splitEarcut(ear); |
| 298 | ||
| 299 | 2x | break; |
| 300 | } | |
| 301 | } | |
| 302 | } | |
| 303 | ||
| 304 | // check whether a polygon node forms a valid ear with adjacent nodes | |
| 305 | template <typename N> | |
| 306 | 172x | bool Earcut<N>::isEar(Node* ear) { |
| 307 | 172x | const Node* a = ear->prev; |
| 308 | 172x | const Node* b = ear; |
| 309 | 172x | const Node* c = ear->next; |
| 310 | ||
| 311 | 172x | if (area(a, b, c) >= 0) return false; // reflex, can't be an ear |
| 312 | ||
| 313 | // now make sure we don't have other points inside the potential ear | |
| 314 | 114x | Node* p = ear->next->next; |
| 315 | ||
| 316 | 2612x | while (p != ear->prev) { |
| 317 | 2538x | if (pointInTriangle(a->x, a->y, b->x, b->y, c->x, c->y, p->x, p->y) && |
| 318 | 40x | area(p->prev, p, p->next) >= 0) return false; |
| 319 | 2498x | p = p->next; |
| 320 | } | |
| 321 | ||
| 322 | 94x | return true; |
| 323 | } | |
| 324 | ||
| 325 | template <typename N> | |
| 326 | ! | bool Earcut<N>::isEarHashed(Node* ear) { |
| 327 | ! | const Node* a = ear->prev; |
| 328 | ! | const Node* b = ear; |
| 329 | ! | const Node* c = ear->next; |
| 330 | ||
| 331 | ! | if (area(a, b, c) >= 0) return false; // reflex, can't be an ear |
| 332 | ||
| 333 | // triangle bbox; min & max are calculated like this for speed | |
| 334 | ! | const double minTX = std::min<double>(a->x, std::min<double>(b->x, c->x)); |
| 335 | ! | const double minTY = std::min<double>(a->y, std::min<double>(b->y, c->y)); |
| 336 | ! | const double maxTX = std::max<double>(a->x, std::max<double>(b->x, c->x)); |
| 337 | ! | const double maxTY = std::max<double>(a->y, std::max<double>(b->y, c->y)); |
| 338 | ||
| 339 | // z-order range for the current triangle bbox; | |
| 340 | ! | const int32_t minZ = zOrder(minTX, minTY); |
| 341 | ! | const int32_t maxZ = zOrder(maxTX, maxTY); |
| 342 | ||
| 343 | // first look for points inside the triangle in increasing z-order | |
| 344 | ! | Node* p = ear->nextZ; |
| 345 | ||
| 346 | ! | while (p && p->z <= maxZ) { |
| 347 | ! | if (p != ear->prev && p != ear->next && |
| 348 | ! | pointInTriangle(a->x, a->y, b->x, b->y, c->x, c->y, p->x, p->y) && |
| 349 | ! | area(p->prev, p, p->next) >= 0) return false; |
| 350 | ! | p = p->nextZ; |
| 351 | } | |
| 352 | ||
| 353 | // then look for points in decreasing z-order | |
| 354 | ! | p = ear->prevZ; |
| 355 | ||
| 356 | ! | while (p && p->z >= minZ) { |
| 357 | ! | if (p != ear->prev && p != ear->next && |
| 358 | ! | pointInTriangle(a->x, a->y, b->x, b->y, c->x, c->y, p->x, p->y) && |
| 359 | ! | area(p->prev, p, p->next) >= 0) return false; |
| 360 | ! | p = p->prevZ; |
| 361 | } | |
| 362 | ||
| 363 | ! | return true; |
| 364 | } | |
| 365 | ||
| 366 | // go through all polygon nodes and cure small local self-intersections | |
| 367 | template <typename N> | |
| 368 | typename Earcut<N>::Node* | |
| 369 | ! | Earcut<N>::cureLocalIntersections(Node* start) { |
| 370 | ! | Node* p = start; |
| 371 | do { | |
| 372 | ! | Node* a = p->prev; |
| 373 | ! | Node* b = p->next->next; |
| 374 | ||
| 375 | // a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2]) | |
| 376 | ! | if (!equals(a, b) && intersects(a, p, p->next, b) && locallyInside(a, b) && locallyInside(b, a)) { |
| 377 | ! | indices.emplace_back(a->i); |
| 378 | ! | indices.emplace_back(p->i); |
| 379 | ! | indices.emplace_back(b->i); |
| 380 | ||
| 381 | // remove two nodes involved | |
| 382 | ! | removeNode(p); |
| 383 | ! | removeNode(p->next); |
| 384 | ||
| 385 | ! | p = start = b; |
| 386 | } | |
| 387 | ! | p = p->next; |
| 388 | ! | } while (p != start); |
| 389 | ||
| 390 | ! | return filterPoints(p); |
| 391 | } | |
| 392 | ||
| 393 | // try splitting polygon into two and triangulate them independently | |
| 394 | template <typename N> | |
| 395 | ! | void Earcut<N>::splitEarcut(Node* start) { |
| 396 | // look for a valid diagonal that divides the polygon into two | |
| 397 | ! | Node* a = start; |
| 398 | do { | |
| 399 | ! | Node* b = a->next->next; |
| 400 | ! | while (b != a->prev) { |
| 401 | ! | if (a->i != b->i && isValidDiagonal(a, b)) { |
| 402 | // split the polygon in two by the diagonal | |
| 403 | ! | Node* c = splitPolygon(a, b); |
| 404 | ||
| 405 | // filter colinear points around the cuts | |
| 406 | ! | a = filterPoints(a, a->next); |
| 407 | ! | c = filterPoints(c, c->next); |
| 408 | ||
| 409 | // run earcut on each half | |
| 410 | ! | earcutLinked(a); |
| 411 | ! | earcutLinked(c); |
| 412 | ! | return; |
| 413 | } | |
| 414 | ! | b = b->next; |
| 415 | } | |
| 416 | ! | a = a->next; |
| 417 | ! | } while (a != start); |
| 418 | } | |
| 419 | ||
| 420 | // link every hole into the outer loop, producing a single-ring polygon without holes | |
| 421 | template <typename N> template <typename Polygon> | |
| 422 | typename Earcut<N>::Node* | |
| 423 | ! | Earcut<N>::eliminateHoles(const Polygon& points, Node* outerNode) { |
| 424 | ! | const size_t len = points.size(); |
| 425 | ||
| 426 | ! | std::vector<Node*> queue; |
| 427 | ! | for (size_t i = 1; i < len; i++) { |
| 428 | ! | Node* list = linkedList(points[i], false); |
| 429 | ! | if (list) { |
| 430 | ! | if (list == list->next) list->steiner = true; |
| 431 | ! | queue.push_back(getLeftmost(list)); |
| 432 | } | |
| 433 | } | |
| 434 | ! | std::sort(queue.begin(), queue.end(), [](const Node* a, const Node* b) { |
| 435 | ! | return a->x < b->x; |
| 436 | }); | |
| 437 | ||
| 438 | // process holes from left to right | |
| 439 | ! | for (size_t i = 0; i < queue.size(); i++) { |
| 440 | ! | outerNode = eliminateHole(queue[i], outerNode); |
| 441 | } | |
| 442 | ||
| 443 | ! | return outerNode; |
| 444 | } | |
| 445 | ||
| 446 | // find a bridge between vertices that connects hole with an outer ring and and link it | |
| 447 | template <typename N> | |
| 448 | typename Earcut<N>::Node* | |
| 449 | ! | Earcut<N>::eliminateHole(Node* hole, Node* outerNode) { |
| 450 | ! | Node* bridge = findHoleBridge(hole, outerNode); |
| 451 | ! | if (!bridge) { |
| 452 | ! | return outerNode; |
| 453 | } | |
| 454 | ||
| 455 | ! | Node* bridgeReverse = splitPolygon(bridge, hole); |
| 456 | ||
| 457 | // filter collinear points around the cuts | |
| 458 | ! | filterPoints(bridgeReverse, bridgeReverse->next); |
| 459 | ||
| 460 | // Check if input node was removed by the filtering | |
| 461 | ! | return filterPoints(bridge, bridge->next); |
| 462 | } | |
| 463 | ||
| 464 | // David Eberly's algorithm for finding a bridge between hole and outer polygon | |
| 465 | template <typename N> | |
| 466 | typename Earcut<N>::Node* | |
| 467 | ! | Earcut<N>::findHoleBridge(Node* hole, Node* outerNode) { |
| 468 | ! | Node* p = outerNode; |
| 469 | ! | double hx = hole->x; |
| 470 | ! | double hy = hole->y; |
| 471 | ! | double qx = -std::numeric_limits<double>::infinity(); |
| 472 | ! | Node* m = nullptr; |
| 473 | ||
| 474 | // find a segment intersected by a ray from the hole's leftmost Vertex to the left; | |
| 475 | // segment's endpoint with lesser x will be potential connection Vertex | |
| 476 | do { | |
| 477 | ! | if (hy <= p->y && hy >= p->next->y && p->next->y != p->y) { |
| 478 | ! | double x = p->x + (hy - p->y) * (p->next->x - p->x) / (p->next->y - p->y); |
| 479 | ! | if (x <= hx && x > qx) { |
| 480 | ! | qx = x; |
| 481 | ! | m = p->x < p->next->x ? p : p->next; |
| 482 | ! | if (x == hx) return m; // hole touches outer segment; pick leftmost endpoint |
| 483 | } | |
| 484 | } | |
| 485 | ! | p = p->next; |
| 486 | ! | } while (p != outerNode); |
| 487 | ||
| 488 | ! | if (!m) return 0; |
| 489 | ||
| 490 | // look for points inside the triangle of hole Vertex, segment intersection and endpoint; | |
| 491 | // if there are no points found, we have a valid connection; | |
| 492 | // otherwise choose the Vertex of the minimum angle with the ray as connection Vertex | |
| 493 | ||
| 494 | ! | const Node* stop = m; |
| 495 | ! | double tanMin = std::numeric_limits<double>::infinity(); |
| 496 | ! | double tanCur = 0; |
| 497 | ||
| 498 | ! | p = m; |
| 499 | ! | double mx = m->x; |
| 500 | ! | double my = m->y; |
| 501 | ||
| 502 | do { | |
| 503 | ! | if (hx >= p->x && p->x >= mx && hx != p->x && |
| 504 | ! | pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p->x, p->y)) { |
| 505 | ||
| 506 | ! | tanCur = std::abs(hy - p->y) / (hx - p->x); // tangential |
| 507 | ||
| 508 | ! | if (locallyInside(p, hole) && |
| 509 | ! | (tanCur < tanMin || (tanCur == tanMin && (p->x > m->x || sectorContainsSector(m, p))))) { |
| 510 | ! | m = p; |
| 511 | ! | tanMin = tanCur; |
| 512 | } | |
| 513 | } | |
| 514 | ||
| 515 | ! | p = p->next; |
| 516 | ! | } while (p != stop); |
| 517 | ||
| 518 | ! | return m; |
| 519 | } | |
| 520 | ||
| 521 | // whether sector in vertex m contains sector in vertex p in the same coordinates | |
| 522 | template <typename N> | |
| 523 | ! | bool Earcut<N>::sectorContainsSector(const Node* m, const Node* p) { |
| 524 | ! | return area(m->prev, m, p->prev) < 0 && area(p->next, m, m->next) < 0; |
| 525 | } | |
| 526 | ||
| 527 | // interlink polygon nodes in z-order | |
| 528 | template <typename N> | |
| 529 | ! | void Earcut<N>::indexCurve(Node* start) { |
| 530 | assert(start); | |
| 531 | ! | Node* p = start; |
| 532 | ||
| 533 | do { | |
| 534 | ! | p->z = p->z ? p->z : zOrder(p->x, p->y); |
| 535 | ! | p->prevZ = p->prev; |
| 536 | ! | p->nextZ = p->next; |
| 537 | ! | p = p->next; |
| 538 | ! | } while (p != start); |
| 539 | ||
| 540 | ! | p->prevZ->nextZ = nullptr; |
| 541 | ! | p->prevZ = nullptr; |
| 542 | ||
| 543 | ! | sortLinked(p); |
| 544 | } | |
| 545 | ||
| 546 | // Simon Tatham's linked list merge sort algorithm | |
| 547 | // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html | |
| 548 | template <typename N> | |
| 549 | typename Earcut<N>::Node* | |
| 550 | ! | Earcut<N>::sortLinked(Node* list) { |
| 551 | assert(list); | |
| 552 | Node* p; | |
| 553 | Node* q; | |
| 554 | Node* e; | |
| 555 | Node* tail; | |
| 556 | int i, numMerges, pSize, qSize; | |
| 557 | ! | int inSize = 1; |
| 558 | ||
| 559 | for (;;) { | |
| 560 | ! | p = list; |
| 561 | ! | list = nullptr; |
| 562 | ! | tail = nullptr; |
| 563 | ! | numMerges = 0; |
| 564 | ||
| 565 | ! | while (p) { |
| 566 | ! | numMerges++; |
| 567 | ! | q = p; |
| 568 | ! | pSize = 0; |
| 569 | ! | for (i = 0; i < inSize; i++) { |
| 570 | ! | pSize++; |
| 571 | ! | q = q->nextZ; |
| 572 | ! | if (!q) break; |
| 573 | } | |
| 574 | ||
| 575 | ! | qSize = inSize; |
| 576 | ||
| 577 | ! | while (pSize > 0 || (qSize > 0 && q)) { |
| 578 | ||
| 579 | ! | if (pSize == 0) { |
| 580 | ! | e = q; |
| 581 | ! | q = q->nextZ; |
| 582 | ! | qSize--; |
| 583 | ! | } else if (qSize == 0 || !q) { |
| 584 | ! | e = p; |
| 585 | ! | p = p->nextZ; |
| 586 | ! | pSize--; |
| 587 | ! | } else if (p->z <= q->z) { |
| 588 | ! | e = p; |
| 589 | ! | p = p->nextZ; |
| 590 | ! | pSize--; |
| 591 | } else { | |
| 592 | ! | e = q; |
| 593 | ! | q = q->nextZ; |
| 594 | ! | qSize--; |
| 595 | } | |
| 596 | ||
| 597 | ! | if (tail) tail->nextZ = e; |
| 598 | ! | else list = e; |
| 599 | ||
| 600 | ! | e->prevZ = tail; |
| 601 | ! | tail = e; |
| 602 | } | |
| 603 | ||
| 604 | ! | p = q; |
| 605 | } | |
| 606 | ||
| 607 | ! | tail->nextZ = nullptr; |
| 608 | ||
| 609 | ! | if (numMerges <= 1) return list; |
| 610 | ||
| 611 | ! | inSize *= 2; |
| 612 | } | |
| 613 | } | |
| 614 | ||
| 615 | // z-order of a Vertex given coords and size of the data bounding box | |
| 616 | template <typename N> | |
| 617 | ! | int32_t Earcut<N>::zOrder(const double x_, const double y_) { |
| 618 | // coords are transformed into non-negative 15-bit integer range | |
| 619 | ! | int32_t x = static_cast<int32_t>((x_ - minX) * inv_size); |
| 620 | ! | int32_t y = static_cast<int32_t>((y_ - minY) * inv_size); |
| 621 | ||
| 622 | ! | x = (x | (x << 8)) & 0x00FF00FF; |
| 623 | ! | x = (x | (x << 4)) & 0x0F0F0F0F; |
| 624 | ! | x = (x | (x << 2)) & 0x33333333; |
| 625 | ! | x = (x | (x << 1)) & 0x55555555; |
| 626 | ||
| 627 | ! | y = (y | (y << 8)) & 0x00FF00FF; |
| 628 | ! | y = (y | (y << 4)) & 0x0F0F0F0F; |
| 629 | ! | y = (y | (y << 2)) & 0x33333333; |
| 630 | ! | y = (y | (y << 1)) & 0x55555555; |
| 631 | ||
| 632 | ! | return x | (y << 1); |
| 633 | } | |
| 634 | ||
| 635 | // find the leftmost node of a polygon ring | |
| 636 | template <typename N> | |
| 637 | typename Earcut<N>::Node* | |
| 638 | ! | Earcut<N>::getLeftmost(Node* start) { |
| 639 | ! | Node* p = start; |
| 640 | ! | Node* leftmost = start; |
| 641 | do { | |
| 642 | ! | if (p->x < leftmost->x || (p->x == leftmost->x && p->y < leftmost->y)) |
| 643 | ! | leftmost = p; |
| 644 | ! | p = p->next; |
| 645 | ! | } while (p != start); |
| 646 | ||
| 647 | ! | return leftmost; |
| 648 | } | |
| 649 | ||
| 650 | // check if a point lies within a convex triangle | |
| 651 | template <typename N> | |
| 652 | 2518x | bool Earcut<N>::pointInTriangle(double ax, double ay, double bx, double by, double cx, double cy, double px, double py) const { |
| 653 | 2544x | return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && |
| 654 | 2538x | (ax - px) * (by - py) >= (bx - px) * (ay - py) && |
| 655 | 2538x | (bx - px) * (cy - py) >= (cx - px) * (by - py); |
| 656 | } | |
| 657 | ||
| 658 | // check if a diagonal between two polygon nodes is valid (lies in polygon interior) | |
| 659 | template <typename N> | |
| 660 | ! | bool Earcut<N>::isValidDiagonal(Node* a, Node* b) { |
| 661 | ! | return a->next->i != b->i && a->prev->i != b->i && !intersectsPolygon(a, b) && // dones't intersect other edges |
| 662 | ! | ((locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible |
| 663 | ! | (area(a->prev, a, b->prev) != 0.0 || area(a, b->prev, b) != 0.0)) || // does not create opposite-facing sectors |
| 664 | ! | (equals(a, b) && area(a->prev, a, a->next) > 0 && area(b->prev, b, b->next) > 0)); // special zero-length case |
| 665 | } | |
| 666 | ||
| 667 | // signed area of a triangle | |
| 668 | template <typename N> | |
| 669 | 204x | double Earcut<N>::area(const Node* p, const Node* q, const Node* r) const { |
| 670 | 204x | return (q->y - p->y) * (r->x - q->x) - (q->x - p->x) * (r->y - q->y); |
| 671 | } | |
| 672 | ||
| 673 | // check if two points are equal | |
| 674 | template <typename N> | |
| 675 | 18x | bool Earcut<N>::equals(const Node* p1, const Node* p2) { |
| 676 | 18x | return p1->x == p2->x && p1->y == p2->y; |
| 677 | } | |
| 678 | ||
| 679 | // check if two segments intersect | |
| 680 | template <typename N> | |
| 681 | ! | bool Earcut<N>::intersects(const Node* p1, const Node* q1, const Node* p2, const Node* q2) { |
| 682 | ! | int o1 = sign(area(p1, q1, p2)); |
| 683 | ! | int o2 = sign(area(p1, q1, q2)); |
| 684 | ! | int o3 = sign(area(p2, q2, p1)); |
| 685 | ! | int o4 = sign(area(p2, q2, q1)); |
| 686 | ||
| 687 | ! | if (o1 != o2 && o3 != o4) return true; // general case |
| 688 | ||
| 689 | ! | if (o1 == 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1 |
| 690 | ! | if (o2 == 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1 |
| 691 | ! | if (o3 == 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2 |
| 692 | ! | if (o4 == 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2 |
| 693 | ||
| 694 | ! | return false; |
| 695 | } | |
| 696 | ||
| 697 | // for collinear points p, q, r, check if point q lies on segment pr | |
| 698 | template <typename N> | |
| 699 | ! | bool Earcut<N>::onSegment(const Node* p, const Node* q, const Node* r) { |
| 700 | ! | return q->x <= std::max<double>(p->x, r->x) && |
| 701 | ! | q->x >= std::min<double>(p->x, r->x) && |
| 702 | ! | q->y <= std::max<double>(p->y, r->y) && |
| 703 | ! | q->y >= std::min<double>(p->y, r->y); |
| 704 | } | |
| 705 | ||
| 706 | template <typename N> | |
| 707 | ! | int Earcut<N>::sign(double val) { |
| 708 | ! | return (0.0 < val) - (val < 0.0); |
| 709 | } | |
| 710 | ||
| 711 | // check if a polygon diagonal intersects any polygon segments | |
| 712 | template <typename N> | |
| 713 | ! | bool Earcut<N>::intersectsPolygon(const Node* a, const Node* b) { |
| 714 | ! | const Node* p = a; |
| 715 | do { | |
| 716 | ! | if (p->i != a->i && p->next->i != a->i && p->i != b->i && p->next->i != b->i && |
| 717 | ! | intersects(p, p->next, a, b)) return true; |
| 718 | ! | p = p->next; |
| 719 | ! | } while (p != a); |
| 720 | ||
| 721 | ! | return false; |
| 722 | } | |
| 723 | ||
| 724 | // check if a polygon diagonal is locally inside the polygon | |
| 725 | template <typename N> | |
| 726 | ! | bool Earcut<N>::locallyInside(const Node* a, const Node* b) { |
| 727 | ! | return area(a->prev, a, a->next) < 0 ? |
| 728 | ! | area(a, b, a->next) >= 0 && area(a, a->prev, b) >= 0 : |
| 729 | ! | area(a, b, a->prev) < 0 || area(a, a->next, b) < 0; |
| 730 | } | |
| 731 | ||
| 732 | // check if the middle Vertex of a polygon diagonal is inside the polygon | |
| 733 | template <typename N> | |
| 734 | ! | bool Earcut<N>::middleInside(const Node* a, const Node* b) { |
| 735 | ! | const Node* p = a; |
| 736 | ! | bool inside = false; |
| 737 | ! | double px = (a->x + b->x) / 2; |
| 738 | ! | double py = (a->y + b->y) / 2; |
| 739 | do { | |
| 740 | ! | if (((p->y > py) != (p->next->y > py)) && p->next->y != p->y && |
| 741 | ! | (px < (p->next->x - p->x) * (py - p->y) / (p->next->y - p->y) + p->x)) |
| 742 | ! | inside = !inside; |
| 743 | ! | p = p->next; |
| 744 | ! | } while (p != a); |
| 745 | ||
| 746 | ! | return inside; |
| 747 | } | |
| 748 | ||
| 749 | // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits | |
| 750 | // polygon into two; if one belongs to the outer ring and another to a hole, it merges it into a | |
| 751 | // single ring | |
| 752 | template <typename N> | |
| 753 | typename Earcut<N>::Node* | |
| 754 | ! | Earcut<N>::splitPolygon(Node* a, Node* b) { |
| 755 | ! | Node* a2 = nodes.construct(a->i, a->x, a->y); |
| 756 | ! | Node* b2 = nodes.construct(b->i, b->x, b->y); |
| 757 | ! | Node* an = a->next; |
| 758 | ! | Node* bp = b->prev; |
| 759 | ||
| 760 | ! | a->next = b; |
| 761 | ! | b->prev = a; |
| 762 | ||
| 763 | ! | a2->next = an; |
| 764 | ! | an->prev = a2; |
| 765 | ||
| 766 | ! | b2->next = a2; |
| 767 | ! | a2->prev = b2; |
| 768 | ||
| 769 | ! | bp->next = b2; |
| 770 | ! | b2->prev = bp; |
| 771 | ||
| 772 | ! | return b2; |
| 773 | } | |
| 774 | ||
| 775 | // create a node and util::optionally link it with previous one (in a circular doubly linked list) | |
| 776 | template <typename N> template <typename Point> | |
| 777 | typename Earcut<N>::Node* | |
| 778 | 102x | Earcut<N>::insertNode(std::size_t i, const Point& pt, Node* last) { |
| 779 | 102x | Node* p = nodes.construct(static_cast<N>(i), util::nth<0, Point>::get(pt), util::nth<1, Point>::get(pt)); |
| 780 | ||
| 781 | 102x | if (!last) { |
| 782 | 2x | p->prev = p; |
| 783 | 2x | p->next = p; |
| 784 | ||
| 785 | } else { | |
| 786 | assert(last); | |
| 787 | 100x | p->next = last->next; |
| 788 | 100x | p->prev = last; |
| 789 | 100x | last->next->prev = p; |
| 790 | 100x | last->next = p; |
| 791 | } | |
| 792 | 102x | return p; |
| 793 | } | |
| 794 | ||
| 795 | template <typename N> | |
| 796 | 98x | void Earcut<N>::removeNode(Node* p) { |
| 797 | 98x | p->next->prev = p->prev; |
| 798 | 98x | p->prev->next = p->next; |
| 799 | ||
| 800 | 98x | if (p->prevZ) p->prevZ->nextZ = p->nextZ; |
| 801 | 98x | if (p->nextZ) p->nextZ->prevZ = p->prevZ; |
| 802 | } | |
| 803 | } | |
| 804 | ||
| 805 | template <typename N = uint32_t, typename Polygon> | |
| 806 | 2x | std::vector<N> earcut(const Polygon& poly) { |
| 807 | 2x | mapbox::detail::Earcut<N> earcut; |
| 808 | 2x | earcut(poly); |
| 809 | 4x | return std::move(earcut.indices); |
| 810 | } | |
| 811 | } |
| 1 | #define TINYPLY_IMPLEMENTATION | |
| 2 | ||
| 3 | #include "Rcpp.h" | |
| 4 | #include "miniply.h" | |
| 5 | ||
| 6 | using namespace Rcpp; | |
| 7 | ||
| 8 | inline char separator_ply() { | |
| 9 | #if defined _WIN32 || defined __CYGWIN__ | |
| 10 | return '\\'; | |
| 11 | #else | |
| 12 | return '/'; | |
| 13 | #endif | |
| 14 | } | |
| 15 | ||
| 16 | template <typename T> | |
| 17 | ! | inline void set_item_impl( List& target, int i, const T& obj, CharacterVector& names, traits::true_type ){ |
| 18 | ! | target[i] = obj.object ; |
| 19 | ! | names[i] = obj.name ; |
| 20 | } | |
| 21 | ||
| 22 | template <typename T> | |
| 23 | inline void set_item_impl( List& target, int i, const T& obj, CharacterVector&, traits::false_type ){ | |
| 24 | target[i] = obj ; | |
| 25 | } | |
| 26 | ||
| 27 | template <typename T> | |
| 28 | ! | inline void set_item( List& target, int i, const T& obj, CharacterVector& names){ |
| 29 | ! | set_item_impl( target, i, obj, names, typename traits::is_named<T>::type() ) ; |
| 30 | } | |
| 31 | ||
| 32 | ||
| 33 | enum class Topology { | |
| 34 | Soup, // Every 3 indices specify a triangle. | |
| 35 | Strip, // Triangle strip, triangle i uses indices i, i-1 and i-2 | |
| 36 | Fan, // Triangle fan, triangle i uses indices, i, i-1 and 0. | |
| 37 | }; | |
| 38 | ||
| 39 | ||
| 40 | struct TriMesh { | |
| 41 | // Per-vertex data | |
| 42 | float* pos = nullptr; // has 3*numVerts elements. | |
| 43 | float* normal = nullptr; // if non-null, has 3 * numVerts elements. | |
| 44 | float* uv = nullptr; // if non-null, has 2 * numVerts elements. | |
| 45 | uint32_t numVerts = 0; | |
| 46 | ||
| 47 | // Per-index data | |
| 48 | int* indices = nullptr; // has numIndices elements. | |
| 49 | uint32_t numIndices = 0; // number of indices = 3 times the number of faces. | |
| 50 | ||
| 51 | Topology topology = Topology::Soup; // How to interpret the indices. | |
| 52 | bool hasTerminator = false; // Only applies when topology != Soup. | |
| 53 | int terminator = -1; // Value indicating the end of a strip or fan. Only applies when topology != Soup. | |
| 54 | ||
| 55 | ! | ~TriMesh() { |
| 56 | ! | delete[] pos; |
| 57 | ! | delete[] normal; |
| 58 | ! | delete[] uv; |
| 59 | ! | delete[] indices; |
| 60 | } | |
| 61 | ||
| 62 | bool all_indices_valid() const { | |
| 63 | bool checkTerminator = topology != Topology::Soup && hasTerminator && (terminator < 0 || terminator >= int(numVerts)); | |
| 64 | for (uint32_t i = 0; i < numIndices; i++) { | |
| 65 | if (checkTerminator && indices[i] == terminator) { | |
| 66 | continue; | |
| 67 | } | |
| 68 | if (indices[i] < 0 || uint32_t(indices[i]) >= numVerts) { | |
| 69 | return false; | |
| 70 | } | |
| 71 | } | |
| 72 | return true; | |
| 73 | } | |
| 74 | }; | |
| 75 | ||
| 76 | ||
| 77 | ! | static TriMesh* parse_file_with_miniply(const char* filename, bool assumeTriangles) { |
| 78 | ! | miniply::PLYReader reader(filename); |
| 79 | ! | if (!reader.valid()) { |
| 80 | ! | Rcpp::Rcout << "Not valid reader \n"; |
| 81 | ! | return nullptr; |
| 82 | } | |
| 83 | ||
| 84 | uint32_t indexes[3]; | |
| 85 | ! | bool gotVerts = false, gotFaces = false; |
| 86 | ||
| 87 | ! | TriMesh* trimesh = new TriMesh(); |
| 88 | ! | while (reader.has_element() && (!gotVerts || !gotFaces)) { |
| 89 | ! | if (reader.element_is(miniply::kPLYVertexElement) && reader.load_element() && reader.find_pos(indexes)) { |
| 90 | ! | trimesh->numVerts = reader.num_rows(); |
| 91 | ! | trimesh->pos = new float[trimesh->numVerts * 3]; |
| 92 | ! | reader.extract_properties(indexes, 3, miniply::PLYPropertyType::Float, trimesh->pos); |
| 93 | ! | if (reader.find_texcoord(indexes)) { |
| 94 | ! | trimesh->uv = new float[trimesh->numVerts * 2]; |
| 95 | ! | reader.extract_properties(indexes, 2, miniply::PLYPropertyType::Float, trimesh->uv); |
| 96 | } | |
| 97 | ! | gotVerts = true; |
| 98 | ! | } else if (reader.element_is(miniply::kPLYFaceElement) && reader.load_element() && reader.find_indices(indexes)) { |
| 99 | ! | uint32_t propIdx = 1; |
| 100 | ! | bool polys = reader.requires_triangulation(propIdx); |
| 101 | ! | if (polys && !gotVerts) { |
| 102 | ! | Rcpp::Rcout << "Error: need vertex positions to triangulate faces.\n"; |
| 103 | ! | break; |
| 104 | } | |
| 105 | ! | if (polys) { |
| 106 | ! | trimesh->numIndices = reader.num_triangles(indexes[0]) * 3; |
| 107 | ! | trimesh->indices = new int[trimesh->numIndices]; |
| 108 | ! | reader.extract_triangles(indexes[0], trimesh->pos, trimesh->numVerts, miniply::PLYPropertyType::Int, trimesh->indices); |
| 109 | } else { | |
| 110 | ! | trimesh->numIndices = reader.num_rows() * 3; |
| 111 | ! | trimesh->indices = new int[trimesh->numIndices]; |
| 112 | ! | reader.extract_list_property(indexes[0], miniply::PLYPropertyType::Int, trimesh->indices); |
| 113 | } | |
| 114 | ! | gotFaces = true; |
| 115 | } | |
| 116 | ! | if (gotVerts && gotFaces) { |
| 117 | ! | break; |
| 118 | } | |
| 119 | ! | reader.next_element(); |
| 120 | } | |
| 121 | ! | if (!gotVerts || !gotFaces) { |
| 122 | ! | std::string vert1 = gotVerts ? "" : "vertices "; |
| 123 | ! | std::string face1 = gotFaces ? "" : "faces"; |
| 124 | ! | Rcpp::Rcout << "Failed to load: " << vert1 << face1 << "\n"; |
| 125 | ! | delete trimesh; |
| 126 | ! | return nullptr; |
| 127 | } | |
| 128 | ||
| 129 | ! | return trimesh; |
| 130 | } | |
| 131 | ||
| 132 | // [[Rcpp::export]] | |
| 133 | ! | List load_ply(std::string inputfile, std::string basedir) { |
| 134 | ! | TriMesh* tri = parse_file_with_miniply(inputfile.c_str(), false); |
| 135 | ||
| 136 | ! | if(tri == nullptr) { |
| 137 | ! | std::string err = inputfile; |
| 138 | ! | throw std::runtime_error("No mesh loaded: " + err); |
| 139 | } | |
| 140 | ! | bool has_normals = false; |
| 141 | ! | if(tri->normal != nullptr) { |
| 142 | ! | has_normals = true; |
| 143 | } | |
| 144 | ||
| 145 | ! | bool has_uv = false; |
| 146 | ! | if(tri->uv != nullptr) { |
| 147 | ! | has_uv = true; |
| 148 | } | |
| 149 | ! | unsigned int numIndices = tri->numIndices; |
| 150 | ! | unsigned int numVerts = tri->numVerts; |
| 151 | ! | unsigned int nv_face = 3; |
| 152 | ||
| 153 | ! | List shape_list(1); |
| 154 | ! | List material_list(1); |
| 155 | List single_shape = List::create( | |
| 156 | ! | Named("indices") = R_NilValue, |
| 157 | ! | Named("tex_indices") = R_NilValue, |
| 158 | ! | Named("norm_indices") = R_NilValue, |
| 159 | ! | Named("material_ids") = R_NilValue, |
| 160 | ! | Named("has_vertex_tex") = R_NilValue, |
| 161 | ! | Named("has_vertex_normals") = R_NilValue |
| 162 | ); | |
| 163 | ! | std::vector<float> verts; |
| 164 | ! | std::vector<float> norms; |
| 165 | ! | std::vector<float> texs; |
| 166 | ||
| 167 | ||
| 168 | ! | for(unsigned int j = 0; j < 3*numVerts; j++) { |
| 169 | ! | verts.push_back(tri->pos[j]); |
| 170 | } | |
| 171 | ||
| 172 | ! | if(has_uv) { |
| 173 | ! | for(unsigned int j = 0; j < 2*numVerts; j++) { |
| 174 | ! | texs.push_back(tri->uv[j]); |
| 175 | } | |
| 176 | } | |
| 177 | ||
| 178 | ! | if(has_normals) { |
| 179 | ! | for(unsigned int j = 0; j < 3*numVerts; j++) { |
| 180 | ! | norms.push_back(tri->normal[j]); |
| 181 | } | |
| 182 | } | |
| 183 | ||
| 184 | ! | std::vector<int> inds; |
| 185 | ! | std::vector<int> tex_inds; |
| 186 | ! | std::vector<int> norm_inds; |
| 187 | ||
| 188 | ! | for(unsigned int j = 0; j < numIndices; j++) { |
| 189 | ! | inds.push_back(tri->indices[j]); |
| 190 | } | |
| 191 | ||
| 192 | ! | if(has_uv) { |
| 193 | ! | for(unsigned int j = 0; j < numIndices; j++) { |
| 194 | ! | tex_inds.push_back(tri->indices[j]); |
| 195 | } | |
| 196 | } | |
| 197 | ! | if(has_normals) { |
| 198 | ! | for(unsigned int j = 0; j < numIndices; j++) { |
| 199 | ! | norm_inds.push_back(tri->indices[j]); |
| 200 | } | |
| 201 | } | |
| 202 | ||
| 203 | ! | single_shape["indices"] = Rcpp::transpose(IntegerMatrix(nv_face, inds.size()/nv_face, inds.begin() )); |
| 204 | ! | single_shape["tex_indices"] = Rcpp::transpose(IntegerMatrix(nv_face, tex_inds.size()/nv_face, tex_inds.begin() )); |
| 205 | ! | single_shape["norm_indices"] = Rcpp::transpose(IntegerMatrix(nv_face, norm_inds.size()/nv_face, norm_inds.begin() )); |
| 206 | ! | single_shape["material_ids"] = Rcpp::transpose(NumericMatrix(1L, inds.size()/nv_face)); |
| 207 | ! | single_shape["has_vertex_tex"] = LogicalVector(inds.size()/nv_face,inds.size() == tex_inds.size()); |
| 208 | ! | single_shape["has_vertex_normals"] = LogicalVector(inds.size()/nv_face,inds.size() == norm_inds.size()); |
| 209 | ! | shape_list[0] = single_shape; |
| 210 | ||
| 211 | ! | const int num_items = 30; |
| 212 | ||
| 213 | ! | List out(num_items); |
| 214 | ! | CharacterVector names(num_items) ; |
| 215 | ! | int item = 0; |
| 216 | ||
| 217 | ! | set_item( out, item++, _["ambient"] = NumericVector::create(0,0,0), names) ; |
| 218 | ! | set_item( out, item++, _["diffuse"] = NumericVector::create(1,1,1), names) ; |
| 219 | ! | set_item( out, item++, _["specular"] = NumericVector::create(0,0,0), names) ; |
| 220 | ! | set_item( out, item++, _["transmittance"] = NumericVector::create(0,0,0), names) ; |
| 221 | ! | set_item( out, item++, _["emission"] = NumericVector::create(0,0,0), names) ; |
| 222 | ! | set_item( out, item++, _["shininess"] = 1.0, names) ; |
| 223 | ! | set_item( out, item++, _["ior"] = 1.0, names) ; |
| 224 | ! | set_item( out, item++, _["dissolve"] = 1.0, names) ; |
| 225 | ! | set_item( out, item++, _["illum"] = 1, names) ; |
| 226 | ! | set_item( out, item++, _["ambient_texname"] = "" , names) ; |
| 227 | ! | set_item( out, item++, _["diffuse_texname"] = "" , names) ; |
| 228 | ! | set_item( out, item++, _["emissive_texname"] = "", names) ; |
| 229 | ! | set_item( out, item++, _["specular_texname"] = "", names) ; |
| 230 | ! | set_item( out, item++, _["normal_texname"] = "" , names) ; |
| 231 | ! | set_item( out, item++, _["bump_texname"] = "" , names) ; |
| 232 | ! | set_item( out, item++, _["diffuse_intensity"] = 1.0 , names) ; |
| 233 | ! | set_item( out, item++, _["bump_intensity"] = 1.0 , names) ; |
| 234 | ! | set_item( out, item++, _["emission_intensity"] = 1.0, names) ; |
| 235 | ! | set_item( out, item++, _["specular_intensity"] = 1.0, names) ; |
| 236 | ! | set_item( out, item++, _["ambient_intensity"] = 1.0, names) ; |
| 237 | ! | set_item( out, item++, _["culling"] = 1, names) ; |
| 238 | ! | set_item( out, item++, _["type"] = "diffuse", names) ; |
| 239 | ! | set_item( out, item++, _["translucent"] = true, names) ; |
| 240 | ! | set_item( out, item++, _["toon_levels"] = 5, names) ; |
| 241 | ! | set_item( out, item++, _["toon_outline_width"] = 0.05, names) ; |
| 242 | ! | set_item( out, item++, _["toon_outline_color"] = NumericVector::create(0,0,0), names) ; |
| 243 | ! | set_item( out, item++, _["reflection_intensity"] = 1.0, names) ; |
| 244 | ! | set_item( out, item++, _["reflection_sharpness"] = 1.0, names) ; |
| 245 | ! | set_item( out, item++, _["two_sided"] = false, names) ; |
| 246 | ! | set_item( out, item++, _["sigma"] = 1.0, names) ; |
| 247 | ||
| 248 | ! | if(item != num_items) { |
| 249 | ! | throw std::runtime_error("Number of items is not equal to specified material length."); |
| 250 | } | |
| 251 | ||
| 252 | ! | out.names() = names ; |
| 253 | ! | material_list[0] = out; |
| 254 | List return_val = List::create( | |
| 255 | ! | Named("shapes") = R_NilValue, |
| 256 | ! | Named("vertices") = R_NilValue, |
| 257 | ! | Named("texcoords") = R_NilValue, |
| 258 | ! | Named("normals") = R_NilValue, |
| 259 | ! | Named("materials") = R_NilValue |
| 260 | ); | |
| 261 | ! | return_val["shapes"] = shape_list; |
| 262 | ! | return_val["materials"] = List::create(material_list); |
| 263 | ! | return_val["vertices"] = List::create(Rcpp::transpose(NumericMatrix(3L, verts.size()/3L, verts.begin()))); |
| 264 | ! | return_val["texcoords"] = List::create(Rcpp::transpose(NumericMatrix(2L, texs.size()/2L, texs.begin()))); |
| 265 | ! | return_val["normals"] = List::create(Rcpp::transpose(NumericMatrix(3L, norms.size()/3L, norms.begin()))); |
| 266 | ! | delete tri; |
| 267 | ! | return return_val; |
| 268 | }; | |
| 269 | ||
| 270 |
| 1 | #include "loopsubdiv.h" | |
| 2 | #include <set> | |
| 3 | #include <map> | |
| 4 | #include "glm.hpp" | |
| 5 | #include "Rcpp.h" | |
| 6 | #include <queue> | |
| 7 | #include <memory> | |
| 8 | ||
| 9 | using namespace Rcpp; | |
| 10 | ||
| 11 | struct SDFace; | |
| 12 | struct SDVertex; | |
| 13 | ||
| 14 | // LoopSubdiv Macros | |
| 15 | #define NEXT(i) (((i) + 1) % 3) | |
| 16 | #define PREV(i) (((i) + 2) % 3) | |
| 17 | ||
| 18 | // LoopSubdiv Local Structures | |
| 19 | struct SDVertex { | |
| 20 | // SDVertex Constructor | |
| 21 | 140x | SDVertex(const glm::vec3 &p = glm::vec3(0, 0, 0), |
| 22 | 140x | const glm::vec2 &uv = glm::vec2(0, 0)) : |
| 23 | 140x | p(p), uv(uv) {} |
| 24 | ||
| 25 | // SDVertex Methods | |
| 26 | int valence(); | |
| 27 | void oneRing(glm::vec3 *p); | |
| 28 | void oneRing(glm::vec2 *p); | |
| 29 | glm::vec3 p; | |
| 30 | glm::vec2 uv; | |
| 31 | SDFace *startFace = nullptr; | |
| 32 | SDVertex *child = nullptr; | |
| 33 | bool regular = false, boundary = false; | |
| 34 | bool initialized = false; //This marks when the vertex has a startFace | |
| 35 | }; | |
| 36 | ||
| 37 | struct SDFace { | |
| 38 | // SDFace Constructor | |
| 39 | 252x | SDFace() { |
| 40 | 1008x | for (int i = 0; i < 3; ++i) { |
| 41 | 756x | v[i] = nullptr; |
| 42 | 756x | f[i] = nullptr; |
| 43 | } | |
| 44 | 252x | MatID = 0; |
| 45 | 252x | vertices_initialized = false; |
| 46 | 252x | faces_initialized = false; |
| 47 | 1260x | for (int i = 0; i < 4; ++i) children[i] = nullptr; |
| 48 | } | |
| 49 | ||
| 50 | // SDFace Methods | |
| 51 | 8026x | int vnum(SDVertex *vert) const { |
| 52 | 16054x | for (int i = 0; i < 3; ++i) { |
| 53 | 16054x | if(!vert) { |
| 54 | ! | Rcpp::stop("Vert not found"); |
| 55 | } | |
| 56 | 16054x | if(!v[i]) { |
| 57 | ! | Rcpp::stop("Vert not initialized"); |
| 58 | } | |
| 59 | 16054x | if (v[i] == vert) { |
| 60 | 8026x | return i; |
| 61 | } | |
| 62 | } | |
| 63 | ! | Rcpp::stop( "Basic logic error in SDFace::vnum()"); |
| 64 | return -1; | |
| 65 | } | |
| 66 | 5544x | SDFace *nextFace(SDVertex *vert) { return f[vnum(vert)]; } |
| 67 | ! | SDFace *prevFace(SDVertex *vert) { return f[PREV(vnum(vert))]; } |
| 68 | 2088x | SDVertex *nextVert(SDVertex *vert) { return v[NEXT(vnum(vert))]; } |
| 69 | ! | SDVertex *prevVert(SDVertex *vert) { return v[PREV(vnum(vert))]; } |
| 70 | 360x | SDVertex *otherVert(SDVertex *v0, SDVertex *v1) { |
| 71 | 720x | for (int i = 0; i < 3; ++i) { |
| 72 | 720x | if (v[i] != v0 && v[i] != v1) { |
| 73 | 360x | return v[i]; |
| 74 | } | |
| 75 | } | |
| 76 | ! | Rcpp::stop( "Basic logic error in SDVertex::otherVert()"); |
| 77 | return nullptr; | |
| 78 | } | |
| 79 | SDVertex *v[3]; | |
| 80 | SDFace *f[3]; | |
| 81 | SDFace *children[4]; | |
| 82 | int MatID; | |
| 83 | bool vertices_initialized; //This marks when the vertices are all initialized | |
| 84 | bool faces_initialized; //This marks when the vertices are all initialized | |
| 85 | }; | |
| 86 | ||
| 87 | struct SDEdge { | |
| 88 | // SDEdge Constructor | |
| 89 | 396x | SDEdge(SDVertex *v0 = nullptr, SDVertex *v1 = nullptr) { |
| 90 | 396x | v[0] = std::min(v0, v1); |
| 91 | 396x | v[1] = std::max(v0, v1); |
| 92 | 396x | f[0] = f[1] = nullptr; |
| 93 | 396x | f0edgeNum = -1; |
| 94 | } | |
| 95 | ||
| 96 | // SDEdge Comparison Function | |
| 97 | 3495x | bool operator<(const SDEdge &e2) const { |
| 98 | 3495x | if (v[0] == e2.v[0]) return v[1] < e2.v[1]; |
| 99 | 1898x | return v[0] < e2.v[0]; |
| 100 | } | |
| 101 | SDVertex *v[2]; | |
| 102 | SDFace *f[2]; | |
| 103 | int f0edgeNum; | |
| 104 | }; | |
| 105 | ||
| 106 | // LoopSubdiv Local Declarations | |
| 107 | template <typename T> | |
| 108 | static T weightOneRing(SDVertex *vert, T vert_data, float beta); | |
| 109 | ||
| 110 | template <typename T> | |
| 111 | static T weightBoundary(SDVertex *vert, T vert_data, float beta); | |
| 112 | ||
| 113 | // LoopSubdiv Inline Functions | |
| 114 | 598x | inline int SDVertex::valence() { |
| 115 | 598x | SDFace *f = startFace; |
| 116 | 598x | if (!boundary) { |
| 117 | // Compute valence of interior vertex | |
| 118 | 598x | int nf = 1; |
| 119 | 3420x | while ((f = f->nextFace(this)) != startFace) { |
| 120 | 2822x | Rcpp::checkUserInterrupt(); |
| 121 | 2822x | ++nf; |
| 122 | } | |
| 123 | 598x | return nf; |
| 124 | } else { | |
| 125 | // Compute valence of boundary vertex | |
| 126 | ! | int nf = 1; |
| 127 | ||
| 128 | ! | while ((f = f->nextFace(this)) != nullptr) { |
| 129 | ! | Rcpp::checkUserInterrupt(); |
| 130 | ! | ++nf; |
| 131 | } | |
| 132 | ! | f = startFace; |
| 133 | ! | while ((f = f->prevFace(this)) != nullptr) { |
| 134 | ! | Rcpp::checkUserInterrupt(); |
| 135 | ! | ++nf; |
| 136 | } | |
| 137 | ! | return nf + 1; |
| 138 | } | |
| 139 | } | |
| 140 | ||
| 141 | 228x | inline float beta(int valence) { |
| 142 | 228x | if (valence == 3) { |
| 143 | ! | return 3.f / 16.f; |
| 144 | } else { | |
| 145 | 228x | return 3.f / (8.f * valence); |
| 146 | } | |
| 147 | } | |
| 148 | ||
| 149 | 196x | inline float loopGamma(int valence) { |
| 150 | 196x | return 1.f / (valence + 3.f / (8.f * beta(valence))); |
| 151 | } | |
| 152 | ||
| 153 | // LoopSubdiv Function Definitions | |
| 154 | // [[Rcpp::export]] | |
| 155 | 1x | List LoopSubdivide(List mesh, |
| 156 | int shape_i, | |
| 157 | const int nLevels, | |
| 158 | bool verbose, | |
| 159 | bool simple_subdivision = false) { | |
| 160 | 1x | if(nLevels <= 1) { |
| 161 | ! | return(List()); |
| 162 | } | |
| 163 | 2x | List shapes_list = as<List>(mesh["shapes"])(shape_i); |
| 164 | 2x | NumericMatrix vertex_matrix = as<NumericMatrix>(as<List>(mesh["vertices"])(shape_i)); |
| 165 | 2x | NumericMatrix texcoord_matrix = as<NumericMatrix>(as<List>(mesh["texcoords"])(shape_i)); |
| 166 | ||
| 167 | 2x | IntegerVector face_material_ids = as<IntegerVector>(shapes_list["material_ids"]); |
| 168 | ||
| 169 | 2x | IntegerVector vertexIndices = as<IntegerVector>(Rcpp::transpose(as<IntegerMatrix>(shapes_list["indices"]))); |
| 170 | 1x | IntegerVector texIndices = as<IntegerVector>(Rcpp::transpose(as<IntegerMatrix>(shapes_list["tex_indices"]))); |
| 171 | ||
| 172 | 1x | int nIndices = vertexIndices.length(); |
| 173 | ||
| 174 | 1x | std::vector<std::unique_ptr<SDVertex> > vertex_storage; |
| 175 | 1x | std::vector<std::unique_ptr<SDFace> > face_storage; |
| 176 | ||
| 177 | 1x | std::vector<glm::vec3> p(vertex_matrix.nrow()); |
| 178 | 9x | for(size_t i = 0; i < static_cast<size_t>(vertex_matrix.nrow()); i++) { |
| 179 | 8x | p[i] = glm::vec3(vertex_matrix(i,0),vertex_matrix(i,1),vertex_matrix(i,2)); |
| 180 | } | |
| 181 | 1x | std::vector<glm::vec2> uv(texcoord_matrix.nrow()); |
| 182 | 5x | for(size_t i = 0; i < static_cast<size_t>(texcoord_matrix.nrow()); i++) { |
| 183 | 4x | uv[i] = glm::vec2(texcoord_matrix(i,0),texcoord_matrix(i,1)); |
| 184 | } | |
| 185 | 1x | bool has_uv = texcoord_matrix.nrow() > 0; |
| 186 | 1x | int nVertices = vertex_matrix.nrow(); |
| 187 | ||
| 188 | ||
| 189 | 1x | std::vector<SDVertex *> vertices; |
| 190 | 1x | std::vector<SDFace *> faces; |
| 191 | // Allocate _LoopSubdiv_ vertices and faces | |
| 192 | 2x | std::vector<glm::vec2> TexcoordsExpanded(nVertices); |
| 193 | 1x | std::vector<int> vertexToTex(nVertices); |
| 194 | 1x | if(has_uv) { |
| 195 | 37x | for(int i = 0; i < vertexIndices.size(); ++i) { |
| 196 | 36x | if(texIndices[i] != -1) { |
| 197 | 36x | TexcoordsExpanded[vertexIndices[i]] = uv[texIndices[i]]; |
| 198 | } | |
| 199 | } | |
| 200 | } | |
| 201 | ||
| 202 | 9x | std::unique_ptr<SDVertex[]> verts(new SDVertex[nVertices]); |
| 203 | 9x | for (int i = 0; i < nVertices; ++i) { |
| 204 | 8x | verts[i] = SDVertex(p[i]); |
| 205 | 8x | if(has_uv) { |
| 206 | 8x | verts[i].uv = TexcoordsExpanded[i]; |
| 207 | } | |
| 208 | 8x | vertices.push_back(&verts[i]); |
| 209 | } | |
| 210 | ||
| 211 | 1x | int nFaces = nIndices / 3; |
| 212 | 13x | std::unique_ptr<SDFace[]> fs(new SDFace[nFaces]); |
| 213 | 13x | for (int i = 0; i < nFaces; ++i) { |
| 214 | 12x | fs[i].MatID = face_material_ids[i]; |
| 215 | 12x | faces.push_back(&fs[i]); |
| 216 | } | |
| 217 | ||
| 218 | // Set face to vertex pointers | |
| 219 | // rayrender addition: This also marks the vertices/faces as initialized | |
| 220 | 1x | const int *vp = vertexIndices.begin(); |
| 221 | ||
| 222 | 13x | for (int i = 0; i < nFaces; ++i, vp += 3) { |
| 223 | 12x | SDFace *f = faces[i]; |
| 224 | 48x | for (int j = 0; j < 3; ++j) { |
| 225 | 36x | SDVertex *v = vertices[vp[j]]; |
| 226 | 36x | f->v[j] = v; |
| 227 | 36x | v->initialized = true; |
| 228 | 36x | v->startFace = f; |
| 229 | } | |
| 230 | 12x | f->vertices_initialized = true; |
| 231 | } | |
| 232 | ||
| 233 | // Set neighbor pointers in _faces_ | |
| 234 | 1x | std::set<SDEdge> edges; |
| 235 | 13x | for (int i = 0; i < nFaces; ++i) { |
| 236 | 12x | SDFace *f = faces[i]; |
| 237 | 48x | for (int edgeNum = 0; edgeNum < 3; ++edgeNum) { |
| 238 | // Update neighbor pointer for _edgeNum_ | |
| 239 | 36x | int v0 = edgeNum, v1 = NEXT(edgeNum); |
| 240 | 36x | SDEdge e(f->v[v0], f->v[v1]); |
| 241 | 36x | if (edges.find(e) == edges.end()) { |
| 242 | // Handle new edge | |
| 243 | 18x | e.f[0] = f; |
| 244 | 18x | e.f0edgeNum = edgeNum; |
| 245 | 18x | edges.insert(e); |
| 246 | } else { | |
| 247 | // Handle previously seen edge | |
| 248 | 18x | e = *edges.find(e); |
| 249 | 18x | e.f[0]->f[e.f0edgeNum] = f; |
| 250 | 18x | f->f[edgeNum] = e.f[0]; |
| 251 | 18x | edges.erase(e); |
| 252 | } | |
| 253 | } | |
| 254 | 12x | f->faces_initialized = true; |
| 255 | } | |
| 256 | ||
| 257 | // Finish vertex initialization | |
| 258 | 9x | for (int i = 0; i < nVertices; ++i) { |
| 259 | 8x | SDVertex *v = vertices[i]; |
| 260 | 8x | SDFace *f = v->startFace; |
| 261 | // SDFace *prevf = nullptr; | |
| 262 | 8x | if(!f || !f->faces_initialized) { |
| 263 | ! | continue; |
| 264 | } | |
| 265 | do { | |
| 266 | 36x | f = f->nextFace(v); |
| 267 | 36x | Rcpp::checkUserInterrupt(); //Add logic here to auto detect loops due to flipped edges |
| 268 | 36x | } while (f && f != v->startFace); |
| 269 | 8x | v->boundary = (f == nullptr); |
| 270 | 8x | if (!v->boundary && v->valence() == 6) { |
| 271 | ! | v->regular = true; |
| 272 | 8x | } else if (v->boundary && v->valence() == 4) { |
| 273 | ! | v->regular = true; |
| 274 | } else { | |
| 275 | 8x | v->regular = false; |
| 276 | } | |
| 277 | 8x | v->initialized = true; |
| 278 | } | |
| 279 | ||
| 280 | // Refine _LoopSubdiv_ into triangles | |
| 281 | ||
| 282 | 1x | std::vector<SDFace *> f = faces; |
| 283 | 1x | std::vector<SDVertex *> v = vertices; |
| 284 | 1x | std::vector<SDFace *> newFaces; |
| 285 | 1x | std::vector<SDVertex *> newVertices; |
| 286 | 3x | for (int i = 0; i < nLevels; ++i) { |
| 287 | 2x | if(verbose) { |
| 288 | ! | Rprintf("Subdividing mesh level %i/%i \n", (int)i+1, nLevels); |
| 289 | } | |
| 290 | 2x | Rcpp::checkUserInterrupt(); |
| 291 | // Update _f_ and _v_ for next level of subdivision | |
| 292 | 2x | newFaces.clear(); |
| 293 | 2x | newVertices.clear(); |
| 294 | ||
| 295 | // Allocate next level of children in mesh tree | |
| 296 | 38x | for (SDVertex *vertex : v) { |
| 297 | 34x | if(vertex->initialized) { |
| 298 | 34x | vertex_storage.push_back(std::make_unique<SDVertex>()); |
| 299 | 34x | vertex->child = vertex_storage.back().get(); |
| 300 | 34x | vertex->child->regular = vertex->regular; |
| 301 | 34x | vertex->child->boundary = vertex->boundary; |
| 302 | 34x | newVertices.push_back(vertex->child); |
| 303 | } | |
| 304 | } | |
| 305 | 64x | for (SDFace *face : f) { |
| 306 | 300x | for (int k = 0; k < 4; ++k) { |
| 307 | 240x | face_storage.push_back(std::make_unique<SDFace>()); |
| 308 | 240x | face->children[k] = face_storage.back().get(); |
| 309 | 240x | face->children[k]->MatID = face->MatID; |
| 310 | 240x | newFaces.push_back(face->children[k]); |
| 311 | } | |
| 312 | } | |
| 313 | ||
| 314 | ||
| 315 | // Update vertex positions and create new edge vertices | |
| 316 | // Update vertex positions for even vertices | |
| 317 | 38x | for (SDVertex *vertex : v) { |
| 318 | 34x | if(!vertex->initialized) { |
| 319 | ! | continue; |
| 320 | } | |
| 321 | 34x | if(simple_subdivision) { |
| 322 | ! | vertex->child->p = vertex->p; |
| 323 | ! | if (has_uv) { |
| 324 | ! | vertex->child->uv = vertex->uv; |
| 325 | } | |
| 326 | } else { | |
| 327 | 34x | if (!vertex->boundary) { |
| 328 | // Apply one-ring rule for even vertex | |
| 329 | 34x | if (vertex->regular) { |
| 330 | 18x | vertex->child->p = weightOneRing<glm::vec3>(vertex, vertex->p, 1.f / 16.f); |
| 331 | } else { | |
| 332 | 16x | vertex->child->p = weightOneRing<glm::vec3>(vertex, vertex->p, beta(vertex->valence())); |
| 333 | } | |
| 334 | 34x | if(has_uv) { |
| 335 | 34x | if (vertex->regular) { |
| 336 | 18x | vertex->child->uv = weightOneRing<glm::vec2>(vertex, vertex->uv, 1.f / 16.f); |
| 337 | } else { | |
| 338 | 16x | vertex->child->uv = weightOneRing<glm::vec2>(vertex, vertex->uv, beta(vertex->valence())); |
| 339 | } | |
| 340 | } | |
| 341 | } else { | |
| 342 | // Apply boundary rule for even vertex | |
| 343 | ! | vertex->child->p = weightBoundary<glm::vec3>(vertex, vertex->p, 1.f / 8.f); |
| 344 | ! | if(has_uv) { |
| 345 | ! | vertex->child->uv = weightBoundary<glm::vec2>(vertex, vertex->uv, 1.f / 8.f); |
| 346 | } | |
| 347 | } | |
| 348 | } | |
| 349 | } | |
| 350 | ||
| 351 | ||
| 352 | // Compute new odd edge vertices | |
| 353 | 2x | std::map<SDEdge, SDVertex *> edgeVerts; |
| 354 | 64x | for (SDFace *face : f) { |
| 355 | 240x | for (int k = 0; k < 3; ++k) { |
| 356 | // Compute odd vertex on _k_th edge | |
| 357 | 180x | SDEdge edge(face->v[k], face->v[NEXT(k)]); |
| 358 | 180x | SDVertex *vert = edgeVerts[edge]; |
| 359 | 180x | if (!vert) { |
| 360 | // Create and initialize new odd vertex | |
| 361 | 90x | vertex_storage.push_back(std::make_unique<SDVertex>()); |
| 362 | 90x | vert = vertex_storage.back().get(); |
| 363 | 90x | newVertices.push_back(vert); |
| 364 | 90x | vert->regular = true; |
| 365 | 90x | vert->boundary = (face->f[k] == nullptr); |
| 366 | 90x | vert->startFace = face->children[3]; |
| 367 | 90x | vert->initialized = true; |
| 368 | ||
| 369 | 90x | if (simple_subdivision) { |
| 370 | // Place vertex at the midpoint of the edge | |
| 371 | ! | vert->p = 0.5f * edge.v[0]->p + 0.5f * edge.v[1]->p; |
| 372 | ! | if (has_uv) { |
| 373 | ! | vert->uv = 0.5f * edge.v[0]->uv + 0.5f * edge.v[1]->uv; |
| 374 | } | |
| 375 | } else { | |
| 376 | // Apply edge rules to compute new vertex position | |
| 377 | 90x | if (vert->boundary) { |
| 378 | ! | vert->p = 0.5f * edge.v[0]->p; |
| 379 | ! | vert->p += 0.5f * edge.v[1]->p; |
| 380 | ! | if(has_uv) { |
| 381 | ! | vert->uv = 0.5f * edge.v[0]->uv; |
| 382 | ! | vert->uv += 0.5f * edge.v[1]->uv; |
| 383 | } | |
| 384 | } else { | |
| 385 | 90x | vert->p = 3.f / 8.f * edge.v[0]->p; |
| 386 | 90x | vert->p += 3.f / 8.f * edge.v[1]->p; |
| 387 | 90x | vert->p += 1.f / 8.f * face->otherVert(edge.v[0], edge.v[1])->p; |
| 388 | 90x | vert->p += 1.f / 8.f * face->f[k]->otherVert(edge.v[0], edge.v[1])->p; |
| 389 | 90x | if(has_uv) { |
| 390 | 90x | vert->uv = 3.f / 8.f * edge.v[0]->uv; |
| 391 | 90x | vert->uv += 3.f / 8.f * edge.v[1]->uv; |
| 392 | 90x | vert->uv += 1.f / 8.f * face->otherVert(edge.v[0], edge.v[1])->uv; |
| 393 | 90x | vert->uv += 1.f / 8.f * face->f[k]->otherVert(edge.v[0], edge.v[1])->uv; |
| 394 | } | |
| 395 | } | |
| 396 | } | |
| 397 | 90x | edgeVerts[edge] = vert; |
| 398 | } | |
| 399 | } | |
| 400 | } | |
| 401 | ||
| 402 | // Update new mesh topology | |
| 403 | ||
| 404 | // Update even vertex face pointers | |
| 405 | 38x | for (SDVertex *vertex : v) { |
| 406 | 34x | if(vertex->initialized) { |
| 407 | 34x | int vertNum = vertex->startFace->vnum(vertex); |
| 408 | 34x | vertex->child->startFace = vertex->startFace->children[vertNum]; |
| 409 | 34x | vertex->child->initialized = true; |
| 410 | } | |
| 411 | } | |
| 412 | ||
| 413 | // Update face neighbor pointers | |
| 414 | 64x | for (SDFace *face : f) { |
| 415 | 240x | for (int j = 0; j < 3; ++j) { |
| 416 | // Update children _f_ pointers for siblings | |
| 417 | 180x | face->children[3]->f[j] = face->children[NEXT(j)]; |
| 418 | 180x | face->children[j]->f[NEXT(j)] = face->children[3]; |
| 419 | ||
| 420 | // Update children _f_ pointers for neighbor children | |
| 421 | 180x | SDFace *f2 = face->f[j]; |
| 422 | 180x | face->children[j]->f[j] = |
| 423 | 180x | f2 ? f2->children[f2->vnum(face->v[j])] : nullptr; |
| 424 | 180x | f2 = face->f[PREV(j)]; |
| 425 | 180x | face->children[j]->f[PREV(j)] = |
| 426 | 180x | f2 ? f2->children[f2->vnum(face->v[j])] : nullptr; |
| 427 | //This helps avoid accessing floating triangles (e.g. which have no adjacent faces) | |
| 428 | 180x | if(!face->children[j]->f[j]) { |
| 429 | ! | continue; |
| 430 | } | |
| 431 | ||
| 432 | 180x | face->children[j]->f[j]->faces_initialized = true; |
| 433 | } | |
| 434 | } | |
| 435 | ||
| 436 | // Update face vertex pointers | |
| 437 | 64x | for (SDFace *face : f) { |
| 438 | 240x | for (int j = 0; j < 3; ++j) { |
| 439 | // Update child vertex pointer to new even vertex | |
| 440 | 180x | face->children[j]->v[j] = face->v[j]->child; |
| 441 | ||
| 442 | // Update child vertex pointer to new odd vertex | |
| 443 | 180x | SDVertex *vert = edgeVerts[SDEdge(face->v[j], face->v[NEXT(j)])]; |
| 444 | 180x | face->children[j]->v[NEXT(j)] = vert; |
| 445 | 180x | face->children[NEXT(j)]->v[j] = vert; |
| 446 | 180x | face->children[3]->v[j] = vert; |
| 447 | 180x | face->vertices_initialized = true; |
| 448 | } | |
| 449 | } | |
| 450 | // Prepare for next level of subdivision | |
| 451 | 2x | f = newFaces; |
| 452 | 2x | v = newVertices; |
| 453 | } | |
| 454 | // Push vertices to limit surface | |
| 455 | 1x | NumericMatrix final_vertices(v.size(), 3); |
| 456 | 99x | for (size_t i = 0; i < v.size(); ++i) { |
| 457 | ||
| 458 | 98x | if(v[i]->initialized) { |
| 459 | 98x | if(simple_subdivision) { |
| 460 | ! | final_vertices(i,0) = v[i]->p[0]; |
| 461 | ! | final_vertices(i,1) = v[i]->p[1]; |
| 462 | ! | final_vertices(i,2) = v[i]->p[2]; |
| 463 | } else { | |
| 464 | 98x | if (v[i]->boundary) { |
| 465 | ! | glm::vec3 tmp_v = weightBoundary<glm::vec3>(v[i], v[i]->p, 1.f / 5.f); |
| 466 | ! | final_vertices(i,0) = tmp_v[0]; |
| 467 | ! | final_vertices(i,1) = tmp_v[1]; |
| 468 | ! | final_vertices(i,2) = tmp_v[2]; |
| 469 | } else { | |
| 470 | 98x | glm::vec3 tmp_v = weightOneRing<glm::vec3>(v[i], v[i]->p, loopGamma(v[i]->valence())); |
| 471 | 98x | final_vertices(i,0) = tmp_v[0]; |
| 472 | 98x | final_vertices(i,1) = tmp_v[1]; |
| 473 | 98x | final_vertices(i,2) = tmp_v[2]; |
| 474 | } | |
| 475 | } | |
| 476 | } | |
| 477 | } | |
| 478 | ||
| 479 | 99x | for (size_t i = 0; i < v.size(); ++i) { |
| 480 | 98x | if(v[i]->initialized) { |
| 481 | 98x | v[i]->p = glm::vec3(final_vertices(i,0), |
| 482 | ! | final_vertices(i,1), |
| 483 | 196x | final_vertices(i,2)); |
| 484 | } | |
| 485 | } | |
| 486 | ||
| 487 | // Compute UVs on limit surface | |
| 488 | 1x | NumericMatrix final_texcoords(v.size(),2); |
| 489 | ||
| 490 | 1x | if(has_uv) { |
| 491 | 99x | for (size_t i = 0; i < v.size(); ++i) { |
| 492 | 98x | if(v[i]->initialized) { |
| 493 | 98x | if (v[i]->boundary) { |
| 494 | ! | glm::vec2 tmp_uv = weightBoundary<glm::vec2>(v[i], v[i]->uv, 1.f / 5.f); |
| 495 | ! | final_texcoords(i,0) = tmp_uv[0]; |
| 496 | ! | final_texcoords(i,1) = tmp_uv[1]; |
| 497 | } else { | |
| 498 | 98x | glm::vec2 tmp_uv = weightOneRing<glm::vec2>(v[i], v[i]->uv, loopGamma(v[i]->valence())); |
| 499 | 98x | final_texcoords(i,0) = tmp_uv[0]; |
| 500 | 98x | final_texcoords(i,1) = tmp_uv[1]; |
| 501 | } | |
| 502 | } | |
| 503 | } | |
| 504 | ||
| 505 | 99x | for (size_t i = 0; i < v.size(); ++i) { |
| 506 | 98x | if(v[i]->initialized) { |
| 507 | 98x | v[i]->uv = glm::vec2(final_texcoords(i,0), |
| 508 | 196x | final_texcoords(i,1)); |
| 509 | } | |
| 510 | } | |
| 511 | } | |
| 512 | ||
| 513 | ||
| 514 | //Visualize the faces as colors related to topology | |
| 515 | // Compute vertex tangents on limit surface | |
| 516 | 1x | Rcpp::NumericMatrix final_normals(v.size(), 3); |
| 517 | 1x | std::vector<glm::vec3> pRing(16, glm::vec3()); |
| 518 | 1x | int cntr = 0; |
| 519 | 100x | for (SDVertex *vertex : v) { |
| 520 | 98x | if(vertex->initialized) { |
| 521 | 98x | glm::vec3 S(0, 0, 0), T(0, 0, 0); |
| 522 | 98x | int valence = vertex->valence(); |
| 523 | 98x | if (valence > (int)pRing.size()) { |
| 524 | ! | pRing.resize(valence); |
| 525 | } | |
| 526 | 98x | vertex->oneRing(&pRing[0]); |
| 527 | 98x | if (!vertex->boundary) { |
| 528 | // Compute tangents of interior face | |
| 529 | 674x | for (int j = 0; j < valence; ++j) { |
| 530 | 576x | S += (float)std::cos(2 * M_PI * j / valence) * glm::vec3(pRing[j]); |
| 531 | 576x | T += (float)std::sin(2 * M_PI * j / valence) * glm::vec3(pRing[j]); |
| 532 | } | |
| 533 | } else { | |
| 534 | // Compute tangents of boundary face | |
| 535 | ! | S = pRing[valence - 1] - pRing[0]; |
| 536 | ! | if (valence == 2) { |
| 537 | ! | T = glm::vec3(pRing[0] + pRing[1] - 2.f * vertex->p); |
| 538 | ! | } else if (valence == 3) { |
| 539 | ! | T = pRing[1] - vertex->p; |
| 540 | ! | } else if (valence == 4) { // regular |
| 541 | ! | T = glm::vec3(-1.f * pRing[0] + 2.0f * pRing[1] + 2.0f * pRing[2] + |
| 542 | ! | -1.f * pRing[3] + -2.f * vertex->p); |
| 543 | } else { | |
| 544 | ! | float theta = M_PI / float(valence - 1); |
| 545 | ! | T = glm::vec3(std::sin(theta) * (pRing[0] + pRing[valence - 1])); |
| 546 | ! | for (int k = 1; k < valence - 1; ++k) { |
| 547 | ! | float wt = (2 * std::cos(theta) - 2) * std::sin((k)*theta); |
| 548 | ! | T += glm::vec3(wt * pRing[k]); |
| 549 | } | |
| 550 | ! | T = -T; |
| 551 | } | |
| 552 | } | |
| 553 | 98x | glm::vec3 norm = (glm::vec3(-cross(S, T))); |
| 554 | 98x | norm = glm::normalize(norm); |
| 555 | 98x | final_normals(cntr, 0) = norm[0]; |
| 556 | 98x | final_normals(cntr, 1) = norm[1]; |
| 557 | 98x | final_normals(cntr, 2) = norm[2]; |
| 558 | } | |
| 559 | 98x | cntr++; |
| 560 | } | |
| 561 | // Create triangle mesh from subdivision mesh | |
| 562 | 1x | size_t ntris = f.size(); |
| 563 | 1x | std::unique_ptr<int[]> indices(new int[3 * ntris]); |
| 564 | 1x | IntegerVector face_material_id(ntris); |
| 565 | 1x | int *vp2 = indices.get(); |
| 566 | 1x | size_t totVerts = v.size(); |
| 567 | 1x | std::map<SDVertex *, int> usedVerts; |
| 568 | 99x | for (size_t i = 0; i < totVerts; ++i) { |
| 569 | 98x | if(v[i]->initialized) { |
| 570 | 98x | usedVerts[v[i]] = i; |
| 571 | } | |
| 572 | } | |
| 573 | ||
| 574 | 193x | for (size_t i = 0; i < ntris; ++i) { |
| 575 | 192x | face_material_id[i] = f[i]->MatID; |
| 576 | 768x | for (int j = 0; j < 3; ++j) { |
| 577 | 576x | *vp2 = usedVerts[f[i]->v[j]]; |
| 578 | 576x | ++vp2; |
| 579 | } | |
| 580 | } | |
| 581 | ||
| 582 | 1x | IntegerMatrix final_shape_indices(ntris, 3); |
| 583 | 1x | IntegerMatrix final_shape_normals(ntris, 3); |
| 584 | 1x | IntegerMatrix final_shape_uvs(ntris, 3); |
| 585 | ||
| 586 | 193x | for (size_t s = 0; s < ntris * 3; s += 3) { |
| 587 | 192x | final_shape_indices(s / 3, 0) = (indices[s]); |
| 588 | 192x | final_shape_indices(s / 3, 1) = (indices[s+1]); |
| 589 | 192x | final_shape_indices(s / 3, 2) = (indices[s+2]); |
| 590 | // if(base_mesh->has_normals) { | |
| 591 | 192x | final_shape_normals(s / 3, 0) = (indices[s]); |
| 592 | 192x | final_shape_normals(s / 3, 1) = (indices[s+1]); |
| 593 | 192x | final_shape_normals(s / 3, 2) = (indices[s+2]); |
| 594 | 192x | if(has_uv) { |
| 595 | 192x | final_shape_uvs(s / 3, 0) = (indices[s]); |
| 596 | 192x | final_shape_uvs(s / 3, 1) = (indices[s+1]); |
| 597 | 192x | final_shape_uvs(s / 3, 2) = (indices[s+2]); |
| 598 | } else { | |
| 599 | ! | final_shape_uvs(s / 3, 0) = -1; |
| 600 | ! | final_shape_uvs(s / 3, 1) = -1; |
| 601 | ! | final_shape_uvs(s / 3, 2) = -1; |
| 602 | } | |
| 603 | } | |
| 604 | // shapes_list["indices"] = Rcpp::clone(final_shape_indices); | |
| 605 | // if(has_uv) { | |
| 606 | // shapes_list["tex_indices"] = Rcpp::clone(final_shape_indices); | |
| 607 | // } | |
| 608 | // shapes_list["norm_indices"] = Rcpp::clone(final_shape_indices); | |
| 609 | // shapes_list["material_ids"] = Rcpp::clone(face_material_id); | |
| 610 | // shapes_list["has_vertex_tex"] = Rcpp::clone(LogicalVector(face_material_id.size(),has_uv)); | |
| 611 | // shapes_list["has_vertex_normals"] = Rcpp::clone(LogicalVector(face_material_id.size(),true)); | |
| 612 | // | |
| 613 | // Rcpp::List mesh_vertices = mesh["vertices"]; | |
| 614 | // Rcpp::List mesh_texcoords = mesh["texcoords"]; | |
| 615 | // Rcpp::List mesh_normals = mesh["normals"]; | |
| 616 | // | |
| 617 | // mesh_vertices(shape_i) = Rcpp::clone(final_vertices); | |
| 618 | // mesh_normals(shape_i) = Rcpp::clone(final_normals); | |
| 619 | // if(has_uv) { | |
| 620 | // mesh_texcoords(shape_i) = Rcpp::clone(final_texcoords); | |
| 621 | // } | |
| 622 | 2x | return(List::create(_["indices"] = final_shape_indices, |
| 623 | 2x | _["face_material_id"] = face_material_id, |
| 624 | 2x | _["vertices"] = final_vertices, |
| 625 | 2x | _["texcoords"] = final_texcoords, |
| 626 | 2x | _["normals"] = final_normals, |
| 627 | 4x | _["has_vertex_tex"] = LogicalVector(face_material_id.size(),has_uv), |
| 628 | 4x | _["has_vertex_normals"] = LogicalVector(face_material_id.size(),true) |
| 629 | )); | |
| 630 | } | |
| 631 | ||
| 632 | #define ALLOCA(TYPE, COUNT) (TYPE *) alloca((COUNT) * sizeof(TYPE)) | |
| 633 | ||
| 634 | template <typename T> | |
| 635 | 264x | static T weightOneRing(SDVertex *vert, T vert_data, float beta) { |
| 636 | // Put _vert_ one-ring in _pRing_ | |
| 637 | 264x | int valence = vert->valence(); |
| 638 | 264x | T *pRing = ALLOCA(T, valence); |
| 639 | 264x | vert->oneRing(pRing); |
| 640 | 264x | T p = (1 - valence * beta) * vert_data; |
| 641 | 1776x | for (int i = 0; i < valence; ++i) { |
| 642 | 1512x | p += beta * pRing[i]; |
| 643 | } | |
| 644 | 264x | return p; |
| 645 | } | |
| 646 | ||
| 647 | //Need methods for each data type | |
| 648 | 230x | void SDVertex::oneRing(glm::vec3 *p) { |
| 649 | 230x | if (!boundary) { |
| 650 | // Get one-ring vertices for interior vertex | |
| 651 | 230x | SDFace *face = startFace; |
| 652 | do { | |
| 653 | 1332x | *p++ = face->nextVert(this)->p; |
| 654 | 1332x | face = face->nextFace(this); |
| 655 | 1332x | } while (face != startFace); |
| 656 | } else { | |
| 657 | // Get one-ring vertices for boundary vertex | |
| 658 | ! | SDFace *face = startFace, *f2; |
| 659 | ! | while ((f2 = face->nextFace(this)) != nullptr) face = f2; |
| 660 | ! | *p++ = face->nextVert(this)->p; |
| 661 | do { | |
| 662 | ! | *p++ = face->prevVert(this)->p; |
| 663 | ! | face = face->prevFace(this); |
| 664 | ! | } while (face != nullptr); |
| 665 | } | |
| 666 | } | |
| 667 | ||
| 668 | 132x | void SDVertex::oneRing(glm::vec2 *p) { |
| 669 | 132x | if (!boundary) { |
| 670 | // Get one-ring vertices for interior vertex | |
| 671 | 132x | SDFace *face = startFace; |
| 672 | do { | |
| 673 | 756x | *p++ = face->nextVert(this)->uv; |
| 674 | 756x | face = face->nextFace(this); |
| 675 | 756x | } while (face != startFace); |
| 676 | } else { | |
| 677 | // Get one-ring vertices for boundary vertex | |
| 678 | ! | SDFace *face = startFace, *f2; |
| 679 | ! | while ((f2 = face->nextFace(this)) != nullptr) face = f2; |
| 680 | ! | *p++ = face->nextVert(this)->uv; |
| 681 | do { | |
| 682 | ! | *p++ = face->prevVert(this)->uv; |
| 683 | ! | face = face->prevFace(this); |
| 684 | ! | } while (face != nullptr); |
| 685 | } | |
| 686 | } | |
| 687 | ||
| 688 | template<typename T> | |
| 689 | ! | static T weightBoundary(SDVertex *vert, T vert_data, float beta) { |
| 690 | // Put _vert_ one-ring in _pRing_ | |
| 691 | ! | int valence = vert->valence(); |
| 692 | ! | T *pRing = ALLOCA(T, valence); //allocate on the stack |
| 693 | ! | vert->oneRing(pRing); |
| 694 | ! | T newValue = (1 - 2 * beta) * vert_data; |
| 695 | ! | newValue += beta * pRing[0]; |
| 696 | ! | newValue += beta * pRing[valence - 1]; |
| 697 | ! | return newValue; |
| 698 | } |
| 1 | /* | |
| 2 | MIT License | |
| 3 | ||
| 4 | Copyright (c) 2019 Vilya Harvey | |
| 5 | ||
| 6 | Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 7 | of this software and associated documentation files (the "Software"), to deal | |
| 8 | in the Software without restriction, including without limitation the rights | |
| 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 10 | copies of the Software, and to permit persons to whom the Software is | |
| 11 | furnished to do so, subject to the following conditions: | |
| 12 | ||
| 13 | The above copyright notice and this permission notice shall be included in all | |
| 14 | copies or substantial portions of the Software. | |
| 15 | ||
| 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 22 | SOFTWARE. | |
| 23 | */ | |
| 24 | ||
| 25 | #include <cstdarg> | |
| 26 | #include <cstdint> | |
| 27 | #include <cstdio> | |
| 28 | #include <string> | |
| 29 | #include <vector> | |
| 30 | ||
| 31 | ||
| 32 | /// miniply - A simple and fast parser for PLY files | |
| 33 | /// ================================================ | |
| 34 | /// | |
| 35 | /// For details about the PLY format see: | |
| 36 | /// * http://paulbourke.net/dataformats/ply/ | |
| 37 | /// * https://en.wikipedia.org/wiki/PLY_(file_format) | |
| 38 | ||
| 39 | namespace miniply { | |
| 40 | ||
| 41 | // | |
| 42 | // Constants | |
| 43 | // | |
| 44 | ||
| 45 | static constexpr uint32_t kInvalidIndex = 0xFFFFFFFFu; | |
| 46 | ||
| 47 | // Standard PLY element names | |
| 48 | extern const char* kPLYVertexElement; // "vertex" | |
| 49 | extern const char* kPLYFaceElement; // "face" | |
| 50 | ||
| 51 | ||
| 52 | // | |
| 53 | // PLY Parsing types | |
| 54 | // | |
| 55 | ||
| 56 | enum class PLYFileType { | |
| 57 | ASCII, | |
| 58 | Binary, | |
| 59 | BinaryBigEndian, | |
| 60 | }; | |
| 61 | ||
| 62 | ||
| 63 | enum class PLYPropertyType { | |
| 64 | Char, | |
| 65 | UChar, | |
| 66 | Short, | |
| 67 | UShort, | |
| 68 | Int, | |
| 69 | UInt, | |
| 70 | Float, | |
| 71 | Double, | |
| 72 | ||
| 73 | None, //!< Special value used in Element::listCountType to indicate a non-list property. | |
| 74 | }; | |
| 75 | ||
| 76 | ||
| 77 | struct PLYProperty { | |
| 78 | std::string name; | |
| 79 | PLYPropertyType type = PLYPropertyType::None; //!< Type of the data. Must be set to a value other than None. | |
| 80 | PLYPropertyType countType = PLYPropertyType::None; //!< None indicates this is not a list type, otherwise it's the type for the list count. | |
| 81 | uint32_t offset = 0; //!< Byte offset from the start of the row. | |
| 82 | uint32_t stride = 0; | |
| 83 | ||
| 84 | std::vector<uint8_t> listData; | |
| 85 | std::vector<uint32_t> rowCount; // Entry `i` is the number of items (*not* the number of bytes) in row `i`. | |
| 86 | }; | |
| 87 | ||
| 88 | ||
| 89 | struct PLYElement { | |
| 90 | std::string name; //!< Name of this element. | |
| 91 | std::vector<PLYProperty> properties; | |
| 92 | uint32_t count = 0; //!< The number of items in this element (e.g. the number of vertices if this is the vertex element). | |
| 93 | bool fixedSize = true; //!< `true` if there are only fixed-size properties in this element, i.e. no list properties. | |
| 94 | uint32_t rowStride = 0; //!< The number of bytes from the start of one row to the start of the next, for this element. | |
| 95 | ||
| 96 | void calculate_offsets(); | |
| 97 | ||
| 98 | /// Returns the index for the named property in this element, or `kInvalidIndex` | |
| 99 | /// if it can't be found. | |
| 100 | uint32_t find_property(const char* propName) const; | |
| 101 | ||
| 102 | /// Return the indices for several properties in one go. Use it like this: | |
| 103 | /// ``` | |
| 104 | /// uint32_t indexes[3]; | |
| 105 | /// if (elem.find_properties(indexes, 3, "foo", "bar", "baz")) { ... } | |
| 106 | /// ``` | |
| 107 | /// `propIdxs` is where the property indexes will be stored. `numIdxs` is | |
| 108 | /// the number of properties we will look up. There must be exactly | |
| 109 | /// `numIdxs` parameters after `numIdxs`; each of the is a c-style string | |
| 110 | /// giving the name of a property. | |
| 111 | /// | |
| 112 | /// The return value will be true if all properties were found. If it was | |
| 113 | /// not true, you should not use any values from propIdxs. | |
| 114 | bool find_properties(uint32_t propIdxs[], uint32_t numIdxs, ...) const; | |
| 115 | ||
| 116 | /// Same as `find_properties`, for when you already have a `va_list`. This | |
| 117 | /// is called internally by both `PLYElement::find_properties` and | |
| 118 | /// `PLYReader::find_properties`. | |
| 119 | bool find_properties_va(uint32_t propIdxs[], uint32_t numIdxs, va_list names) const; | |
| 120 | ||
| 121 | /// Call this on the element at some point before you load its data, when | |
| 122 | /// you know that every row's list will have the same length. It will | |
| 123 | /// replace the single variable-size property with a set of new fixed-size | |
| 124 | /// properties: one for the list count, followed by one for each of the | |
| 125 | /// list values. This will allow miniply to load and extract the property | |
| 126 | /// data a lot more efficiently, giving a big performance increase. | |
| 127 | /// | |
| 128 | /// After you've called this, you must use PLYReader's `extract_columns` | |
| 129 | /// method to get the data, rather than `extract_list_column`. | |
| 130 | /// | |
| 131 | /// The `newPropIdxs` parameter must be an array with at least `listSize` | |
| 132 | /// entries. If the function returns true, this will have been populated | |
| 133 | /// with the indices of the new properties that represent the list values | |
| 134 | /// (i.e. not including the list count property, which will have the same | |
| 135 | /// index as the old list property). | |
| 136 | /// | |
| 137 | /// The function returns false if the property index is invalid, or the | |
| 138 | /// property it refers to is not a list property. In these cases it will | |
| 139 | /// not modify anything. Otherwise it will return true. | |
| 140 | bool convert_list_to_fixed_size(uint32_t listPropIdx, uint32_t listSize, uint32_t newPropIdxs[]); | |
| 141 | }; | |
| 142 | ||
| 143 | ||
| 144 | class PLYReader { | |
| 145 | public: | |
| 146 | PLYReader(const char* filename); | |
| 147 | ~PLYReader(); | |
| 148 | ||
| 149 | bool valid() const; | |
| 150 | bool has_element() const; | |
| 151 | const PLYElement* element() const; | |
| 152 | bool load_element(); | |
| 153 | void next_element(); | |
| 154 | ||
| 155 | PLYFileType file_type() const; | |
| 156 | int version_major() const; | |
| 157 | int version_minor() const; | |
| 158 | uint32_t num_elements() const; | |
| 159 | uint32_t find_element(const char* name) const; | |
| 160 | PLYElement* get_element(uint32_t idx); | |
| 161 | ||
| 162 | /// Check whether the current element has the given name. | |
| 163 | bool element_is(const char* name) const; | |
| 164 | ||
| 165 | /// Number of rows in the current element. | |
| 166 | uint32_t num_rows() const; | |
| 167 | ||
| 168 | /// Returns the index for the named property in the current element, or | |
| 169 | /// `kInvalidIndex` if it can't be found. | |
| 170 | uint32_t find_property(const char* name) const; | |
| 171 | ||
| 172 | /// Equivalent to calling `find_properties` on the current element. | |
| 173 | bool find_properties(uint32_t propIdxs[], uint32_t numIdxs, ...) const; | |
| 174 | ||
| 175 | /// Copy the data for the specified properties into `dest`, which must be | |
| 176 | /// an array with at least enough space to hold all of the extracted column | |
| 177 | /// data. `propIdxs` is an array containing the indexes of the properties | |
| 178 | /// to copy; it has `numProps` elements. | |
| 179 | /// | |
| 180 | /// `destType` specifies the data type for values stored in `dest`. All | |
| 181 | /// property values will be converted to this type if necessary. | |
| 182 | /// | |
| 183 | /// This function does some checks up front to pick the most efficient code | |
| 184 | /// path for extracting the data. It considers: | |
| 185 | /// (a) whether any data conversion is required. | |
| 186 | /// (b) whether all property values to be extracted are in contiguous | |
| 187 | /// memory locations for any given item. | |
| 188 | /// (c) whether the data for all rows is contiguous in memory. | |
| 189 | /// In the best case it reduces to a single memcpy call. In the worst case | |
| 190 | /// we must iterate over all values to be copied, applying type conversions | |
| 191 | /// as we go. | |
| 192 | /// | |
| 193 | /// Note that this function does not handle list-valued properties. Use | |
| 194 | /// `extract_list_column()` for those instead. | |
| 195 | bool extract_properties(const uint32_t propIdxs[], uint32_t numProps, PLYPropertyType destType, void* dest) const; | |
| 196 | ||
| 197 | /// Get the array of item counts for a list property. Entry `i` in this | |
| 198 | /// array is the number of items in the `i`th list. | |
| 199 | const uint32_t* get_list_counts(uint32_t propIdx) const; | |
| 200 | ||
| 201 | /// Get the sum of all item counts for a list property. This can be useful | |
| 202 | /// to determine how big a destination array you'll need for a call to | |
| 203 | /// `extract_list_property`. It's equivalent to summing up all the values | |
| 204 | /// in the array returned by `get_list_counts`, but faster. | |
| 205 | uint32_t sum_of_list_counts(uint32_t propIdx) const; | |
| 206 | ||
| 207 | const uint8_t* get_list_data(uint32_t propIdx) const; | |
| 208 | bool extract_list_property(uint32_t propIdx, PLYPropertyType destType, void* dest) const; | |
| 209 | ||
| 210 | uint32_t num_triangles(uint32_t propIdx) const; | |
| 211 | bool requires_triangulation(uint32_t propIdx) const; | |
| 212 | bool extract_triangles(uint32_t propIdx, const float pos[], uint32_t numVerts, PLYPropertyType destType, void* dest) const; | |
| 213 | ||
| 214 | bool find_pos(uint32_t propIdxs[3]) const; | |
| 215 | bool find_normal(uint32_t propIdxs[3]) const; | |
| 216 | bool find_texcoord(uint32_t propIdxs[2]) const; | |
| 217 | bool find_color(uint32_t propIdxs[3]) const; | |
| 218 | bool find_indices(uint32_t propIdxs[1]) const; | |
| 219 | ||
| 220 | private: | |
| 221 | bool refill_buffer(); | |
| 222 | bool rewind_to_safe_char(); | |
| 223 | bool accept(); | |
| 224 | bool advance(); | |
| 225 | bool next_line(); | |
| 226 | bool match(const char* str); | |
| 227 | bool which(const char* values[], uint32_t* index); | |
| 228 | bool which_property_type(PLYPropertyType* type); | |
| 229 | bool keyword(const char* kw); | |
| 230 | bool identifier(char* dest, size_t destLen); | |
| 231 | ||
| 232 | template <class T> // T must be a type compatible with uint32_t. | |
| 233 | ! | bool typed_which(const char* values[], T* index) { |
| 234 | ! | return which(values, reinterpret_cast<uint32_t*>(index)); |
| 235 | } | |
| 236 | ||
| 237 | bool int_literal(int* value); | |
| 238 | bool float_literal(float* value); | |
| 239 | bool double_literal(double* value); | |
| 240 | ||
| 241 | bool parse_elements(); | |
| 242 | bool parse_element(); | |
| 243 | bool parse_property(std::vector<PLYProperty>& properties); | |
| 244 | ||
| 245 | bool load_fixed_size_element(PLYElement& elem); | |
| 246 | bool load_variable_size_element(PLYElement& elem); | |
| 247 | ||
| 248 | bool load_ascii_scalar_property(PLYProperty& prop, size_t& destIndex); | |
| 249 | bool load_ascii_list_property(PLYProperty& prop); | |
| 250 | bool load_binary_scalar_property(PLYProperty& prop, size_t& destIndex); | |
| 251 | bool load_binary_list_property(PLYProperty& prop); | |
| 252 | bool load_binary_scalar_property_big_endian(PLYProperty& prop, size_t& destIndex); | |
| 253 | bool load_binary_list_property_big_endian(PLYProperty& prop); | |
| 254 | ||
| 255 | bool ascii_value(PLYPropertyType propType, uint8_t value[8]); | |
| 256 | ||
| 257 | private: | |
| 258 | FILE* m_f = nullptr; | |
| 259 | char* m_buf = nullptr; | |
| 260 | const char* m_bufEnd = nullptr; | |
| 261 | const char* m_pos = nullptr; | |
| 262 | const char* m_end = nullptr; | |
| 263 | bool m_inDataSection = false; | |
| 264 | bool m_atEOF = false; | |
| 265 | int64_t m_bufOffset = 0; | |
| 266 | ||
| 267 | bool m_valid = false; | |
| 268 | ||
| 269 | PLYFileType m_fileType = PLYFileType::ASCII; //!< Whether the file was ascii, binary little-endian, or binary big-endian. | |
| 270 | int m_majorVersion = 0; | |
| 271 | int m_minorVersion = 0; | |
| 272 | std::vector<PLYElement> m_elements; //!< Element descriptors for this file. | |
| 273 | ||
| 274 | size_t m_currentElement = 0; | |
| 275 | bool m_elementLoaded = false; | |
| 276 | std::vector<uint8_t> m_elementData; | |
| 277 | ||
| 278 | char* m_tmpBuf = nullptr; | |
| 279 | }; | |
| 280 | ||
| 281 | ||
| 282 | /// Given a polygon with `n` vertices, where `n` > 3, triangulate it and | |
| 283 | /// store the indices for the resulting triangles in `dst`. The `pos` | |
| 284 | /// parameter is the array of all vertex positions for the mesh; `indices` is | |
| 285 | /// the list of `n` indices for the polygon we're triangulating; and `dst` is | |
| 286 | /// where we write the new indices to. | |
| 287 | /// | |
| 288 | /// The triangulation will always produce `n - 2` triangles, so `dst` must | |
| 289 | /// have enough space for `3 * (n - 2)` indices. | |
| 290 | /// | |
| 291 | /// If `n == 3`, we simply copy the input indices to `dst`. If `n < 3`, | |
| 292 | /// nothing gets written to dst. | |
| 293 | /// | |
| 294 | /// The return value is the number of triangles. | |
| 295 | uint32_t triangulate_polygon(uint32_t n, const float pos[], uint32_t numVerts, const int indices[], int dst[]); | |
| 296 | ||
| 297 | } // namespace miniply |
| 1 | /* | |
| 2 | MIT License | |
| 3 | ||
| 4 | Copyright (c) 2019 Vilya Harvey | |
| 5 | ||
| 6 | Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 7 | of this software and associated documentation files (the "Software"), to deal | |
| 8 | in the Software without restriction, including without limitation the rights | |
| 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 10 | copies of the Software, and to permit persons to whom the Software is | |
| 11 | furnished to do so, subject to the following conditions: | |
| 12 | ||
| 13 | The above copyright notice and this permission notice shall be included in all | |
| 14 | copies or substantial portions of the Software. | |
| 15 | ||
| 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 22 | SOFTWARE. | |
| 23 | */ | |
| 24 | ||
| 25 | //Added for Solaris off64_t support | |
| 26 | #define _LARGEFILE64_SOURCE | |
| 27 | #define _FILE_OFFSET_BITS 64 | |
| 28 | ||
| 29 | #include "miniply.h" | |
| 30 | ||
| 31 | #include <cassert> | |
| 32 | #include <cctype> | |
| 33 | #include <cmath> | |
| 34 | #include <cstdarg> | |
| 35 | #include <cstdio> | |
| 36 | #include <cstring> | |
| 37 | #include <string> | |
| 38 | #include <stdexcept> | |
| 39 | ||
| 40 | #ifndef _WIN32 | |
| 41 | #include <errno.h> | |
| 42 | #endif | |
| 43 | ||
| 44 | ||
| 45 | namespace miniply { | |
| 46 | ||
| 47 | // | |
| 48 | // Public constants | |
| 49 | // | |
| 50 | ||
| 51 | // Standard PLY element names | |
| 52 | const char* kPLYVertexElement = "vertex"; | |
| 53 | const char* kPLYFaceElement = "face"; | |
| 54 | ||
| 55 | ||
| 56 | // | |
| 57 | // PLY constants | |
| 58 | // | |
| 59 | ||
| 60 | static constexpr uint32_t kPLYReadBufferSize = 128 * 1024; | |
| 61 | static constexpr uint32_t kPLYTempBufferSize = kPLYReadBufferSize; | |
| 62 | ||
| 63 | static const char* kPLYFileTypes[] = { "ascii", "binary_little_endian", "binary_big_endian", nullptr }; | |
| 64 | static const uint32_t kPLYPropertySize[]= { 1, 1, 2, 2, 4, 4, 4, 8 }; | |
| 65 | ||
| 66 | struct PLYTypeAlias { | |
| 67 | const char* name; | |
| 68 | PLYPropertyType type; | |
| 69 | }; | |
| 70 | ||
| 71 | static const PLYTypeAlias kTypeAliases[] = { | |
| 72 | { "char", PLYPropertyType::Char }, | |
| 73 | { "uchar", PLYPropertyType::UChar }, | |
| 74 | { "short", PLYPropertyType::Short }, | |
| 75 | { "ushort", PLYPropertyType::UShort }, | |
| 76 | { "int", PLYPropertyType::Int }, | |
| 77 | { "uint", PLYPropertyType::UInt }, | |
| 78 | { "float", PLYPropertyType::Float }, | |
| 79 | { "float32",PLYPropertyType::Float }, | |
| 80 | { "float64",PLYPropertyType::Double }, | |
| 81 | { "double", PLYPropertyType::Double }, | |
| 82 | ||
| 83 | { "uint8", PLYPropertyType::UChar }, | |
| 84 | { "uint16", PLYPropertyType::UShort }, | |
| 85 | { "uint32", PLYPropertyType::UInt }, | |
| 86 | ||
| 87 | { "int8", PLYPropertyType::Char }, | |
| 88 | { "int16", PLYPropertyType::Short }, | |
| 89 | { "int32", PLYPropertyType::Int }, | |
| 90 | ||
| 91 | { nullptr, PLYPropertyType::None } | |
| 92 | }; | |
| 93 | ||
| 94 | ||
| 95 | // | |
| 96 | // Constants | |
| 97 | // | |
| 98 | ||
| 99 | static constexpr double kDoubleDigits[10] = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 }; | |
| 100 | ||
| 101 | static constexpr float kPi = 3.14159265358979323846f; | |
| 102 | ||
| 103 | ||
| 104 | // | |
| 105 | // Vec2 type | |
| 106 | // | |
| 107 | ||
| 108 | struct Vec2 { | |
| 109 | float x, y; | |
| 110 | }; | |
| 111 | ||
| 112 | ! | static inline Vec2 operator - (Vec2 lhs, Vec2 rhs) { return Vec2{ lhs.x - rhs.x, lhs.y - rhs.y }; } |
| 113 | ||
| 114 | ! | static inline float dot(Vec2 lhs, Vec2 rhs) { return lhs.x * rhs.x + lhs.y * rhs.y; } |
| 115 | ! | static inline float length(Vec2 v) { return std::sqrt(dot(v, v)); } |
| 116 | ! | static inline Vec2 normalize(Vec2 v) { float len = length(v); return Vec2{ v.x / len, v.y / len }; } |
| 117 | ||
| 118 | ||
| 119 | // | |
| 120 | // Vec3 type | |
| 121 | // | |
| 122 | ||
| 123 | struct Vec3 { | |
| 124 | float x, y, z; | |
| 125 | }; | |
| 126 | ||
| 127 | ! | static inline Vec3 operator - (Vec3 lhs, Vec3 rhs) { return Vec3{ lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z }; } |
| 128 | ||
| 129 | ! | static inline float dot(Vec3 lhs, Vec3 rhs) { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; } |
| 130 | ! | static inline float length(Vec3 v) { return std::sqrt(dot(v, v)); } |
| 131 | ! | static inline Vec3 normalize(Vec3 v) { float len = length(v); return Vec3{ v.x / len, v.y / len, v.z / len }; } |
| 132 | ! | static inline Vec3 cross(Vec3 lhs, Vec3 rhs) { return Vec3{ lhs.y * rhs.z - lhs.z * rhs.y, lhs.z * rhs.x - lhs.x * rhs.z, lhs.x * rhs.y - lhs.y * rhs.x }; } |
| 133 | ||
| 134 | ||
| 135 | // | |
| 136 | // Internal-only functions | |
| 137 | // | |
| 138 | ||
| 139 | ! | static inline bool is_whitespace(char ch) |
| 140 | { | |
| 141 | ! | return ch == ' ' || ch == '\t' || ch == '\r'; |
| 142 | } | |
| 143 | ||
| 144 | ||
| 145 | ! | static inline bool is_digit(char ch) |
| 146 | { | |
| 147 | ! | return ch >= '0' && ch <= '9'; |
| 148 | } | |
| 149 | ||
| 150 | ||
| 151 | ! | static inline bool is_letter(char ch) |
| 152 | { | |
| 153 | ! | ch |= 32; // upper and lower case letters differ only at this bit. |
| 154 | ! | return ch >= 'a' && ch <= 'z'; |
| 155 | } | |
| 156 | ||
| 157 | ||
| 158 | ! | static inline bool is_alnum(char ch) |
| 159 | { | |
| 160 | ! | return is_digit(ch) || is_letter(ch); |
| 161 | } | |
| 162 | ||
| 163 | ||
| 164 | ! | static inline bool is_keyword_start(char ch) |
| 165 | { | |
| 166 | ! | return is_letter(ch) || ch == '_'; |
| 167 | } | |
| 168 | ||
| 169 | ||
| 170 | ! | static inline bool is_keyword_part(char ch) |
| 171 | { | |
| 172 | ! | return is_alnum(ch) || ch == '_'; |
| 173 | } | |
| 174 | ||
| 175 | ||
| 176 | ! | static inline bool is_safe_buffer_end(char ch) |
| 177 | { | |
| 178 | ! | return (ch > 0 && ch <= 32) || (ch >= 127); |
| 179 | } | |
| 180 | ||
| 181 | ||
| 182 | ! | static int file_open(FILE** f, const char* filename, const char* mode) |
| 183 | { | |
| 184 | #ifdef _WIN32 | |
| 185 | return fopen_s(f, filename, mode); | |
| 186 | #else | |
| 187 | ! | *f = fopen(filename, mode); |
| 188 | ! | return (*f != nullptr) ? 0 : errno; |
| 189 | #endif | |
| 190 | } | |
| 191 | ||
| 192 | ||
| 193 | ! | static inline int file_seek(FILE* file, int64_t offset, int origin) |
| 194 | { | |
| 195 | #ifdef _WIN32 | |
| 196 | return _fseeki64(file, offset, origin); | |
| 197 | #else | |
| 198 | static_assert(sizeof(off_t) == sizeof(int64_t), "off_t is not 64 bits."); | |
| 199 | ! | return fseeko(file, offset, origin); |
| 200 | #endif | |
| 201 | } | |
| 202 | ||
| 203 | ||
| 204 | ! | static bool int_literal(const char* start, char const** end, int* val) |
| 205 | { | |
| 206 | ! | const char* pos = start; |
| 207 | ||
| 208 | ! | bool negative = false; |
| 209 | ! | if (*pos == '-') { |
| 210 | ! | negative = true; |
| 211 | ! | ++pos; |
| 212 | } | |
| 213 | ! | else if (*pos == '+') { |
| 214 | ! | ++pos; |
| 215 | } | |
| 216 | ||
| 217 | ! | bool hasLeadingZeroes = *pos == '0'; |
| 218 | ! | if (hasLeadingZeroes) { |
| 219 | do { | |
| 220 | ! | ++pos; |
| 221 | ! | } while (*pos == '0'); |
| 222 | } | |
| 223 | ||
| 224 | ! | int numDigits = 0; |
| 225 | ! | int localVal = 0; |
| 226 | ! | while (is_digit(*pos)) { |
| 227 | // FIXME: this will overflow if we get too many digits. | |
| 228 | ! | localVal = localVal * 10 + static_cast<int>(*pos - '0'); |
| 229 | ! | ++numDigits; |
| 230 | ! | ++pos; |
| 231 | } | |
| 232 | ||
| 233 | ! | if (numDigits == 0 && hasLeadingZeroes) { |
| 234 | ! | numDigits = 1; |
| 235 | } | |
| 236 | ||
| 237 | ! | if (numDigits == 0 || is_letter(*pos) || *pos == '_') { |
| 238 | ! | return false; |
| 239 | } | |
| 240 | ! | else if (numDigits > 10) { |
| 241 | // Overflow, literal value is larger than an int can hold. | |
| 242 | // FIXME: this won't catch *all* cases of overflow, make it exact. | |
| 243 | ! | return false; |
| 244 | } | |
| 245 | ||
| 246 | ! | if (val != nullptr) { |
| 247 | ! | *val = negative ? -localVal : localVal; |
| 248 | } | |
| 249 | ! | if (end != nullptr) { |
| 250 | ! | *end = pos; |
| 251 | } | |
| 252 | ! | return true; |
| 253 | } | |
| 254 | ||
| 255 | ||
| 256 | ! | static bool double_literal(const char* start, char const** end, double* val) |
| 257 | { | |
| 258 | ! | const char* pos = start; |
| 259 | ||
| 260 | ! | bool negative = false; |
| 261 | ! | if (*pos == '-') { |
| 262 | ! | negative = true; |
| 263 | ! | ++pos; |
| 264 | } | |
| 265 | ! | else if (*pos == '+') { |
| 266 | ! | ++pos; |
| 267 | } | |
| 268 | ||
| 269 | ! | double localVal = 0.0; |
| 270 | ||
| 271 | ! | bool hasIntDigits = is_digit(*pos); |
| 272 | ! | if (hasIntDigits) { |
| 273 | do { | |
| 274 | ! | localVal = localVal * 10.0 + kDoubleDigits[*pos - '0']; |
| 275 | ! | ++pos; |
| 276 | ! | } while (is_digit(*pos)); |
| 277 | } | |
| 278 | ! | else if (*pos != '.') { |
| 279 | // set_error("Not a floating point number"); | |
| 280 | ! | return false; |
| 281 | } | |
| 282 | ||
| 283 | ! | bool hasFracDigits = false; |
| 284 | ! | if (*pos == '.') { |
| 285 | ! | ++pos; |
| 286 | ! | hasFracDigits = is_digit(*pos); |
| 287 | ! | if (hasFracDigits) { |
| 288 | ! | double scale = 0.1; |
| 289 | do { | |
| 290 | ! | localVal += scale * kDoubleDigits[*pos - '0']; |
| 291 | ! | scale *= 0.1; |
| 292 | ! | ++pos; |
| 293 | ! | } while (is_digit(*pos)); |
| 294 | } | |
| 295 | ! | else if (!hasIntDigits) { |
| 296 | // set_error("Floating point number has no digits before or after the decimal point"); | |
| 297 | ! | return false; |
| 298 | } | |
| 299 | } | |
| 300 | ||
| 301 | ! | bool hasExponent = *pos == 'e' || *pos == 'E'; |
| 302 | ! | if (hasExponent) { |
| 303 | ! | ++pos; |
| 304 | ! | bool negativeExponent = false; |
| 305 | ! | if (*pos == '-') { |
| 306 | ! | negativeExponent = true; |
| 307 | ! | ++pos; |
| 308 | } | |
| 309 | ! | else if (*pos == '+') { |
| 310 | ! | ++pos; |
| 311 | } | |
| 312 | ||
| 313 | ! | if (!is_digit(*pos)) { |
| 314 | // set_error("Floating point exponent has no digits"); | |
| 315 | ! | return false; // error: exponent part has no digits. |
| 316 | } | |
| 317 | ||
| 318 | ! | double exponent = 0.0; |
| 319 | do { | |
| 320 | ! | exponent = exponent * 10.0 + kDoubleDigits[*pos - '0']; |
| 321 | ! | ++pos; |
| 322 | ! | } while (is_digit(*pos)); |
| 323 | ||
| 324 | ! | if (val != nullptr) { |
| 325 | ! | if (negativeExponent) { |
| 326 | ! | exponent = -exponent; |
| 327 | } | |
| 328 | ! | localVal *= std::pow(10.0, exponent); |
| 329 | } | |
| 330 | } | |
| 331 | ||
| 332 | ! | if (*pos == '.' || *pos == '_' || is_alnum(*pos)) { |
| 333 | // set_error("Floating point number has trailing chars"); | |
| 334 | ! | return false; |
| 335 | } | |
| 336 | ||
| 337 | ! | if (negative) { |
| 338 | ! | localVal = -localVal; |
| 339 | } | |
| 340 | ||
| 341 | ! | if (val != nullptr) { |
| 342 | ! | *val = localVal; |
| 343 | } | |
| 344 | ! | if (end != nullptr) { |
| 345 | ! | *end = pos; |
| 346 | } | |
| 347 | ! | return true; |
| 348 | } | |
| 349 | ||
| 350 | ||
| 351 | ! | static bool float_literal(const char* start, char const** end, float* val) |
| 352 | { | |
| 353 | ! | double tmp = 0.0; |
| 354 | ! | bool ok = double_literal(start, end, &tmp); |
| 355 | ! | if (ok && val != nullptr) { |
| 356 | ! | *val = static_cast<float>(tmp); |
| 357 | } | |
| 358 | ! | return ok; |
| 359 | } | |
| 360 | ||
| 361 | ||
| 362 | ! | static inline void endian_swap_2(uint8_t* data) |
| 363 | { | |
| 364 | ! | uint16_t tmp = *reinterpret_cast<uint16_t*>(data); |
| 365 | ! | tmp = static_cast<uint16_t>((tmp >> 8) | (tmp << 8)); |
| 366 | ! | *reinterpret_cast<uint16_t*>(data) = tmp; |
| 367 | } | |
| 368 | ||
| 369 | ||
| 370 | ! | static inline void endian_swap_4(uint8_t* data) |
| 371 | { | |
| 372 | ! | uint32_t tmp = *reinterpret_cast<uint32_t*>(data); |
| 373 | ! | tmp = (tmp >> 16) | (tmp << 16); |
| 374 | ! | tmp = ((tmp & 0xFF00FF00) >> 8) | ((tmp & 0x00FF00FF) << 8); |
| 375 | ! | *reinterpret_cast<uint32_t*>(data) = tmp; |
| 376 | } | |
| 377 | ||
| 378 | ||
| 379 | ! | static inline void endian_swap_8(uint8_t* data) |
| 380 | { | |
| 381 | ! | uint64_t tmp = *reinterpret_cast<uint64_t*>(data); |
| 382 | ! | tmp = (tmp >> 32) | (tmp << 32); |
| 383 | ! | tmp = ((tmp & 0xFFFF0000FFFF0000) >> 16) | ((tmp & 0x0000FFFF0000FFFF) << 16); |
| 384 | ! | tmp = ((tmp & 0xFF00FF00FF00FF00) >> 8) | ((tmp & 0x00FF00FF00FF00FF) << 8); |
| 385 | ! | *reinterpret_cast<uint64_t*>(data) = tmp; |
| 386 | } | |
| 387 | ||
| 388 | ||
| 389 | ! | static inline void endian_swap(uint8_t* data, PLYPropertyType type) |
| 390 | { | |
| 391 | ! | switch (kPLYPropertySize[uint32_t(type)]) { |
| 392 | ! | case 2: endian_swap_2(data); break; |
| 393 | ! | case 4: endian_swap_4(data); break; |
| 394 | ! | case 8: endian_swap_8(data); break; |
| 395 | ! | default: break; |
| 396 | } | |
| 397 | } | |
| 398 | ||
| 399 | ||
| 400 | ! | static inline void endian_swap_array(uint8_t* data, PLYPropertyType type, int n) |
| 401 | { | |
| 402 | ! | switch (kPLYPropertySize[uint32_t(type)]) { |
| 403 | ! | case 2: |
| 404 | ! | for (const uint8_t* end = data + 2 * n; data < end; data += 2) { |
| 405 | ! | endian_swap_2(data); |
| 406 | } | |
| 407 | ! | break; |
| 408 | ! | case 4: |
| 409 | ! | for (const uint8_t* end = data + 4 * n; data < end; data += 4) { |
| 410 | ! | endian_swap_4(data); |
| 411 | } | |
| 412 | ! | break; |
| 413 | ! | case 8: |
| 414 | ! | for (const uint8_t* end = data + 8 * n; data < end; data += 8) { |
| 415 | ! | endian_swap_8(data); |
| 416 | } | |
| 417 | ! | break; |
| 418 | ! | default: |
| 419 | ! | break; |
| 420 | } | |
| 421 | } | |
| 422 | ||
| 423 | ||
| 424 | template <class T> | |
| 425 | ! | static void copy_and_convert_to(T* dest, const uint8_t* src, PLYPropertyType srcType) |
| 426 | { | |
| 427 | ! | switch (srcType) { |
| 428 | ! | case PLYPropertyType::Char: *dest = static_cast<T>(*reinterpret_cast<const int8_t*>(src)); break; |
| 429 | ! | case PLYPropertyType::UChar: *dest = static_cast<T>(*reinterpret_cast<const uint8_t*>(src)); break; |
| 430 | ! | case PLYPropertyType::Short: *dest = static_cast<T>(*reinterpret_cast<const int16_t*>(src)); break; |
| 431 | ! | case PLYPropertyType::UShort: *dest = static_cast<T>(*reinterpret_cast<const uint16_t*>(src)); break; |
| 432 | ! | case PLYPropertyType::Int: *dest = static_cast<T>(*reinterpret_cast<const int*>(src)); break; |
| 433 | ! | case PLYPropertyType::UInt: *dest = static_cast<T>(*reinterpret_cast<const uint32_t*>(src)); break; |
| 434 | ! | case PLYPropertyType::Float: *dest = static_cast<T>(*reinterpret_cast<const float*>(src)); break; |
| 435 | ! | case PLYPropertyType::Double: *dest = static_cast<T>(*reinterpret_cast<const double*>(src)); break; |
| 436 | ! | case PLYPropertyType::None: break; |
| 437 | } | |
| 438 | } | |
| 439 | ||
| 440 | ||
| 441 | ! | static void copy_and_convert(uint8_t* dest, PLYPropertyType destType, const uint8_t* src, PLYPropertyType srcType) |
| 442 | { | |
| 443 | ! | switch (destType) { |
| 444 | ! | case PLYPropertyType::Char: copy_and_convert_to(reinterpret_cast<int8_t*> (dest), src, srcType); break; |
| 445 | ! | case PLYPropertyType::UChar: copy_and_convert_to(reinterpret_cast<uint8_t*> (dest), src, srcType); break; |
| 446 | ! | case PLYPropertyType::Short: copy_and_convert_to(reinterpret_cast<int16_t*> (dest), src, srcType); break; |
| 447 | ! | case PLYPropertyType::UShort: copy_and_convert_to(reinterpret_cast<uint16_t*>(dest), src, srcType); break; |
| 448 | ! | case PLYPropertyType::Int: copy_and_convert_to(reinterpret_cast<int32_t*> (dest), src, srcType); break; |
| 449 | ! | case PLYPropertyType::UInt: copy_and_convert_to(reinterpret_cast<uint32_t*>(dest), src, srcType); break; |
| 450 | ! | case PLYPropertyType::Float: copy_and_convert_to(reinterpret_cast<float*> (dest), src, srcType); break; |
| 451 | ! | case PLYPropertyType::Double: copy_and_convert_to(reinterpret_cast<double*> (dest), src, srcType); break; |
| 452 | ! | case PLYPropertyType::None: break; |
| 453 | } | |
| 454 | } | |
| 455 | ||
| 456 | ||
| 457 | ! | static inline bool compatible_types(PLYPropertyType srcType, PLYPropertyType destType) |
| 458 | { | |
| 459 | ! | return (srcType == destType) || |
| 460 | ! | (srcType < PLYPropertyType::Float && (uint32_t(srcType) ^ 0x1) == uint32_t(destType)); |
| 461 | } | |
| 462 | ||
| 463 | ||
| 464 | // | |
| 465 | // PLYElement methods | |
| 466 | // | |
| 467 | ||
| 468 | ! | void PLYElement::calculate_offsets() |
| 469 | { | |
| 470 | ! | fixedSize = true; |
| 471 | ! | for (PLYProperty& prop : properties) { |
| 472 | ! | if (prop.countType != PLYPropertyType::None) { |
| 473 | ! | fixedSize = false; |
| 474 | ! | break; |
| 475 | } | |
| 476 | } | |
| 477 | ||
| 478 | // Note that each list property gets its own separate storage. Only fixed | |
| 479 | // size properties go into the common data block. The `rowStride` is the | |
| 480 | // size of a row in the common data block. | |
| 481 | ! | rowStride = 0; |
| 482 | ! | for (PLYProperty& prop : properties) { |
| 483 | ! | if (prop.countType != PLYPropertyType::None) { |
| 484 | ! | continue; |
| 485 | } | |
| 486 | ! | prop.offset = rowStride; |
| 487 | ! | rowStride += kPLYPropertySize[uint32_t(prop.type)]; |
| 488 | } | |
| 489 | } | |
| 490 | ||
| 491 | ||
| 492 | ! | uint32_t PLYElement::find_property(const char *propName) const |
| 493 | { | |
| 494 | ! | for (uint32_t i = 0, endI = uint32_t(properties.size()); i < endI; i++) { |
| 495 | ! | if (strcmp(propName, properties.at(i).name.c_str()) == 0) { |
| 496 | ! | return i; |
| 497 | } | |
| 498 | } | |
| 499 | ! | return kInvalidIndex; |
| 500 | } | |
| 501 | ||
| 502 | ||
| 503 | ! | bool PLYElement::find_properties(uint32_t propIdxs[], uint32_t numIdxs, ...) const |
| 504 | { | |
| 505 | va_list args; | |
| 506 | ! | va_start(args, numIdxs); |
| 507 | ! | bool foundAll = find_properties_va(propIdxs, numIdxs, args); |
| 508 | ! | va_end(args); |
| 509 | ! | return foundAll; |
| 510 | } | |
| 511 | ||
| 512 | ||
| 513 | ! | bool PLYElement::find_properties_va(uint32_t propIdxs[], uint32_t numIdxs, va_list names) const |
| 514 | { | |
| 515 | ! | for (uint32_t i = 0; i < numIdxs; i++) { |
| 516 | ! | propIdxs[i] = find_property(va_arg(names, const char*)); |
| 517 | ! | if (propIdxs[i] == kInvalidIndex) { |
| 518 | ! | return false; |
| 519 | } | |
| 520 | } | |
| 521 | ! | return true; |
| 522 | } | |
| 523 | ||
| 524 | ||
| 525 | ! | bool PLYElement::convert_list_to_fixed_size(uint32_t listPropIdx, uint32_t listSize, uint32_t newPropIdxs[]) |
| 526 | { | |
| 527 | ! | if (fixedSize || listPropIdx >= properties.size() || properties[listPropIdx].countType == PLYPropertyType::None) { |
| 528 | ! | return false; |
| 529 | } | |
| 530 | ||
| 531 | ! | PLYProperty oldListProp = properties[listPropIdx]; |
| 532 | ||
| 533 | // If the generated names are less than 256 chars, we will use an array on | |
| 534 | // the stack as temporary storage. In the rare case that they're longer, | |
| 535 | // we'll allocate an array of sufficient size on the heap and use that | |
| 536 | // instead. This means we'll avoid allocating in all but the most extreme | |
| 537 | // cases. | |
| 538 | char inlineBuf[256]; | |
| 539 | ! | size_t nameBufSize = oldListProp.name.size() + 12; // the +12 allows space for an '_', a number up to 10 digits long and the terminating null. |
| 540 | ! | char* nameBuf = inlineBuf; |
| 541 | ! | if (nameBufSize > sizeof(inlineBuf)) { |
| 542 | ! | nameBuf = new char[nameBufSize]; |
| 543 | } | |
| 544 | ||
| 545 | // Set up a property for the list count column. | |
| 546 | ! | PLYProperty& countProp = properties[listPropIdx]; |
| 547 | ! | snprintf(nameBuf, nameBufSize, "%s_count", oldListProp.name.c_str()); |
| 548 | ! | countProp.name = nameBuf; |
| 549 | ! | countProp.type = oldListProp.countType; |
| 550 | ! | countProp.countType = PLYPropertyType::None; |
| 551 | ! | countProp.stride = kPLYPropertySize[uint32_t(oldListProp.countType)]; |
| 552 | ||
| 553 | ! | if (listSize > 0) { |
| 554 | // Set up additional properties for the list entries, 1 per entry. | |
| 555 | ! | if (listPropIdx + 1 == properties.size()) { |
| 556 | ! | properties.resize(properties.size() + listSize); |
| 557 | } | |
| 558 | else { | |
| 559 | ! | properties.insert(properties.begin() + listPropIdx + 1, listSize, PLYProperty()); |
| 560 | } | |
| 561 | ||
| 562 | ! | for (uint32_t i = 0; i < listSize; i++) { |
| 563 | ! | uint32_t propIdx = listPropIdx + 1 + i; |
| 564 | ||
| 565 | ! | PLYProperty& itemProp = properties[propIdx]; |
| 566 | ! | int ret = snprintf(nameBuf, nameBufSize, "%s_%u", oldListProp.name.c_str(), i); |
| 567 | ! | if(ret < 0) { |
| 568 | ! | throw std::runtime_error("just compile without warnings please (ignore this error)"); |
| 569 | } | |
| 570 | ! | itemProp.name = nameBuf; |
| 571 | ! | itemProp.type = oldListProp.type; |
| 572 | ! | itemProp.countType = PLYPropertyType::None; |
| 573 | ! | itemProp.stride = kPLYPropertySize[uint32_t(oldListProp.type)]; |
| 574 | ||
| 575 | ! | newPropIdxs[i] = propIdx; |
| 576 | } | |
| 577 | } | |
| 578 | ||
| 579 | ! | if (nameBuf != inlineBuf) { |
| 580 | ! | delete[] nameBuf; |
| 581 | } | |
| 582 | ||
| 583 | ! | calculate_offsets(); |
| 584 | ! | return true; |
| 585 | } | |
| 586 | ||
| 587 | ||
| 588 | // | |
| 589 | // PLYReader methods | |
| 590 | // | |
| 591 | ||
| 592 | ! | PLYReader::PLYReader(const char* filename) |
| 593 | { | |
| 594 | ! | m_buf = new char[kPLYReadBufferSize + 1]; |
| 595 | ! | m_buf[kPLYReadBufferSize] = '\0'; |
| 596 | ||
| 597 | ! | m_tmpBuf = new char[kPLYTempBufferSize + 1]; |
| 598 | ! | m_tmpBuf[kPLYTempBufferSize] = '\0'; |
| 599 | ||
| 600 | ! | m_bufEnd = m_buf + kPLYReadBufferSize; |
| 601 | ! | m_pos = m_bufEnd; |
| 602 | ! | m_end = m_bufEnd; |
| 603 | ||
| 604 | ! | if (file_open(&m_f, filename, "rb") != 0) { |
| 605 | ! | m_f = nullptr; |
| 606 | ! | m_valid = false; |
| 607 | ! | return; |
| 608 | } | |
| 609 | ! | m_valid = true; |
| 610 | ||
| 611 | ! | refill_buffer(); |
| 612 | ||
| 613 | ! | m_valid = keyword("ply") && next_line() && |
| 614 | ! | keyword("format") && advance() && |
| 615 | ! | typed_which(kPLYFileTypes, &m_fileType) && advance() && |
| 616 | ! | int_literal(&m_majorVersion) && advance() && |
| 617 | ! | match(".") && advance() && |
| 618 | ! | int_literal(&m_minorVersion) && next_line() && |
| 619 | ! | parse_elements() && |
| 620 | ! | keyword("end_header") && advance() && match("\n") && accept(); |
| 621 | ! | if (!m_valid) { |
| 622 | ! | return; |
| 623 | } | |
| 624 | ! | m_inDataSection = true; |
| 625 | ! | if (m_fileType == PLYFileType::ASCII) { |
| 626 | ! | advance(); |
| 627 | } | |
| 628 | ||
| 629 | ! | for (PLYElement& elem : m_elements) { |
| 630 | ! | elem.calculate_offsets(); |
| 631 | } | |
| 632 | } | |
| 633 | ||
| 634 | ||
| 635 | ! | PLYReader::~PLYReader() |
| 636 | { | |
| 637 | ! | if (m_f != nullptr) { |
| 638 | ! | fclose(m_f); |
| 639 | } | |
| 640 | ! | delete[] m_buf; |
| 641 | ! | delete[] m_tmpBuf; |
| 642 | } | |
| 643 | ||
| 644 | ||
| 645 | ! | bool PLYReader::valid() const |
| 646 | { | |
| 647 | ! | return m_valid; |
| 648 | } | |
| 649 | ||
| 650 | ||
| 651 | ! | bool PLYReader::has_element() const |
| 652 | { | |
| 653 | ! | return m_valid && m_currentElement < m_elements.size(); |
| 654 | } | |
| 655 | ||
| 656 | ||
| 657 | ! | const PLYElement* PLYReader::element() const |
| 658 | { | |
| 659 | assert(has_element()); | |
| 660 | ! | return &m_elements[m_currentElement]; |
| 661 | } | |
| 662 | ||
| 663 | ||
| 664 | ! | bool PLYReader::load_element() |
| 665 | { | |
| 666 | assert(has_element()); | |
| 667 | ! | if (m_elementLoaded) { |
| 668 | ! | return true; |
| 669 | } | |
| 670 | ||
| 671 | ! | PLYElement& elem = m_elements[m_currentElement]; |
| 672 | ! | return elem.fixedSize ? load_fixed_size_element(elem) : load_variable_size_element(elem); |
| 673 | } | |
| 674 | ||
| 675 | ||
| 676 | ! | void PLYReader::next_element() |
| 677 | { | |
| 678 | ! | if (!has_element()) { |
| 679 | ! | return; |
| 680 | } | |
| 681 | ||
| 682 | // If the element was loaded, the read buffer should already be positioned at | |
| 683 | // the start of the next element. | |
| 684 | ! | PLYElement& elem = m_elements[m_currentElement]; |
| 685 | ! | m_currentElement++; |
| 686 | ||
| 687 | ! | if (m_elementLoaded) { |
| 688 | // Clear any temporary storage used for list properties in the current element. | |
| 689 | ! | for (PLYProperty& prop : elem.properties) { |
| 690 | ! | if (prop.countType == PLYPropertyType::None) { |
| 691 | ! | continue; |
| 692 | } | |
| 693 | ! | prop.listData.clear(); |
| 694 | ! | prop.listData.shrink_to_fit(); |
| 695 | ! | prop.rowCount.clear(); |
| 696 | ! | prop.rowCount.shrink_to_fit(); |
| 697 | } | |
| 698 | ||
| 699 | // Clear temporary storage for the non-list properties in the current element. | |
| 700 | ! | m_elementData.clear(); |
| 701 | ! | m_elementLoaded = false; |
| 702 | ! | return; |
| 703 | } | |
| 704 | ||
| 705 | // If the element wasn't loaded, we have to move the file pointer past its | |
| 706 | // contents. How we do that depends on whether this is an ASCII or binary | |
| 707 | // file and, if it's a binary, whether the element is fixed or variable | |
| 708 | // size. | |
| 709 | ! | if (m_fileType == PLYFileType::ASCII) { |
| 710 | ! | for (uint32_t row = 0; row < elem.count; row++) { |
| 711 | ! | next_line(); |
| 712 | } | |
| 713 | } | |
| 714 | ! | else if (elem.fixedSize) { |
| 715 | ! | int64_t elementStart = static_cast<int64_t>(m_pos - m_buf); |
| 716 | ! | int64_t elementSize = elem.rowStride * elem.count; |
| 717 | ! | int64_t elementEnd = elementStart + elementSize; |
| 718 | ! | if (elementEnd >= kPLYReadBufferSize) { |
| 719 | ! | m_bufOffset += elementEnd; |
| 720 | ! | file_seek(m_f, m_bufOffset, SEEK_SET); |
| 721 | ! | m_bufEnd = m_buf + kPLYReadBufferSize; |
| 722 | ! | m_pos = m_bufEnd; |
| 723 | ! | m_end = m_bufEnd; |
| 724 | ! | refill_buffer(); |
| 725 | } | |
| 726 | else { | |
| 727 | ! | m_pos = m_buf + elementEnd; |
| 728 | ! | m_end = m_pos; |
| 729 | } | |
| 730 | } | |
| 731 | ! | else if (m_fileType == PLYFileType::Binary) { |
| 732 | ! | for (uint32_t row = 0; row < elem.count; row++) { |
| 733 | ! | for (const PLYProperty& prop : elem.properties) { |
| 734 | ! | if (prop.countType == PLYPropertyType::None) { |
| 735 | ! | uint32_t numBytes = kPLYPropertySize[uint32_t(prop.type)]; |
| 736 | ! | if (m_pos + numBytes > m_bufEnd) { |
| 737 | ! | if (!refill_buffer() || m_pos + numBytes > m_bufEnd) { |
| 738 | ! | m_valid = false; |
| 739 | ! | return; |
| 740 | } | |
| 741 | } | |
| 742 | ! | m_pos += numBytes; |
| 743 | ! | m_end = m_pos; |
| 744 | ! | continue; |
| 745 | } | |
| 746 | ||
| 747 | ! | uint32_t numBytes = kPLYPropertySize[uint32_t(prop.countType)]; |
| 748 | ! | if (m_pos + numBytes > m_bufEnd) { |
| 749 | ! | if (!refill_buffer() || m_pos + numBytes > m_bufEnd) { |
| 750 | ! | m_valid = false; |
| 751 | ! | return; |
| 752 | } | |
| 753 | } | |
| 754 | ||
| 755 | ! | int count = 0; |
| 756 | ! | copy_and_convert_to(&count, reinterpret_cast<const uint8_t*>(m_pos), prop.countType); |
| 757 | ||
| 758 | ! | if (count < 0) { |
| 759 | ! | m_valid = false; |
| 760 | ! | return; |
| 761 | } | |
| 762 | ||
| 763 | ! | numBytes += uint32_t(count) * kPLYPropertySize[uint32_t(prop.type)]; |
| 764 | ! | if (m_pos + numBytes > m_bufEnd) { |
| 765 | ! | if (!refill_buffer() || m_pos + numBytes > m_bufEnd) { |
| 766 | ! | m_valid = false; |
| 767 | ! | return; |
| 768 | } | |
| 769 | } | |
| 770 | ! | m_pos += numBytes; |
| 771 | ! | m_end = m_pos; |
| 772 | } | |
| 773 | } | |
| 774 | } | |
| 775 | else { // PLYFileType::BinaryBigEndian | |
| 776 | ! | for (uint32_t row = 0; row < elem.count; row++) { |
| 777 | ! | for (const PLYProperty& prop : elem.properties) { |
| 778 | ! | if (prop.countType == PLYPropertyType::None) { |
| 779 | ! | uint32_t numBytes = kPLYPropertySize[uint32_t(prop.type)]; |
| 780 | ! | if (m_pos + numBytes > m_bufEnd) { |
| 781 | ! | if (!refill_buffer() || m_pos + numBytes > m_bufEnd) { |
| 782 | ! | m_valid = false; |
| 783 | ! | return; |
| 784 | } | |
| 785 | } | |
| 786 | ! | m_pos += numBytes; |
| 787 | ! | m_end = m_pos; |
| 788 | ! | continue; |
| 789 | } | |
| 790 | ||
| 791 | ! | uint32_t numBytes = kPLYPropertySize[uint32_t(prop.countType)]; |
| 792 | ! | if (m_pos + numBytes > m_bufEnd) { |
| 793 | ! | if (!refill_buffer() || m_pos + numBytes > m_bufEnd) { |
| 794 | ! | m_valid = false; |
| 795 | ! | return; |
| 796 | } | |
| 797 | } | |
| 798 | ||
| 799 | ! | int count = 0; |
| 800 | uint8_t tmp[8]; | |
| 801 | ! | memcpy(tmp, m_pos, numBytes); |
| 802 | ! | endian_swap(tmp, prop.countType); |
| 803 | ! | copy_and_convert_to(&count, tmp, prop.countType); |
| 804 | ||
| 805 | ! | if (count < 0) { |
| 806 | ! | m_valid = false; |
| 807 | ! | return; |
| 808 | } | |
| 809 | ||
| 810 | ! | numBytes += uint32_t(count) * kPLYPropertySize[uint32_t(prop.type)]; |
| 811 | ! | if (m_pos + numBytes > m_bufEnd) { |
| 812 | ! | if (!refill_buffer() || m_pos + numBytes > m_bufEnd) { |
| 813 | ! | m_valid = false; |
| 814 | ! | return; |
| 815 | } | |
| 816 | } | |
| 817 | ||
| 818 | ! | m_pos += numBytes; |
| 819 | ! | m_end = m_pos; |
| 820 | } | |
| 821 | } | |
| 822 | } | |
| 823 | } | |
| 824 | ||
| 825 | ||
| 826 | ! | PLYFileType PLYReader::file_type() const |
| 827 | { | |
| 828 | ! | return m_fileType; |
| 829 | } | |
| 830 | ||
| 831 | ||
| 832 | ! | int PLYReader::version_major() const |
| 833 | { | |
| 834 | ! | return m_majorVersion; |
| 835 | } | |
| 836 | ||
| 837 | ||
| 838 | ! | int PLYReader::version_minor() const |
| 839 | { | |
| 840 | ! | return m_minorVersion; |
| 841 | } | |
| 842 | ||
| 843 | ||
| 844 | ! | uint32_t PLYReader::num_elements() const |
| 845 | { | |
| 846 | ! | return m_valid ? static_cast<uint32_t>(m_elements.size()) : 0; |
| 847 | } | |
| 848 | ||
| 849 | ||
| 850 | ! | uint32_t PLYReader::find_element(const char* name) const |
| 851 | { | |
| 852 | ! | for (uint32_t i = 0, endI = num_elements(); i < endI; i++) { |
| 853 | ! | const PLYElement& elem = m_elements[i]; |
| 854 | ! | if (strcmp(elem.name.c_str(), name) == 0) { |
| 855 | ! | return i; |
| 856 | } | |
| 857 | } | |
| 858 | ! | return kInvalidIndex; |
| 859 | } | |
| 860 | ||
| 861 | ||
| 862 | ! | PLYElement* PLYReader::get_element(uint32_t idx) |
| 863 | { | |
| 864 | ! | return (idx < num_elements()) ? &m_elements[idx] : nullptr; |
| 865 | } | |
| 866 | ||
| 867 | ||
| 868 | ! | bool PLYReader::element_is(const char* name) const |
| 869 | { | |
| 870 | ! | return has_element() && strcmp(element()->name.c_str(), name) == 0; |
| 871 | } | |
| 872 | ||
| 873 | ||
| 874 | ! | uint32_t PLYReader::num_rows() const |
| 875 | { | |
| 876 | ! | return has_element() ? element()->count : 0; |
| 877 | } | |
| 878 | ||
| 879 | ||
| 880 | ! | uint32_t PLYReader::find_property(const char* name) const |
| 881 | { | |
| 882 | ! | return has_element() ? element()->find_property(name) : kInvalidIndex; |
| 883 | } | |
| 884 | ||
| 885 | ||
| 886 | ! | bool PLYReader::find_properties(uint32_t propIdxs[], uint32_t numIdxs, ...) const |
| 887 | { | |
| 888 | ! | if (!has_element()) { |
| 889 | ! | return false; |
| 890 | } | |
| 891 | va_list args; | |
| 892 | ! | va_start(args, numIdxs); |
| 893 | ! | bool foundAll = element()->find_properties_va(propIdxs, numIdxs, args); |
| 894 | ! | va_end(args); |
| 895 | ! | return foundAll; |
| 896 | } | |
| 897 | ||
| 898 | ||
| 899 | ! | bool PLYReader::extract_properties(const uint32_t propIdxs[], uint32_t numProps, PLYPropertyType destType, void *dest) const |
| 900 | { | |
| 901 | ! | if (numProps == 0) { |
| 902 | ! | return false; |
| 903 | } | |
| 904 | ||
| 905 | ! | const PLYElement* elem = element(); |
| 906 | ||
| 907 | // Make sure all property indexes are valid and that none of the properties | |
| 908 | // are lists (this function only extracts non-list data). | |
| 909 | ! | for (uint32_t i = 0; i < numProps; i++) { |
| 910 | ! | if (propIdxs[i] >= elem->properties.size()) { |
| 911 | ! | return false; |
| 912 | } | |
| 913 | } | |
| 914 | ||
| 915 | // Find out whether we have contiguous columns. If so, we may be able to | |
| 916 | // use a more efficient data extraction technique. | |
| 917 | ! | bool contiguousCols = true; |
| 918 | ! | uint32_t expectedOffset = elem->properties[propIdxs[0]].offset; |
| 919 | ! | for (uint32_t i = 0; i < numProps; i++) { |
| 920 | ! | uint32_t propIdx = propIdxs[i]; |
| 921 | ! | const PLYProperty& prop = elem->properties[propIdx]; |
| 922 | ! | if (prop.offset != expectedOffset) { |
| 923 | ! | contiguousCols = false; |
| 924 | ! | break; |
| 925 | } | |
| 926 | ! | expectedOffset = prop.offset + kPLYPropertySize[uint32_t(prop.type)]; |
| 927 | } | |
| 928 | ||
| 929 | // If the row we're extracting is contiguous in memory (i.e. there are no | |
| 930 | // gaps anywhere in a row - start, end or middle), we can use an even MORE | |
| 931 | // efficient data extraction technique. | |
| 932 | ! | bool contiguousRows = contiguousCols && |
| 933 | ! | (elem->properties[propIdxs[0]].offset == 0) && |
| 934 | ! | (expectedOffset == elem->rowStride); |
| 935 | ||
| 936 | // If no data conversion is required, we can memcpy chunks of data | |
| 937 | // directly over to `dest`. How big those chunks will be depends on whether | |
| 938 | // the columns and/or rows are contiguous, as determined above. | |
| 939 | ! | bool conversionRequired = false; |
| 940 | ! | for (uint32_t i = 0; i < numProps; i++) { |
| 941 | ! | uint32_t propIdx = propIdxs[i]; |
| 942 | ! | const PLYProperty& prop = elem->properties[propIdx]; |
| 943 | ! | if (!compatible_types(prop.type, destType)) { |
| 944 | ! | conversionRequired = true; |
| 945 | ! | break; |
| 946 | } | |
| 947 | } | |
| 948 | ||
| 949 | ! | uint8_t* to = reinterpret_cast<uint8_t*>(dest); |
| 950 | ! | if (!conversionRequired) { |
| 951 | // If no data conversion is required, we can just use memcpy to get | |
| 952 | // values into dest. | |
| 953 | ! | if (contiguousRows) { |
| 954 | // Most efficient case is when the rows are contiguous. It means we're | |
| 955 | // simply copying the entire data block for this element, which we can | |
| 956 | // do with a single memcpy. | |
| 957 | ! | std::memcpy(to, m_elementData.data(), m_elementData.size()); |
| 958 | } | |
| 959 | ! | else if (contiguousCols) { |
| 960 | // If the rows aren't contiguous, but the columns we're extracting | |
| 961 | // within each row are, then we can do a single memcpy per row. | |
| 962 | ! | const uint8_t* from = m_elementData.data() + elem->properties[propIdxs[0]].offset; |
| 963 | ! | const uint8_t* end = m_elementData.data() + m_elementData.size(); |
| 964 | ! | const size_t numBytes = expectedOffset - elem->properties[propIdxs[0]].offset; |
| 965 | ! | while (from < end) { |
| 966 | ! | std::memcpy(to, from, numBytes); |
| 967 | ! | from += elem->rowStride; |
| 968 | ! | to += numBytes; |
| 969 | } | |
| 970 | } | |
| 971 | else { | |
| 972 | // If the columns aren't contiguous, we must memcpy each one separately. | |
| 973 | ! | const uint8_t* row = m_elementData.data(); |
| 974 | ! | const uint8_t* end = m_elementData.data() + m_elementData.size(); |
| 975 | ! | uint8_t* to = reinterpret_cast<uint8_t*>(dest); |
| 976 | ! | size_t colBytes = kPLYPropertySize[uint32_t(destType)]; // size of an output column in bytes. |
| 977 | ! | while (row < end) { |
| 978 | ! | for (uint32_t i = 0; i < numProps; i++) { |
| 979 | ! | uint32_t propIdx = propIdxs[i]; |
| 980 | ! | const PLYProperty& prop = elem->properties[propIdx]; |
| 981 | ! | std::memcpy(to, row + prop.offset, colBytes); |
| 982 | ! | to += colBytes; |
| 983 | } | |
| 984 | ! | row += elem->rowStride; |
| 985 | } | |
| 986 | } | |
| 987 | } | |
| 988 | else { | |
| 989 | // We will have to do data type conversions on the column values here. We | |
| 990 | // cannot simply use memcpy in this case, every column has to be | |
| 991 | // processed separately. | |
| 992 | ! | const uint8_t* row = m_elementData.data(); |
| 993 | ! | const uint8_t* end = m_elementData.data() + m_elementData.size(); |
| 994 | ! | uint8_t* to = reinterpret_cast<uint8_t*>(dest); |
| 995 | ! | size_t colBytes = kPLYPropertySize[uint32_t(destType)]; // size of an output column in bytes. |
| 996 | ! | while (row < end) { |
| 997 | ! | for (uint32_t i = 0; i < numProps; i++) { |
| 998 | ! | uint32_t propIdx = propIdxs[i]; |
| 999 | ! | const PLYProperty& prop = elem->properties[propIdx]; |
| 1000 | ! | copy_and_convert(to, destType, row + prop.offset, prop.type); |
| 1001 | ! | to += colBytes; |
| 1002 | } | |
| 1003 | ! | row += elem->rowStride; |
| 1004 | } | |
| 1005 | } | |
| 1006 | ||
| 1007 | ! | return true; |
| 1008 | } | |
| 1009 | ||
| 1010 | ||
| 1011 | ! | const uint32_t* PLYReader::get_list_counts(uint32_t propIdx) const |
| 1012 | { | |
| 1013 | ! | if (!has_element() || propIdx >= element()->properties.size() || element()->properties[propIdx].countType == PLYPropertyType::None) { |
| 1014 | ! | return nullptr; |
| 1015 | } | |
| 1016 | ! | return element()->properties[propIdx].rowCount.data(); |
| 1017 | } | |
| 1018 | ||
| 1019 | ||
| 1020 | ! | uint32_t PLYReader::sum_of_list_counts(uint32_t propIdx) const |
| 1021 | { | |
| 1022 | ! | if (!has_element() || propIdx >= element()->properties.size() || element()->properties[propIdx].countType == PLYPropertyType::None) { |
| 1023 | ! | return 0; |
| 1024 | } | |
| 1025 | ! | const PLYProperty& prop = element()->properties[propIdx]; |
| 1026 | ! | return prop.listData.size() / kPLYPropertySize[uint32_t(prop.type)]; |
| 1027 | } | |
| 1028 | ||
| 1029 | ||
| 1030 | ! | const uint8_t* PLYReader::get_list_data(uint32_t propIdx) const |
| 1031 | { | |
| 1032 | ! | if (!has_element() || propIdx >= element()->properties.size() || element()->properties[propIdx].countType == PLYPropertyType::None) { |
| 1033 | ! | return nullptr; |
| 1034 | } | |
| 1035 | ! | return element()->properties[propIdx].listData.data(); |
| 1036 | } | |
| 1037 | ||
| 1038 | ||
| 1039 | ! | bool PLYReader::extract_list_property(uint32_t propIdx, PLYPropertyType destType, void *dest) const |
| 1040 | { | |
| 1041 | ! | if (!has_element() || propIdx >= element()->properties.size() || element()->properties[propIdx].countType == PLYPropertyType::None) { |
| 1042 | ! | return false; |
| 1043 | } | |
| 1044 | ||
| 1045 | ! | const PLYProperty& prop = element()->properties[propIdx]; |
| 1046 | ! | if (compatible_types(prop.type, destType)) { |
| 1047 | // If no type conversion is required, we can just copy the list data | |
| 1048 | // directly over with a single memcpy. | |
| 1049 | ! | std::memcpy(dest, prop.listData.data(), prop.listData.size()); |
| 1050 | } | |
| 1051 | else { | |
| 1052 | // If type conversion is required we'll have to process each list value separately. | |
| 1053 | ! | const uint8_t* from = prop.listData.data(); |
| 1054 | ! | const uint8_t* end = prop.listData.data() + prop.listData.size(); |
| 1055 | ! | uint8_t* to = reinterpret_cast<uint8_t*>(dest); |
| 1056 | ! | const size_t toBytes = kPLYPropertySize[uint32_t(destType)]; |
| 1057 | ! | const size_t fromBytes = kPLYPropertySize[uint32_t(prop.type)]; |
| 1058 | ! | while (from < end) { |
| 1059 | ! | copy_and_convert(to, destType, from, prop.type); |
| 1060 | ! | to += toBytes; |
| 1061 | ! | from += fromBytes; |
| 1062 | } | |
| 1063 | } | |
| 1064 | ||
| 1065 | ! | return true; |
| 1066 | } | |
| 1067 | ||
| 1068 | ||
| 1069 | ! | uint32_t PLYReader::num_triangles(uint32_t propIdx) const |
| 1070 | { | |
| 1071 | ! | const uint32_t* counts = get_list_counts(propIdx); |
| 1072 | ! | if (counts == nullptr) { |
| 1073 | ! | return 0; |
| 1074 | } | |
| 1075 | ||
| 1076 | ! | const uint32_t numRows = element()->count; |
| 1077 | ! | uint32_t num = 0; |
| 1078 | ! | for (uint32_t i = 0; i < numRows; i++) { |
| 1079 | ! | if (counts[i] >= 3) { |
| 1080 | ! | num += counts[i] - 2; |
| 1081 | } | |
| 1082 | } | |
| 1083 | ! | return num; |
| 1084 | } | |
| 1085 | ||
| 1086 | ||
| 1087 | ! | bool PLYReader::requires_triangulation(uint32_t propIdx) const |
| 1088 | { | |
| 1089 | ! | const uint32_t* counts = get_list_counts(propIdx); |
| 1090 | ! | if (counts == nullptr) { |
| 1091 | ! | return false; |
| 1092 | } | |
| 1093 | ||
| 1094 | ! | const uint32_t numRows = element()->count; |
| 1095 | ! | for (uint32_t i = 0; i < numRows; i++) { |
| 1096 | ! | if (counts[i] != 3) { |
| 1097 | ! | return true; |
| 1098 | } | |
| 1099 | } | |
| 1100 | ! | return false; |
| 1101 | } | |
| 1102 | ||
| 1103 | ||
| 1104 | ! | bool PLYReader::extract_triangles(uint32_t propIdx, const float pos[], uint32_t numVerts, PLYPropertyType destType, void *dest) const |
| 1105 | { | |
| 1106 | ! | if (!requires_triangulation(propIdx)) { |
| 1107 | ! | return extract_list_property(propIdx, destType, dest); |
| 1108 | } | |
| 1109 | ||
| 1110 | ! | const PLYElement* elem = element(); |
| 1111 | ! | const PLYProperty& prop = elem->properties[propIdx]; |
| 1112 | ||
| 1113 | ! | const uint32_t* counts = prop.rowCount.data(); |
| 1114 | ! | const uint8_t* data = prop.listData.data(); |
| 1115 | ||
| 1116 | ! | uint8_t* to = reinterpret_cast<uint8_t*>(dest); |
| 1117 | ||
| 1118 | ! | bool convertSrc = !compatible_types(elem->properties[propIdx].type, PLYPropertyType::Int); |
| 1119 | ! | bool convertDst = !compatible_types(PLYPropertyType::Int, destType); |
| 1120 | ||
| 1121 | ! | size_t srcValBytes = kPLYPropertySize[uint32_t(prop.type)]; |
| 1122 | ! | size_t destValBytes = kPLYPropertySize[uint32_t(destType)]; |
| 1123 | ||
| 1124 | ! | if (convertSrc && convertDst) { |
| 1125 | ! | std::vector<int> faceIndices, triIndices; |
| 1126 | ! | faceIndices.reserve(32); |
| 1127 | ! | triIndices.reserve(64); |
| 1128 | ! | const uint8_t* face = data; |
| 1129 | ! | for (uint32_t faceIdx = 0; faceIdx < elem->count; faceIdx++) { |
| 1130 | ! | const uint8_t* faceEnd = face + srcValBytes * counts[faceIdx]; |
| 1131 | ! | faceIndices.clear(); |
| 1132 | ! | faceIndices.reserve(counts[faceIdx]); |
| 1133 | ! | for (; face < faceEnd; face += srcValBytes) { |
| 1134 | ! | int idx = -1; |
| 1135 | ! | copy_and_convert_to(&idx, face, prop.type); |
| 1136 | ! | faceIndices.push_back(idx); |
| 1137 | } | |
| 1138 | ||
| 1139 | ! | triIndices.resize((counts[faceIdx] - 2) * 3); |
| 1140 | ! | triangulate_polygon(counts[faceIdx], pos, numVerts, faceIndices.data(), triIndices.data()); |
| 1141 | ! | for (int idx : triIndices) { |
| 1142 | ! | copy_and_convert(to, destType, reinterpret_cast<const uint8_t*>(&idx), PLYPropertyType::Int); |
| 1143 | ! | to += destValBytes; |
| 1144 | } | |
| 1145 | } | |
| 1146 | } | |
| 1147 | ! | else if (convertSrc) { |
| 1148 | ! | std::vector<int> faceIndices; |
| 1149 | ! | faceIndices.reserve(32); |
| 1150 | ! | const uint8_t* face = data; |
| 1151 | ! | for (uint32_t faceIdx = 0; faceIdx < elem->count; faceIdx++) { |
| 1152 | ! | const uint8_t* faceEnd = face + srcValBytes * counts[faceIdx]; |
| 1153 | ! | faceIndices.clear(); |
| 1154 | ! | faceIndices.reserve(counts[faceIdx]); |
| 1155 | ! | for (; face < faceEnd; face += srcValBytes) { |
| 1156 | ! | int idx = -1; |
| 1157 | ! | copy_and_convert_to(&idx, face, prop.type); |
| 1158 | ! | faceIndices.push_back(idx); |
| 1159 | } | |
| 1160 | ||
| 1161 | ! | uint32_t numTris = triangulate_polygon(counts[faceIdx], pos, numVerts, faceIndices.data(), reinterpret_cast<int*>(to)); |
| 1162 | ! | to += numTris * 3 * destValBytes; |
| 1163 | } | |
| 1164 | } | |
| 1165 | ! | else if (convertDst) { |
| 1166 | ! | std::vector<int> triIndices; |
| 1167 | ! | triIndices.reserve(64); |
| 1168 | ! | const uint8_t* face = data; |
| 1169 | ! | for (uint32_t faceIdx = 0; faceIdx < elem->count; faceIdx++) { |
| 1170 | ! | triIndices.resize((counts[faceIdx] - 2) * 3); |
| 1171 | ! | triangulate_polygon(counts[faceIdx], pos, numVerts, reinterpret_cast<const int*>(face), triIndices.data()); |
| 1172 | ! | for (int idx : triIndices) { |
| 1173 | ! | copy_and_convert(to, destType, reinterpret_cast<const uint8_t*>(&idx), PLYPropertyType::Int); |
| 1174 | ! | to += destValBytes; |
| 1175 | } | |
| 1176 | ! | face += srcValBytes * counts[faceIdx]; |
| 1177 | } | |
| 1178 | } | |
| 1179 | else { | |
| 1180 | ! | const uint8_t* face = data; |
| 1181 | ! | for (uint32_t faceIdx = 0; faceIdx < elem->count; faceIdx++) { |
| 1182 | ! | uint32_t numTris = triangulate_polygon(counts[faceIdx], pos, numVerts, reinterpret_cast<const int*>(face), reinterpret_cast<int*>(to)); |
| 1183 | ! | face += counts[faceIdx] * srcValBytes; |
| 1184 | ! | to += numTris * 3 * destValBytes; |
| 1185 | } | |
| 1186 | } | |
| 1187 | ||
| 1188 | ! | return true; |
| 1189 | } | |
| 1190 | ||
| 1191 | ||
| 1192 | ! | bool PLYReader::find_pos(uint32_t propIdxs[3]) const |
| 1193 | { | |
| 1194 | ! | return find_properties(propIdxs, 3, "x", "y", "z"); |
| 1195 | } | |
| 1196 | ||
| 1197 | ||
| 1198 | ! | bool PLYReader::find_normal(uint32_t propIdxs[3]) const |
| 1199 | { | |
| 1200 | ! | return find_properties(propIdxs, 3, "nx", "ny", "nz"); |
| 1201 | } | |
| 1202 | ||
| 1203 | ||
| 1204 | ! | bool PLYReader::find_texcoord(uint32_t propIdxs[2]) const |
| 1205 | { | |
| 1206 | ! | return find_properties(propIdxs, 2, "u", "v") || |
| 1207 | ! | find_properties(propIdxs, 2, "s", "t") || |
| 1208 | ! | find_properties(propIdxs, 2, "texture_u", "texture_v") || |
| 1209 | ! | find_properties(propIdxs, 2, "texture_s", "texture_t"); |
| 1210 | } | |
| 1211 | ||
| 1212 | ||
| 1213 | ! | bool PLYReader::find_color(uint32_t propIdxs[3]) const |
| 1214 | { | |
| 1215 | ! | return find_properties(propIdxs, 3, "r", "g", "b"); |
| 1216 | } | |
| 1217 | ||
| 1218 | ||
| 1219 | ! | bool PLYReader::find_indices(uint32_t propIdxs[1]) const |
| 1220 | { | |
| 1221 | ! | return find_properties(propIdxs, 1, "vertex_index") || find_properties(propIdxs, 1, "vertex_indices"); |
| 1222 | } | |
| 1223 | ||
| 1224 | ||
| 1225 | // | |
| 1226 | // PLYReader private methods | |
| 1227 | // | |
| 1228 | ||
| 1229 | ! | bool PLYReader::refill_buffer() |
| 1230 | { | |
| 1231 | ! | if (m_f == nullptr || m_atEOF) { |
| 1232 | // Nothing left to read. | |
| 1233 | ! | return false; |
| 1234 | } | |
| 1235 | ||
| 1236 | ! | if (m_pos == m_buf && m_end == m_bufEnd) { |
| 1237 | // Can't make any more room in the buffer! | |
| 1238 | ! | return false; |
| 1239 | } | |
| 1240 | ||
| 1241 | // Move everything from the start of the current token onwards, to the | |
| 1242 | // start of the read buffer. | |
| 1243 | ! | int64_t bufSize = static_cast<int64_t>(m_bufEnd - m_buf); |
| 1244 | ! | if (bufSize < kPLYReadBufferSize) { |
| 1245 | ! | m_buf[bufSize] = m_buf[kPLYReadBufferSize]; |
| 1246 | ! | m_buf[kPLYReadBufferSize] = '\0'; |
| 1247 | ! | m_bufEnd = m_buf + kPLYReadBufferSize; |
| 1248 | } | |
| 1249 | ! | size_t keep = static_cast<size_t>(m_bufEnd - m_pos); |
| 1250 | ! | if (keep > 0 && m_pos > m_buf) { |
| 1251 | ! | std::memmove(m_buf, m_pos, sizeof(char) * keep); |
| 1252 | ! | m_bufOffset += static_cast<int64_t>(m_pos - m_buf); |
| 1253 | } | |
| 1254 | ! | m_end = m_buf + (m_end - m_pos); |
| 1255 | ! | m_pos = m_buf; |
| 1256 | ||
| 1257 | // Fill the remaining space in the buffer with data from the file. | |
| 1258 | ! | size_t fetched = fread(m_buf + keep, sizeof(char), kPLYReadBufferSize - keep, m_f) + keep; |
| 1259 | ! | m_atEOF = fetched < kPLYReadBufferSize; |
| 1260 | ! | m_bufEnd = m_buf + fetched; |
| 1261 | ||
| 1262 | ! | if (!m_inDataSection || m_fileType == PLYFileType::ASCII) { |
| 1263 | ! | return rewind_to_safe_char(); |
| 1264 | } | |
| 1265 | ! | return true; |
| 1266 | } | |
| 1267 | ||
| 1268 | ||
| 1269 | ! | bool PLYReader::rewind_to_safe_char() |
| 1270 | { | |
| 1271 | // If it looks like a token might run past the end of this buffer, move | |
| 1272 | // the buffer end pointer back before it & rewind the file. This way the | |
| 1273 | // next refill will pick up the whole of the token. | |
| 1274 | ! | if (!m_atEOF && (m_bufEnd[-1] == '\n' || !is_safe_buffer_end(m_bufEnd[-1]))) { |
| 1275 | ! | const char* safe = m_bufEnd - 2; |
| 1276 | // If '\n' is the last char in the buffer, then a call to `next_line()` | |
| 1277 | // will move `m_pos` to point at the null terminator but won't refresh | |
| 1278 | // the buffer. It would be clearer to fix this in `next_line()` but I | |
| 1279 | // believe it'll be more performant to simply treat `\n` as an unsafe | |
| 1280 | // character here. | |
| 1281 | ! | while (safe >= m_end && (*safe == '\n' || !is_safe_buffer_end(*safe))) { |
| 1282 | ! | --safe; |
| 1283 | } | |
| 1284 | ! | if (safe < m_end) { |
| 1285 | // No safe places to rewind to in the whole buffer! | |
| 1286 | ! | return false; |
| 1287 | } | |
| 1288 | ! | ++safe; |
| 1289 | ! | m_buf[kPLYReadBufferSize] = *safe; |
| 1290 | ! | m_bufEnd = safe; |
| 1291 | } | |
| 1292 | ! | m_buf[m_bufEnd - m_buf] = '\0'; |
| 1293 | ||
| 1294 | ! | return true; |
| 1295 | } | |
| 1296 | ||
| 1297 | ||
| 1298 | ! | bool PLYReader::accept() |
| 1299 | { | |
| 1300 | ! | m_pos = m_end; |
| 1301 | ! | return true; |
| 1302 | } | |
| 1303 | ||
| 1304 | ||
| 1305 | // Advances to end of line or to next non-whitespace char. | |
| 1306 | ! | bool PLYReader::advance() |
| 1307 | { | |
| 1308 | ! | m_pos = m_end; |
| 1309 | while (true) { | |
| 1310 | ! | while (is_whitespace(*m_pos)) { |
| 1311 | ! | ++m_pos; |
| 1312 | } | |
| 1313 | ! | if (m_pos == m_bufEnd) { |
| 1314 | ! | m_end = m_pos; |
| 1315 | ! | if (refill_buffer()) { |
| 1316 | ! | continue; |
| 1317 | } | |
| 1318 | ! | return false; |
| 1319 | } | |
| 1320 | ! | break; |
| 1321 | } | |
| 1322 | ! | m_end = m_pos; |
| 1323 | ! | return true; |
| 1324 | } | |
| 1325 | ||
| 1326 | ||
| 1327 | ! | bool PLYReader::next_line() |
| 1328 | { | |
| 1329 | ! | m_pos = m_end; |
| 1330 | do { | |
| 1331 | ! | while (*m_pos != '\n') { |
| 1332 | ! | if (m_pos == m_bufEnd) { |
| 1333 | ! | m_end = m_pos; |
| 1334 | ! | if (refill_buffer()) { |
| 1335 | ! | continue; |
| 1336 | } | |
| 1337 | ! | return false; |
| 1338 | } | |
| 1339 | ! | ++m_pos; |
| 1340 | } | |
| 1341 | ! | ++m_pos; // move past the newline char |
| 1342 | ! | m_end = m_pos; |
| 1343 | ! | } while (match("comment") || match("obj_info")); |
| 1344 | ||
| 1345 | ! | return true; |
| 1346 | } | |
| 1347 | ||
| 1348 | ||
| 1349 | ! | bool PLYReader::match(const char* str) |
| 1350 | { | |
| 1351 | ! | m_end = m_pos; |
| 1352 | ! | while (m_end < m_bufEnd && *str != '\0' && *m_end == *str) { |
| 1353 | ! | ++m_end; |
| 1354 | ! | ++str; |
| 1355 | } | |
| 1356 | ! | if (*str != '\0') { |
| 1357 | ! | return false; |
| 1358 | } | |
| 1359 | ! | return true; |
| 1360 | } | |
| 1361 | ||
| 1362 | ||
| 1363 | ! | bool PLYReader::which(const char* values[], uint32_t* index) |
| 1364 | { | |
| 1365 | ! | for (uint32_t i = 0; values[i] != nullptr; i++) { |
| 1366 | ! | if (keyword(values[i])) { |
| 1367 | ! | *index = i; |
| 1368 | ! | return true; |
| 1369 | } | |
| 1370 | } | |
| 1371 | ! | return false; |
| 1372 | } | |
| 1373 | ||
| 1374 | ||
| 1375 | ! | bool PLYReader::which_property_type(PLYPropertyType* type) |
| 1376 | { | |
| 1377 | ! | for (uint32_t i = 0; kTypeAliases[i].name != nullptr; i++) { |
| 1378 | ! | if (keyword(kTypeAliases[i].name)) { |
| 1379 | ! | *type = kTypeAliases[i].type; |
| 1380 | ! | return true; |
| 1381 | } | |
| 1382 | } | |
| 1383 | ! | return false; |
| 1384 | } | |
| 1385 | ||
| 1386 | ||
| 1387 | ! | bool PLYReader::keyword(const char* kw) |
| 1388 | { | |
| 1389 | ! | return match(kw) && !is_keyword_part(*m_end); |
| 1390 | } | |
| 1391 | ||
| 1392 | ||
| 1393 | ! | bool PLYReader::identifier(char* dest, size_t destLen) |
| 1394 | { | |
| 1395 | ! | m_end = m_pos; |
| 1396 | ! | if (!is_keyword_start(*m_end) || destLen == 0) { |
| 1397 | ! | return false; |
| 1398 | } | |
| 1399 | do { | |
| 1400 | ! | ++m_end; |
| 1401 | ! | } while (is_keyword_part(*m_end)); |
| 1402 | ||
| 1403 | ! | size_t len = static_cast<size_t>(m_end - m_pos); |
| 1404 | ! | if (len >= destLen) { |
| 1405 | ! | return false; // identifier too large for dest! |
| 1406 | } | |
| 1407 | ! | std::memcpy(dest, m_pos, sizeof(char) * len); |
| 1408 | ! | dest[len] = '\0'; |
| 1409 | ! | return true; |
| 1410 | } | |
| 1411 | ||
| 1412 | ||
| 1413 | ! | bool PLYReader::int_literal(int* value) |
| 1414 | { | |
| 1415 | ! | return miniply::int_literal(m_pos, &m_end, value); |
| 1416 | } | |
| 1417 | ||
| 1418 | ||
| 1419 | ! | bool PLYReader::float_literal(float* value) |
| 1420 | { | |
| 1421 | ! | return miniply::float_literal(m_pos, &m_end, value); |
| 1422 | } | |
| 1423 | ||
| 1424 | ||
| 1425 | ! | bool PLYReader::double_literal(double* value) |
| 1426 | { | |
| 1427 | ! | return miniply::double_literal(m_pos, &m_end, value); |
| 1428 | } | |
| 1429 | ||
| 1430 | ||
| 1431 | ! | bool PLYReader::parse_elements() |
| 1432 | { | |
| 1433 | ! | m_elements.reserve(4); |
| 1434 | ! | while (m_valid && keyword("element")) { |
| 1435 | ! | parse_element(); |
| 1436 | } | |
| 1437 | ! | return true; |
| 1438 | } | |
| 1439 | ||
| 1440 | ||
| 1441 | ! | bool PLYReader::parse_element() |
| 1442 | { | |
| 1443 | ! | int count = 0; |
| 1444 | ||
| 1445 | ! | m_valid = keyword("element") && advance() && |
| 1446 | ! | identifier(m_tmpBuf, kPLYTempBufferSize) && advance() && |
| 1447 | ! | int_literal(&count) && next_line(); |
| 1448 | ! | if (!m_valid || count < 0) { |
| 1449 | ! | return false; |
| 1450 | } | |
| 1451 | ||
| 1452 | ! | m_elements.push_back(PLYElement()); |
| 1453 | ! | PLYElement& elem = m_elements.back(); |
| 1454 | ! | elem.name = m_tmpBuf; |
| 1455 | ! | elem.count = static_cast<uint32_t>(count); |
| 1456 | ! | elem.properties.reserve(10); |
| 1457 | ||
| 1458 | ! | while (m_valid && keyword("property")) { |
| 1459 | ! | parse_property(elem.properties); |
| 1460 | } | |
| 1461 | ||
| 1462 | ! | return true; |
| 1463 | } | |
| 1464 | ||
| 1465 | ||
| 1466 | ! | bool PLYReader::parse_property(std::vector<PLYProperty>& properties) |
| 1467 | { | |
| 1468 | ! | PLYPropertyType type = PLYPropertyType::None; |
| 1469 | ! | PLYPropertyType countType = PLYPropertyType::None; |
| 1470 | ||
| 1471 | ! | m_valid = keyword("property") && advance(); |
| 1472 | ! | if (!m_valid) { |
| 1473 | ! | return false; |
| 1474 | } | |
| 1475 | ||
| 1476 | ! | if (keyword("list")) { |
| 1477 | // This is a list property | |
| 1478 | ! | m_valid = advance() && which_property_type(&countType) && advance(); |
| 1479 | ! | if (!m_valid) { |
| 1480 | ! | return false; |
| 1481 | } | |
| 1482 | } | |
| 1483 | ||
| 1484 | ! | m_valid = which_property_type(&type) && advance() && |
| 1485 | ! | identifier(m_tmpBuf, kPLYTempBufferSize) && next_line(); |
| 1486 | ! | if (!m_valid) { |
| 1487 | ! | return false; |
| 1488 | } | |
| 1489 | ||
| 1490 | ! | properties.push_back(PLYProperty()); |
| 1491 | ! | PLYProperty& prop = properties.back(); |
| 1492 | ! | prop.name = m_tmpBuf; |
| 1493 | ! | prop.type = type; |
| 1494 | ! | prop.countType = countType; |
| 1495 | ||
| 1496 | ! | return true; |
| 1497 | } | |
| 1498 | ||
| 1499 | ||
| 1500 | ! | bool PLYReader::load_fixed_size_element(PLYElement& elem) |
| 1501 | { | |
| 1502 | ! | size_t numBytes = elem.count * elem.rowStride; |
| 1503 | ||
| 1504 | ! | m_elementData.resize(numBytes); |
| 1505 | ||
| 1506 | ! | if (m_fileType == PLYFileType::ASCII) { |
| 1507 | ! | size_t back = 0; |
| 1508 | ||
| 1509 | ! | for (uint32_t row = 0; row < elem.count; row++) { |
| 1510 | ! | for (PLYProperty& prop : elem.properties) { |
| 1511 | ! | if (!load_ascii_scalar_property(prop, back)) { |
| 1512 | ! | m_valid = false; |
| 1513 | ! | return false; |
| 1514 | } | |
| 1515 | } | |
| 1516 | ! | next_line(); |
| 1517 | } | |
| 1518 | } | |
| 1519 | else { | |
| 1520 | ! | uint8_t* dst = m_elementData.data(); |
| 1521 | ! | uint8_t* dstEnd = dst + numBytes; |
| 1522 | ! | while (dst < dstEnd) { |
| 1523 | ! | size_t bytesAvailable = static_cast<size_t>(m_bufEnd - m_pos); |
| 1524 | ! | if (dst + bytesAvailable > dstEnd) { |
| 1525 | ! | bytesAvailable = static_cast<size_t>(dstEnd - dst); |
| 1526 | } | |
| 1527 | ! | std::memcpy(dst, m_pos, bytesAvailable); |
| 1528 | ! | m_pos += bytesAvailable; |
| 1529 | ! | m_end = m_pos; |
| 1530 | ! | dst += bytesAvailable; |
| 1531 | ! | if (!refill_buffer()) { |
| 1532 | ! | break; |
| 1533 | } | |
| 1534 | } | |
| 1535 | ! | if (dst < dstEnd) { |
| 1536 | ! | m_valid = false; |
| 1537 | ! | return false; |
| 1538 | } | |
| 1539 | ||
| 1540 | // We assume the CPU is little endian, so if the file is big-endian we | |
| 1541 | // need to do an endianness swap on every data item in the block. | |
| 1542 | ! | if (m_fileType == PLYFileType::BinaryBigEndian) { |
| 1543 | ! | uint8_t* data = m_elementData.data(); |
| 1544 | ! | for (uint32_t row = 0; row < elem.count; row++) { |
| 1545 | ! | for (PLYProperty& prop : elem.properties) { |
| 1546 | ! | size_t numBytes = kPLYPropertySize[uint32_t(prop.type)]; |
| 1547 | ! | switch (numBytes) { |
| 1548 | ! | case 2: |
| 1549 | ! | endian_swap_2(data); |
| 1550 | ! | break; |
| 1551 | ! | case 4: |
| 1552 | ! | endian_swap_4(data); |
| 1553 | ! | break; |
| 1554 | ! | case 8: |
| 1555 | ! | endian_swap_8(data); |
| 1556 | ! | break; |
| 1557 | ! | default: |
| 1558 | ! | break; |
| 1559 | } | |
| 1560 | ! | data += numBytes; |
| 1561 | } | |
| 1562 | } | |
| 1563 | } | |
| 1564 | } | |
| 1565 | ||
| 1566 | ! | m_elementLoaded = true; |
| 1567 | ! | return true; |
| 1568 | } | |
| 1569 | ||
| 1570 | ||
| 1571 | ! | bool PLYReader::load_variable_size_element(PLYElement& elem) |
| 1572 | { | |
| 1573 | ! | m_elementData.resize(elem.count * elem.rowStride); |
| 1574 | ||
| 1575 | // Preallocate enough space for each row in the property to contain three | |
| 1576 | // items. This is based on the assumptions that (a) the most common use for | |
| 1577 | // list properties is vertex indices; and (b) most faces are triangles. | |
| 1578 | // This gives a performance boost because we won't have to grow the | |
| 1579 | // listData vector as many times during loading. | |
| 1580 | ! | for (PLYProperty& prop : elem.properties) { |
| 1581 | ! | if (prop.countType != PLYPropertyType::None) { |
| 1582 | ! | prop.listData.reserve(elem.count * kPLYPropertySize[uint32_t(prop.type)] * 3); |
| 1583 | } | |
| 1584 | } | |
| 1585 | ||
| 1586 | ! | if (m_fileType == PLYFileType::Binary) { |
| 1587 | ! | size_t back = 0; |
| 1588 | ! | for (uint32_t row = 0; row < elem.count; row++) { |
| 1589 | ! | for (PLYProperty& prop : elem.properties) { |
| 1590 | ! | if (prop.countType == PLYPropertyType::None) { |
| 1591 | ! | m_valid = load_binary_scalar_property(prop, back); |
| 1592 | } | |
| 1593 | else { | |
| 1594 | ! | load_binary_list_property(prop); |
| 1595 | } | |
| 1596 | } | |
| 1597 | } | |
| 1598 | } | |
| 1599 | ! | else if (m_fileType == PLYFileType::ASCII) { |
| 1600 | ! | size_t back = 0; |
| 1601 | ! | for (uint32_t row = 0; row < elem.count; row++) { |
| 1602 | ! | for (PLYProperty& prop : elem.properties) { |
| 1603 | ! | if (prop.countType == PLYPropertyType::None) { |
| 1604 | ! | m_valid = load_ascii_scalar_property(prop, back); |
| 1605 | } | |
| 1606 | else { | |
| 1607 | ! | load_ascii_list_property(prop); |
| 1608 | } | |
| 1609 | } | |
| 1610 | ! | next_line(); |
| 1611 | } | |
| 1612 | } | |
| 1613 | else { // m_fileType == PLYFileType::BinaryBigEndian | |
| 1614 | ! | size_t back = 0; |
| 1615 | ! | for (uint32_t row = 0; row < elem.count; row++) { |
| 1616 | ! | for (PLYProperty& prop : elem.properties) { |
| 1617 | ! | if (prop.countType == PLYPropertyType::None) { |
| 1618 | ! | m_valid = load_binary_scalar_property_big_endian(prop, back); |
| 1619 | } | |
| 1620 | else { | |
| 1621 | ! | load_binary_list_property_big_endian(prop); |
| 1622 | } | |
| 1623 | } | |
| 1624 | } | |
| 1625 | } | |
| 1626 | ||
| 1627 | ! | m_elementLoaded = true; |
| 1628 | ! | return true; |
| 1629 | } | |
| 1630 | ||
| 1631 | ||
| 1632 | ! | bool PLYReader::load_ascii_scalar_property(PLYProperty& prop, size_t& destIndex) |
| 1633 | { | |
| 1634 | uint8_t value[8]; | |
| 1635 | ! | if (!ascii_value(prop.type, value)) { |
| 1636 | ! | return false; |
| 1637 | } | |
| 1638 | ||
| 1639 | ! | size_t numBytes = kPLYPropertySize[uint32_t(prop.type)]; |
| 1640 | ! | std::memcpy(m_elementData.data() + destIndex, value, numBytes); |
| 1641 | ! | destIndex += numBytes; |
| 1642 | ! | return true; |
| 1643 | } | |
| 1644 | ||
| 1645 | ||
| 1646 | ! | bool PLYReader::load_ascii_list_property(PLYProperty& prop) |
| 1647 | { | |
| 1648 | ! | int count = 0; |
| 1649 | ! | m_valid = (prop.countType < PLYPropertyType::Float) && int_literal(&count) && advance() && (count >= 0); |
| 1650 | ! | if (!m_valid) { |
| 1651 | ! | return false; |
| 1652 | } | |
| 1653 | ||
| 1654 | ! | const size_t numBytes = kPLYPropertySize[uint32_t(prop.type)]; |
| 1655 | ||
| 1656 | ! | size_t back = prop.listData.size(); |
| 1657 | ! | prop.rowCount.push_back(static_cast<uint32_t>(count)); |
| 1658 | ! | prop.listData.resize(back + numBytes * size_t(count)); |
| 1659 | ||
| 1660 | ! | for (uint32_t i = 0; i < uint32_t(count); i++) { |
| 1661 | ! | if (!ascii_value(prop.type, prop.listData.data() + back)) { |
| 1662 | ! | m_valid = false; |
| 1663 | ! | return false; |
| 1664 | } | |
| 1665 | ! | back += numBytes; |
| 1666 | } | |
| 1667 | ||
| 1668 | ! | return true; |
| 1669 | } | |
| 1670 | ||
| 1671 | ||
| 1672 | ! | bool PLYReader::load_binary_scalar_property(PLYProperty& prop, size_t& destIndex) |
| 1673 | { | |
| 1674 | ! | size_t numBytes = kPLYPropertySize[uint32_t(prop.type)]; |
| 1675 | ! | if (m_pos + numBytes > m_bufEnd) { |
| 1676 | ! | if (!refill_buffer() || m_pos + numBytes > m_bufEnd) { |
| 1677 | ! | m_valid = false; |
| 1678 | ! | return false; |
| 1679 | } | |
| 1680 | } | |
| 1681 | ! | std::memcpy(m_elementData.data() + destIndex, m_pos, numBytes); |
| 1682 | ! | m_pos += numBytes; |
| 1683 | ! | m_end = m_pos; |
| 1684 | ! | destIndex += numBytes; |
| 1685 | ! | return true; |
| 1686 | } | |
| 1687 | ||
| 1688 | ||
| 1689 | ! | bool PLYReader::load_binary_list_property(PLYProperty& prop) |
| 1690 | { | |
| 1691 | ! | size_t countBytes = kPLYPropertySize[uint32_t(prop.countType)]; |
| 1692 | ! | if (m_pos + countBytes > m_bufEnd) { |
| 1693 | ! | if (!refill_buffer() || m_pos + countBytes > m_bufEnd) { |
| 1694 | ! | m_valid = false; |
| 1695 | ! | return false; |
| 1696 | } | |
| 1697 | } | |
| 1698 | ||
| 1699 | ! | int count = 0; |
| 1700 | ! | copy_and_convert_to(&count, reinterpret_cast<const uint8_t*>(m_pos), prop.countType); |
| 1701 | ||
| 1702 | ! | if (count < 0) { |
| 1703 | ! | m_valid = false; |
| 1704 | ! | return false; |
| 1705 | } | |
| 1706 | ||
| 1707 | ! | m_pos += countBytes; |
| 1708 | ! | m_end = m_pos; |
| 1709 | ||
| 1710 | ! | const size_t listBytes = kPLYPropertySize[uint32_t(prop.type)] * uint32_t(count); |
| 1711 | ! | if (m_pos + listBytes > m_bufEnd) { |
| 1712 | ! | if (!refill_buffer() || m_pos + listBytes > m_bufEnd) { |
| 1713 | ! | m_valid = false; |
| 1714 | ! | return false; |
| 1715 | } | |
| 1716 | } | |
| 1717 | ! | size_t back = prop.listData.size(); |
| 1718 | ! | prop.rowCount.push_back(static_cast<uint32_t>(count)); |
| 1719 | ! | prop.listData.resize(back + listBytes); |
| 1720 | ! | std::memcpy(prop.listData.data() + back, m_pos, listBytes); |
| 1721 | ||
| 1722 | ! | m_pos += listBytes; |
| 1723 | ! | m_end = m_pos; |
| 1724 | ! | return true; |
| 1725 | } | |
| 1726 | ||
| 1727 | ||
| 1728 | ! | bool PLYReader::load_binary_scalar_property_big_endian(PLYProperty &prop, size_t &destIndex) |
| 1729 | { | |
| 1730 | ! | size_t startIndex = destIndex; |
| 1731 | ! | if (load_binary_scalar_property(prop, destIndex)) { |
| 1732 | ! | endian_swap(m_elementData.data() + startIndex, prop.type); |
| 1733 | ! | return true; |
| 1734 | } | |
| 1735 | else { | |
| 1736 | ! | return false; |
| 1737 | } | |
| 1738 | } | |
| 1739 | ||
| 1740 | ||
| 1741 | ! | bool PLYReader::load_binary_list_property_big_endian(PLYProperty &prop) |
| 1742 | { | |
| 1743 | ! | size_t countBytes = kPLYPropertySize[uint32_t(prop.countType)]; |
| 1744 | ! | if (m_pos + countBytes > m_bufEnd) { |
| 1745 | ! | if (!refill_buffer() || m_pos + countBytes > m_bufEnd) { |
| 1746 | ! | m_valid = false; |
| 1747 | ! | return false; |
| 1748 | } | |
| 1749 | } | |
| 1750 | ||
| 1751 | ! | int count = 0; |
| 1752 | uint8_t tmp[8]; | |
| 1753 | ! | std::memcpy(tmp, m_pos, countBytes); |
| 1754 | ! | endian_swap(tmp, prop.countType); |
| 1755 | ! | copy_and_convert_to(&count, tmp, prop.countType); |
| 1756 | ||
| 1757 | ! | if (count < 0) { |
| 1758 | ! | m_valid = false; |
| 1759 | ! | return false; |
| 1760 | } | |
| 1761 | ||
| 1762 | ! | m_pos += countBytes; |
| 1763 | ! | m_end = m_pos; |
| 1764 | ||
| 1765 | ! | const size_t typeBytes = kPLYPropertySize[uint32_t(prop.type)]; |
| 1766 | ! | const size_t listBytes = typeBytes * uint32_t(count); |
| 1767 | ! | if (m_pos + listBytes > m_bufEnd) { |
| 1768 | ! | if (!refill_buffer() || m_pos + listBytes > m_bufEnd) { |
| 1769 | ! | m_valid = false; |
| 1770 | ! | return false; |
| 1771 | } | |
| 1772 | } | |
| 1773 | ! | size_t back = prop.listData.size(); |
| 1774 | ! | prop.rowCount.push_back(static_cast<uint32_t>(count)); |
| 1775 | ! | prop.listData.resize(back + listBytes); |
| 1776 | ||
| 1777 | ! | uint8_t* list = prop.listData.data() + back; |
| 1778 | ! | std::memcpy(list, m_pos, listBytes); |
| 1779 | ! | endian_swap_array(list, prop.type, count); |
| 1780 | ||
| 1781 | ! | m_pos += listBytes; |
| 1782 | ! | m_end = m_pos; |
| 1783 | ! | return true; |
| 1784 | } | |
| 1785 | ||
| 1786 | ||
| 1787 | ! | bool PLYReader::ascii_value(PLYPropertyType propType, uint8_t value[8]) |
| 1788 | { | |
| 1789 | ! | int tmpInt = 0; |
| 1790 | ||
| 1791 | ! | switch (propType) { |
| 1792 | ! | case PLYPropertyType::Char: |
| 1793 | case PLYPropertyType::UChar: | |
| 1794 | case PLYPropertyType::Short: | |
| 1795 | case PLYPropertyType::UShort: | |
| 1796 | ! | m_valid = int_literal(&tmpInt); |
| 1797 | ! | break; |
| 1798 | ! | case PLYPropertyType::Int: |
| 1799 | case PLYPropertyType::UInt: | |
| 1800 | ! | m_valid = int_literal(reinterpret_cast<int*>(value)); |
| 1801 | ! | break; |
| 1802 | ! | case PLYPropertyType::Float: |
| 1803 | ! | m_valid = float_literal(reinterpret_cast<float*>(value)); |
| 1804 | ! | break; |
| 1805 | ! | case PLYPropertyType::Double: |
| 1806 | default: | |
| 1807 | ! | m_valid = double_literal(reinterpret_cast<double*>(value)); |
| 1808 | ! | break; |
| 1809 | } | |
| 1810 | ||
| 1811 | ! | if (!m_valid) { |
| 1812 | ! | return false; |
| 1813 | } | |
| 1814 | ! | advance(); |
| 1815 | ||
| 1816 | ! | switch (propType) { |
| 1817 | ! | case PLYPropertyType::Char: |
| 1818 | ! | reinterpret_cast<int8_t*>(value)[0] = static_cast<int8_t>(tmpInt); |
| 1819 | ! | break; |
| 1820 | ! | case PLYPropertyType::UChar: |
| 1821 | ! | value[0] = static_cast<uint8_t>(tmpInt); |
| 1822 | ! | break; |
| 1823 | ! | case PLYPropertyType::Short: |
| 1824 | ! | reinterpret_cast<int16_t*>(value)[0] = static_cast<int16_t>(tmpInt); |
| 1825 | ! | break; |
| 1826 | ! | case PLYPropertyType::UShort: |
| 1827 | ! | reinterpret_cast<uint16_t*>(value)[0] = static_cast<uint16_t>(tmpInt); |
| 1828 | ! | break; |
| 1829 | ! | default: |
| 1830 | ! | break; |
| 1831 | } | |
| 1832 | ! | return true; |
| 1833 | } | |
| 1834 | ||
| 1835 | ||
| 1836 | // | |
| 1837 | // Polygon triangulation | |
| 1838 | // | |
| 1839 | ||
| 1840 | ! | static float angle_at_vert(uint32_t idx, |
| 1841 | const std::vector<Vec2>& points2D, | |
| 1842 | const std::vector<uint32_t>& prev, | |
| 1843 | const std::vector<uint32_t>& next) | |
| 1844 | { | |
| 1845 | ! | Vec2 xaxis = normalize(points2D[next[idx]] - points2D[idx]); |
| 1846 | ! | Vec2 yaxis = Vec2{-xaxis.y, xaxis.x}; |
| 1847 | ! | Vec2 p2p0 = points2D[prev[idx]] - points2D[idx]; |
| 1848 | ! | float angle = std::atan2(dot(p2p0, yaxis), dot(p2p0, xaxis)); |
| 1849 | ! | if (angle <= 0.0f || angle >= kPi) { |
| 1850 | ! | angle = 10000.0f; |
| 1851 | } | |
| 1852 | ! | return angle; |
| 1853 | } | |
| 1854 | ||
| 1855 | ||
| 1856 | ! | uint32_t triangulate_polygon(uint32_t n, const float pos[], uint32_t numVerts, const int indices[], int dst[]) |
| 1857 | { | |
| 1858 | ! | if (n < 3) { |
| 1859 | ! | return 0; |
| 1860 | } | |
| 1861 | ! | else if (n == 3) { |
| 1862 | ! | dst[0] = indices[0]; |
| 1863 | ! | dst[1] = indices[1]; |
| 1864 | ! | dst[2] = indices[2]; |
| 1865 | ! | return 1; |
| 1866 | } | |
| 1867 | ! | else if (n == 4) { |
| 1868 | ! | dst[0] = indices[0]; |
| 1869 | ! | dst[1] = indices[1]; |
| 1870 | ! | dst[2] = indices[3]; |
| 1871 | ||
| 1872 | ! | dst[3] = indices[2]; |
| 1873 | ! | dst[4] = indices[3]; |
| 1874 | ! | dst[5] = indices[1]; |
| 1875 | ! | return 2; |
| 1876 | } | |
| 1877 | ||
| 1878 | // Check that all indices for this face are in the valid range before we | |
| 1879 | // try to dereference them. | |
| 1880 | ! | for (uint32_t i = 0; i < n; i++) { |
| 1881 | ! | if (indices[i] < 0 || uint32_t(indices[i]) >= numVerts) { |
| 1882 | ! | return 0; |
| 1883 | } | |
| 1884 | } | |
| 1885 | ||
| 1886 | ! | const Vec3* vpos = reinterpret_cast<const Vec3*>(pos); |
| 1887 | ||
| 1888 | // Calculate the geometric normal of the face | |
| 1889 | ! | Vec3 origin = vpos[indices[0]]; |
| 1890 | ! | Vec3 faceU = normalize(vpos[indices[1]] - origin); |
| 1891 | ! | Vec3 faceNormal = normalize(cross(faceU, normalize(vpos[indices[n - 1]] - origin))); |
| 1892 | ! | Vec3 faceV = normalize(cross(faceNormal, faceU)); |
| 1893 | ||
| 1894 | // Project the faces points onto the plane perpendicular to the normal. | |
| 1895 | ! | std::vector<Vec2> points2D(n, Vec2{0.0f, 0.0f}); |
| 1896 | ! | for (uint32_t i = 1; i < n; i++) { |
| 1897 | ! | Vec3 p = vpos[indices[i]] - origin; |
| 1898 | ! | points2D[i] = Vec2{dot(p, faceU), dot(p, faceV)}; |
| 1899 | } | |
| 1900 | ||
| 1901 | ! | std::vector<uint32_t> next(n, 0u); |
| 1902 | ! | std::vector<uint32_t> prev(n, 0u); |
| 1903 | ! | uint32_t first = 0; |
| 1904 | ! | for (uint32_t i = 0, j = n - 1; i < n; i++) { |
| 1905 | ! | next[j] = i; |
| 1906 | ! | prev[i] = j; |
| 1907 | ! | j = i; |
| 1908 | } | |
| 1909 | ||
| 1910 | // Do ear clipping. | |
| 1911 | ! | while (n > 3) { |
| 1912 | // Find the (remaining) vertex with the sharpest angle. | |
| 1913 | ! | uint32_t bestI = first; |
| 1914 | ! | float bestAngle = angle_at_vert(first, points2D, prev, next); |
| 1915 | ! | for (uint32_t i = next[first]; i != first; i = next[i]) { |
| 1916 | ! | float angle = angle_at_vert(i, points2D, prev, next); |
| 1917 | ! | if (angle < bestAngle) { |
| 1918 | ! | bestI = i; |
| 1919 | ! | bestAngle = angle; |
| 1920 | } | |
| 1921 | } | |
| 1922 | ||
| 1923 | // Clip the triangle at bestI. | |
| 1924 | ! | uint32_t nextI = next[bestI]; |
| 1925 | ! | uint32_t prevI = prev[bestI]; |
| 1926 | ||
| 1927 | ! | dst[0] = indices[bestI]; |
| 1928 | ! | dst[1] = indices[nextI]; |
| 1929 | ! | dst[2] = indices[prevI]; |
| 1930 | ! | dst += 3; |
| 1931 | ||
| 1932 | ! | if (bestI == first) { |
| 1933 | ! | first = nextI; |
| 1934 | } | |
| 1935 | ! | next[prevI] = nextI; |
| 1936 | ! | prev[nextI] = prevI; |
| 1937 | ! | --n; |
| 1938 | } | |
| 1939 | ||
| 1940 | // Add the final triangle. | |
| 1941 | ! | dst[0] = indices[first]; |
| 1942 | ! | dst[1] = indices[next[first]]; |
| 1943 | ! | dst[2] = indices[prev[first]]; |
| 1944 | ||
| 1945 | ! | return n - 2; |
| 1946 | } | |
| 1947 | ||
| 1948 | } // namespace miniply |
| 1 | #ifndef RAYRASTERH | |
| 2 | #define RAYRASTERH | |
| 3 | ||
| 4 | #include "Rcpp.h" | |
| 5 | ||
| 6 | #define FLOAT_AS_DOUBLE | |
| 7 | // #ifndef FLOAT_AS_DOUBLE | |
| 8 | // typedef float Float; | |
| 9 | // #else | |
| 10 | // typedef double Float; | |
| 11 | // #endif | |
| 12 | ||
| 13 | #include <functional> | |
| 14 | #include <algorithm> | |
| 15 | #include <utility> | |
| 16 | #include <memory> | |
| 17 | #include "glm.hpp" | |
| 18 | #include "gtc/matrix_transform.hpp" | |
| 19 | #include "defines.h" | |
| 20 | #include "filltri.h" | |
| 21 | ||
| 22 | #include "shaders.h" | |
| 23 | #include "rayimage.h" | |
| 24 | ||
| 25 | #include "line.h" | |
| 26 | ||
| 27 | // typedef glm::dvec4 vec4; | |
| 28 | // typedef glm::dvec3 vec3; | |
| 29 | // typedef glm::dvec2 vec2; | |
| 30 | // typedef glm::dmat4x4 Mat; | |
| 31 | ||
| 32 | using namespace Rcpp; | |
| 33 | ||
| 34 | inline vec3 clamp(const vec3& c, Float clamplow, Float clamphigh) { | |
| 35 | vec3 temp = c; | |
| 36 | if(c[0] > clamphigh) { | |
| 37 | temp[0] = clamphigh; | |
| 38 | } else if(c[0] < clamplow) { | |
| 39 | temp[0] = clamplow; | |
| 40 | } | |
| 41 | if(c[1] > clamphigh) { | |
| 42 | temp[1] = clamphigh; | |
| 43 | } else if(c[1] < clamplow) { | |
| 44 | temp[1] = clamplow; | |
| 45 | } | |
| 46 | if(c[2] > clamphigh) { | |
| 47 | temp[2] = clamphigh; | |
| 48 | } else if(c[2] < clamplow) { | |
| 49 | temp[2] = clamplow; | |
| 50 | } | |
| 51 | return(temp); | |
| 52 | } | |
| 53 | ||
| 54 | inline vec4 clamp(const vec4& c, Float clamplow, Float clamphigh) { | |
| 55 | vec4 temp = c; | |
| 56 | if(c[0] > clamphigh) { | |
| 57 | temp[0] = clamphigh; | |
| 58 | } else if(c[0] < clamplow) { | |
| 59 | temp[0] = clamplow; | |
| 60 | } | |
| 61 | if(c[1] > clamphigh) { | |
| 62 | temp[1] = clamphigh; | |
| 63 | } else if(c[1] < clamplow) { | |
| 64 | temp[1] = clamplow; | |
| 65 | } | |
| 66 | if(c[2] > clamphigh) { | |
| 67 | temp[2] = clamphigh; | |
| 68 | } else if(c[2] < clamplow) { | |
| 69 | temp[2] = clamplow; | |
| 70 | } | |
| 71 | if(c[3] > clamphigh) { | |
| 72 | temp[3] = clamphigh; | |
| 73 | } else if(c[3] < clamplow) { | |
| 74 | temp[3] = clamplow; | |
| 75 | } | |
| 76 | return(temp); | |
| 77 | } | |
| 78 | ||
| 79 | template<class T> | |
| 80 | inline T lerp(Float t, T v1, T v2) { | |
| 81 | return((1-t) * v1 + t * v2); | |
| 82 | } | |
| 83 | // [[Rcpp::export]] | |
| 84 | ! | List rasterize_lines_rcpp(NumericMatrix line_mat, |
| 85 | int nx, int ny, | |
| 86 | NumericVector model_color, | |
| 87 | NumericVector lookfrom, | |
| 88 | NumericVector lookat, | |
| 89 | double fov, | |
| 90 | double near_clip, | |
| 91 | double far_clip, | |
| 92 | NumericVector bounds, | |
| 93 | NumericVector camera_up, | |
| 94 | double alpha_line, double line_offset, | |
| 95 | NumericVector ortho_dims, | |
| 96 | bool aa_lines) { | |
| 97 | //Convert R vectors to vec3 | |
| 98 | ! | vec3 eye(lookfrom(0),lookfrom(1),lookfrom(2)); //lookfrom |
| 99 | ! | vec3 center(lookat(0),lookat(1),lookat(2)); //lookat |
| 100 | ! | vec3 cam_up = vec3(camera_up(0),camera_up(1),camera_up(2)); |
| 101 | ! | vec3 color(model_color(0),model_color(1),model_color(2)); |
| 102 | ||
| 103 | //Account for colinear camera direction/cam_up vectors | |
| 104 | ! | if(glm::length(glm::cross(eye-center,cam_up)) == 0) { |
| 105 | ! | cam_up = vec3(0.,0.,1.f); |
| 106 | } | |
| 107 | ||
| 108 | //Generate MVP matrices | |
| 109 | ! | Mat View = glm::lookAt(eye, center, cam_up); |
| 110 | ! | Mat Model = glm::translate(Mat(1.0), vec3(0.0, 0.0, 0.0)); |
| 111 | ! | Mat Projection = fov != 0.0 ? glm::perspective(glm::radians((Float)fov), |
| 112 | ! | (Float)nx / (Float)ny, |
| 113 | (Float)near_clip, | |
| 114 | (Float)far_clip) : | |
| 115 | ! | glm::ortho(-(Float)ortho_dims(0)/2, (Float)ortho_dims(0)/2, -(Float)ortho_dims(1)/2, (Float)ortho_dims(1)/2); |
| 116 | ! | vec4 viewport(0.0f, 0.0f, (Float)nx-1, (Float)ny-1); |
| 117 | ||
| 118 | ||
| 119 | ! | Mat vp = glm::scale(glm::translate(Mat(1.0f), |
| 120 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)), |
| 121 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)); |
| 122 | ||
| 123 | //Initialize output matrices | |
| 124 | ! | NumericMatrix r(nx,ny); |
| 125 | ! | NumericMatrix g(nx,ny); |
| 126 | ! | NumericMatrix b(nx,ny); |
| 127 | ||
| 128 | //Create buffers | |
| 129 | ! | rayimage image(r,g,b,nx,ny); |
| 130 | ||
| 131 | //Depth buffer | |
| 132 | ! | NumericMatrix zbuffer(nx,ny); |
| 133 | ||
| 134 | ||
| 135 | //Position space buffer | |
| 136 | ! | NumericMatrix xxbuffer(nx,ny); |
| 137 | ! | NumericMatrix yybuffer(nx,ny); |
| 138 | ! | NumericMatrix zzbuffer(nx,ny); |
| 139 | ||
| 140 | //Normal space buffer | |
| 141 | ! | NumericMatrix nxbuffer(nx,ny); |
| 142 | ! | NumericMatrix nybuffer(nx,ny); |
| 143 | ! | NumericMatrix nzbuffer(nx,ny); |
| 144 | ||
| 145 | //UV buffer | |
| 146 | ! | NumericMatrix uvxbuffer(nx,ny); |
| 147 | ! | NumericMatrix uvybuffer(nx,ny); |
| 148 | ! | NumericMatrix uvzbuffer(nx,ny); |
| 149 | ||
| 150 | //Initialize rayimage buffers | |
| 151 | ! | rayimage positionbuffer(xxbuffer,yybuffer,zzbuffer,nx,ny); |
| 152 | ! | rayimage normalbuffer(nxbuffer,nybuffer,nzbuffer,nx,ny); |
| 153 | ! | rayimage uvbuffer(uvxbuffer,uvybuffer,uvzbuffer,nx,ny); |
| 154 | ||
| 155 | //Initialize zbuffer | |
| 156 | ! | std::fill(zbuffer.begin(), zbuffer.end(), std::numeric_limits<Float>::infinity() ) ; |
| 157 | ||
| 158 | // vec3 light_up = vec3(0.,1.,0.); | |
| 159 | ||
| 160 | // vec3 sceneboundmin = vec3(bounds(0),bounds(1),bounds(2)); | |
| 161 | // vec3 sceneboundmax = vec3(bounds(3),bounds(4),bounds(5)); | |
| 162 | // Float scene_diag = glm::length(sceneboundmax-sceneboundmin)+0.5; | |
| 163 | // vec3 scene_center = (sceneboundmax+sceneboundmin)/(Float)2.0; | |
| 164 | ||
| 165 | //For alpha transparency | |
| 166 | ! | std::vector<std::map<Float, alpha_info> > alpha_depths(nx*ny); |
| 167 | ||
| 168 | ! | std::vector<vec3> ndc_line_verts_start; |
| 169 | ! | std::vector<vec3> ndc_line_verts_end; |
| 170 | ! | std::vector<vec3> line_verts_cols; |
| 171 | ||
| 172 | //Lines go here (no light) | |
| 173 | ! | Mat vpMVP = vp * Projection * View * Model; |
| 174 | ! | for(int i = 0; i < line_mat.nrow(); i++) { |
| 175 | ! | vec4 temp_line_vertex_start = vpMVP * vec4(line_mat(i,0),line_mat(i,1),line_mat(i,2),1.0f); |
| 176 | ! | temp_line_vertex_start /= temp_line_vertex_start.w; |
| 177 | ! | vec4 temp_line_vertex_end = vpMVP * vec4(line_mat(i,3),line_mat(i,4),line_mat(i,5),1.0f); |
| 178 | ! | temp_line_vertex_end /= temp_line_vertex_end.w; |
| 179 | ! | ndc_line_verts_start.push_back(temp_line_vertex_start); |
| 180 | ! | ndc_line_verts_end.push_back(temp_line_vertex_end); |
| 181 | ! | line_verts_cols.push_back(vec3(line_mat(i,6),line_mat(i,7),line_mat(i,8))); |
| 182 | } | |
| 183 | ||
| 184 | ! | if(ndc_line_verts_start.size() > 0) { |
| 185 | ! | if(aa_lines) { |
| 186 | ! | aa_line(ndc_line_verts_start, ndc_line_verts_end, line_verts_cols, zbuffer, alpha_depths, alpha_line, line_offset); |
| 187 | } else { | |
| 188 | ! | noaa_line(ndc_line_verts_start, ndc_line_verts_end, line_verts_cols, zbuffer, alpha_depths, alpha_line, line_offset); |
| 189 | } | |
| 190 | } | |
| 191 | ||
| 192 | ! | for(int i = 0; i < nx; i++) { |
| 193 | ! | for(int j = 0; j < ny; j++) { |
| 194 | ! | for(std::map<Float, alpha_info>::reverse_iterator it = alpha_depths[j + ny*i].rbegin(); |
| 195 | ! | it != alpha_depths[j + ny*i].rend(); ++it) { |
| 196 | ! | if(it->first <= zbuffer(i,j)) { |
| 197 | ! | zbuffer(i,j) = it->first; |
| 198 | ! | vec4 temp_col = it->second.color; |
| 199 | ! | vec3 old_color = image.get_color(i,j); |
| 200 | ! | vec3 new_color = vec3(temp_col)*temp_col.w + vec3(old_color)*(1-temp_col.w); |
| 201 | ! | image.set_color(i,j,new_color); |
| 202 | ! | normalbuffer.set_color(i,j,it->second.normal); |
| 203 | ! | positionbuffer.set_color(i,j,it->second.position); |
| 204 | ! | uvbuffer.set_color(i,j,it->second.uv); |
| 205 | } | |
| 206 | } | |
| 207 | } | |
| 208 | } | |
| 209 | ||
| 210 | ! | return(List::create(_["r"] = r, _["g"] = g, _["b"] = b, |
| 211 | ! | _["depth"] = zbuffer, |
| 212 | ! | _["normalx"] = nxbuffer, _["normaly"] = nybuffer, _["normalz"] = nzbuffer, |
| 213 | ! | _["positionx"] = xxbuffer, _["positiony"] = yybuffer, _["positionz"] = zzbuffer, |
| 214 | ! | _["uvx"] = uvxbuffer, _["uvy"] = uvybuffer, _["uvz"] = uvzbuffer)); |
| 215 | } | |
| 216 | ||
| 217 | #endif |
| 1 | namespace glm | |
| 2 | { | |
| 3 | template<typename T> | |
| 4 | ! | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> ortho(T left, T right, T bottom, T top) |
| 5 | { | |
| 6 | ! | mat<4, 4, T, defaultp> Result(static_cast<T>(1)); |
| 7 | ! | Result[0][0] = static_cast<T>(2) / (right - left); |
| 8 | ! | Result[1][1] = static_cast<T>(2) / (top - bottom); |
| 9 | ! | Result[2][2] = - static_cast<T>(1); |
| 10 | ! | Result[3][0] = - (right + left) / (right - left); |
| 11 | ! | Result[3][1] = - (top + bottom) / (top - bottom); |
| 12 | ! | return Result; |
| 13 | } | |
| 14 | ||
| 15 | template<typename T> | |
| 16 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> orthoLH_ZO(T left, T right, T bottom, T top, T zNear, T zFar) | |
| 17 | { | |
| 18 | mat<4, 4, T, defaultp> Result(1); | |
| 19 | Result[0][0] = static_cast<T>(2) / (right - left); | |
| 20 | Result[1][1] = static_cast<T>(2) / (top - bottom); | |
| 21 | Result[2][2] = static_cast<T>(1) / (zFar - zNear); | |
| 22 | Result[3][0] = - (right + left) / (right - left); | |
| 23 | Result[3][1] = - (top + bottom) / (top - bottom); | |
| 24 | Result[3][2] = - zNear / (zFar - zNear); | |
| 25 | return Result; | |
| 26 | } | |
| 27 | ||
| 28 | template<typename T> | |
| 29 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> orthoLH_NO(T left, T right, T bottom, T top, T zNear, T zFar) | |
| 30 | { | |
| 31 | mat<4, 4, T, defaultp> Result(1); | |
| 32 | Result[0][0] = static_cast<T>(2) / (right - left); | |
| 33 | Result[1][1] = static_cast<T>(2) / (top - bottom); | |
| 34 | Result[2][2] = static_cast<T>(2) / (zFar - zNear); | |
| 35 | Result[3][0] = - (right + left) / (right - left); | |
| 36 | Result[3][1] = - (top + bottom) / (top - bottom); | |
| 37 | Result[3][2] = - (zFar + zNear) / (zFar - zNear); | |
| 38 | return Result; | |
| 39 | } | |
| 40 | ||
| 41 | template<typename T> | |
| 42 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> orthoRH_ZO(T left, T right, T bottom, T top, T zNear, T zFar) | |
| 43 | { | |
| 44 | mat<4, 4, T, defaultp> Result(1); | |
| 45 | Result[0][0] = static_cast<T>(2) / (right - left); | |
| 46 | Result[1][1] = static_cast<T>(2) / (top - bottom); | |
| 47 | Result[2][2] = - static_cast<T>(1) / (zFar - zNear); | |
| 48 | Result[3][0] = - (right + left) / (right - left); | |
| 49 | Result[3][1] = - (top + bottom) / (top - bottom); | |
| 50 | Result[3][2] = - zNear / (zFar - zNear); | |
| 51 | return Result; | |
| 52 | } | |
| 53 | ||
| 54 | template<typename T> | |
| 55 | 5x | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> orthoRH_NO(T left, T right, T bottom, T top, T zNear, T zFar) |
| 56 | { | |
| 57 | 5x | mat<4, 4, T, defaultp> Result(1); |
| 58 | 5x | Result[0][0] = static_cast<T>(2) / (right - left); |
| 59 | 5x | Result[1][1] = static_cast<T>(2) / (top - bottom); |
| 60 | 5x | Result[2][2] = - static_cast<T>(2) / (zFar - zNear); |
| 61 | 5x | Result[3][0] = - (right + left) / (right - left); |
| 62 | 5x | Result[3][1] = - (top + bottom) / (top - bottom); |
| 63 | 5x | Result[3][2] = - (zFar + zNear) / (zFar - zNear); |
| 64 | 5x | return Result; |
| 65 | } | |
| 66 | ||
| 67 | template<typename T> | |
| 68 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> orthoZO(T left, T right, T bottom, T top, T zNear, T zFar) | |
| 69 | { | |
| 70 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_LH_BIT | |
| 71 | return orthoLH_ZO(left, right, bottom, top, zNear, zFar); | |
| 72 | # else | |
| 73 | return orthoRH_ZO(left, right, bottom, top, zNear, zFar); | |
| 74 | # endif | |
| 75 | } | |
| 76 | ||
| 77 | template<typename T> | |
| 78 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> orthoNO(T left, T right, T bottom, T top, T zNear, T zFar) | |
| 79 | { | |
| 80 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_LH_BIT | |
| 81 | return orthoLH_NO(left, right, bottom, top, zNear, zFar); | |
| 82 | # else | |
| 83 | return orthoRH_NO(left, right, bottom, top, zNear, zFar); | |
| 84 | # endif | |
| 85 | } | |
| 86 | ||
| 87 | template<typename T> | |
| 88 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> orthoLH(T left, T right, T bottom, T top, T zNear, T zFar) | |
| 89 | { | |
| 90 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_ZO_BIT | |
| 91 | return orthoLH_ZO(left, right, bottom, top, zNear, zFar); | |
| 92 | # else | |
| 93 | return orthoLH_NO(left, right, bottom, top, zNear, zFar); | |
| 94 | # endif | |
| 95 | ||
| 96 | } | |
| 97 | ||
| 98 | template<typename T> | |
| 99 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> orthoRH(T left, T right, T bottom, T top, T zNear, T zFar) | |
| 100 | { | |
| 101 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_ZO_BIT | |
| 102 | return orthoRH_ZO(left, right, bottom, top, zNear, zFar); | |
| 103 | # else | |
| 104 | return orthoRH_NO(left, right, bottom, top, zNear, zFar); | |
| 105 | # endif | |
| 106 | } | |
| 107 | ||
| 108 | template<typename T> | |
| 109 | 5x | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> ortho(T left, T right, T bottom, T top, T zNear, T zFar) |
| 110 | { | |
| 111 | # if GLM_CONFIG_CLIP_CONTROL == GLM_CLIP_CONTROL_LH_ZO | |
| 112 | return orthoLH_ZO(left, right, bottom, top, zNear, zFar); | |
| 113 | # elif GLM_CONFIG_CLIP_CONTROL == GLM_CLIP_CONTROL_LH_NO | |
| 114 | return orthoLH_NO(left, right, bottom, top, zNear, zFar); | |
| 115 | # elif GLM_CONFIG_CLIP_CONTROL == GLM_CLIP_CONTROL_RH_ZO | |
| 116 | return orthoRH_ZO(left, right, bottom, top, zNear, zFar); | |
| 117 | # elif GLM_CONFIG_CLIP_CONTROL == GLM_CLIP_CONTROL_RH_NO | |
| 118 | 5x | return orthoRH_NO(left, right, bottom, top, zNear, zFar); |
| 119 | # endif | |
| 120 | } | |
| 121 | ||
| 122 | template<typename T> | |
| 123 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> frustumLH_ZO(T left, T right, T bottom, T top, T nearVal, T farVal) | |
| 124 | { | |
| 125 | mat<4, 4, T, defaultp> Result(0); | |
| 126 | Result[0][0] = (static_cast<T>(2) * nearVal) / (right - left); | |
| 127 | Result[1][1] = (static_cast<T>(2) * nearVal) / (top - bottom); | |
| 128 | Result[2][0] = (right + left) / (right - left); | |
| 129 | Result[2][1] = (top + bottom) / (top - bottom); | |
| 130 | Result[2][2] = farVal / (farVal - nearVal); | |
| 131 | Result[2][3] = static_cast<T>(1); | |
| 132 | Result[3][2] = -(farVal * nearVal) / (farVal - nearVal); | |
| 133 | return Result; | |
| 134 | } | |
| 135 | ||
| 136 | template<typename T> | |
| 137 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> frustumLH_NO(T left, T right, T bottom, T top, T nearVal, T farVal) | |
| 138 | { | |
| 139 | mat<4, 4, T, defaultp> Result(0); | |
| 140 | Result[0][0] = (static_cast<T>(2) * nearVal) / (right - left); | |
| 141 | Result[1][1] = (static_cast<T>(2) * nearVal) / (top - bottom); | |
| 142 | Result[2][0] = (right + left) / (right - left); | |
| 143 | Result[2][1] = (top + bottom) / (top - bottom); | |
| 144 | Result[2][2] = (farVal + nearVal) / (farVal - nearVal); | |
| 145 | Result[2][3] = static_cast<T>(1); | |
| 146 | Result[3][2] = - (static_cast<T>(2) * farVal * nearVal) / (farVal - nearVal); | |
| 147 | return Result; | |
| 148 | } | |
| 149 | ||
| 150 | template<typename T> | |
| 151 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> frustumRH_ZO(T left, T right, T bottom, T top, T nearVal, T farVal) | |
| 152 | { | |
| 153 | mat<4, 4, T, defaultp> Result(0); | |
| 154 | Result[0][0] = (static_cast<T>(2) * nearVal) / (right - left); | |
| 155 | Result[1][1] = (static_cast<T>(2) * nearVal) / (top - bottom); | |
| 156 | Result[2][0] = (right + left) / (right - left); | |
| 157 | Result[2][1] = (top + bottom) / (top - bottom); | |
| 158 | Result[2][2] = farVal / (nearVal - farVal); | |
| 159 | Result[2][3] = static_cast<T>(-1); | |
| 160 | Result[3][2] = -(farVal * nearVal) / (farVal - nearVal); | |
| 161 | return Result; | |
| 162 | } | |
| 163 | ||
| 164 | template<typename T> | |
| 165 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> frustumRH_NO(T left, T right, T bottom, T top, T nearVal, T farVal) | |
| 166 | { | |
| 167 | mat<4, 4, T, defaultp> Result(0); | |
| 168 | Result[0][0] = (static_cast<T>(2) * nearVal) / (right - left); | |
| 169 | Result[1][1] = (static_cast<T>(2) * nearVal) / (top - bottom); | |
| 170 | Result[2][0] = (right + left) / (right - left); | |
| 171 | Result[2][1] = (top + bottom) / (top - bottom); | |
| 172 | Result[2][2] = - (farVal + nearVal) / (farVal - nearVal); | |
| 173 | Result[2][3] = static_cast<T>(-1); | |
| 174 | Result[3][2] = - (static_cast<T>(2) * farVal * nearVal) / (farVal - nearVal); | |
| 175 | return Result; | |
| 176 | } | |
| 177 | ||
| 178 | template<typename T> | |
| 179 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> frustumZO(T left, T right, T bottom, T top, T nearVal, T farVal) | |
| 180 | { | |
| 181 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_LH_BIT | |
| 182 | return frustumLH_ZO(left, right, bottom, top, nearVal, farVal); | |
| 183 | # else | |
| 184 | return frustumRH_ZO(left, right, bottom, top, nearVal, farVal); | |
| 185 | # endif | |
| 186 | } | |
| 187 | ||
| 188 | template<typename T> | |
| 189 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> frustumNO(T left, T right, T bottom, T top, T nearVal, T farVal) | |
| 190 | { | |
| 191 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_LH_BIT | |
| 192 | return frustumLH_NO(left, right, bottom, top, nearVal, farVal); | |
| 193 | # else | |
| 194 | return frustumRH_NO(left, right, bottom, top, nearVal, farVal); | |
| 195 | # endif | |
| 196 | } | |
| 197 | ||
| 198 | template<typename T> | |
| 199 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> frustumLH(T left, T right, T bottom, T top, T nearVal, T farVal) | |
| 200 | { | |
| 201 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_ZO_BIT | |
| 202 | return frustumLH_ZO(left, right, bottom, top, nearVal, farVal); | |
| 203 | # else | |
| 204 | return frustumLH_NO(left, right, bottom, top, nearVal, farVal); | |
| 205 | # endif | |
| 206 | } | |
| 207 | ||
| 208 | template<typename T> | |
| 209 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> frustumRH(T left, T right, T bottom, T top, T nearVal, T farVal) | |
| 210 | { | |
| 211 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_ZO_BIT | |
| 212 | return frustumRH_ZO(left, right, bottom, top, nearVal, farVal); | |
| 213 | # else | |
| 214 | return frustumRH_NO(left, right, bottom, top, nearVal, farVal); | |
| 215 | # endif | |
| 216 | } | |
| 217 | ||
| 218 | template<typename T> | |
| 219 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> frustum(T left, T right, T bottom, T top, T nearVal, T farVal) | |
| 220 | { | |
| 221 | # if GLM_CONFIG_CLIP_CONTROL == GLM_CLIP_CONTROL_LH_ZO | |
| 222 | return frustumLH_ZO(left, right, bottom, top, nearVal, farVal); | |
| 223 | # elif GLM_CONFIG_CLIP_CONTROL == GLM_CLIP_CONTROL_LH_NO | |
| 224 | return frustumLH_NO(left, right, bottom, top, nearVal, farVal); | |
| 225 | # elif GLM_CONFIG_CLIP_CONTROL == GLM_CLIP_CONTROL_RH_ZO | |
| 226 | return frustumRH_ZO(left, right, bottom, top, nearVal, farVal); | |
| 227 | # elif GLM_CONFIG_CLIP_CONTROL == GLM_CLIP_CONTROL_RH_NO | |
| 228 | return frustumRH_NO(left, right, bottom, top, nearVal, farVal); | |
| 229 | # endif | |
| 230 | } | |
| 231 | ||
| 232 | template<typename T> | |
| 233 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveRH_ZO(T fovy, T aspect, T zNear, T zFar) | |
| 234 | { | |
| 235 | assert(abs(aspect - std::numeric_limits<T>::epsilon()) > static_cast<T>(0)); | |
| 236 | ||
| 237 | T const tanHalfFovy = tan(fovy / static_cast<T>(2)); | |
| 238 | ||
| 239 | mat<4, 4, T, defaultp> Result(static_cast<T>(0)); | |
| 240 | Result[0][0] = static_cast<T>(1) / (aspect * tanHalfFovy); | |
| 241 | Result[1][1] = static_cast<T>(1) / (tanHalfFovy); | |
| 242 | Result[2][2] = zFar / (zNear - zFar); | |
| 243 | Result[2][3] = - static_cast<T>(1); | |
| 244 | Result[3][2] = -(zFar * zNear) / (zFar - zNear); | |
| 245 | return Result; | |
| 246 | } | |
| 247 | ||
| 248 | template<typename T> | |
| 249 | 5x | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveRH_NO(T fovy, T aspect, T zNear, T zFar) |
| 250 | { | |
| 251 | assert(abs(aspect - std::numeric_limits<T>::epsilon()) > static_cast<T>(0)); | |
| 252 | ||
| 253 | 5x | T const tanHalfFovy = tan(fovy / static_cast<T>(2)); |
| 254 | ||
| 255 | 5x | mat<4, 4, T, defaultp> Result(static_cast<T>(0)); |
| 256 | 5x | Result[0][0] = static_cast<T>(1) / (aspect * tanHalfFovy); |
| 257 | 5x | Result[1][1] = static_cast<T>(1) / (tanHalfFovy); |
| 258 | 5x | Result[2][2] = - (zFar + zNear) / (zFar - zNear); |
| 259 | 5x | Result[2][3] = - static_cast<T>(1); |
| 260 | 5x | Result[3][2] = - (static_cast<T>(2) * zFar * zNear) / (zFar - zNear); |
| 261 | 5x | return Result; |
| 262 | } | |
| 263 | ||
| 264 | template<typename T> | |
| 265 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveLH_ZO(T fovy, T aspect, T zNear, T zFar) | |
| 266 | { | |
| 267 | assert(abs(aspect - std::numeric_limits<T>::epsilon()) > static_cast<T>(0)); | |
| 268 | ||
| 269 | T const tanHalfFovy = tan(fovy / static_cast<T>(2)); | |
| 270 | ||
| 271 | mat<4, 4, T, defaultp> Result(static_cast<T>(0)); | |
| 272 | Result[0][0] = static_cast<T>(1) / (aspect * tanHalfFovy); | |
| 273 | Result[1][1] = static_cast<T>(1) / (tanHalfFovy); | |
| 274 | Result[2][2] = zFar / (zFar - zNear); | |
| 275 | Result[2][3] = static_cast<T>(1); | |
| 276 | Result[3][2] = -(zFar * zNear) / (zFar - zNear); | |
| 277 | return Result; | |
| 278 | } | |
| 279 | ||
| 280 | template<typename T> | |
| 281 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveLH_NO(T fovy, T aspect, T zNear, T zFar) | |
| 282 | { | |
| 283 | assert(abs(aspect - std::numeric_limits<T>::epsilon()) > static_cast<T>(0)); | |
| 284 | ||
| 285 | T const tanHalfFovy = tan(fovy / static_cast<T>(2)); | |
| 286 | ||
| 287 | mat<4, 4, T, defaultp> Result(static_cast<T>(0)); | |
| 288 | Result[0][0] = static_cast<T>(1) / (aspect * tanHalfFovy); | |
| 289 | Result[1][1] = static_cast<T>(1) / (tanHalfFovy); | |
| 290 | Result[2][2] = (zFar + zNear) / (zFar - zNear); | |
| 291 | Result[2][3] = static_cast<T>(1); | |
| 292 | Result[3][2] = - (static_cast<T>(2) * zFar * zNear) / (zFar - zNear); | |
| 293 | return Result; | |
| 294 | } | |
| 295 | ||
| 296 | template<typename T> | |
| 297 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveZO(T fovy, T aspect, T zNear, T zFar) | |
| 298 | { | |
| 299 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_LH_BIT | |
| 300 | return perspectiveLH_ZO(fovy, aspect, zNear, zFar); | |
| 301 | # else | |
| 302 | return perspectiveRH_ZO(fovy, aspect, zNear, zFar); | |
| 303 | # endif | |
| 304 | } | |
| 305 | ||
| 306 | template<typename T> | |
| 307 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveNO(T fovy, T aspect, T zNear, T zFar) | |
| 308 | { | |
| 309 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_LH_BIT | |
| 310 | return perspectiveLH_NO(fovy, aspect, zNear, zFar); | |
| 311 | # else | |
| 312 | return perspectiveRH_NO(fovy, aspect, zNear, zFar); | |
| 313 | # endif | |
| 314 | } | |
| 315 | ||
| 316 | template<typename T> | |
| 317 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveLH(T fovy, T aspect, T zNear, T zFar) | |
| 318 | { | |
| 319 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_ZO_BIT | |
| 320 | return perspectiveLH_ZO(fovy, aspect, zNear, zFar); | |
| 321 | # else | |
| 322 | return perspectiveLH_NO(fovy, aspect, zNear, zFar); | |
| 323 | # endif | |
| 324 | ||
| 325 | } | |
| 326 | ||
| 327 | template<typename T> | |
| 328 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveRH(T fovy, T aspect, T zNear, T zFar) | |
| 329 | { | |
| 330 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_ZO_BIT | |
| 331 | return perspectiveRH_ZO(fovy, aspect, zNear, zFar); | |
| 332 | # else | |
| 333 | return perspectiveRH_NO(fovy, aspect, zNear, zFar); | |
| 334 | # endif | |
| 335 | } | |
| 336 | ||
| 337 | template<typename T> | |
| 338 | 5x | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspective(T fovy, T aspect, T zNear, T zFar) |
| 339 | { | |
| 340 | # if GLM_CONFIG_CLIP_CONTROL == GLM_CLIP_CONTROL_LH_ZO | |
| 341 | return perspectiveLH_ZO(fovy, aspect, zNear, zFar); | |
| 342 | # elif GLM_CONFIG_CLIP_CONTROL == GLM_CLIP_CONTROL_LH_NO | |
| 343 | return perspectiveLH_NO(fovy, aspect, zNear, zFar); | |
| 344 | # elif GLM_CONFIG_CLIP_CONTROL == GLM_CLIP_CONTROL_RH_ZO | |
| 345 | return perspectiveRH_ZO(fovy, aspect, zNear, zFar); | |
| 346 | # elif GLM_CONFIG_CLIP_CONTROL == GLM_CLIP_CONTROL_RH_NO | |
| 347 | 5x | return perspectiveRH_NO(fovy, aspect, zNear, zFar); |
| 348 | # endif | |
| 349 | } | |
| 350 | ||
| 351 | template<typename T> | |
| 352 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveFovRH_ZO(T fov, T width, T height, T zNear, T zFar) | |
| 353 | { | |
| 354 | assert(width > static_cast<T>(0)); | |
| 355 | assert(height > static_cast<T>(0)); | |
| 356 | assert(fov > static_cast<T>(0)); | |
| 357 | ||
| 358 | T const rad = fov; | |
| 359 | T const h = glm::cos(static_cast<T>(0.5) * rad) / glm::sin(static_cast<T>(0.5) * rad); | |
| 360 | T const w = h * height / width; ///todo max(width , Height) / min(width , Height)? | |
| 361 | ||
| 362 | mat<4, 4, T, defaultp> Result(static_cast<T>(0)); | |
| 363 | Result[0][0] = w; | |
| 364 | Result[1][1] = h; | |
| 365 | Result[2][2] = zFar / (zNear - zFar); | |
| 366 | Result[2][3] = - static_cast<T>(1); | |
| 367 | Result[3][2] = -(zFar * zNear) / (zFar - zNear); | |
| 368 | return Result; | |
| 369 | } | |
| 370 | ||
| 371 | template<typename T> | |
| 372 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveFovRH_NO(T fov, T width, T height, T zNear, T zFar) | |
| 373 | { | |
| 374 | assert(width > static_cast<T>(0)); | |
| 375 | assert(height > static_cast<T>(0)); | |
| 376 | assert(fov > static_cast<T>(0)); | |
| 377 | ||
| 378 | T const rad = fov; | |
| 379 | T const h = glm::cos(static_cast<T>(0.5) * rad) / glm::sin(static_cast<T>(0.5) * rad); | |
| 380 | T const w = h * height / width; ///todo max(width , Height) / min(width , Height)? | |
| 381 | ||
| 382 | mat<4, 4, T, defaultp> Result(static_cast<T>(0)); | |
| 383 | Result[0][0] = w; | |
| 384 | Result[1][1] = h; | |
| 385 | Result[2][2] = - (zFar + zNear) / (zFar - zNear); | |
| 386 | Result[2][3] = - static_cast<T>(1); | |
| 387 | Result[3][2] = - (static_cast<T>(2) * zFar * zNear) / (zFar - zNear); | |
| 388 | return Result; | |
| 389 | } | |
| 390 | ||
| 391 | template<typename T> | |
| 392 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveFovLH_ZO(T fov, T width, T height, T zNear, T zFar) | |
| 393 | { | |
| 394 | assert(width > static_cast<T>(0)); | |
| 395 | assert(height > static_cast<T>(0)); | |
| 396 | assert(fov > static_cast<T>(0)); | |
| 397 | ||
| 398 | T const rad = fov; | |
| 399 | T const h = glm::cos(static_cast<T>(0.5) * rad) / glm::sin(static_cast<T>(0.5) * rad); | |
| 400 | T const w = h * height / width; ///todo max(width , Height) / min(width , Height)? | |
| 401 | ||
| 402 | mat<4, 4, T, defaultp> Result(static_cast<T>(0)); | |
| 403 | Result[0][0] = w; | |
| 404 | Result[1][1] = h; | |
| 405 | Result[2][2] = zFar / (zFar - zNear); | |
| 406 | Result[2][3] = static_cast<T>(1); | |
| 407 | Result[3][2] = -(zFar * zNear) / (zFar - zNear); | |
| 408 | return Result; | |
| 409 | } | |
| 410 | ||
| 411 | template<typename T> | |
| 412 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveFovLH_NO(T fov, T width, T height, T zNear, T zFar) | |
| 413 | { | |
| 414 | assert(width > static_cast<T>(0)); | |
| 415 | assert(height > static_cast<T>(0)); | |
| 416 | assert(fov > static_cast<T>(0)); | |
| 417 | ||
| 418 | T const rad = fov; | |
| 419 | T const h = glm::cos(static_cast<T>(0.5) * rad) / glm::sin(static_cast<T>(0.5) * rad); | |
| 420 | T const w = h * height / width; ///todo max(width , Height) / min(width , Height)? | |
| 421 | ||
| 422 | mat<4, 4, T, defaultp> Result(static_cast<T>(0)); | |
| 423 | Result[0][0] = w; | |
| 424 | Result[1][1] = h; | |
| 425 | Result[2][2] = (zFar + zNear) / (zFar - zNear); | |
| 426 | Result[2][3] = static_cast<T>(1); | |
| 427 | Result[3][2] = - (static_cast<T>(2) * zFar * zNear) / (zFar - zNear); | |
| 428 | return Result; | |
| 429 | } | |
| 430 | ||
| 431 | template<typename T> | |
| 432 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveFovZO(T fov, T width, T height, T zNear, T zFar) | |
| 433 | { | |
| 434 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_LH_BIT | |
| 435 | return perspectiveFovLH_ZO(fov, width, height, zNear, zFar); | |
| 436 | # else | |
| 437 | return perspectiveFovRH_ZO(fov, width, height, zNear, zFar); | |
| 438 | # endif | |
| 439 | } | |
| 440 | ||
| 441 | template<typename T> | |
| 442 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveFovNO(T fov, T width, T height, T zNear, T zFar) | |
| 443 | { | |
| 444 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_LH_BIT | |
| 445 | return perspectiveFovLH_NO(fov, width, height, zNear, zFar); | |
| 446 | # else | |
| 447 | return perspectiveFovRH_NO(fov, width, height, zNear, zFar); | |
| 448 | # endif | |
| 449 | } | |
| 450 | ||
| 451 | template<typename T> | |
| 452 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveFovLH(T fov, T width, T height, T zNear, T zFar) | |
| 453 | { | |
| 454 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_ZO_BIT | |
| 455 | return perspectiveFovLH_ZO(fov, width, height, zNear, zFar); | |
| 456 | # else | |
| 457 | return perspectiveFovLH_NO(fov, width, height, zNear, zFar); | |
| 458 | # endif | |
| 459 | } | |
| 460 | ||
| 461 | template<typename T> | |
| 462 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveFovRH(T fov, T width, T height, T zNear, T zFar) | |
| 463 | { | |
| 464 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_ZO_BIT | |
| 465 | return perspectiveFovRH_ZO(fov, width, height, zNear, zFar); | |
| 466 | # else | |
| 467 | return perspectiveFovRH_NO(fov, width, height, zNear, zFar); | |
| 468 | # endif | |
| 469 | } | |
| 470 | ||
| 471 | template<typename T> | |
| 472 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> perspectiveFov(T fov, T width, T height, T zNear, T zFar) | |
| 473 | { | |
| 474 | # if GLM_CONFIG_CLIP_CONTROL == GLM_CLIP_CONTROL_LH_ZO | |
| 475 | return perspectiveFovLH_ZO(fov, width, height, zNear, zFar); | |
| 476 | # elif GLM_CONFIG_CLIP_CONTROL == GLM_CLIP_CONTROL_LH_NO | |
| 477 | return perspectiveFovLH_NO(fov, width, height, zNear, zFar); | |
| 478 | # elif GLM_CONFIG_CLIP_CONTROL == GLM_CLIP_CONTROL_RH_ZO | |
| 479 | return perspectiveFovRH_ZO(fov, width, height, zNear, zFar); | |
| 480 | # elif GLM_CONFIG_CLIP_CONTROL == GLM_CLIP_CONTROL_RH_NO | |
| 481 | return perspectiveFovRH_NO(fov, width, height, zNear, zFar); | |
| 482 | # endif | |
| 483 | } | |
| 484 | ||
| 485 | template<typename T> | |
| 486 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> infinitePerspectiveRH(T fovy, T aspect, T zNear) | |
| 487 | { | |
| 488 | T const range = tan(fovy / static_cast<T>(2)) * zNear; | |
| 489 | T const left = -range * aspect; | |
| 490 | T const right = range * aspect; | |
| 491 | T const bottom = -range; | |
| 492 | T const top = range; | |
| 493 | ||
| 494 | mat<4, 4, T, defaultp> Result(static_cast<T>(0)); | |
| 495 | Result[0][0] = (static_cast<T>(2) * zNear) / (right - left); | |
| 496 | Result[1][1] = (static_cast<T>(2) * zNear) / (top - bottom); | |
| 497 | Result[2][2] = - static_cast<T>(1); | |
| 498 | Result[2][3] = - static_cast<T>(1); | |
| 499 | Result[3][2] = - static_cast<T>(2) * zNear; | |
| 500 | return Result; | |
| 501 | } | |
| 502 | ||
| 503 | template<typename T> | |
| 504 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> infinitePerspectiveLH(T fovy, T aspect, T zNear) | |
| 505 | { | |
| 506 | T const range = tan(fovy / static_cast<T>(2)) * zNear; | |
| 507 | T const left = -range * aspect; | |
| 508 | T const right = range * aspect; | |
| 509 | T const bottom = -range; | |
| 510 | T const top = range; | |
| 511 | ||
| 512 | mat<4, 4, T, defaultp> Result(T(0)); | |
| 513 | Result[0][0] = (static_cast<T>(2) * zNear) / (right - left); | |
| 514 | Result[1][1] = (static_cast<T>(2) * zNear) / (top - bottom); | |
| 515 | Result[2][2] = static_cast<T>(1); | |
| 516 | Result[2][3] = static_cast<T>(1); | |
| 517 | Result[3][2] = - static_cast<T>(2) * zNear; | |
| 518 | return Result; | |
| 519 | } | |
| 520 | ||
| 521 | template<typename T> | |
| 522 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> infinitePerspective(T fovy, T aspect, T zNear) | |
| 523 | { | |
| 524 | # if GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_LH_BIT | |
| 525 | return infinitePerspectiveLH(fovy, aspect, zNear); | |
| 526 | # else | |
| 527 | return infinitePerspectiveRH(fovy, aspect, zNear); | |
| 528 | # endif | |
| 529 | } | |
| 530 | ||
| 531 | // Infinite projection matrix: http://www.terathon.com/gdc07_lengyel.pdf | |
| 532 | template<typename T> | |
| 533 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> tweakedInfinitePerspective(T fovy, T aspect, T zNear, T ep) | |
| 534 | { | |
| 535 | T const range = tan(fovy / static_cast<T>(2)) * zNear; | |
| 536 | T const left = -range * aspect; | |
| 537 | T const right = range * aspect; | |
| 538 | T const bottom = -range; | |
| 539 | T const top = range; | |
| 540 | ||
| 541 | mat<4, 4, T, defaultp> Result(static_cast<T>(0)); | |
| 542 | Result[0][0] = (static_cast<T>(2) * zNear) / (right - left); | |
| 543 | Result[1][1] = (static_cast<T>(2) * zNear) / (top - bottom); | |
| 544 | Result[2][2] = ep - static_cast<T>(1); | |
| 545 | Result[2][3] = static_cast<T>(-1); | |
| 546 | Result[3][2] = (ep - static_cast<T>(2)) * zNear; | |
| 547 | return Result; | |
| 548 | } | |
| 549 | ||
| 550 | template<typename T> | |
| 551 | GLM_FUNC_QUALIFIER mat<4, 4, T, defaultp> tweakedInfinitePerspective(T fovy, T aspect, T zNear) | |
| 552 | { | |
| 553 | return tweakedInfinitePerspective(fovy, aspect, zNear, epsilon<T>()); | |
| 554 | } | |
| 555 | }//namespace glm |
| 1 | #include "../matrix.hpp" | |
| 2 | ||
| 3 | namespace glm | |
| 4 | { | |
| 5 | // -- Constructors -- | |
| 6 | ||
| 7 | # if GLM_CONFIG_DEFAULTED_FUNCTIONS == GLM_DISABLE | |
| 8 | template<typename T, qualifier Q> | |
| 9 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 4, T, Q>::mat() | |
| 10 | # if GLM_CONFIG_CTOR_INIT == GLM_CTOR_INITIALIZER_LIST | |
| 11 | : value{col_type(1, 0, 0, 0), col_type(0, 1, 0, 0), col_type(0, 0, 1, 0), col_type(0, 0, 0, 1)} | |
| 12 | # endif | |
| 13 | { | |
| 14 | # if GLM_CONFIG_CTOR_INIT == GLM_CTOR_INITIALISATION | |
| 15 | this->value[0] = col_type(1, 0, 0, 0); | |
| 16 | this->value[1] = col_type(0, 1, 0, 0); | |
| 17 | this->value[2] = col_type(0, 0, 1, 0); | |
| 18 | this->value[3] = col_type(0, 0, 0, 1); | |
| 19 | # endif | |
| 20 | } | |
| 21 | # endif | |
| 22 | ||
| 23 | template<typename T, qualifier Q> | |
| 24 | template<qualifier P> | |
| 25 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 4, T, Q>::mat(mat<4, 4, T, P> const& m) | |
| 26 | # if GLM_HAS_INITIALIZER_LISTS | |
| 27 | : value{col_type(m[0]), col_type(m[1]), col_type(m[2]), col_type(m[3])} | |
| 28 | # endif | |
| 29 | { | |
| 30 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 31 | this->value[0] = m[0]; | |
| 32 | this->value[1] = m[1]; | |
| 33 | this->value[2] = m[2]; | |
| 34 | this->value[3] = m[3]; | |
| 35 | # endif | |
| 36 | } | |
| 37 | ||
| 38 | template<typename T, qualifier Q> | |
| 39 | 37x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 4, T, Q>::mat(T const& s) |
| 40 | # if GLM_HAS_INITIALIZER_LISTS | |
| 41 | 37x | : value{col_type(s, 0, 0, 0), col_type(0, s, 0, 0), col_type(0, 0, s, 0), col_type(0, 0, 0, s)} |
| 42 | # endif | |
| 43 | { | |
| 44 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 45 | this->value[0] = col_type(s, 0, 0, 0); | |
| 46 | this->value[1] = col_type(0, s, 0, 0); | |
| 47 | this->value[2] = col_type(0, 0, s, 0); | |
| 48 | this->value[3] = col_type(0, 0, 0, s); | |
| 49 | # endif | |
| 50 | } | |
| 51 | ||
| 52 | template<typename T, qualifier Q> | |
| 53 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 4, T, Q>::mat | |
| 54 | ( | |
| 55 | T const& x0, T const& y0, T const& z0, T const& w0, | |
| 56 | T const& x1, T const& y1, T const& z1, T const& w1, | |
| 57 | T const& x2, T const& y2, T const& z2, T const& w2, | |
| 58 | T const& x3, T const& y3, T const& z3, T const& w3 | |
| 59 | ) | |
| 60 | # if GLM_HAS_INITIALIZER_LISTS | |
| 61 | : value{ | |
| 62 | col_type(x0, y0, z0, w0), | |
| 63 | col_type(x1, y1, z1, w1), | |
| 64 | col_type(x2, y2, z2, w2), | |
| 65 | col_type(x3, y3, z3, w3)} | |
| 66 | # endif | |
| 67 | { | |
| 68 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 69 | this->value[0] = col_type(x0, y0, z0, w0); | |
| 70 | this->value[1] = col_type(x1, y1, z1, w1); | |
| 71 | this->value[2] = col_type(x2, y2, z2, w2); | |
| 72 | this->value[3] = col_type(x3, y3, z3, w3); | |
| 73 | # endif | |
| 74 | } | |
| 75 | ||
| 76 | template<typename T, qualifier Q> | |
| 77 | 54x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 4, T, Q>::mat(col_type const& v0, col_type const& v1, col_type const& v2, col_type const& v3) |
| 78 | # if GLM_HAS_INITIALIZER_LISTS | |
| 79 | 54x | : value{col_type(v0), col_type(v1), col_type(v2), col_type(v3)} |
| 80 | # endif | |
| 81 | { | |
| 82 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 83 | this->value[0] = v0; | |
| 84 | this->value[1] = v1; | |
| 85 | this->value[2] = v2; | |
| 86 | this->value[3] = v3; | |
| 87 | # endif | |
| 88 | } | |
| 89 | ||
| 90 | template<typename T, qualifier Q> | |
| 91 | template<typename U, qualifier P> | |
| 92 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 4, T, Q>::mat(mat<4, 4, U, P> const& m) | |
| 93 | # if GLM_HAS_INITIALIZER_LISTS | |
| 94 | : value{col_type(m[0]), col_type(m[1]), col_type(m[2]), col_type(m[3])} | |
| 95 | # endif | |
| 96 | { | |
| 97 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 98 | this->value[0] = col_type(m[0]); | |
| 99 | this->value[1] = col_type(m[1]); | |
| 100 | this->value[2] = col_type(m[2]); | |
| 101 | this->value[3] = col_type(m[3]); | |
| 102 | # endif | |
| 103 | } | |
| 104 | ||
| 105 | // -- Conversions -- | |
| 106 | ||
| 107 | template<typename T, qualifier Q> | |
| 108 | template< | |
| 109 | typename X1, typename Y1, typename Z1, typename W1, | |
| 110 | typename X2, typename Y2, typename Z2, typename W2, | |
| 111 | typename X3, typename Y3, typename Z3, typename W3, | |
| 112 | typename X4, typename Y4, typename Z4, typename W4> | |
| 113 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 4, T, Q>::mat | |
| 114 | ( | |
| 115 | X1 const& x1, Y1 const& y1, Z1 const& z1, W1 const& w1, | |
| 116 | X2 const& x2, Y2 const& y2, Z2 const& z2, W2 const& w2, | |
| 117 | X3 const& x3, Y3 const& y3, Z3 const& z3, W3 const& w3, | |
| 118 | X4 const& x4, Y4 const& y4, Z4 const& z4, W4 const& w4 | |
| 119 | ) | |
| 120 | # if GLM_HAS_INITIALIZER_LISTS | |
| 121 | : value{col_type(x1, y1, z1, w1), col_type(x2, y2, z2, w2), col_type(x3, y3, z3, w3), col_type(x4, y4, z4, w4)} | |
| 122 | # endif | |
| 123 | { | |
| 124 | GLM_STATIC_ASSERT(std::numeric_limits<X1>::is_iec559 || std::numeric_limits<X1>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 1st parameter type invalid."); | |
| 125 | GLM_STATIC_ASSERT(std::numeric_limits<Y1>::is_iec559 || std::numeric_limits<Y1>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 2nd parameter type invalid."); | |
| 126 | GLM_STATIC_ASSERT(std::numeric_limits<Z1>::is_iec559 || std::numeric_limits<Z1>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 3rd parameter type invalid."); | |
| 127 | GLM_STATIC_ASSERT(std::numeric_limits<W1>::is_iec559 || std::numeric_limits<W1>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 4th parameter type invalid."); | |
| 128 | ||
| 129 | GLM_STATIC_ASSERT(std::numeric_limits<X2>::is_iec559 || std::numeric_limits<X2>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 5th parameter type invalid."); | |
| 130 | GLM_STATIC_ASSERT(std::numeric_limits<Y2>::is_iec559 || std::numeric_limits<Y2>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 6th parameter type invalid."); | |
| 131 | GLM_STATIC_ASSERT(std::numeric_limits<Z2>::is_iec559 || std::numeric_limits<Z2>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 7th parameter type invalid."); | |
| 132 | GLM_STATIC_ASSERT(std::numeric_limits<W2>::is_iec559 || std::numeric_limits<W2>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 8th parameter type invalid."); | |
| 133 | ||
| 134 | GLM_STATIC_ASSERT(std::numeric_limits<X3>::is_iec559 || std::numeric_limits<X3>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 9th parameter type invalid."); | |
| 135 | GLM_STATIC_ASSERT(std::numeric_limits<Y3>::is_iec559 || std::numeric_limits<Y3>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 10th parameter type invalid."); | |
| 136 | GLM_STATIC_ASSERT(std::numeric_limits<Z3>::is_iec559 || std::numeric_limits<Z3>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 11th parameter type invalid."); | |
| 137 | GLM_STATIC_ASSERT(std::numeric_limits<W3>::is_iec559 || std::numeric_limits<W3>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 12th parameter type invalid."); | |
| 138 | ||
| 139 | GLM_STATIC_ASSERT(std::numeric_limits<X4>::is_iec559 || std::numeric_limits<X4>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 13th parameter type invalid."); | |
| 140 | GLM_STATIC_ASSERT(std::numeric_limits<Y4>::is_iec559 || std::numeric_limits<Y4>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 14th parameter type invalid."); | |
| 141 | GLM_STATIC_ASSERT(std::numeric_limits<Z4>::is_iec559 || std::numeric_limits<Z4>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 15th parameter type invalid."); | |
| 142 | GLM_STATIC_ASSERT(std::numeric_limits<W4>::is_iec559 || std::numeric_limits<W4>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 16th parameter type invalid."); | |
| 143 | ||
| 144 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 145 | this->value[0] = col_type(x1, y1, z1, w1); | |
| 146 | this->value[1] = col_type(x2, y2, z2, w2); | |
| 147 | this->value[2] = col_type(x3, y3, z3, w3); | |
| 148 | this->value[3] = col_type(x4, y4, z4, w4); | |
| 149 | # endif | |
| 150 | } | |
| 151 | ||
| 152 | template<typename T, qualifier Q> | |
| 153 | template<typename V1, typename V2, typename V3, typename V4> | |
| 154 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 4, T, Q>::mat(vec<4, V1, Q> const& v1, vec<4, V2, Q> const& v2, vec<4, V3, Q> const& v3, vec<4, V4, Q> const& v4) | |
| 155 | # if GLM_HAS_INITIALIZER_LISTS | |
| 156 | : value{col_type(v1), col_type(v2), col_type(v3), col_type(v4)} | |
| 157 | # endif | |
| 158 | { | |
| 159 | GLM_STATIC_ASSERT(std::numeric_limits<V1>::is_iec559 || std::numeric_limits<V1>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 1st parameter type invalid."); | |
| 160 | GLM_STATIC_ASSERT(std::numeric_limits<V2>::is_iec559 || std::numeric_limits<V2>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 2nd parameter type invalid."); | |
| 161 | GLM_STATIC_ASSERT(std::numeric_limits<V3>::is_iec559 || std::numeric_limits<V3>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 3rd parameter type invalid."); | |
| 162 | GLM_STATIC_ASSERT(std::numeric_limits<V4>::is_iec559 || std::numeric_limits<V4>::is_integer || GLM_CONFIG_UNRESTRICTED_GENTYPE, "*mat4x4 constructor only takes float and integer types, 4th parameter type invalid."); | |
| 163 | ||
| 164 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 165 | this->value[0] = col_type(v1); | |
| 166 | this->value[1] = col_type(v2); | |
| 167 | this->value[2] = col_type(v3); | |
| 168 | this->value[3] = col_type(v4); | |
| 169 | # endif | |
| 170 | } | |
| 171 | ||
| 172 | // -- Matrix conversions -- | |
| 173 | ||
| 174 | template<typename T, qualifier Q> | |
| 175 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 4, T, Q>::mat(mat<2, 2, T, Q> const& m) | |
| 176 | # if GLM_HAS_INITIALIZER_LISTS | |
| 177 | : value{col_type(m[0], 0, 0), col_type(m[1], 0, 0), col_type(0, 0, 1, 0), col_type(0, 0, 0, 1)} | |
| 178 | # endif | |
| 179 | { | |
| 180 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 181 | this->value[0] = col_type(m[0], 0, 0); | |
| 182 | this->value[1] = col_type(m[1], 0, 0); | |
| 183 | this->value[2] = col_type(0, 0, 1, 0); | |
| 184 | this->value[3] = col_type(0, 0, 0, 1); | |
| 185 | # endif | |
| 186 | } | |
| 187 | ||
| 188 | template<typename T, qualifier Q> | |
| 189 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 4, T, Q>::mat(mat<3, 3, T, Q> const& m) | |
| 190 | # if GLM_HAS_INITIALIZER_LISTS | |
| 191 | : value{col_type(m[0], 0), col_type(m[1], 0), col_type(m[2], 0), col_type(0, 0, 0, 1)} | |
| 192 | # endif | |
| 193 | { | |
| 194 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 195 | this->value[0] = col_type(m[0], 0); | |
| 196 | this->value[1] = col_type(m[1], 0); | |
| 197 | this->value[2] = col_type(m[2], 0); | |
| 198 | this->value[3] = col_type(0, 0, 0, 1); | |
| 199 | # endif | |
| 200 | } | |
| 201 | ||
| 202 | template<typename T, qualifier Q> | |
| 203 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 4, T, Q>::mat(mat<2, 3, T, Q> const& m) | |
| 204 | # if GLM_HAS_INITIALIZER_LISTS | |
| 205 | : value{col_type(m[0], 0), col_type(m[1], 0), col_type(0, 0, 1, 0), col_type(0, 0, 0, 1)} | |
| 206 | # endif | |
| 207 | { | |
| 208 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 209 | this->value[0] = col_type(m[0], 0); | |
| 210 | this->value[1] = col_type(m[1], 0); | |
| 211 | this->value[2] = col_type(0, 0, 1, 0); | |
| 212 | this->value[3] = col_type(0, 0, 0, 1); | |
| 213 | # endif | |
| 214 | } | |
| 215 | ||
| 216 | template<typename T, qualifier Q> | |
| 217 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 4, T, Q>::mat(mat<3, 2, T, Q> const& m) | |
| 218 | # if GLM_HAS_INITIALIZER_LISTS | |
| 219 | : value{col_type(m[0], 0, 0), col_type(m[1], 0, 0), col_type(m[2], 1, 0), col_type(0, 0, 0, 1)} | |
| 220 | # endif | |
| 221 | { | |
| 222 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 223 | this->value[0] = col_type(m[0], 0, 0); | |
| 224 | this->value[1] = col_type(m[1], 0, 0); | |
| 225 | this->value[2] = col_type(m[2], 1, 0); | |
| 226 | this->value[3] = col_type(0, 0, 0, 1); | |
| 227 | # endif | |
| 228 | } | |
| 229 | ||
| 230 | template<typename T, qualifier Q> | |
| 231 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 4, T, Q>::mat(mat<2, 4, T, Q> const& m) | |
| 232 | # if GLM_HAS_INITIALIZER_LISTS | |
| 233 | : value{col_type(m[0]), col_type(m[1]), col_type(0, 0, 1, 0), col_type(0, 0, 0, 1)} | |
| 234 | # endif | |
| 235 | { | |
| 236 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 237 | this->value[0] = m[0]; | |
| 238 | this->value[1] = m[1]; | |
| 239 | this->value[2] = col_type(0, 0, 1, 0); | |
| 240 | this->value[3] = col_type(0, 0, 0, 1); | |
| 241 | # endif | |
| 242 | } | |
| 243 | ||
| 244 | template<typename T, qualifier Q> | |
| 245 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 4, T, Q>::mat(mat<4, 2, T, Q> const& m) | |
| 246 | # if GLM_HAS_INITIALIZER_LISTS | |
| 247 | : value{col_type(m[0], 0, 0), col_type(m[1], 0, 0), col_type(0, 0, 1, 0), col_type(0, 0, 0, 1)} | |
| 248 | # endif | |
| 249 | { | |
| 250 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 251 | this->value[0] = col_type(m[0], 0, 0); | |
| 252 | this->value[1] = col_type(m[1], 0, 0); | |
| 253 | this->value[2] = col_type(0, 0, 1, 0); | |
| 254 | this->value[3] = col_type(0, 0, 0, 1); | |
| 255 | # endif | |
| 256 | } | |
| 257 | ||
| 258 | template<typename T, qualifier Q> | |
| 259 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 4, T, Q>::mat(mat<3, 4, T, Q> const& m) | |
| 260 | # if GLM_HAS_INITIALIZER_LISTS | |
| 261 | : value{col_type(m[0]), col_type(m[1]), col_type(m[2]), col_type(0, 0, 0, 1)} | |
| 262 | # endif | |
| 263 | { | |
| 264 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 265 | this->value[0] = m[0]; | |
| 266 | this->value[1] = m[1]; | |
| 267 | this->value[2] = m[2]; | |
| 268 | this->value[3] = col_type(0, 0, 0, 1); | |
| 269 | # endif | |
| 270 | } | |
| 271 | ||
| 272 | template<typename T, qualifier Q> | |
| 273 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<4, 4, T, Q>::mat(mat<4, 3, T, Q> const& m) | |
| 274 | # if GLM_HAS_INITIALIZER_LISTS | |
| 275 | : value{col_type(m[0], 0), col_type(m[1], 0), col_type(m[2], 0), col_type(m[3], 1)} | |
| 276 | # endif | |
| 277 | { | |
| 278 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 279 | this->value[0] = col_type(m[0], 0); | |
| 280 | this->value[1] = col_type(m[1], 0); | |
| 281 | this->value[2] = col_type(m[2], 0); | |
| 282 | this->value[3] = col_type(m[3], 1); | |
| 283 | # endif | |
| 284 | } | |
| 285 | ||
| 286 | // -- Accesses -- | |
| 287 | ||
| 288 | template<typename T, qualifier Q> | |
| 289 | 21776x | GLM_FUNC_QUALIFIER typename mat<4, 4, T, Q>::col_type & mat<4, 4, T, Q>::operator[](typename mat<4, 4, T, Q>::length_type i) |
| 290 | { | |
| 291 | assert(i < this->length()); | |
| 292 | 21776x | return this->value[i]; |
| 293 | } | |
| 294 | ||
| 295 | template<typename T, qualifier Q> | |
| 296 | 5477867x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR typename mat<4, 4, T, Q>::col_type const& mat<4, 4, T, Q>::operator[](typename mat<4, 4, T, Q>::length_type i) const |
| 297 | { | |
| 298 | assert(i < this->length()); | |
| 299 | 5477867x | return this->value[i]; |
| 300 | } | |
| 301 | ||
| 302 | // -- Unary arithmetic operators -- | |
| 303 | ||
| 304 | template<typename T, qualifier Q> | |
| 305 | template<typename U> | |
| 306 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q>& mat<4, 4, T, Q>::operator=(mat<4, 4, U, Q> const& m) | |
| 307 | { | |
| 308 | //memcpy could be faster | |
| 309 | //memcpy(&this->value, &m.value, 16 * sizeof(valType)); | |
| 310 | this->value[0] = m[0]; | |
| 311 | this->value[1] = m[1]; | |
| 312 | this->value[2] = m[2]; | |
| 313 | this->value[3] = m[3]; | |
| 314 | return *this; | |
| 315 | } | |
| 316 | ||
| 317 | template<typename T, qualifier Q> | |
| 318 | template<typename U> | |
| 319 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q>& mat<4, 4, T, Q>::operator+=(U s) | |
| 320 | { | |
| 321 | this->value[0] += s; | |
| 322 | this->value[1] += s; | |
| 323 | this->value[2] += s; | |
| 324 | this->value[3] += s; | |
| 325 | return *this; | |
| 326 | } | |
| 327 | ||
| 328 | template<typename T, qualifier Q> | |
| 329 | template<typename U> | |
| 330 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q>& mat<4, 4, T, Q>::operator+=(mat<4, 4, U, Q> const& m) | |
| 331 | { | |
| 332 | this->value[0] += m[0]; | |
| 333 | this->value[1] += m[1]; | |
| 334 | this->value[2] += m[2]; | |
| 335 | this->value[3] += m[3]; | |
| 336 | return *this; | |
| 337 | } | |
| 338 | ||
| 339 | template<typename T, qualifier Q> | |
| 340 | template<typename U> | |
| 341 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> & mat<4, 4, T, Q>::operator-=(U s) | |
| 342 | { | |
| 343 | this->value[0] -= s; | |
| 344 | this->value[1] -= s; | |
| 345 | this->value[2] -= s; | |
| 346 | this->value[3] -= s; | |
| 347 | return *this; | |
| 348 | } | |
| 349 | ||
| 350 | template<typename T, qualifier Q> | |
| 351 | template<typename U> | |
| 352 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> & mat<4, 4, T, Q>::operator-=(mat<4, 4, U, Q> const& m) | |
| 353 | { | |
| 354 | this->value[0] -= m[0]; | |
| 355 | this->value[1] -= m[1]; | |
| 356 | this->value[2] -= m[2]; | |
| 357 | this->value[3] -= m[3]; | |
| 358 | return *this; | |
| 359 | } | |
| 360 | ||
| 361 | template<typename T, qualifier Q> | |
| 362 | template<typename U> | |
| 363 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> & mat<4, 4, T, Q>::operator*=(U s) | |
| 364 | { | |
| 365 | this->value[0] *= s; | |
| 366 | this->value[1] *= s; | |
| 367 | this->value[2] *= s; | |
| 368 | this->value[3] *= s; | |
| 369 | return *this; | |
| 370 | } | |
| 371 | ||
| 372 | template<typename T, qualifier Q> | |
| 373 | template<typename U> | |
| 374 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> & mat<4, 4, T, Q>::operator*=(mat<4, 4, U, Q> const& m) | |
| 375 | { | |
| 376 | return (*this = *this * m); | |
| 377 | } | |
| 378 | ||
| 379 | template<typename T, qualifier Q> | |
| 380 | template<typename U> | |
| 381 | 11x | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> & mat<4, 4, T, Q>::operator/=(U s) |
| 382 | { | |
| 383 | 11x | this->value[0] /= s; |
| 384 | 11x | this->value[1] /= s; |
| 385 | 11x | this->value[2] /= s; |
| 386 | 11x | this->value[3] /= s; |
| 387 | 11x | return *this; |
| 388 | } | |
| 389 | ||
| 390 | template<typename T, qualifier Q> | |
| 391 | template<typename U> | |
| 392 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> & mat<4, 4, T, Q>::operator/=(mat<4, 4, U, Q> const& m) | |
| 393 | { | |
| 394 | return *this *= inverse(m); | |
| 395 | } | |
| 396 | ||
| 397 | // -- Increment and decrement operators -- | |
| 398 | ||
| 399 | template<typename T, qualifier Q> | |
| 400 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> & mat<4, 4, T, Q>::operator++() | |
| 401 | { | |
| 402 | ++this->value[0]; | |
| 403 | ++this->value[1]; | |
| 404 | ++this->value[2]; | |
| 405 | ++this->value[3]; | |
| 406 | return *this; | |
| 407 | } | |
| 408 | ||
| 409 | template<typename T, qualifier Q> | |
| 410 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> & mat<4, 4, T, Q>::operator--() | |
| 411 | { | |
| 412 | --this->value[0]; | |
| 413 | --this->value[1]; | |
| 414 | --this->value[2]; | |
| 415 | --this->value[3]; | |
| 416 | return *this; | |
| 417 | } | |
| 418 | ||
| 419 | template<typename T, qualifier Q> | |
| 420 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> mat<4, 4, T, Q>::operator++(int) | |
| 421 | { | |
| 422 | mat<4, 4, T, Q> Result(*this); | |
| 423 | ++*this; | |
| 424 | return Result; | |
| 425 | } | |
| 426 | ||
| 427 | template<typename T, qualifier Q> | |
| 428 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> mat<4, 4, T, Q>::operator--(int) | |
| 429 | { | |
| 430 | mat<4, 4, T, Q> Result(*this); | |
| 431 | --*this; | |
| 432 | return Result; | |
| 433 | } | |
| 434 | ||
| 435 | // -- Unary constant operators -- | |
| 436 | ||
| 437 | template<typename T, qualifier Q> | |
| 438 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> operator+(mat<4, 4, T, Q> const& m) | |
| 439 | { | |
| 440 | return m; | |
| 441 | } | |
| 442 | ||
| 443 | template<typename T, qualifier Q> | |
| 444 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> operator-(mat<4, 4, T, Q> const& m) | |
| 445 | { | |
| 446 | return mat<4, 4, T, Q>( | |
| 447 | -m[0], | |
| 448 | -m[1], | |
| 449 | -m[2], | |
| 450 | -m[3]); | |
| 451 | } | |
| 452 | ||
| 453 | // -- Binary arithmetic operators -- | |
| 454 | ||
| 455 | template<typename T, qualifier Q> | |
| 456 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> operator+(mat<4, 4, T, Q> const& m, T const& s) | |
| 457 | { | |
| 458 | return mat<4, 4, T, Q>( | |
| 459 | m[0] + s, | |
| 460 | m[1] + s, | |
| 461 | m[2] + s, | |
| 462 | m[3] + s); | |
| 463 | } | |
| 464 | ||
| 465 | template<typename T, qualifier Q> | |
| 466 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> operator+(T const& s, mat<4, 4, T, Q> const& m) | |
| 467 | { | |
| 468 | return mat<4, 4, T, Q>( | |
| 469 | m[0] + s, | |
| 470 | m[1] + s, | |
| 471 | m[2] + s, | |
| 472 | m[3] + s); | |
| 473 | } | |
| 474 | ||
| 475 | template<typename T, qualifier Q> | |
| 476 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> operator+(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2) | |
| 477 | { | |
| 478 | return mat<4, 4, T, Q>( | |
| 479 | m1[0] + m2[0], | |
| 480 | m1[1] + m2[1], | |
| 481 | m1[2] + m2[2], | |
| 482 | m1[3] + m2[3]); | |
| 483 | } | |
| 484 | ||
| 485 | template<typename T, qualifier Q> | |
| 486 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> operator-(mat<4, 4, T, Q> const& m, T const& s) | |
| 487 | { | |
| 488 | return mat<4, 4, T, Q>( | |
| 489 | m[0] - s, | |
| 490 | m[1] - s, | |
| 491 | m[2] - s, | |
| 492 | m[3] - s); | |
| 493 | } | |
| 494 | ||
| 495 | template<typename T, qualifier Q> | |
| 496 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> operator-(T const& s, mat<4, 4, T, Q> const& m) | |
| 497 | { | |
| 498 | return mat<4, 4, T, Q>( | |
| 499 | s - m[0], | |
| 500 | s - m[1], | |
| 501 | s - m[2], | |
| 502 | s - m[3]); | |
| 503 | } | |
| 504 | ||
| 505 | template<typename T, qualifier Q> | |
| 506 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> operator-(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2) | |
| 507 | { | |
| 508 | return mat<4, 4, T, Q>( | |
| 509 | m1[0] - m2[0], | |
| 510 | m1[1] - m2[1], | |
| 511 | m1[2] - m2[2], | |
| 512 | m1[3] - m2[3]); | |
| 513 | } | |
| 514 | ||
| 515 | template<typename T, qualifier Q> | |
| 516 | 27x | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> operator*(mat<4, 4, T, Q> const& m, T const & s) |
| 517 | { | |
| 518 | return mat<4, 4, T, Q>( | |
| 519 | 27x | m[0] * s, |
| 520 | 27x | m[1] * s, |
| 521 | 27x | m[2] * s, |
| 522 | 54x | m[3] * s); |
| 523 | } | |
| 524 | ||
| 525 | template<typename T, qualifier Q> | |
| 526 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> operator*(T const& s, mat<4, 4, T, Q> const& m) | |
| 527 | { | |
| 528 | return mat<4, 4, T, Q>( | |
| 529 | m[0] * s, | |
| 530 | m[1] * s, | |
| 531 | m[2] * s, | |
| 532 | m[3] * s); | |
| 533 | } | |
| 534 | ||
| 535 | template<typename T, qualifier Q> | |
| 536 | 1357875x | GLM_FUNC_QUALIFIER typename mat<4, 4, T, Q>::col_type operator* |
| 537 | ( | |
| 538 | mat<4, 4, T, Q> const& m, | |
| 539 | typename mat<4, 4, T, Q>::row_type const& v | |
| 540 | ) | |
| 541 | { | |
| 542 | /* | |
| 543 | __m128 v0 = _mm_shuffle_ps(v.data, v.data, _MM_SHUFFLE(0, 0, 0, 0)); | |
| 544 | __m128 v1 = _mm_shuffle_ps(v.data, v.data, _MM_SHUFFLE(1, 1, 1, 1)); | |
| 545 | __m128 v2 = _mm_shuffle_ps(v.data, v.data, _MM_SHUFFLE(2, 2, 2, 2)); | |
| 546 | __m128 v3 = _mm_shuffle_ps(v.data, v.data, _MM_SHUFFLE(3, 3, 3, 3)); | |
| 547 | ||
| 548 | __m128 m0 = _mm_mul_ps(m[0].data, v0); | |
| 549 | __m128 m1 = _mm_mul_ps(m[1].data, v1); | |
| 550 | __m128 a0 = _mm_add_ps(m0, m1); | |
| 551 | ||
| 552 | __m128 m2 = _mm_mul_ps(m[2].data, v2); | |
| 553 | __m128 m3 = _mm_mul_ps(m[3].data, v3); | |
| 554 | __m128 a1 = _mm_add_ps(m2, m3); | |
| 555 | ||
| 556 | __m128 a2 = _mm_add_ps(a0, a1); | |
| 557 | ||
| 558 | return typename mat<4, 4, T, Q>::col_type(a2); | |
| 559 | */ | |
| 560 | ||
| 561 | 1357875x | typename mat<4, 4, T, Q>::col_type const Mov0(v[0]); |
| 562 | 1357875x | typename mat<4, 4, T, Q>::col_type const Mov1(v[1]); |
| 563 | 1357875x | typename mat<4, 4, T, Q>::col_type const Mul0 = m[0] * Mov0; |
| 564 | 1357875x | typename mat<4, 4, T, Q>::col_type const Mul1 = m[1] * Mov1; |
| 565 | 1357875x | typename mat<4, 4, T, Q>::col_type const Add0 = Mul0 + Mul1; |
| 566 | 1357875x | typename mat<4, 4, T, Q>::col_type const Mov2(v[2]); |
| 567 | 1357875x | typename mat<4, 4, T, Q>::col_type const Mov3(v[3]); |
| 568 | 1357875x | typename mat<4, 4, T, Q>::col_type const Mul2 = m[2] * Mov2; |
| 569 | 1357875x | typename mat<4, 4, T, Q>::col_type const Mul3 = m[3] * Mov3; |
| 570 | 1357875x | typename mat<4, 4, T, Q>::col_type const Add1 = Mul2 + Mul3; |
| 571 | 1357875x | typename mat<4, 4, T, Q>::col_type const Add2 = Add0 + Add1; |
| 572 | 2715750x | return Add2; |
| 573 | ||
| 574 | /* | |
| 575 | return typename mat<4, 4, T, Q>::col_type( | |
| 576 | m[0][0] * v[0] + m[1][0] * v[1] + m[2][0] * v[2] + m[3][0] * v[3], | |
| 577 | m[0][1] * v[0] + m[1][1] * v[1] + m[2][1] * v[2] + m[3][1] * v[3], | |
| 578 | m[0][2] * v[0] + m[1][2] * v[1] + m[2][2] * v[2] + m[3][2] * v[3], | |
| 579 | m[0][3] * v[0] + m[1][3] * v[1] + m[2][3] * v[2] + m[3][3] * v[3]); | |
| 580 | */ | |
| 581 | } | |
| 582 | ||
| 583 | template<typename T, qualifier Q> | |
| 584 | GLM_FUNC_QUALIFIER typename mat<4, 4, T, Q>::row_type operator* | |
| 585 | ( | |
| 586 | typename mat<4, 4, T, Q>::col_type const& v, | |
| 587 | mat<4, 4, T, Q> const& m | |
| 588 | ) | |
| 589 | { | |
| 590 | return typename mat<4, 4, T, Q>::row_type( | |
| 591 | m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2] + m[0][3] * v[3], | |
| 592 | m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2] + m[1][3] * v[3], | |
| 593 | m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2] + m[2][3] * v[3], | |
| 594 | m[3][0] * v[0] + m[3][1] * v[1] + m[3][2] * v[2] + m[3][3] * v[3]); | |
| 595 | } | |
| 596 | ||
| 597 | template<typename T, qualifier Q> | |
| 598 | GLM_FUNC_QUALIFIER mat<2, 4, T, Q> operator*(mat<4, 4, T, Q> const& m1, mat<2, 4, T, Q> const& m2) | |
| 599 | { | |
| 600 | return mat<2, 4, T, Q>( | |
| 601 | m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3], | |
| 602 | m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3], | |
| 603 | m1[0][2] * m2[0][0] + m1[1][2] * m2[0][1] + m1[2][2] * m2[0][2] + m1[3][2] * m2[0][3], | |
| 604 | m1[0][3] * m2[0][0] + m1[1][3] * m2[0][1] + m1[2][3] * m2[0][2] + m1[3][3] * m2[0][3], | |
| 605 | m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3], | |
| 606 | m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3], | |
| 607 | m1[0][2] * m2[1][0] + m1[1][2] * m2[1][1] + m1[2][2] * m2[1][2] + m1[3][2] * m2[1][3], | |
| 608 | m1[0][3] * m2[1][0] + m1[1][3] * m2[1][1] + m1[2][3] * m2[1][2] + m1[3][3] * m2[1][3]); | |
| 609 | } | |
| 610 | ||
| 611 | template<typename T, qualifier Q> | |
| 612 | GLM_FUNC_QUALIFIER mat<3, 4, T, Q> operator*(mat<4, 4, T, Q> const& m1, mat<3, 4, T, Q> const& m2) | |
| 613 | { | |
| 614 | return mat<3, 4, T, Q>( | |
| 615 | m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3], | |
| 616 | m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3], | |
| 617 | m1[0][2] * m2[0][0] + m1[1][2] * m2[0][1] + m1[2][2] * m2[0][2] + m1[3][2] * m2[0][3], | |
| 618 | m1[0][3] * m2[0][0] + m1[1][3] * m2[0][1] + m1[2][3] * m2[0][2] + m1[3][3] * m2[0][3], | |
| 619 | m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3], | |
| 620 | m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3], | |
| 621 | m1[0][2] * m2[1][0] + m1[1][2] * m2[1][1] + m1[2][2] * m2[1][2] + m1[3][2] * m2[1][3], | |
| 622 | m1[0][3] * m2[1][0] + m1[1][3] * m2[1][1] + m1[2][3] * m2[1][2] + m1[3][3] * m2[1][3], | |
| 623 | m1[0][0] * m2[2][0] + m1[1][0] * m2[2][1] + m1[2][0] * m2[2][2] + m1[3][0] * m2[2][3], | |
| 624 | m1[0][1] * m2[2][0] + m1[1][1] * m2[2][1] + m1[2][1] * m2[2][2] + m1[3][1] * m2[2][3], | |
| 625 | m1[0][2] * m2[2][0] + m1[1][2] * m2[2][1] + m1[2][2] * m2[2][2] + m1[3][2] * m2[2][3], | |
| 626 | m1[0][3] * m2[2][0] + m1[1][3] * m2[2][1] + m1[2][3] * m2[2][2] + m1[3][3] * m2[2][3]); | |
| 627 | } | |
| 628 | ||
| 629 | template<typename T, qualifier Q> | |
| 630 | 5277x | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> operator*(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2) |
| 631 | { | |
| 632 | 5277x | typename mat<4, 4, T, Q>::col_type const SrcA0 = m1[0]; |
| 633 | 5277x | typename mat<4, 4, T, Q>::col_type const SrcA1 = m1[1]; |
| 634 | 5277x | typename mat<4, 4, T, Q>::col_type const SrcA2 = m1[2]; |
| 635 | 5277x | typename mat<4, 4, T, Q>::col_type const SrcA3 = m1[3]; |
| 636 | ||
| 637 | 5277x | typename mat<4, 4, T, Q>::col_type const SrcB0 = m2[0]; |
| 638 | 5277x | typename mat<4, 4, T, Q>::col_type const SrcB1 = m2[1]; |
| 639 | 5277x | typename mat<4, 4, T, Q>::col_type const SrcB2 = m2[2]; |
| 640 | 5277x | typename mat<4, 4, T, Q>::col_type const SrcB3 = m2[3]; |
| 641 | ||
| 642 | mat<4, 4, T, Q> Result; | |
| 643 | 5277x | Result[0] = SrcA0 * SrcB0[0] + SrcA1 * SrcB0[1] + SrcA2 * SrcB0[2] + SrcA3 * SrcB0[3]; |
| 644 | 5277x | Result[1] = SrcA0 * SrcB1[0] + SrcA1 * SrcB1[1] + SrcA2 * SrcB1[2] + SrcA3 * SrcB1[3]; |
| 645 | 5277x | Result[2] = SrcA0 * SrcB2[0] + SrcA1 * SrcB2[1] + SrcA2 * SrcB2[2] + SrcA3 * SrcB2[3]; |
| 646 | 5277x | Result[3] = SrcA0 * SrcB3[0] + SrcA1 * SrcB3[1] + SrcA2 * SrcB3[2] + SrcA3 * SrcB3[3]; |
| 647 | 10554x | return Result; |
| 648 | } | |
| 649 | ||
| 650 | template<typename T, qualifier Q> | |
| 651 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> operator/(mat<4, 4, T, Q> const& m, T const& s) | |
| 652 | { | |
| 653 | return mat<4, 4, T, Q>( | |
| 654 | m[0] / s, | |
| 655 | m[1] / s, | |
| 656 | m[2] / s, | |
| 657 | m[3] / s); | |
| 658 | } | |
| 659 | ||
| 660 | template<typename T, qualifier Q> | |
| 661 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> operator/(T const& s, mat<4, 4, T, Q> const& m) | |
| 662 | { | |
| 663 | return mat<4, 4, T, Q>( | |
| 664 | s / m[0], | |
| 665 | s / m[1], | |
| 666 | s / m[2], | |
| 667 | s / m[3]); | |
| 668 | } | |
| 669 | ||
| 670 | template<typename T, qualifier Q> | |
| 671 | GLM_FUNC_QUALIFIER typename mat<4, 4, T, Q>::col_type operator/(mat<4, 4, T, Q> const& m, typename mat<4, 4, T, Q>::row_type const& v) | |
| 672 | { | |
| 673 | return inverse(m) * v; | |
| 674 | } | |
| 675 | ||
| 676 | template<typename T, qualifier Q> | |
| 677 | GLM_FUNC_QUALIFIER typename mat<4, 4, T, Q>::row_type operator/(typename mat<4, 4, T, Q>::col_type const& v, mat<4, 4, T, Q> const& m) | |
| 678 | { | |
| 679 | return v * inverse(m); | |
| 680 | } | |
| 681 | ||
| 682 | template<typename T, qualifier Q> | |
| 683 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> operator/(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2) | |
| 684 | { | |
| 685 | mat<4, 4, T, Q> m1_copy(m1); | |
| 686 | return m1_copy /= m2; | |
| 687 | } | |
| 688 | ||
| 689 | // -- Boolean operators -- | |
| 690 | ||
| 691 | template<typename T, qualifier Q> | |
| 692 | GLM_FUNC_QUALIFIER bool operator==(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2) | |
| 693 | { | |
| 694 | return (m1[0] == m2[0]) && (m1[1] == m2[1]) && (m1[2] == m2[2]) && (m1[3] == m2[3]); | |
| 695 | } | |
| 696 | ||
| 697 | template<typename T, qualifier Q> | |
| 698 | GLM_FUNC_QUALIFIER bool operator!=(mat<4, 4, T, Q> const& m1, mat<4, 4, T, Q> const& m2) | |
| 699 | { | |
| 700 | return (m1[0] != m2[0]) || (m1[1] != m2[1]) || (m1[2] != m2[2]) || (m1[3] != m2[3]); | |
| 701 | } | |
| 702 | }//namespace glm | |
| 703 | ||
| 704 | #if GLM_CONFIG_SIMD == GLM_ENABLE | |
| 705 | # include "type_mat4x4_simd.inl" | |
| 706 | #endif |
| 1 | namespace glm | |
| 2 | { | |
| 3 | template<typename genType> | |
| 4 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR genType identity() | |
| 5 | { | |
| 6 | return detail::init_gentype<genType, detail::genTypeTrait<genType>::GENTYPE>::identity(); | |
| 7 | } | |
| 8 | ||
| 9 | template<typename T, qualifier Q> | |
| 10 | 37x | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> translate(mat<4, 4, T, Q> const& m, vec<3, T, Q> const& v) |
| 11 | { | |
| 12 | 37x | mat<4, 4, T, Q> Result(m); |
| 13 | 37x | Result[3] = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3]; |
| 14 | 37x | return Result; |
| 15 | } | |
| 16 | ||
| 17 | template<typename T, qualifier Q> | |
| 18 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> rotate(mat<4, 4, T, Q> const& m, T angle, vec<3, T, Q> const& v) | |
| 19 | { | |
| 20 | T const a = angle; | |
| 21 | T const c = cos(a); | |
| 22 | T const s = sin(a); | |
| 23 | ||
| 24 | vec<3, T, Q> axis(normalize(v)); | |
| 25 | vec<3, T, Q> temp((T(1) - c) * axis); | |
| 26 | ||
| 27 | mat<4, 4, T, Q> Rotate; | |
| 28 | Rotate[0][0] = c + temp[0] * axis[0]; | |
| 29 | Rotate[0][1] = temp[0] * axis[1] + s * axis[2]; | |
| 30 | Rotate[0][2] = temp[0] * axis[2] - s * axis[1]; | |
| 31 | ||
| 32 | Rotate[1][0] = temp[1] * axis[0] - s * axis[2]; | |
| 33 | Rotate[1][1] = c + temp[1] * axis[1]; | |
| 34 | Rotate[1][2] = temp[1] * axis[2] + s * axis[0]; | |
| 35 | ||
| 36 | Rotate[2][0] = temp[2] * axis[0] + s * axis[1]; | |
| 37 | Rotate[2][1] = temp[2] * axis[1] - s * axis[0]; | |
| 38 | Rotate[2][2] = c + temp[2] * axis[2]; | |
| 39 | ||
| 40 | mat<4, 4, T, Q> Result; | |
| 41 | Result[0] = m[0] * Rotate[0][0] + m[1] * Rotate[0][1] + m[2] * Rotate[0][2]; | |
| 42 | Result[1] = m[0] * Rotate[1][0] + m[1] * Rotate[1][1] + m[2] * Rotate[1][2]; | |
| 43 | Result[2] = m[0] * Rotate[2][0] + m[1] * Rotate[2][1] + m[2] * Rotate[2][2]; | |
| 44 | Result[3] = m[3]; | |
| 45 | return Result; | |
| 46 | } | |
| 47 | ||
| 48 | template<typename T, qualifier Q> | |
| 49 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> rotate_slow(mat<4, 4, T, Q> const& m, T angle, vec<3, T, Q> const& v) | |
| 50 | { | |
| 51 | T const a = angle; | |
| 52 | T const c = cos(a); | |
| 53 | T const s = sin(a); | |
| 54 | mat<4, 4, T, Q> Result; | |
| 55 | ||
| 56 | vec<3, T, Q> axis = normalize(v); | |
| 57 | ||
| 58 | Result[0][0] = c + (static_cast<T>(1) - c) * axis.x * axis.x; | |
| 59 | Result[0][1] = (static_cast<T>(1) - c) * axis.x * axis.y + s * axis.z; | |
| 60 | Result[0][2] = (static_cast<T>(1) - c) * axis.x * axis.z - s * axis.y; | |
| 61 | Result[0][3] = static_cast<T>(0); | |
| 62 | ||
| 63 | Result[1][0] = (static_cast<T>(1) - c) * axis.y * axis.x - s * axis.z; | |
| 64 | Result[1][1] = c + (static_cast<T>(1) - c) * axis.y * axis.y; | |
| 65 | Result[1][2] = (static_cast<T>(1) - c) * axis.y * axis.z + s * axis.x; | |
| 66 | Result[1][3] = static_cast<T>(0); | |
| 67 | ||
| 68 | Result[2][0] = (static_cast<T>(1) - c) * axis.z * axis.x + s * axis.y; | |
| 69 | Result[2][1] = (static_cast<T>(1) - c) * axis.z * axis.y - s * axis.x; | |
| 70 | Result[2][2] = c + (static_cast<T>(1) - c) * axis.z * axis.z; | |
| 71 | Result[2][3] = static_cast<T>(0); | |
| 72 | ||
| 73 | Result[3] = vec<4, T, Q>(0, 0, 0, 1); | |
| 74 | return m * Result; | |
| 75 | } | |
| 76 | ||
| 77 | template<typename T, qualifier Q> | |
| 78 | 32x | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> scale(mat<4, 4, T, Q> const& m, vec<3, T, Q> const& v) |
| 79 | { | |
| 80 | mat<4, 4, T, Q> Result; | |
| 81 | 32x | Result[0] = m[0] * v[0]; |
| 82 | 32x | Result[1] = m[1] * v[1]; |
| 83 | 32x | Result[2] = m[2] * v[2]; |
| 84 | 32x | Result[3] = m[3]; |
| 85 | 32x | return Result; |
| 86 | } | |
| 87 | ||
| 88 | template<typename T, qualifier Q> | |
| 89 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> scale_slow(mat<4, 4, T, Q> const& m, vec<3, T, Q> const& v) | |
| 90 | { | |
| 91 | mat<4, 4, T, Q> Result(T(1)); | |
| 92 | Result[0][0] = v.x; | |
| 93 | Result[1][1] = v.y; | |
| 94 | Result[2][2] = v.z; | |
| 95 | return m * Result; | |
| 96 | } | |
| 97 | ||
| 98 | template<typename T, qualifier Q> | |
| 99 | 10x | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> lookAtRH(vec<3, T, Q> const& eye, vec<3, T, Q> const& center, vec<3, T, Q> const& up) |
| 100 | { | |
| 101 | 10x | vec<3, T, Q> const f(normalize(center - eye)); |
| 102 | 10x | vec<3, T, Q> const s(normalize(cross(f, up))); |
| 103 | 10x | vec<3, T, Q> const u(cross(s, f)); |
| 104 | ||
| 105 | 10x | mat<4, 4, T, Q> Result(1); |
| 106 | 10x | Result[0][0] = s.x; |
| 107 | 10x | Result[1][0] = s.y; |
| 108 | 10x | Result[2][0] = s.z; |
| 109 | 10x | Result[0][1] = u.x; |
| 110 | 10x | Result[1][1] = u.y; |
| 111 | 10x | Result[2][1] = u.z; |
| 112 | 10x | Result[0][2] =-f.x; |
| 113 | 10x | Result[1][2] =-f.y; |
| 114 | 10x | Result[2][2] =-f.z; |
| 115 | 10x | Result[3][0] =-dot(s, eye); |
| 116 | 10x | Result[3][1] =-dot(u, eye); |
| 117 | 10x | Result[3][2] = dot(f, eye); |
| 118 | 20x | return Result; |
| 119 | } | |
| 120 | ||
| 121 | template<typename T, qualifier Q> | |
| 122 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> lookAtLH(vec<3, T, Q> const& eye, vec<3, T, Q> const& center, vec<3, T, Q> const& up) | |
| 123 | { | |
| 124 | vec<3, T, Q> const f(normalize(center - eye)); | |
| 125 | vec<3, T, Q> const s(normalize(cross(up, f))); | |
| 126 | vec<3, T, Q> const u(cross(f, s)); | |
| 127 | ||
| 128 | mat<4, 4, T, Q> Result(1); | |
| 129 | Result[0][0] = s.x; | |
| 130 | Result[1][0] = s.y; | |
| 131 | Result[2][0] = s.z; | |
| 132 | Result[0][1] = u.x; | |
| 133 | Result[1][1] = u.y; | |
| 134 | Result[2][1] = u.z; | |
| 135 | Result[0][2] = f.x; | |
| 136 | Result[1][2] = f.y; | |
| 137 | Result[2][2] = f.z; | |
| 138 | Result[3][0] = -dot(s, eye); | |
| 139 | Result[3][1] = -dot(u, eye); | |
| 140 | Result[3][2] = -dot(f, eye); | |
| 141 | return Result; | |
| 142 | } | |
| 143 | ||
| 144 | template<typename T, qualifier Q> | |
| 145 | 10x | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> lookAt(vec<3, T, Q> const& eye, vec<3, T, Q> const& center, vec<3, T, Q> const& up) |
| 146 | { | |
| 147 | GLM_IF_CONSTEXPR(GLM_CONFIG_CLIP_CONTROL & GLM_CLIP_CONTROL_LH_BIT) | |
| 148 | return lookAtLH(eye, center, up); | |
| 149 | else | |
| 150 | 10x | return lookAtRH(eye, center, up); |
| 151 | } | |
| 152 | }//namespace glm |
| 1 | #include "_vectorize.hpp" | |
| 2 | #include <cmath> | |
| 3 | #include <limits> | |
| 4 | ||
| 5 | namespace glm | |
| 6 | { | |
| 7 | // radians | |
| 8 | template<typename genType> | |
| 9 | 5x | GLM_FUNC_QUALIFIER GLM_CONSTEXPR genType radians(genType degrees) |
| 10 | { | |
| 11 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'radians' only accept floating-point input"); | |
| 12 | ||
| 13 | 5x | return degrees * static_cast<genType>(0.01745329251994329576923690768489); |
| 14 | } | |
| 15 | ||
| 16 | template<length_t L, typename T, qualifier Q> | |
| 17 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<L, T, Q> radians(vec<L, T, Q> const& v) | |
| 18 | { | |
| 19 | return detail::functor1<vec, L, T, T, Q>::call(radians, v); | |
| 20 | } | |
| 21 | ||
| 22 | // degrees | |
| 23 | template<typename genType> | |
| 24 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR genType degrees(genType radians) | |
| 25 | { | |
| 26 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'degrees' only accept floating-point input"); | |
| 27 | ||
| 28 | return radians * static_cast<genType>(57.295779513082320876798154814105); | |
| 29 | } | |
| 30 | ||
| 31 | template<length_t L, typename T, qualifier Q> | |
| 32 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<L, T, Q> degrees(vec<L, T, Q> const& v) | |
| 33 | { | |
| 34 | return detail::functor1<vec, L, T, T, Q>::call(degrees, v); | |
| 35 | } | |
| 36 | ||
| 37 | // sin | |
| 38 | using ::std::sin; | |
| 39 | ||
| 40 | template<length_t L, typename T, qualifier Q> | |
| 41 | GLM_FUNC_QUALIFIER vec<L, T, Q> sin(vec<L, T, Q> const& v) | |
| 42 | { | |
| 43 | return detail::functor1<vec, L, T, T, Q>::call(sin, v); | |
| 44 | } | |
| 45 | ||
| 46 | // cos | |
| 47 | using std::cos; | |
| 48 | ||
| 49 | template<length_t L, typename T, qualifier Q> | |
| 50 | GLM_FUNC_QUALIFIER vec<L, T, Q> cos(vec<L, T, Q> const& v) | |
| 51 | { | |
| 52 | return detail::functor1<vec, L, T, T, Q>::call(cos, v); | |
| 53 | } | |
| 54 | ||
| 55 | // tan | |
| 56 | using std::tan; | |
| 57 | ||
| 58 | template<length_t L, typename T, qualifier Q> | |
| 59 | GLM_FUNC_QUALIFIER vec<L, T, Q> tan(vec<L, T, Q> const& v) | |
| 60 | { | |
| 61 | return detail::functor1<vec, L, T, T, Q>::call(tan, v); | |
| 62 | } | |
| 63 | ||
| 64 | // asin | |
| 65 | using std::asin; | |
| 66 | ||
| 67 | template<length_t L, typename T, qualifier Q> | |
| 68 | GLM_FUNC_QUALIFIER vec<L, T, Q> asin(vec<L, T, Q> const& v) | |
| 69 | { | |
| 70 | return detail::functor1<vec, L, T, T, Q>::call(asin, v); | |
| 71 | } | |
| 72 | ||
| 73 | // acos | |
| 74 | using std::acos; | |
| 75 | ||
| 76 | template<length_t L, typename T, qualifier Q> | |
| 77 | GLM_FUNC_QUALIFIER vec<L, T, Q> acos(vec<L, T, Q> const& v) | |
| 78 | { | |
| 79 | return detail::functor1<vec, L, T, T, Q>::call(acos, v); | |
| 80 | } | |
| 81 | ||
| 82 | // atan | |
| 83 | template<typename genType> | |
| 84 | GLM_FUNC_QUALIFIER genType atan(genType y, genType x) | |
| 85 | { | |
| 86 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'atan' only accept floating-point input"); | |
| 87 | ||
| 88 | return ::std::atan2(y, x); | |
| 89 | } | |
| 90 | ||
| 91 | template<length_t L, typename T, qualifier Q> | |
| 92 | GLM_FUNC_QUALIFIER vec<L, T, Q> atan(vec<L, T, Q> const& a, vec<L, T, Q> const& b) | |
| 93 | { | |
| 94 | return detail::functor2<vec, L, T, Q>::call(::std::atan2, a, b); | |
| 95 | } | |
| 96 | ||
| 97 | using std::atan; | |
| 98 | ||
| 99 | template<length_t L, typename T, qualifier Q> | |
| 100 | GLM_FUNC_QUALIFIER vec<L, T, Q> atan(vec<L, T, Q> const& v) | |
| 101 | { | |
| 102 | return detail::functor1<vec, L, T, T, Q>::call(atan, v); | |
| 103 | } | |
| 104 | ||
| 105 | // sinh | |
| 106 | using std::sinh; | |
| 107 | ||
| 108 | template<length_t L, typename T, qualifier Q> | |
| 109 | GLM_FUNC_QUALIFIER vec<L, T, Q> sinh(vec<L, T, Q> const& v) | |
| 110 | { | |
| 111 | return detail::functor1<vec, L, T, T, Q>::call(sinh, v); | |
| 112 | } | |
| 113 | ||
| 114 | // cosh | |
| 115 | using std::cosh; | |
| 116 | ||
| 117 | template<length_t L, typename T, qualifier Q> | |
| 118 | GLM_FUNC_QUALIFIER vec<L, T, Q> cosh(vec<L, T, Q> const& v) | |
| 119 | { | |
| 120 | return detail::functor1<vec, L, T, T, Q>::call(cosh, v); | |
| 121 | } | |
| 122 | ||
| 123 | // tanh | |
| 124 | using std::tanh; | |
| 125 | ||
| 126 | template<length_t L, typename T, qualifier Q> | |
| 127 | GLM_FUNC_QUALIFIER vec<L, T, Q> tanh(vec<L, T, Q> const& v) | |
| 128 | { | |
| 129 | return detail::functor1<vec, L, T, T, Q>::call(tanh, v); | |
| 130 | } | |
| 131 | ||
| 132 | // asinh | |
| 133 | # if GLM_HAS_CXX11_STL | |
| 134 | using std::asinh; | |
| 135 | # else | |
| 136 | template<typename genType> | |
| 137 | GLM_FUNC_QUALIFIER genType asinh(genType x) | |
| 138 | { | |
| 139 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'asinh' only accept floating-point input"); | |
| 140 | ||
| 141 | return (x < static_cast<genType>(0) ? static_cast<genType>(-1) : (x > static_cast<genType>(0) ? static_cast<genType>(1) : static_cast<genType>(0))) * log(std::abs(x) + sqrt(static_cast<genType>(1) + x * x)); | |
| 142 | } | |
| 143 | # endif | |
| 144 | ||
| 145 | template<length_t L, typename T, qualifier Q> | |
| 146 | GLM_FUNC_QUALIFIER vec<L, T, Q> asinh(vec<L, T, Q> const& v) | |
| 147 | { | |
| 148 | return detail::functor1<vec, L, T, T, Q>::call(asinh, v); | |
| 149 | } | |
| 150 | ||
| 151 | // acosh | |
| 152 | # if GLM_HAS_CXX11_STL | |
| 153 | using std::acosh; | |
| 154 | # else | |
| 155 | template<typename genType> | |
| 156 | GLM_FUNC_QUALIFIER genType acosh(genType x) | |
| 157 | { | |
| 158 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'acosh' only accept floating-point input"); | |
| 159 | ||
| 160 | if(x < static_cast<genType>(1)) | |
| 161 | return static_cast<genType>(0); | |
| 162 | return log(x + sqrt(x * x - static_cast<genType>(1))); | |
| 163 | } | |
| 164 | # endif | |
| 165 | ||
| 166 | template<length_t L, typename T, qualifier Q> | |
| 167 | GLM_FUNC_QUALIFIER vec<L, T, Q> acosh(vec<L, T, Q> const& v) | |
| 168 | { | |
| 169 | return detail::functor1<vec, L, T, T, Q>::call(acosh, v); | |
| 170 | } | |
| 171 | ||
| 172 | // atanh | |
| 173 | # if GLM_HAS_CXX11_STL | |
| 174 | using std::atanh; | |
| 175 | # else | |
| 176 | template<typename genType> | |
| 177 | GLM_FUNC_QUALIFIER genType atanh(genType x) | |
| 178 | { | |
| 179 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'atanh' only accept floating-point input"); | |
| 180 | ||
| 181 | if(std::abs(x) >= static_cast<genType>(1)) | |
| 182 | return 0; | |
| 183 | return static_cast<genType>(0.5) * log((static_cast<genType>(1) + x) / (static_cast<genType>(1) - x)); | |
| 184 | } | |
| 185 | # endif | |
| 186 | ||
| 187 | template<length_t L, typename T, qualifier Q> | |
| 188 | GLM_FUNC_QUALIFIER vec<L, T, Q> atanh(vec<L, T, Q> const& v) | |
| 189 | { | |
| 190 | return detail::functor1<vec, L, T, T, Q>::call(atanh, v); | |
| 191 | } | |
| 192 | }//namespace glm | |
| 193 | ||
| 194 | #if GLM_CONFIG_SIMD == GLM_ENABLE | |
| 195 | # include "func_trigonometric_simd.inl" | |
| 196 | #endif | |
| 197 |
| 1 | #include "rayimage.h" | |
| 2 | ||
| 3 | 24503x | vec4 trivalue(Float uu, Float vv, float* data, |
| 4 | int nx, int ny, int channels) { | |
| 5 | // Wrap to [0,1] | |
| 6 | 24503x | uu = uu - floor(uu); |
| 7 | 24503x | vv = vv - floor(vv); |
| 8 | ||
| 9 | // Map to texel space | |
| 10 | 24503x | Float x = uu * (Float)(nx - 1); |
| 11 | 24503x | Float y = (1 - vv) * (Float)(ny - 1); |
| 12 | ||
| 13 | 24503x | int x0 = (int)floor(x); |
| 14 | 24503x | int x1 = std::min(x0 + 1, nx - 1); |
| 15 | 24503x | int y0 = (int)floor(y); |
| 16 | 24503x | int y1 = std::min(y0 + 1, ny - 1); |
| 17 | ||
| 18 | 24503x | Float tx = x - (Float)x0; |
| 19 | 24503x | Float ty = y - (Float)y0; |
| 20 | ||
| 21 | 98012x | auto sample = [&](int xi, int yi) -> vec4 { |
| 22 | 98012x | int idx = channels*xi + channels*nx*yi; |
| 23 | 98012x | Float r = data[idx]; |
| 24 | 98012x | Float g = data[idx + 1]; |
| 25 | 98012x | Float b = data[idx + 2]; |
| 26 | 98012x | Float a = channels == 4 ? data[idx + 3] : 1.0f; |
| 27 | 98012x | return vec4(r,g,b,a); |
| 28 | }; | |
| 29 | ||
| 30 | 24503x | vec4 c00 = sample(x0,y0); |
| 31 | 24503x | vec4 c10 = sample(x1,y0); |
| 32 | 24503x | vec4 c01 = sample(x0,y1); |
| 33 | 24503x | vec4 c11 = sample(x1,y1); |
| 34 | ||
| 35 | // Bilinear interpolation | |
| 36 | 24503x | vec4 c0 = c00 * (1 - tx) + c10 * tx; |
| 37 | 24503x | vec4 c1 = c01 * (1 - tx) + c11 * tx; |
| 38 | 24503x | vec4 c = c0 * (1 - ty) + c1 * ty; |
| 39 | 49006x | return c; |
| 40 | } | |
| 41 | ||
| 42 | ! | vec4 trivalue(Float uu, Float vv, reflection_map_info ref) { |
| 43 | ! | int nx = ref.nx; |
| 44 | ! | int ny = ref.ny; |
| 45 | ! | int channels = ref.nn; |
| 46 | ||
| 47 | // Wrap to [0,1] | |
| 48 | ! | uu = uu - floor(uu); |
| 49 | ! | vv = vv - floor(vv); |
| 50 | ||
| 51 | // Map to texel space | |
| 52 | ! | Float x = uu * (Float)(nx - 1); |
| 53 | ! | Float y = (1 - vv) * (Float)(ny - 1); |
| 54 | ||
| 55 | ! | int x0 = (int)floor(x); |
| 56 | ! | int x1 = std::min(x0 + 1, nx - 1); |
| 57 | ! | int y0 = (int)floor(y); |
| 58 | ! | int y1 = std::min(y0 + 1, ny - 1); |
| 59 | ||
| 60 | ! | Float tx = x - (Float)x0; |
| 61 | ! | Float ty = y - (Float)y0; |
| 62 | ||
| 63 | ! | auto sample = [&](int xi, int yi) -> vec4 { |
| 64 | ! | int idx = channels*xi + channels*nx*yi; |
| 65 | ! | Float r = ref.reflection[idx]; |
| 66 | ! | Float g = ref.reflection[idx + 1]; |
| 67 | ! | Float b = ref.reflection[idx + 2]; |
| 68 | ! | return vec4(r,g,b,1.0f); |
| 69 | }; | |
| 70 | ||
| 71 | ! | vec4 c00 = sample(x0,y0); |
| 72 | ! | vec4 c10 = sample(x1,y0); |
| 73 | ! | vec4 c01 = sample(x0,y1); |
| 74 | ! | vec4 c11 = sample(x1,y1); |
| 75 | ||
| 76 | ! | vec4 c0 = c00 * (1 - tx) + c10 * tx; |
| 77 | ! | vec4 c1 = c01 * (1 - tx) + c11 * tx; |
| 78 | ! | vec4 c = c0 * (1 - ty) + c1 * ty; |
| 79 | ! | return c; |
| 80 | } |
| 1 | #define STB_IMAGE_IMPLEMENTATION | |
| 2 | #define STB_IMAGE_RESIZE_IMPLEMENTATION | |
| 3 | ||
| 4 | #ifndef RAYRASTERH | |
| 5 | #define RAYRASTERH | |
| 6 | ||
| 7 | #include "Rcpp.h" | |
| 8 | ||
| 9 | #ifdef __EMSCRIPTEN__ | |
| 10 | #ifdef __EMSCRIPTEN_PTHREADS__ | |
| 11 | #define HAVE_THREADS | |
| 12 | #else | |
| 13 | #endif | |
| 14 | #else | |
| 15 | #define HAVE_THREADS | |
| 16 | #endif | |
| 17 | ||
| 18 | ||
| 19 | #define FLOAT_AS_DOUBLE | |
| 20 | // #ifndef FLOAT_AS_DOUBLE | |
| 21 | // typedef float Float; | |
| 22 | // #else | |
| 23 | // typedef double Float; | |
| 24 | // #endif | |
| 25 | ||
| 26 | #include <vector> | |
| 27 | #include <cstdint> | |
| 28 | #include <limits> | |
| 29 | #include <cmath> | |
| 30 | #include <functional> | |
| 31 | #include <algorithm> | |
| 32 | #include <utility> | |
| 33 | #include "stbimageheaders/stb_image.h" | |
| 34 | #include "stbimageheaders/stb_image_resize2.h" | |
| 35 | #include <memory> | |
| 36 | #include "glm.hpp" | |
| 37 | #include "gtc/matrix_transform.hpp" | |
| 38 | #include "defines.h" | |
| 39 | #include "filltri.h" | |
| 40 | ||
| 41 | #include "shaders.h" | |
| 42 | #include "rayimage.h" | |
| 43 | #include "model.h" | |
| 44 | #include "single_sample.h" | |
| 45 | // [[Rcpp::depends(RcppThread)]] | |
| 46 | #include "RcppThread.h" | |
| 47 | #include "dummythreadpool.h" | |
| 48 | ||
| 49 | #include "material.h" | |
| 50 | ||
| 51 | #include "light.h" | |
| 52 | #include "line.h" | |
| 53 | #include "GBuffer.h" | |
| 54 | ||
| 55 | using namespace Rcpp; | |
| 56 | ||
| 57 | ! | inline stbir_pixel_layout stbir_layout_from_channels(int channels) { |
| 58 | ! | switch(channels) { |
| 59 | ! | case 1: |
| 60 | ! | return STBIR_1CHANNEL; |
| 61 | ! | case 2: |
| 62 | ! | return STBIR_2CHANNEL; |
| 63 | ! | case 3: |
| 64 | ! | return STBIR_RGB; |
| 65 | ! | case 4: |
| 66 | ! | return STBIR_4CHANNEL; |
| 67 | ! | default: |
| 68 | ! | throw std::runtime_error("Reflection map must have between 1 and 4 channels"); |
| 69 | } | |
| 70 | } | |
| 71 | ||
| 72 | ! | inline void resize_reflection_map(const float* input_pixels, int input_w, int input_h, |
| 73 | float* output_pixels, int output_w, int output_h, | |
| 74 | int channels) { | |
| 75 | ! | void* resize_result = stbir_resize(input_pixels, input_w, input_h, 0, |
| 76 | output_pixels, output_w, output_h, 0, | |
| 77 | stbir_layout_from_channels(channels), | |
| 78 | STBIR_TYPE_FLOAT, STBIR_EDGE_WRAP, | |
| 79 | STBIR_FILTER_CUBICBSPLINE); | |
| 80 | ! | if(resize_result == nullptr) { |
| 81 | ! | throw std::runtime_error("Reflection map resizing failed"); |
| 82 | } | |
| 83 | } | |
| 84 | ||
| 85 | inline vec3 clamp(const vec3& c, Float clamplow, Float clamphigh) { | |
| 86 | vec3 temp = c; | |
| 87 | if(c[0] > clamphigh) { | |
| 88 | temp[0] = clamphigh; | |
| 89 | } else if(c[0] < clamplow) { | |
| 90 | temp[0] = clamplow; | |
| 91 | } | |
| 92 | if(c[1] > clamphigh) { | |
| 93 | temp[1] = clamphigh; | |
| 94 | } else if(c[1] < clamplow) { | |
| 95 | temp[1] = clamplow; | |
| 96 | } | |
| 97 | if(c[2] > clamphigh) { | |
| 98 | temp[2] = clamphigh; | |
| 99 | } else if(c[2] < clamplow) { | |
| 100 | temp[2] = clamplow; | |
| 101 | } | |
| 102 | return(temp); | |
| 103 | } | |
| 104 | ||
| 105 | inline vec4 clamp(const vec4& c, Float clamplow, Float clamphigh) { | |
| 106 | vec4 temp = c; | |
| 107 | if(c[0] > clamphigh) { | |
| 108 | temp[0] = clamphigh; | |
| 109 | } else if(c[0] < clamplow) { | |
| 110 | temp[0] = clamplow; | |
| 111 | } | |
| 112 | if(c[1] > clamphigh) { | |
| 113 | temp[1] = clamphigh; | |
| 114 | } else if(c[1] < clamplow) { | |
| 115 | temp[1] = clamplow; | |
| 116 | } | |
| 117 | if(c[2] > clamphigh) { | |
| 118 | temp[2] = clamphigh; | |
| 119 | } else if(c[2] < clamplow) { | |
| 120 | temp[2] = clamplow; | |
| 121 | } | |
| 122 | if(c[3] > clamphigh) { | |
| 123 | temp[3] = clamphigh; | |
| 124 | } else if(c[3] < clamplow) { | |
| 125 | temp[3] = clamplow; | |
| 126 | } | |
| 127 | return(temp); | |
| 128 | } | |
| 129 | ||
| 130 | template<class T> | |
| 131 | inline T lerp(Float t, T v1, T v2) { | |
| 132 | return((1-t) * v1 + t * v2); | |
| 133 | } | |
| 134 | ||
| 135 | struct JFASeed { | |
| 136 | int x; | |
| 137 | int y; | |
| 138 | }; | |
| 139 | static void | |
| 140 | ! | apply_toon_outlines_jfa(std::vector<vec3> &color_buffer, |
| 141 | const std::vector<OutlineGBufferPixel> &gbuffer, | |
| 142 | int width, int height, Float fov_y, | |
| 143 | Float ortho_view_height, | |
| 144 | NumericMatrix &zbuffer, | |
| 145 | NumericMatrix &linear_depth) { | |
| 146 | ! | if (width <= 1 || height <= 1) { |
| 147 | ! | return; |
| 148 | } | |
| 149 | ! | const std::size_t n = |
| 150 | ! | static_cast<std::size_t>(width) * static_cast<std::size_t>(height); |
| 151 | ! | if (color_buffer.size() != n || gbuffer.size() != n) { |
| 152 | ! | return; |
| 153 | } | |
| 154 | ||
| 155 | ! | std::vector<JFASeed> seeds_curr(n); |
| 156 | ! | std::vector<JFASeed> seeds_next(n); |
| 157 | ||
| 158 | ! | for (int y = 0; y < height; ++y) { |
| 159 | ! | for (int x = 0; x < width; ++x) { |
| 160 | ! | std::size_t idx = static_cast<std::size_t>(y) * width + x; |
| 161 | ! | const OutlineGBufferPixel &px = gbuffer[idx]; |
| 162 | ||
| 163 | // Default value | |
| 164 | ! | seeds_curr[idx].x = -1; |
| 165 | ! | seeds_curr[idx].y = -1; |
| 166 | ||
| 167 | ! | if (px.outline_width <= 0.0f || std::isinf(px.depth_view)) { |
| 168 | ! | continue; |
| 169 | } | |
| 170 | ||
| 171 | ! | bool is_edge = false; |
| 172 | ||
| 173 | // Check 8-neighborhood for a discontinuity in occupancy/material | |
| 174 | ! | for (int dy = -1; dy <= 1 && !is_edge; ++dy) { |
| 175 | ! | for (int dx = -1; dx <= 1 && !is_edge; ++dx) { |
| 176 | ! | if (dx == 0 && dy == 0) { |
| 177 | ! | continue; |
| 178 | } | |
| 179 | ! | int nx = x + dx; |
| 180 | ! | int ny = y + dy; |
| 181 | ! | if (nx < 0 || nx >= width || ny < 0 || ny >= height) { |
| 182 | ! | continue; |
| 183 | } | |
| 184 | ! | std::size_t nidx = static_cast<std::size_t>(ny) * width + nx; |
| 185 | ! | const OutlineGBufferPixel &npx = gbuffer[nidx]; |
| 186 | ||
| 187 | ! | bool n_has_geom = !std::isinf(npx.depth_view); |
| 188 | ||
| 189 | // Edge if neighbor has no geometry, or different material | |
| 190 | ! | if (!n_has_geom || npx.material_id != px.material_id) { |
| 191 | ! | is_edge = true; |
| 192 | ! | break; |
| 193 | } | |
| 194 | } | |
| 195 | } | |
| 196 | ||
| 197 | ! | if (is_edge) { |
| 198 | ! | seeds_curr[idx].x = x; |
| 199 | ! | seeds_curr[idx].y = y; |
| 200 | } | |
| 201 | } | |
| 202 | } | |
| 203 | ||
| 204 | // Jump Flood | |
| 205 | ! | int max_dim = std::max(width, height); |
| 206 | ! | int step = 1; |
| 207 | ! | while (step < max_dim) { |
| 208 | ! | step <<= 1; |
| 209 | } | |
| 210 | ! | step >>= 1; |
| 211 | ||
| 212 | static const int dirs[9][2] = { | |
| 213 | {-1, -1}, {0, -1}, {1, -1}, | |
| 214 | {-1, 0}, {0, 0}, {1, 0}, | |
| 215 | {-1, 1}, {0, 1}, {1, 1} | |
| 216 | }; | |
| 217 | ||
| 218 | ! | for (; step >= 1; step >>= 1) { |
| 219 | ! | for (int y = 0; y < height; ++y) { |
| 220 | ! | for (int x = 0; x < width; ++x) { |
| 221 | ! | std::size_t idx = static_cast<std::size_t>(y) * width + x; |
| 222 | ||
| 223 | ! | JFASeed best = seeds_curr[idx]; |
| 224 | ! | Float best_dist2 = std::numeric_limits<Float>::infinity(); |
| 225 | ! | if (best.x >= 0) { |
| 226 | ! | Float dx = (Float)(best.x - x); |
| 227 | ! | Float dy = (Float)(best.y - y); |
| 228 | ! | best_dist2 = dx * dx + dy * dy; |
| 229 | } | |
| 230 | ||
| 231 | ! | for (int k = 0; k < 9; ++k) { |
| 232 | ! | int nx = x + dirs[k][0] * step; |
| 233 | ! | int ny = y + dirs[k][1] * step; |
| 234 | ! | if (nx < 0 || nx >= width || ny < 0 || ny >= height) { |
| 235 | ! | continue; |
| 236 | } | |
| 237 | ! | std::size_t nidx = static_cast<std::size_t>(ny) * width + nx; |
| 238 | ! | const JFASeed &cand = seeds_curr[nidx]; |
| 239 | ! | if (cand.x < 0) { |
| 240 | ! | continue; |
| 241 | } | |
| 242 | ! | Float dx = (Float)(cand.x - x); |
| 243 | ! | Float dy = (Float)(cand.y - y); |
| 244 | ! | Float d2 = dx * dx + dy * dy; |
| 245 | ! | if (d2 < best_dist2) { |
| 246 | ! | best_dist2 = d2; |
| 247 | ! | best = cand; |
| 248 | } | |
| 249 | } | |
| 250 | ||
| 251 | ! | seeds_next[idx] = best; |
| 252 | } | |
| 253 | } | |
| 254 | ! | seeds_curr.swap(seeds_next); |
| 255 | } | |
| 256 | ||
| 257 | // Apply outlines | |
| 258 | ! | std::vector<vec3> out_colors = color_buffer; |
| 259 | ||
| 260 | ||
| 261 | ! | for (int y = 0; y < height; ++y) { |
| 262 | ! | for (int x = 0; x < width; ++x) { |
| 263 | ! | std::size_t idx = static_cast<std::size_t>(y) * width + x; |
| 264 | ! | const JFASeed &s = seeds_curr[idx]; |
| 265 | ||
| 266 | ! | if (s.x < 0) { |
| 267 | ! | continue; // no edge reachable |
| 268 | } | |
| 269 | ||
| 270 | ! | std::size_t sidx = static_cast<std::size_t>(s.y) * width + s.x; |
| 271 | ! | const OutlineGBufferPixel &seed_px = gbuffer[sidx]; |
| 272 | ! | const OutlineGBufferPixel &dst_px = gbuffer[idx]; |
| 273 | ||
| 274 | ! | Float radius_px = seed_px.outline_width; |
| 275 | ! | if (radius_px <= 0.5f) { |
| 276 | ! | continue; |
| 277 | } | |
| 278 | ||
| 279 | ! | Float dx = (Float)(x - s.x); |
| 280 | ! | Float dy = (Float)(y - s.y); |
| 281 | ! | Float dist2 = dx * dx + dy * dy; |
| 282 | ||
| 283 | ! | if (dist2 > radius_px * radius_px) { |
| 284 | ! | continue; |
| 285 | } | |
| 286 | ||
| 287 | ! | bool dst_has_geom = !std::isinf(dst_px.depth_view); |
| 288 | ||
| 289 | // Never draw on the same toon surface itself. | |
| 290 | // Any pixel that originally belonged to the same toon material | |
| 291 | // (has outline_width > 0) is considered "interior" for the purpose | |
| 292 | // of outline drawing, regardless of its depth. | |
| 293 | ! | bool same_toon_surface = dst_has_geom && dst_px.outline_width > 0.0f && |
| 294 | ! | dst_px.material_id == seed_px.material_id; |
| 295 | ||
| 296 | ! | if (same_toon_surface) { |
| 297 | ! | continue; |
| 298 | } | |
| 299 | ||
| 300 | // Occluder check: if there is geometry in front of the edge, | |
| 301 | // don't draw the outline through it. | |
| 302 | ! | if (dst_has_geom && dst_px.depth_view < seed_px.depth_view) { |
| 303 | ! | continue; |
| 304 | } | |
| 305 | ||
| 306 | ! | out_colors[idx] = seed_px.outline_color; |
| 307 | ! | int sx = s.x; |
| 308 | ! | int sy = s.y; |
| 309 | ||
| 310 | ! | zbuffer(x, y) = zbuffer(sx, sy); |
| 311 | ! | linear_depth(x, y) = seed_px.depth_view; |
| 312 | } | |
| 313 | } | |
| 314 | ! | color_buffer.swap(out_colors); |
| 315 | } | |
| 316 | ||
| 317 | // [[Rcpp::export]] | |
| 318 | 5x | List rasterize(List mesh, |
| 319 | NumericMatrix lightinfo, | |
| 320 | NumericMatrix line_mat, | |
| 321 | int nx, int ny, | |
| 322 | NumericVector model_color, | |
| 323 | NumericVector lookfrom, | |
| 324 | NumericVector lookat, | |
| 325 | double fov, | |
| 326 | IntegerVector typevals, | |
| 327 | bool has_shadow_map, | |
| 328 | bool calc_ambient, | |
| 329 | bool tbn, | |
| 330 | double ambient_radius, | |
| 331 | double shadow_map_bias, | |
| 332 | int numbercores, | |
| 333 | int max_indices, | |
| 334 | LogicalVector has_normals_vec, | |
| 335 | LogicalVector has_tex_vec, | |
| 336 | LogicalVector has_texture, | |
| 337 | LogicalVector has_ambient_texture, | |
| 338 | LogicalVector has_bump_texture, | |
| 339 | LogicalVector has_normal_texture, | |
| 340 | LogicalVector has_specular_texture, | |
| 341 | LogicalVector has_emissive_texture, | |
| 342 | int block_size, | |
| 343 | bool use_default_material, | |
| 344 | double near_clip, | |
| 345 | double far_clip, | |
| 346 | double shadow_map_intensity, | |
| 347 | NumericVector bounds, | |
| 348 | IntegerVector shadowdims, | |
| 349 | NumericVector camera_up, | |
| 350 | double alpha_line, double line_offset, | |
| 351 | NumericVector ortho_dims, LogicalVector is_dir_light, | |
| 352 | bool aa_lines, LogicalVector &has_vertex_tex, LogicalVector &has_vertex_normals, | |
| 353 | LogicalVector has_reflection_map, Rcpp::String reflection_map_file, | |
| 354 | double background_sharpness, | |
| 355 | LogicalVector has_refraction, bool environment_map_hdr, | |
| 356 | bool has_environment_map, NumericVector bg_color, | |
| 357 | bool transparent_background, | |
| 358 | bool verbose) { | |
| 359 | 5x | List materials = as<List>(mesh["materials"]); |
| 360 | 5x | int number_materials = materials.size(); |
| 361 | ||
| 362 | 10x | Environment pkg = Environment::namespace_env("rayvertex"); |
| 363 | ||
| 364 | 5x | Function print_time = pkg["print_time"]; |
| 365 | ||
| 366 | //Turn off gamma correction or get seams in textures/normal maps | |
| 367 | 5x | stbi_ldr_to_hdr_gamma(1.0f); |
| 368 | ||
| 369 | //Resize reflection map for different roughness materials | |
| 370 | 5x | float* reflection_map_data = nullptr; |
| 371 | 5x | int nx_r = 0, ny_r = 0, nn_r = 0; |
| 372 | 5x | std::vector<reflection_map_info> reflection_maps; |
| 373 | reflection_map_info main_reflection_map; | |
| 374 | 5x | std::vector<float* > reflection_data; |
| 375 | ||
| 376 | ||
| 377 | 5x | if(has_environment_map) { |
| 378 | ! | reflection_map_data = stbi_loadf(reflection_map_file.get_cstring(), &nx_r, &ny_r, &nn_r, 0); |
| 379 | ! | if(nx_r == 0 || ny_r == 0 || nn_r == 0) { |
| 380 | ! | throw std::runtime_error("Reflection map loading failed"); |
| 381 | } | |
| 382 | ! | if(environment_map_hdr) { |
| 383 | ! | float gamma_exp = 1.0/2.2f; |
| 384 | ! | for(int j = 0; j < nx_r * ny_r * nn_r; j++) { |
| 385 | ! | reflection_map_data[j] = powf(reflection_map_data[j],gamma_exp); |
| 386 | } | |
| 387 | } | |
| 388 | ! | main_reflection_map.reflection = reflection_map_data; |
| 389 | ! | main_reflection_map.nx = nx_r; |
| 390 | ! | main_reflection_map.ny = ny_r; |
| 391 | ! | main_reflection_map.nn = nn_r; |
| 392 | } | |
| 393 | ||
| 394 | 11x | for(unsigned int i = 0; i < has_reflection_map.size(); i++) { |
| 395 | 6x | if(has_reflection_map(i) || has_refraction(i)) { |
| 396 | ! | List single_material = as<List>(materials(i)); |
| 397 | ! | double reflection_sharpness = as<double>(single_material["reflection_sharpness"]); |
| 398 | ||
| 399 | ! | int nx_r_resize = (double)nx_r * reflection_sharpness; |
| 400 | ! | int ny_r_resize = (double)ny_r * reflection_sharpness; |
| 401 | ! | float* reflection_map_data_new = new float[nx_r * ny_r * nn_r]; |
| 402 | ! | if(reflection_sharpness < 1.0 && reflection_sharpness > 0.0) { |
| 403 | ! | float* reflection_map_data_temp = new float[nx_r_resize * ny_r_resize * nn_r]; |
| 404 | ! | resize_reflection_map(reflection_map_data, nx_r, ny_r, |
| 405 | reflection_map_data_temp, nx_r_resize, ny_r_resize, | |
| 406 | nn_r); | |
| 407 | ||
| 408 | ! | resize_reflection_map(reflection_map_data_temp, nx_r_resize, ny_r_resize, |
| 409 | reflection_map_data_new, nx_r, ny_r, | |
| 410 | nn_r); | |
| 411 | ! | delete[] reflection_map_data_temp; |
| 412 | } else { | |
| 413 | ! | memcpy(reflection_map_data_new, main_reflection_map.reflection, sizeof(float) * nx_r * ny_r * nn_r); |
| 414 | } | |
| 415 | ! | reflection_data.push_back(reflection_map_data_new); |
| 416 | reflection_map_info reflection_map { | |
| 417 | reflection_map_data_new, | |
| 418 | nx_r, | |
| 419 | ny_r, | |
| 420 | nn_r | |
| 421 | }; | |
| 422 | ! | reflection_maps.push_back(reflection_map); |
| 423 | } else { | |
| 424 | 6x | reflection_map_info reflection_map { |
| 425 | nullptr, | |
| 426 | nx_r, | |
| 427 | ny_r, | |
| 428 | nn_r | |
| 429 | }; | |
| 430 | 6x | reflection_maps.push_back(reflection_map); |
| 431 | } | |
| 432 | } | |
| 433 | 5x | print_time(verbose, "Loaded environment maps" ); |
| 434 | ||
| 435 | //Convert R vectors to vec3 | |
| 436 | 5x | vec3 eye(lookfrom(0),lookfrom(1),lookfrom(2)); //lookfrom |
| 437 | 5x | vec3 center(lookat(0),lookat(1),lookat(2)); //lookat |
| 438 | 5x | vec3 cam_up = vec3(camera_up(0),camera_up(1),camera_up(2)); |
| 439 | 5x | vec3 color(model_color(0),model_color(1),model_color(2)); |
| 440 | ||
| 441 | //Account for colinear camera direction/cam_up vectors | |
| 442 | 5x | if(glm::length(glm::cross(eye-center,cam_up)) == 0) { |
| 443 | ! | const std::string warn_string("Look direction and camera up colinear--using c(0,0,1) for up."); |
| 444 | ! | Rcpp::warning(warn_string); |
| 445 | ! | cam_up = vec3(0.,0.,1.f); |
| 446 | } | |
| 447 | ||
| 448 | 5x | Float dist_to_focus = glm::length(eye-center)+0.5; |
| 449 | 5x | vec3 sceneboundmin = vec3(bounds(0),bounds(1),bounds(2)); |
| 450 | 5x | vec3 sceneboundmax = vec3(bounds(3),bounds(4),bounds(5)); |
| 451 | 5x | Float scene_diag = glm::length(sceneboundmax-sceneboundmin)+0.5; |
| 452 | 5x | vec3 scene_center = (sceneboundmax+sceneboundmin)/(Float)2.0; |
| 453 | ||
| 454 | 5x | far_clip = scene_diag + dist_to_focus; |
| 455 | ||
| 456 | ||
| 457 | //Generate MVP matrices | |
| 458 | 5x | Mat View = glm::lookAt(eye, center, cam_up); |
| 459 | 5x | Mat Model = glm::translate(Mat(1.0), vec3(0.0, 0.0, 0.0)); |
| 460 | 10x | Mat Projection = fov != 0.0 ? glm::perspective(glm::radians((Float)fov), |
| 461 | 5x | (Float)nx / (Float)ny, |
| 462 | (Float)near_clip, | |
| 463 | (Float)far_clip) : | |
| 464 | ! | glm::ortho(-(Float)ortho_dims(0)/2, (Float)ortho_dims(0)/2, -(Float)ortho_dims(1)/2, (Float)ortho_dims(1)/2); |
| 465 | 5x | vec4 viewport(0.0f, 0.0f, (Float)nx-1, (Float)ny-1); |
| 466 | 5x | vec4 viewport_depth(0.0f, 0.0f, (Float)shadowdims(0)-1, (Float)shadowdims(1)-1); |
| 467 | 5x | int nx_d = shadowdims(0); |
| 468 | 5x | int ny_d = shadowdims(1); |
| 469 | ||
| 470 | ||
| 471 | 5x | Mat vp = glm::scale(glm::translate(Mat(1.0f), |
| 472 | 5x | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)), |
| 473 | 5x | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)); |
| 474 | ||
| 475 | 5x | Mat vp_shadow = glm::scale(glm::translate(Mat(1.0f), |
| 476 | 5x | vec3(viewport_depth[2]/2.0f,viewport_depth[3]/2.0f,1.0f/2.0f)), |
| 477 | 5x | vec3(viewport_depth[2]/2.0f,viewport_depth[3]/2.0f,1.0f/2.0f)); |
| 478 | //Initialize output matrices | |
| 479 | 5x | NumericMatrix r(nx,ny); |
| 480 | 5x | NumericMatrix g(nx,ny); |
| 481 | 5x | NumericMatrix b(nx,ny); |
| 482 | 5x | NumericMatrix a(nx,ny); |
| 483 | ||
| 484 | ||
| 485 | //Fill bg color | |
| 486 | 5x | std::fill(r.begin(), r.end(), bg_color[0]) ; |
| 487 | 5x | std::fill(g.begin(), g.end(), bg_color[1] ) ; |
| 488 | 5x | std::fill(b.begin(), b.end(), bg_color[2] ) ; |
| 489 | 5x | float default_alpha = !transparent_background ? 1.0f : 0.0f; |
| 490 | 5x | std::fill(a.begin(), a.end(), default_alpha ) ; |
| 491 | ||
| 492 | ||
| 493 | //Create buffers | |
| 494 | 5x | rayimage image(r,g,b,a, nx,ny); |
| 495 | ||
| 496 | //Depth buffer | |
| 497 | 5x | NumericMatrix zbuffer(nx,ny); |
| 498 | 5x | NumericMatrix sbuffer(shadowdims(0),shadowdims(1)); |
| 499 | 5x | NumericMatrix zbuffer_depth(shadowdims(0),shadowdims(1)); |
| 500 | ||
| 501 | 5x | NumericMatrix abuffer(nx,ny); |
| 502 | ||
| 503 | //Fill ambient occlusion buffer | |
| 504 | 5x | std::fill(abuffer.begin(), abuffer.end(), 1.0f ) ; |
| 505 | ||
| 506 | ||
| 507 | //Position space buffer | |
| 508 | 5x | NumericMatrix xxbuffer(nx,ny); |
| 509 | 5x | NumericMatrix yybuffer(nx,ny); |
| 510 | 5x | NumericMatrix zzbuffer(nx,ny); |
| 511 | ||
| 512 | // Material ID buffer (topmost visible material index per pixel) | |
| 513 | 5x | IntegerMatrix material_id_buffer(nx, ny); |
| 514 | 5x | std::fill(material_id_buffer.begin(), material_id_buffer.end(), -1); |
| 515 | ||
| 516 | ||
| 517 | //Normal space buffer | |
| 518 | 5x | NumericMatrix nxbuffer(nx,ny); |
| 519 | 5x | NumericMatrix nybuffer(nx,ny); |
| 520 | 5x | NumericMatrix nzbuffer(nx,ny); |
| 521 | ||
| 522 | //UV buffer | |
| 523 | 5x | NumericMatrix uvxbuffer(nx,ny); |
| 524 | 5x | NumericMatrix uvybuffer(nx,ny); |
| 525 | 5x | NumericMatrix uvzbuffer(nx,ny); |
| 526 | ||
| 527 | //Initialize rayimage buffers | |
| 528 | 5x | rayimage shadowbuffer(sbuffer, shadowdims(0), shadowdims(1),shadow_map_intensity); |
| 529 | 5x | rayimage ambientbuffer(abuffer, nx, ny); |
| 530 | 5x | rayimage positionbuffer(xxbuffer,yybuffer,zzbuffer,nx,ny); |
| 531 | 5x | rayimage normalbuffer(nxbuffer,nybuffer,nzbuffer,nx,ny); |
| 532 | 5x | rayimage uvbuffer(uvxbuffer,uvybuffer,uvzbuffer,nx,ny); |
| 533 | ||
| 534 | //Initialize zbuffer | |
| 535 | 5x | std::fill(zbuffer.begin(), zbuffer.end(), std::numeric_limits<Float>::infinity() ) ; |
| 536 | 5x | std::fill(zbuffer_depth.begin(), zbuffer_depth.end(), std::numeric_limits<Float>::infinity() ) ; |
| 537 | 5x | print_time(verbose, "Initialized buffers" ); |
| 538 | ||
| 539 | //Initialize Shadow Map bounds and orientation | |
| 540 | //If changed to 0.1-100.0 doesn't work anymore | |
| 541 | 5x | Float near_plane = 0.1, far_plane = 10.0; |
| 542 | // Float near_plane = 0.1f, far_plane = 100.0f; | |
| 543 | ||
| 544 | 5x | Mat shadow_inv = glm::inverse(vp * Projection * View * Model); |
| 545 | ||
| 546 | 5x | std::vector<Light> point_lights; |
| 547 | 10x | for(int i = 0; i < lightinfo.nrow(); i++) { |
| 548 | 5x | if(!is_dir_light(i)) { |
| 549 | ! | vec3 light_position = View * Model * vec4(lightinfo(i,0),lightinfo(i,1),lightinfo(i,2),1.0); |
| 550 | ! | point_lights.push_back(Light(light_position, |
| 551 | ! | vec3(lightinfo(i,3),lightinfo(i,4),lightinfo(i,5)), |
| 552 | ! | lightinfo(i,6),lightinfo(i,7),lightinfo(i,8), |
| 553 | ! | lightinfo(i,9))); |
| 554 | } | |
| 555 | } | |
| 556 | ||
| 557 | 5x | std::vector<rayimage > shadowbuffers; |
| 558 | 5x | std::vector<Rcpp::NumericMatrix> shadowbuffer_mats; |
| 559 | ||
| 560 | 5x | std::vector<DirectionalLight> directional_lights; |
| 561 | 10x | for(unsigned int i = 0; i < is_dir_light.length(); i++) { |
| 562 | 5x | if(is_dir_light(i)) { |
| 563 | 5x | shadowbuffer_mats.push_back(NumericMatrix(shadowdims(0),shadowdims(1))); |
| 564 | 5x | std::fill(shadowbuffer_mats.back().begin(), shadowbuffer_mats.back().end(), |
| 565 | 5x | std::numeric_limits<double>::infinity() ) ; |
| 566 | ||
| 567 | 5x | rayimage shadowbuffer_temp(shadowbuffer_mats.back(),shadowdims(0),shadowdims(1),shadow_map_intensity); |
| 568 | ||
| 569 | 5x | shadowbuffers.push_back(shadowbuffer_temp); |
| 570 | ||
| 571 | 5x | vec3 light_dir_temp = glm::normalize(vec3(lightinfo(i,0),lightinfo(i,1),lightinfo(i,2))); |
| 572 | 5x | vec3 light_up_dir = vec3(0.,1.,0.); |
| 573 | 5x | if(glm::length(glm::cross(light_dir_temp,light_up_dir)) == 0) { |
| 574 | 4x | light_up_dir = vec3(0.f,0.f,1.0f); |
| 575 | } | |
| 576 | 5x | directional_lights.push_back(DirectionalLight(light_dir_temp, |
| 577 | 5x | vec3(lightinfo(i,3),lightinfo(i,4),lightinfo(i,5)), |
| 578 | scene_center, light_up_dir, scene_diag, | |
| 579 | near_plane, far_plane, | |
| 580 | vp_shadow, Model, shadow_inv, | |
| 581 | 10x | lightinfo(i,9))); |
| 582 | } | |
| 583 | } | |
| 584 | 5x | print_time(verbose, "Initialized shadowmaps" ); |
| 585 | ||
| 586 | ||
| 587 | 5x | std::vector<rayimage > transparency_buffers; |
| 588 | 5x | std::vector<Rcpp::NumericMatrix> transparency_buffer_mats_r; |
| 589 | 5x | std::vector<Rcpp::NumericMatrix> transparency_buffer_mats_g; |
| 590 | 5x | std::vector<Rcpp::NumericMatrix> transparency_buffer_mats_b; |
| 591 | 5x | std::vector<Rcpp::NumericMatrix> transparency_buffer_mats_a; |
| 592 | ||
| 593 | 10x | for(int i = 0; i < is_dir_light.length(); i++) { |
| 594 | 5x | if(is_dir_light(i)) { |
| 595 | 5x | transparency_buffer_mats_r.push_back(NumericMatrix(shadowdims(0),shadowdims(1))); |
| 596 | 5x | transparency_buffer_mats_g.push_back(NumericMatrix(shadowdims(0),shadowdims(1))); |
| 597 | 5x | transparency_buffer_mats_b.push_back(NumericMatrix(shadowdims(0),shadowdims(1))); |
| 598 | 5x | transparency_buffer_mats_a.push_back(NumericMatrix(shadowdims(0),shadowdims(1))); |
| 599 | ||
| 600 | 5x | std::fill(transparency_buffer_mats_r.back().begin(), transparency_buffer_mats_r.back().end(), 1.0) ; |
| 601 | 5x | std::fill(transparency_buffer_mats_g.back().begin(), transparency_buffer_mats_g.back().end(), 1.0) ; |
| 602 | 5x | std::fill(transparency_buffer_mats_b.back().begin(), transparency_buffer_mats_b.back().end(), 1.0) ; |
| 603 | 5x | std::fill(transparency_buffer_mats_a.back().begin(), transparency_buffer_mats_a.back().end(), 0.0) ; |
| 604 | ||
| 605 | 5x | rayimage trans_buffer_temp(transparency_buffer_mats_r.back(), |
| 606 | 5x | transparency_buffer_mats_g.back(), |
| 607 | 5x | transparency_buffer_mats_b.back(), |
| 608 | 5x | transparency_buffer_mats_a.back(), |
| 609 | 10x | shadowdims(0),shadowdims(1),shadow_map_intensity); |
| 610 | ||
| 611 | 5x | transparency_buffers.push_back(trans_buffer_temp); |
| 612 | } | |
| 613 | } | |
| 614 | 5x | print_time(verbose, "Initialized alpha buffers" ); |
| 615 | ||
| 616 | ||
| 617 | /// | |
| 618 | //Parse mesh3d | |
| 619 | // | |
| 620 | 5x | List shapes = as<List>(mesh["shapes"]); |
| 621 | 5x | int number_shapes = shapes.size(); |
| 622 | ||
| 623 | //Start by generating a shader for every material | |
| 624 | 5x | std::vector<material_info> mat_info; |
| 625 | 5x | std::vector<IShader*> shaders; |
| 626 | ||
| 627 | // Count total faces across all shapes so we can size varying buffers correctly | |
| 628 | 5x | int total_faces = 0; |
| 629 | 10x | for(int i = 0; i < number_shapes; i++) { |
| 630 | 5x | List single_shape = as<List>(shapes(i)); |
| 631 | 5x | IntegerMatrix shape_inds = as<IntegerMatrix>(single_shape["indices"]); |
| 632 | 5x | total_faces += shape_inds.nrow(); |
| 633 | } | |
| 634 | 5x | std::vector<vec3> vec_varying_intensity; |
| 635 | 5x | std::vector<std::vector<vec3> > vec_varying_uv; |
| 636 | 5x | std::vector<std::vector<vec4> > vec_varying_tri; |
| 637 | 5x | std::vector<std::vector<vec3> > vec_varying_pos; |
| 638 | 5x | std::vector<std::vector<vec3> > vec_varying_world_nrm; |
| 639 | 5x | std::vector<std::vector<vec3> > vec_varying_ndc_tri; |
| 640 | 5x | std::vector<std::vector<vec3> > vec_varying_nrm; |
| 641 | ||
| 642 | 1729x | for(int i = 0; i < total_faces; i++ ) { |
| 643 | 1724x | vec_varying_intensity.push_back(vec3(0.0f)); |
| 644 | 3448x | std::vector<vec3> tempuv(3); |
| 645 | 3448x | std::vector<vec4> temptri(3); |
| 646 | 3448x | std::vector<vec3> temppos(3); |
| 647 | 3448x | std::vector<vec3> tempnrm(3); |
| 648 | 3448x | std::vector<vec3> tempndc(3); |
| 649 | 1724x | std::vector<vec3> tempnrm2(3); |
| 650 | ||
| 651 | 1724x | vec_varying_uv.push_back(tempuv); |
| 652 | 1724x | vec_varying_tri.push_back(temptri); |
| 653 | 1724x | vec_varying_pos.push_back(temppos); |
| 654 | 1724x | vec_varying_world_nrm.push_back(tempnrm); |
| 655 | 1724x | vec_varying_ndc_tri.push_back(tempndc); |
| 656 | 1724x | vec_varying_nrm.push_back(tempnrm2); |
| 657 | } | |
| 658 | ||
| 659 | 11x | for(int i = 0; i < number_materials; i++) { |
| 660 | 6x | List single_material = as<List>(materials(i)); |
| 661 | 12x | NumericVector ambient = as<NumericVector>(single_material["ambient"]); |
| 662 | 12x | NumericVector diffuse = as<NumericVector>(single_material["diffuse"]); |
| 663 | 12x | NumericVector specular = as<NumericVector>(single_material["specular"]); |
| 664 | 12x | NumericVector transmittance = as<NumericVector>(single_material["transmittance"]); |
| 665 | 12x | NumericVector emission = as<NumericVector>(single_material["emission"]); |
| 666 | 12x | Float shininess = as<Float>(single_material["shininess"]); |
| 667 | 12x | Float ior = as<Float>(single_material["ior"]); |
| 668 | 12x | Float dissolve = as<Float>(single_material["dissolve"]); |
| 669 | 12x | Float illum = as<Float>(single_material["illum"]); |
| 670 | 12x | String ambient_texname = as<String>(single_material["ambient_texname"]); |
| 671 | 12x | String diffuse_texname = as<String>(single_material["diffuse_texname"]); |
| 672 | // String bump_texname = as<String>(single_material["bump_texname"]); | |
| 673 | 12x | String specular_texname = as<String>(single_material["specular_texname"]); |
| 674 | 12x | String normal_texname = as<String>(single_material["normal_texname"]); |
| 675 | 12x | String emissive_texname = as<String>(single_material["emissive_texname"]); |
| 676 | 12x | Float diffuse_intensity = as<Float>(single_material["diffuse_intensity"]); |
| 677 | // Float bump_intensity = as<Float>(single_material["bump_intensity"]); | |
| 678 | 12x | Float specular_intensity = as<Float>(single_material["specular_intensity"]); |
| 679 | 12x | Float emission_intensity = as<Float>(single_material["emission_intensity"]); |
| 680 | 12x | Float ambient_intensity = as<Float>(single_material["ambient_intensity"]); |
| 681 | 12x | int cull_type = as<int>(single_material["culling"]); |
| 682 | 12x | bool is_translucent = as<bool>(single_material["translucent"]); |
| 683 | 12x | Float toon_levels = as<Float>(single_material["toon_levels"]); |
| 684 | 12x | Float toon_outline_width = as<Float>(single_material["toon_outline_width"]); |
| 685 | 12x | NumericVector toon_outline_color = as<NumericVector>(single_material["toon_outline_color"]); |
| 686 | 12x | Float reflection_intensity = as<Float>(single_material["reflection_intensity"]); |
| 687 | 12x | bool two_sided = as<bool>(single_material["two_sided"]); |
| 688 | 6x | Float sigma = as<Float>(single_material["sigma"]); |
| 689 | ||
| 690 | 6x | int type = typevals(i); |
| 691 | ||
| 692 | 6x | if(type != 9 && type != 10) { |
| 693 | 6x | toon_outline_width = 0.0f; |
| 694 | } | |
| 695 | //Change cull type to none if two sided | |
| 696 | 6x | cull_type = !two_sided ? cull_type : 3; |
| 697 | ||
| 698 | 6x | bool has_texture_single = has_texture(i); |
| 699 | 6x | bool has_ambient_texture_single = has_ambient_texture(i); |
| 700 | // bool has_bump_texture_single = has_bump_texture(i); | |
| 701 | 6x | bool has_normal_texture_single = has_normal_texture(i); |
| 702 | 6x | bool has_specular_texture_single = has_specular_texture(i); |
| 703 | 6x | bool has_emissive_texture_single = has_emissive_texture(i); |
| 704 | material_info temp = { | |
| 705 | 6x | vec3(ambient(0),ambient(1),ambient(2)), |
| 706 | 6x | vec3(diffuse(0),diffuse(1),diffuse(2)), |
| 707 | 6x | vec3(specular(0),specular(1),specular(2)), |
| 708 | 6x | vec3(transmittance(0),transmittance(1),transmittance(2)), //Not used currently |
| 709 | 6x | vec3(emission(0),emission(1),emission(2)), //Not used currently |
| 710 | shininess, | |
| 711 | ior, | |
| 712 | dissolve, | |
| 713 | illum, | |
| 714 | ambient_texname, | |
| 715 | diffuse_texname, | |
| 716 | specular_texname, | |
| 717 | normal_texname, | |
| 718 | emissive_texname, | |
| 719 | max_indices, | |
| 720 | (Float)emission_intensity, | |
| 721 | (Float)diffuse_intensity, | |
| 722 | (Float)specular_intensity, | |
| 723 | (Float)ambient_intensity, | |
| 724 | has_texture_single, | |
| 725 | has_ambient_texture_single, | |
| 726 | has_normal_texture_single, | |
| 727 | has_specular_texture_single, | |
| 728 | has_emissive_texture_single, | |
| 729 | cull_type, | |
| 730 | is_translucent, | |
| 731 | toon_levels, | |
| 732 | toon_outline_width, | |
| 733 | ! | vec3(toon_outline_color(0),toon_outline_color(1),toon_outline_color(2)), |
| 734 | reflection_intensity, | |
| 735 | sigma | |
| 736 | }; | |
| 737 | 6x | mat_info.push_back(temp); |
| 738 | ||
| 739 | IShader* shader; | |
| 740 | 6x | if(type == 1) { |
| 741 | ! | shader = new GouraudShader(Model, Projection, View, viewport, |
| 742 | has_shadow_map, | |
| 743 | ! | shadow_map_bias,mat_info[i], point_lights, |
| 744 | directional_lights, | |
| 745 | shadowbuffers, | |
| 746 | transparency_buffers, | |
| 747 | vec_varying_intensity, | |
| 748 | vec_varying_uv, | |
| 749 | vec_varying_tri, | |
| 750 | vec_varying_pos, | |
| 751 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 752 | ! | reflection_maps[i], has_reflection_map(i), has_refraction(i)); |
| 753 | 6x | } else if (type == 2) { |
| 754 | 6x | if(sigma <= 0) { |
| 755 | ! | shader = new DiffuseShader(Model, Projection, View, viewport, |
| 756 | has_shadow_map, | |
| 757 | 6x | shadow_map_bias,mat_info[i], point_lights, |
| 758 | directional_lights, | |
| 759 | shadowbuffers, | |
| 760 | transparency_buffers, | |
| 761 | vec_varying_intensity, | |
| 762 | vec_varying_uv, | |
| 763 | vec_varying_tri, | |
| 764 | vec_varying_pos, | |
| 765 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 766 | ! | reflection_maps[i], has_reflection_map(i), has_refraction(i), |
| 767 | 12x | two_sided); |
| 768 | } else { | |
| 769 | ! | shader = new OrenNayerShader(Model, Projection, View, viewport, |
| 770 | has_shadow_map, | |
| 771 | ! | shadow_map_bias,mat_info[i], point_lights, |
| 772 | directional_lights, | |
| 773 | shadowbuffers, | |
| 774 | transparency_buffers, | |
| 775 | vec_varying_intensity, | |
| 776 | vec_varying_uv, | |
| 777 | vec_varying_tri, | |
| 778 | vec_varying_pos, | |
| 779 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 780 | ! | reflection_maps[i], has_reflection_map(i), has_refraction(i), |
| 781 | ! | two_sided); |
| 782 | } | |
| 783 | ! | } else if (type == 3) { |
| 784 | ! | shader = new PhongShader(Model, Projection, View, viewport, |
| 785 | has_shadow_map, | |
| 786 | ! | shadow_map_bias,mat_info[i], point_lights, |
| 787 | directional_lights, | |
| 788 | shadowbuffers, | |
| 789 | transparency_buffers, | |
| 790 | vec_varying_intensity, | |
| 791 | vec_varying_uv, | |
| 792 | vec_varying_tri, | |
| 793 | vec_varying_pos, | |
| 794 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 795 | ! | reflection_maps[i], has_reflection_map(i), has_refraction(i)); |
| 796 | ! | } else if (type == 4) { |
| 797 | ! | shader = new DiffuseNormalShader(Model, Projection, View, viewport, |
| 798 | has_shadow_map, | |
| 799 | ! | shadow_map_bias,mat_info[i], point_lights, |
| 800 | directional_lights, | |
| 801 | shadowbuffers, | |
| 802 | transparency_buffers, | |
| 803 | vec_varying_intensity, | |
| 804 | vec_varying_uv, | |
| 805 | vec_varying_tri, | |
| 806 | vec_varying_pos, | |
| 807 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 808 | ! | reflection_maps[i], has_reflection_map(i), has_refraction(i)); |
| 809 | ! | } else if (type == 5) { |
| 810 | ! | shader = new DiffuseShaderTangent(Model, Projection, View, viewport, |
| 811 | has_shadow_map, | |
| 812 | ! | shadow_map_bias,mat_info[i], point_lights, |
| 813 | directional_lights, | |
| 814 | shadowbuffers, | |
| 815 | transparency_buffers, | |
| 816 | vec_varying_intensity, | |
| 817 | vec_varying_uv, | |
| 818 | vec_varying_tri, | |
| 819 | vec_varying_pos, | |
| 820 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 821 | ! | reflection_maps[i], has_reflection_map(i), has_refraction(i)); |
| 822 | ! | } else if (type == 6) { |
| 823 | ! | shader = new PhongNormalShader(Model, Projection, View, viewport, |
| 824 | has_shadow_map, | |
| 825 | ! | shadow_map_bias,mat_info[i], point_lights, |
| 826 | directional_lights, | |
| 827 | shadowbuffers, | |
| 828 | transparency_buffers, | |
| 829 | vec_varying_intensity, | |
| 830 | vec_varying_uv, | |
| 831 | vec_varying_tri, | |
| 832 | vec_varying_pos, | |
| 833 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 834 | ! | reflection_maps[i], has_reflection_map(i), has_refraction(i)); |
| 835 | ! | } else if (type == 7) { |
| 836 | ! | shader = new PhongShaderTangent(Model, Projection, View, viewport, |
| 837 | has_shadow_map, | |
| 838 | ! | shadow_map_bias,mat_info[i], point_lights, |
| 839 | directional_lights, | |
| 840 | shadowbuffers, | |
| 841 | transparency_buffers, | |
| 842 | vec_varying_intensity, | |
| 843 | vec_varying_uv, | |
| 844 | vec_varying_tri, | |
| 845 | vec_varying_pos, | |
| 846 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 847 | ! | reflection_maps[i], has_reflection_map(i), has_refraction(i)); |
| 848 | ! | } else if (type == 8) { |
| 849 | ! | shader = new ColorShader(Model, Projection, View, viewport,mat_info[i], |
| 850 | vec_varying_intensity, | |
| 851 | vec_varying_uv, | |
| 852 | vec_varying_tri, | |
| 853 | vec_varying_pos, | |
| 854 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 855 | ! | reflection_maps[i], has_reflection_map(i), has_refraction(i)); |
| 856 | ! | } else if (type == 9) { |
| 857 | ! | shader = new ToonShader(Model, Projection, View, viewport, |
| 858 | has_shadow_map, | |
| 859 | ! | shadow_map_bias,mat_info[i], point_lights, |
| 860 | directional_lights, | |
| 861 | shadowbuffers, | |
| 862 | transparency_buffers, | |
| 863 | vec_varying_intensity, | |
| 864 | vec_varying_uv, | |
| 865 | vec_varying_tri, | |
| 866 | vec_varying_pos, | |
| 867 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 868 | ! | reflection_maps[i], has_reflection_map(i), has_refraction(i)); |
| 869 | ! | } else if (type == 10) { |
| 870 | ! | shader = new ToonShaderPhong(Model, Projection, View, viewport, |
| 871 | has_shadow_map, | |
| 872 | ! | shadow_map_bias,mat_info[i], point_lights, |
| 873 | directional_lights, | |
| 874 | shadowbuffers, | |
| 875 | transparency_buffers, | |
| 876 | vec_varying_intensity, | |
| 877 | vec_varying_uv, | |
| 878 | vec_varying_tri, | |
| 879 | vec_varying_pos, | |
| 880 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 881 | ! | reflection_maps[i], has_reflection_map(i), has_refraction(i)); |
| 882 | } else { | |
| 883 | ! | throw std::runtime_error("shader not recognized"); |
| 884 | } | |
| 885 | 6x | shaders.push_back(shader); |
| 886 | } | |
| 887 | ||
| 888 | 5x | reflection_map_info reflection_map_default { |
| 889 | nullptr, | |
| 890 | 1, | |
| 891 | 1, | |
| 892 | 1 | |
| 893 | }; | |
| 894 | ||
| 895 | //Initialize default material | |
| 896 | 5x | Rcpp::String fill(""); |
| 897 | 5x | material_info default_mat = { |
| 898 | vec3(0.0,0.0,0.0), | |
| 899 | color, | |
| 900 | vec3(1.0), | |
| 901 | vec3(0.0), | |
| 902 | vec3(0.0), | |
| 903 | (Float)10.0, | |
| 904 | 1.0, | |
| 905 | 1.0, | |
| 906 | 1.0, | |
| 907 | fill,fill,fill,fill,fill, | |
| 908 | max_indices, //Maybe an issue? | |
| 909 | (Float)1.0, | |
| 910 | (Float)1.0, | |
| 911 | (Float)1.0, | |
| 912 | (Float)1.0, | |
| 913 | false, | |
| 914 | false, | |
| 915 | false, | |
| 916 | false, | |
| 917 | false, | |
| 918 | 1, | |
| 919 | false, | |
| 920 | 5, | |
| 921 | 0.0, // toon_outline_width | |
| 922 | vec3(0.0), // toon_outline_color | |
| 923 | 0.0, | |
| 924 | 0 | |
| 925 | }; | |
| 926 | ||
| 927 | 5x | mat_info.push_back(default_mat); |
| 928 | ||
| 929 | //Add default shader to vector | |
| 930 | 5x | if(typevals(0) == 1) { |
| 931 | ! | shaders.push_back(new GouraudShader(Model, Projection, View, viewport, |
| 932 | has_shadow_map, | |
| 933 | ! | shadow_map_bias,mat_info.back(), point_lights, |
| 934 | directional_lights, | |
| 935 | shadowbuffers, | |
| 936 | transparency_buffers, | |
| 937 | vec_varying_intensity, | |
| 938 | vec_varying_uv, | |
| 939 | vec_varying_tri, | |
| 940 | vec_varying_pos, | |
| 941 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 942 | ! | reflection_map_default, false, false)); |
| 943 | 5x | } else if (typevals(0) == 2 || typevals(0) == 4 || typevals(0) == 5) { |
| 944 | 10x | shaders.push_back(new DiffuseShader(Model, Projection, View, viewport, |
| 945 | has_shadow_map, | |
| 946 | 5x | shadow_map_bias,mat_info.back(), point_lights, |
| 947 | directional_lights, | |
| 948 | shadowbuffers, | |
| 949 | transparency_buffers, | |
| 950 | vec_varying_intensity, | |
| 951 | vec_varying_uv, | |
| 952 | vec_varying_tri, | |
| 953 | vec_varying_pos, | |
| 954 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 955 | 15x | reflection_map_default, false, false, false)); |
| 956 | ! | } else if (typevals(0) == 3 || typevals(0) == 6 || typevals(0) == 7) { |
| 957 | ! | shaders.push_back(new PhongShader(Model, Projection, View, viewport, |
| 958 | has_shadow_map, | |
| 959 | ! | shadow_map_bias,mat_info.back(), point_lights, |
| 960 | directional_lights, | |
| 961 | shadowbuffers, | |
| 962 | transparency_buffers, | |
| 963 | vec_varying_intensity, | |
| 964 | vec_varying_uv, | |
| 965 | vec_varying_tri, | |
| 966 | vec_varying_pos, | |
| 967 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 968 | ! | reflection_map_default, false, false)); |
| 969 | ! | } else if (typevals(0) == 8) { |
| 970 | ! | shaders.push_back(new ColorShader(Model, Projection, View, viewport,mat_info.back(), |
| 971 | vec_varying_intensity, | |
| 972 | vec_varying_uv, | |
| 973 | vec_varying_tri, | |
| 974 | vec_varying_pos, | |
| 975 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 976 | ! | reflection_map_default, false, false)); |
| 977 | ! | } else if (typevals(0) == 9) { |
| 978 | ! | shaders.push_back(new ToonShader(Model, Projection, View, viewport, |
| 979 | has_shadow_map, | |
| 980 | ! | shadow_map_bias,mat_info.back(), point_lights, |
| 981 | directional_lights, | |
| 982 | shadowbuffers, | |
| 983 | transparency_buffers, | |
| 984 | vec_varying_intensity, | |
| 985 | vec_varying_uv, | |
| 986 | vec_varying_tri, | |
| 987 | vec_varying_pos, | |
| 988 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 989 | ! | reflection_map_default, false, false)); |
| 990 | ! | } else if (typevals(0) == 10) { |
| 991 | ! | shaders.push_back(new ToonShaderPhong(Model, Projection, View, viewport, |
| 992 | has_shadow_map, | |
| 993 | ! | shadow_map_bias,mat_info.back(), point_lights, |
| 994 | directional_lights, | |
| 995 | shadowbuffers, | |
| 996 | transparency_buffers, | |
| 997 | vec_varying_intensity, | |
| 998 | vec_varying_uv, | |
| 999 | vec_varying_tri, | |
| 1000 | vec_varying_pos, | |
| 1001 | vec_varying_world_nrm,vec_varying_ndc_tri,vec_varying_nrm, | |
| 1002 | ! | reflection_map_default, false, false)); |
| 1003 | } | |
| 1004 | 5x | print_time(verbose, "Initialized shaders" ); |
| 1005 | ||
| 1006 | ||
| 1007 | //Initialize Model vectors | |
| 1008 | 5x | std::vector<ModelInfo> models; |
| 1009 | ||
| 1010 | //Initialize vertex storage vectors | |
| 1011 | 5x | std::vector<std::vector<std::vector<vec4> > > ndc_verts; |
| 1012 | 5x | std::vector<std::vector<std::vector<Float> > > ndc_inv_w; |
| 1013 | 5x | std::vector<std::vector<std::vector<vec4> > > ndc_verts_depth; |
| 1014 | 5x | std::vector<std::vector<std::vector<Float> > > ndc_inv_w_depth; |
| 1015 | ||
| 1016 | //Fill vectors for each shape in the model | |
| 1017 | //order: [model_num][triangle vertex][face] | |
| 1018 | 10x | NumericMatrix mesh_verts = as<NumericMatrix>(mesh["vertices"]); |
| 1019 | 10x | NumericMatrix mesh_texcoords = as<NumericMatrix>(mesh["texcoords"]); |
| 1020 | 5x | NumericMatrix mesh_normals = as<NumericMatrix>(mesh["normals"]); |
| 1021 | ||
| 1022 | 5x | int running_face_offset = 0; |
| 1023 | 10x | for(int i = 0; i < number_shapes; i++) { |
| 1024 | 5x | List single_shape = as<List>(shapes(i)); |
| 1025 | 10x | IntegerMatrix shape_inds = as<IntegerMatrix>(single_shape["indices"]); |
| 1026 | 10x | IntegerMatrix tex_inds = as<IntegerMatrix>(single_shape["tex_indices"]); |
| 1027 | 10x | IntegerMatrix norm_inds = as<IntegerMatrix>(single_shape["norm_indices"]); |
| 1028 | 5x | IntegerVector shape_materials = as<IntegerVector>(single_shape["material_ids"]); |
| 1029 | ||
| 1030 | 5x | int n = shape_inds.nrow(); |
| 1031 | ||
| 1032 | 10x | ndc_verts.push_back(std::vector<std::vector<vec4> >(3, std::vector<vec4>(n))); |
| 1033 | 10x | ndc_inv_w.push_back(std::vector<std::vector<Float> >(3, std::vector<Float>(n))); |
| 1034 | 5x | if(has_shadow_map) { |
| 1035 | 10x | ndc_verts_depth.push_back(std::vector<std::vector<vec4> >(3, std::vector<vec4>(n))); |
| 1036 | 10x | ndc_inv_w_depth.push_back(std::vector<std::vector<Float> >(3, std::vector<Float>(n))); |
| 1037 | } | |
| 1038 | ||
| 1039 | //Create model object | |
| 1040 | ModelInfo model(mesh_verts, mesh_texcoords, mesh_normals, | |
| 1041 | shape_inds, tex_inds, norm_inds, | |
| 1042 | has_vertex_tex, has_vertex_normals, | |
| 1043 | shape_materials, | |
| 1044 | ! | has_normals_vec(i), has_tex_vec(i), tbn, |
| 1045 | 5x | running_face_offset); |
| 1046 | 5x | models.push_back(model); |
| 1047 | 5x | running_face_offset += n; |
| 1048 | } | |
| 1049 | 5x | print_time(verbose, "Initialized 3D models" ); |
| 1050 | ||
| 1051 | ||
| 1052 | //For alpha transparency | |
| 1053 | 5x | std::vector<std::map<Float, alpha_info> > alpha_depths(nx*ny); |
| 1054 | ||
| 1055 | //For per-light transparent colors | |
| 1056 | 5x | std::vector<std::vector<std::map<Float, alpha_info> > > alpha_depths_trans; |
| 1057 | 10x | for(unsigned int i = 0; i < shadowbuffers.size(); i++) { |
| 1058 | 5x | std::vector<std::map<Float, alpha_info> > temp_adt(shadowdims(0) * shadowdims(1)); |
| 1059 | 5x | alpha_depths_trans.push_back(temp_adt); |
| 1060 | } | |
| 1061 | ||
| 1062 | ||
| 1063 | //Set up blocks | |
| 1064 | 5x | int blocksize = block_size; |
| 1065 | ||
| 1066 | //Inner-most index model, then block, then index | |
| 1067 | 5x | std::vector<std::vector<std::vector<int> > > blocks; |
| 1068 | ||
| 1069 | 5x | std::vector<vec2> min_block_bound; |
| 1070 | 5x | std::vector<vec2> max_block_bound; |
| 1071 | 5x | int nx_blocks = ceil((Float)nx/(Float)blocksize); |
| 1072 | 5x | int ny_blocks = ceil((Float)ny/(Float)blocksize); |
| 1073 | ||
| 1074 | 5x | std::vector<std::vector<int> > single_model_blocks; |
| 1075 | ||
| 1076 | //Generate block bounds | |
| 1077 | 237x | for(int i = 0; i < nx; i += blocksize) { |
| 1078 | 40488x | for(int j = 0; j < ny; j += blocksize) { |
| 1079 | 40256x | min_block_bound.push_back(vec2(i,j)); |
| 1080 | 40256x | max_block_bound.push_back(vec2(std::min(i+blocksize,nx),std::min(j+blocksize,ny))); |
| 1081 | } | |
| 1082 | } | |
| 1083 | ||
| 1084 | //Generate a group of index vectors for each model | |
| 1085 | 237x | for(int i = 0; i < nx_blocks; i++) { |
| 1086 | 40488x | for(int j = 0; j < ny_blocks; j++) { |
| 1087 | 40256x | std::vector<std::vector<int> > temp; |
| 1088 | 40256x | blocks.push_back(temp); |
| 1089 | //This is a vector of all the models for that block | |
| 1090 | //blocks[j + ny_blocks * i] | |
| 1091 | 80512x | for(unsigned int k = 0; k < models.size(); k++) { |
| 1092 | 40256x | std::vector<int> model_inds_temp; |
| 1093 | //This is a vector for per-model indices in that specific block | |
| 1094 | //blocks[j + ny_blocks * i][model_num] | |
| 1095 | 40256x | blocks[j + ny_blocks * i].push_back(model_inds_temp); |
| 1096 | } | |
| 1097 | } | |
| 1098 | } | |
| 1099 | ||
| 1100 | //Light, Inner-most index model, then block, then index | |
| 1101 | 5x | std::vector<std::vector<std::vector<int> > > blocks_depth; |
| 1102 | ||
| 1103 | 5x | std::vector<vec2> min_block_bound_depth; |
| 1104 | 5x | std::vector<vec2> max_block_bound_depth; |
| 1105 | 5x | int nx_blocks_depth = ceil((Float)nx_d/(Float)blocksize); |
| 1106 | 5x | int ny_blocks_depth = ceil((Float)ny_d/(Float)blocksize); |
| 1107 | ||
| 1108 | 5x | std::vector<std::vector<int> > single_model_blocks_depth; |
| 1109 | ||
| 1110 | //Generate block bounds | |
| 1111 | 237x | for(int i = 0; i < nx_d; i += blocksize) { |
| 1112 | 40488x | for(int j = 0; j < ny_d; j += blocksize) { |
| 1113 | 40256x | min_block_bound_depth.push_back(vec2(i,j)); |
| 1114 | 40256x | max_block_bound_depth.push_back(vec2(std::min(i+blocksize,nx_d),std::min(j+blocksize,ny_d))); |
| 1115 | } | |
| 1116 | } | |
| 1117 | ||
| 1118 | //Generate a group of index vectors for each model | |
| 1119 | 237x | for(int i = 0; i < nx_blocks_depth; i++) { |
| 1120 | 40488x | for(int j = 0; j < ny_blocks_depth; j++) { |
| 1121 | 40256x | std::vector<std::vector<int> > temp; |
| 1122 | 40256x | blocks_depth.push_back(temp); |
| 1123 | //This is a vector of all the models for that block | |
| 1124 | //blocks[j + ny_blocks * i] | |
| 1125 | 80512x | for(unsigned int k = 0; k < models.size(); k++) { |
| 1126 | 40256x | std::vector<int> model_inds_temp; |
| 1127 | //This is a vector for per-model indices in that specific block | |
| 1128 | //blocks[j + ny_blocks * i][model_num] | |
| 1129 | 40256x | blocks_depth[j + ny_blocks_depth * i].push_back(model_inds_temp); |
| 1130 | } | |
| 1131 | } | |
| 1132 | } | |
| 1133 | ||
| 1134 | 5x | std::vector<std::vector<IShader*> > depthshaders(directional_lights.size()); |
| 1135 | 10x | for(unsigned int j = 0; j < directional_lights.size(); j++) { |
| 1136 | 16x | for(int i = 0; i < number_materials+1; i++ ) { |
| 1137 | 33x | depthshaders[j].push_back(new DepthShader(Model, directional_lights[j].lightProjection, |
| 1138 | 11x | directional_lights[j].lightView, viewport_depth, |
| 1139 | 11x | mat_info[i], |
| 1140 | max_indices, | |
| 1141 | vec_varying_uv, | |
| 1142 | 33x | vec_varying_tri)); |
| 1143 | } | |
| 1144 | } | |
| 1145 | ||
| 1146 | 5x | if(has_shadow_map) { |
| 1147 | 10x | for(unsigned int sb = 0; sb < shadowbuffers.size(); sb++) { |
| 1148 | ||
| 1149 | 10x | for(unsigned int model_num = 0; model_num < models.size(); model_num++ ) { |
| 1150 | 5x | ModelInfo &shp = models[model_num]; |
| 1151 | 1729x | for(int i = 0; i < shp.num_indices; i++) { |
| 1152 | 3448x | int mat_num = shp.materials[i] >= 0 && shp.materials[i] < (int)shaders.size() ? |
| 1153 | 3448x | shp.materials[i] : shaders.size()-1; |
| 1154 | ||
| 1155 | 1724x | ndc_verts_depth[model_num][0][i] = depthshaders[sb][mat_num]->vertex(i,0, shp); |
| 1156 | 1724x | ndc_verts_depth[model_num][1][i] = depthshaders[sb][mat_num]->vertex(i,1, shp); |
| 1157 | 1724x | ndc_verts_depth[model_num][2][i] = depthshaders[sb][mat_num]->vertex(i,2, shp); |
| 1158 | ||
| 1159 | 1724x | ndc_verts[model_num][0][i].w = ndc_verts[model_num][0][i].w < near_clip ? near_clip : ndc_verts[model_num][0][i].w; |
| 1160 | 1724x | ndc_verts[model_num][1][i].w = ndc_verts[model_num][1][i].w < near_clip ? near_clip : ndc_verts[model_num][1][i].w; |
| 1161 | 1724x | ndc_verts[model_num][2][i].w = ndc_verts[model_num][2][i].w < near_clip ? near_clip : ndc_verts[model_num][2][i].w; |
| 1162 | ||
| 1163 | 1724x | ndc_inv_w_depth[model_num][0][i] = 1.0f/ndc_verts_depth[model_num][0][i].w; |
| 1164 | 1724x | ndc_inv_w_depth[model_num][1][i] = 1.0f/ndc_verts_depth[model_num][1][i].w; |
| 1165 | 1724x | ndc_inv_w_depth[model_num][2][i] = 1.0f/ndc_verts_depth[model_num][2][i].w; |
| 1166 | ||
| 1167 | 1724x | vec3 v1 = ndc_verts_depth[model_num][0][i] * ndc_inv_w_depth[model_num][0][i]; |
| 1168 | 1724x | vec3 v2 = ndc_verts_depth[model_num][1][i] * ndc_inv_w_depth[model_num][1][i]; |
| 1169 | 1724x | vec3 v3 = ndc_verts_depth[model_num][2][i] * ndc_inv_w_depth[model_num][2][i]; |
| 1170 | ||
| 1171 | vec3 min_bounds = vec3(fmin(v1.x,fmin(v2.x,v3.x)), | |
| 1172 | fmin(v1.y,fmin(v2.y,v3.y)), | |
| 1173 | 1724x | fmin(v1.z,fmin(v2.z,v3.z))); |
| 1174 | ||
| 1175 | vec3 max_bounds = vec3(fmax(v1.x,fmax(v2.x,v3.x)), | |
| 1176 | fmax(v1.y,fmax(v2.y,v3.y)), | |
| 1177 | 1724x | fmax(v1.z,fmax(v2.z,v3.z))); |
| 1178 | ||
| 1179 | 1724x | int min_x_block = std::fmax(floor(min_bounds.x / (Float)blocksize), 0); |
| 1180 | 1724x | int min_y_block = std::fmax(floor(min_bounds.y / (Float)blocksize), 0); |
| 1181 | 1724x | int max_x_block = std::fmin(ceil(max_bounds.x / (Float)blocksize), nx_blocks_depth); |
| 1182 | 1724x | int max_y_block = std::fmin(ceil(max_bounds.y / (Float)blocksize), ny_blocks_depth); |
| 1183 | 1724x | if(max_x_block >= 0 && max_y_block >= 0 && min_x_block < nx_blocks_depth && min_y_block < ny_blocks_depth) { |
| 1184 | 11595x | for(int j = min_x_block; j < max_x_block; j++) { |
| 1185 | 89199x | for(int k = min_y_block; k < max_y_block; k++) { |
| 1186 | 79328x | blocks_depth[k + ny_blocks_depth * j][model_num].push_back(i); |
| 1187 | } | |
| 1188 | } | |
| 1189 | } | |
| 1190 | } | |
| 1191 | } | |
| 1192 | ||
| 1193 | 5x | rayimage& shadowbuff = shadowbuffers[sb]; |
| 1194 | 5x | std::vector<IShader*>& depth_shader_single = depthshaders[sb]; |
| 1195 | 5x | std::vector<std::map<Float, alpha_info> >& alpha_depth_single = alpha_depths_trans[sb]; |
| 1196 | //Calculate shadow buffer | |
| 1197 | 40256x | auto task = [&depth_shader_single, &blocks_depth, &ndc_verts_depth, &ndc_inv_w_depth, |
| 1198 | &min_block_bound_depth, &max_block_bound_depth, | |
| 1199 | &zbuffer_depth, &shadowbuff, &normalbuffer, &positionbuffer, &uvbuffer, | |
| 1200 | &models, &alpha_depth_single] (unsigned int i) { | |
| 1201 | 80512x | fill_tri_blocks(blocks_depth[i], |
| 1202 | ndc_verts_depth, | |
| 1203 | ndc_inv_w_depth, | |
| 1204 | 40256x | min_block_bound_depth[i], |
| 1205 | 40256x | max_block_bound_depth[i], |
| 1206 | depth_shader_single, | |
| 1207 | zbuffer_depth, | |
| 1208 | shadowbuff, | |
| 1209 | normalbuffer, | |
| 1210 | positionbuffer, | |
| 1211 | uvbuffer, | |
| 1212 | models, true, | |
| 1213 | alpha_depth_single, | |
| 1214 | nullptr); | |
| 1215 | }; | |
| 1216 | #ifdef HAVE_THREADS | |
| 1217 | 5x | RcppThread::ThreadPool pool2(numbercores); |
| 1218 | #else | |
| 1219 | DummyThreadPool pool2; | |
| 1220 | #endif | |
| 1221 | 40261x | for(int i = 0; i < nx_blocks_depth*ny_blocks_depth; i++) { |
| 1222 | 40256x | pool2.push(task, i); |
| 1223 | } | |
| 1224 | 5x | pool2.join(); |
| 1225 | 40261x | for(unsigned int j = 0; j < blocks_depth.size(); j++) { |
| 1226 | 80512x | for(unsigned int model_num = 0; model_num < models.size(); model_num++ ) { |
| 1227 | 40256x | blocks_depth[j][model_num].clear(); |
| 1228 | } | |
| 1229 | } | |
| 1230 | //Calculate transparency buffer | |
| 1231 | 933x | for(int i = 0; i < shadowdims(0); i++) { |
| 1232 | 645024x | for(int j = 0; j < shadowdims(1); j++) { |
| 1233 | 644096x | for(std::map<Float, alpha_info>::reverse_iterator it = alpha_depth_single[j + shadowdims(1)*i].rbegin(); |
| 1234 | 644096x | it != alpha_depth_single[j + shadowdims(1)*i].rend(); ++it) { |
| 1235 | ! | if(it->first <= zbuffer_depth(i,j)) { |
| 1236 | // zbuffer_depth(i,j) = it->first; | |
| 1237 | ! | vec4 temp_col = it->second.color; |
| 1238 | ! | vec4 old_color = transparency_buffers[sb].get_color_a(i,j); |
| 1239 | ! | Float d = (1 - old_color.w) * (1 - temp_col.w) ; |
| 1240 | ! | old_color *= temp_col; |
| 1241 | ! | old_color.w = (1-d); |
| 1242 | ! | transparency_buffers[sb].set_color(i,j,old_color); |
| 1243 | } | |
| 1244 | } | |
| 1245 | } | |
| 1246 | } | |
| 1247 | 5x | std::fill(zbuffer_depth.begin(), zbuffer_depth.end(), std::numeric_limits<Float>::infinity() ) ; |
| 1248 | } | |
| 1249 | } | |
| 1250 | 5x | print_time(verbose, "Calculated depth buffer(s)" ); |
| 1251 | ||
| 1252 | ||
| 1253 | //Calculate Image | |
| 1254 | 5x | std::fill(zbuffer.begin(), zbuffer.end(), std::numeric_limits<Float>::infinity() ) ; |
| 1255 | ||
| 1256 | 10x | for(unsigned int model_num = 0; model_num < models.size(); model_num++ ) { |
| 1257 | 5x | ModelInfo &shp = models[model_num]; |
| 1258 | 1729x | for(int i = 0; i < shp.num_indices; i++) { |
| 1259 | ||
| 1260 | 3448x | int mat_num = shp.materials[i] >= 0 && shp.materials[i] < (int)shaders.size() ? |
| 1261 | 3448x | shp.materials[i] : shaders.size()-1; |
| 1262 | 1724x | ndc_verts[model_num][0][i] = shaders[mat_num]->vertex(i,0, shp); |
| 1263 | 1724x | ndc_verts[model_num][1][i] = shaders[mat_num]->vertex(i,1, shp); |
| 1264 | 1724x | ndc_verts[model_num][2][i] = shaders[mat_num]->vertex(i,2, shp); |
| 1265 | ||
| 1266 | //Depth clamping | |
| 1267 | 1724x | ndc_verts[model_num][0][i].w = ndc_verts[model_num][0][i].w < near_clip ? near_clip : ndc_verts[model_num][0][i].w; |
| 1268 | 1724x | ndc_verts[model_num][1][i].w = ndc_verts[model_num][1][i].w < near_clip ? near_clip : ndc_verts[model_num][1][i].w; |
| 1269 | 1724x | ndc_verts[model_num][2][i].w = ndc_verts[model_num][2][i].w < near_clip ? near_clip : ndc_verts[model_num][2][i].w; |
| 1270 | ||
| 1271 | //Depth clamping | |
| 1272 | 1724x | ndc_verts[model_num][0][i].w = ndc_verts[model_num][0][i].w > far_clip ? far_clip : ndc_verts[model_num][0][i].w; |
| 1273 | 1724x | ndc_verts[model_num][1][i].w = ndc_verts[model_num][1][i].w > far_clip ? far_clip : ndc_verts[model_num][1][i].w; |
| 1274 | 1724x | ndc_verts[model_num][2][i].w = ndc_verts[model_num][2][i].w > far_clip ? far_clip : ndc_verts[model_num][2][i].w; |
| 1275 | ||
| 1276 | 1724x | ndc_inv_w[model_num][0][i] = 1.0f/ndc_verts[model_num][0][i].w; |
| 1277 | 1724x | ndc_inv_w[model_num][1][i] = 1.0f/ndc_verts[model_num][1][i].w; |
| 1278 | 1724x | ndc_inv_w[model_num][2][i] = 1.0f/ndc_verts[model_num][2][i].w; |
| 1279 | ||
| 1280 | 1724x | vec3 v1 = ndc_verts[model_num][0][i] * ndc_inv_w[model_num][0][i]; |
| 1281 | 1724x | vec3 v2 = ndc_verts[model_num][1][i] * ndc_inv_w[model_num][1][i]; |
| 1282 | 1724x | vec3 v3 = ndc_verts[model_num][2][i] * ndc_inv_w[model_num][2][i]; |
| 1283 | ||
| 1284 | vec3 min_bounds = vec3(fmin(v1.x,fmin(v2.x,v3.x)), | |
| 1285 | fmin(v1.y,fmin(v2.y,v3.y)), | |
| 1286 | 1724x | fmin(v1.z,fmin(v2.z,v3.z))); |
| 1287 | ||
| 1288 | vec3 max_bounds = vec3(fmax(v1.x,fmax(v2.x,v3.x)), | |
| 1289 | fmax(v1.y,fmax(v2.y,v3.y)), | |
| 1290 | 1724x | fmax(v1.z,fmax(v2.z,v3.z))); |
| 1291 | ||
| 1292 | ||
| 1293 | 1724x | int min_x_block = std::fmax(floor(min_bounds.x / (Float)blocksize), 0); |
| 1294 | 1724x | int min_y_block = std::fmax(floor(min_bounds.y / (Float)blocksize), 0); |
| 1295 | 1724x | int max_x_block = std::fmin(ceil(max_bounds.x / (Float)blocksize), nx_blocks); |
| 1296 | 1724x | int max_y_block = std::fmin(ceil(max_bounds.y / (Float)blocksize), ny_blocks); |
| 1297 | 1724x | if(max_x_block >= 0 && max_y_block >= 0 && min_x_block < nx_blocks && min_y_block < ny_blocks) { |
| 1298 | 8740x | for(int j = min_x_block; j < max_x_block; j++) { |
| 1299 | 298381x | for(int k = min_y_block; k < max_y_block; k++) { |
| 1300 | 290524x | blocks[k + ny_blocks * j][model_num].push_back(i); |
| 1301 | } | |
| 1302 | } | |
| 1303 | } | |
| 1304 | } | |
| 1305 | } | |
| 1306 | ||
| 1307 | 40256x | auto task = [&shaders, &models, &blocks, &ndc_verts, &ndc_inv_w, &min_block_bound, &max_block_bound, |
| 1308 | &zbuffer, &image, &normalbuffer, &positionbuffer, &uvbuffer, &material_id_buffer, | |
| 1309 | &alpha_depths] (unsigned int i) { | |
| 1310 | 80512x | fill_tri_blocks(blocks[i], |
| 1311 | ndc_verts, | |
| 1312 | ndc_inv_w, | |
| 1313 | 40256x | min_block_bound[i], |
| 1314 | 40256x | max_block_bound[i], |
| 1315 | shaders, | |
| 1316 | zbuffer, | |
| 1317 | image, | |
| 1318 | normalbuffer, | |
| 1319 | positionbuffer, | |
| 1320 | uvbuffer, | |
| 1321 | models, false, | |
| 1322 | alpha_depths, | |
| 1323 | &material_id_buffer); | |
| 1324 | }; | |
| 1325 | ||
| 1326 | #ifdef HAVE_THREADS | |
| 1327 | 5x | RcppThread::ThreadPool pool(numbercores); |
| 1328 | #else | |
| 1329 | DummyThreadPool pool; | |
| 1330 | #endif | |
| 1331 | 40261x | for(int i = 0; i < nx_blocks*ny_blocks; i++) { |
| 1332 | 40256x | pool.push(task, i); |
| 1333 | } | |
| 1334 | 5x | pool.join(); |
| 1335 | 5x | print_time(verbose, "Executed pixel shaders" ); |
| 1336 | ||
| 1337 | ||
| 1338 | //Ambient occlusion | |
| 1339 | 5x | if(calc_ambient) { |
| 1340 | ! | constexpr unsigned int kernelSize=64; |
| 1341 | ! | vec3 kernel[kernelSize]; |
| 1342 | ! | for (unsigned int i = 0; i < kernelSize; ++i) { |
| 1343 | ! | kernel[i] = normalize(vec3( |
| 1344 | ! | spacefillr::sobol_owen_single(i,0,0) * 2.0f - 1.0f, |
| 1345 | ! | spacefillr::sobol_owen_single(i,1,0) * 2.0f - 1.0f, |
| 1346 | ! | spacefillr::sobol_owen_single(i,2,0))); |
| 1347 | ! | Float scale = Float(i) / Float(kernelSize); |
| 1348 | ! | scale = lerp((Float)0.1, (Float)1.0, scale * scale); |
| 1349 | ! | kernel[i] *= scale; |
| 1350 | } | |
| 1351 | ||
| 1352 | ! | constexpr unsigned int noiseSize=16; |
| 1353 | ! | vec3 noise[noiseSize]; |
| 1354 | ! | for (unsigned int i = 0; i < noiseSize; ++i) { |
| 1355 | ! | noise[i] = normalize(vec3( |
| 1356 | ! | spacefillr::sobol_owen_single(i,0,1) * 2.0f - 1.0f, |
| 1357 | ! | spacefillr::sobol_owen_single(i,1,1) * 2.0f - 1.0f, |
| 1358 | ! | spacefillr::sobol_owen_single(i,2,1))); |
| 1359 | } | |
| 1360 | ! | for (int x = 0; x < nx; x++) { |
| 1361 | ! | for (int y = 0; y < ny; y++) { |
| 1362 | ! | if (nxbuffer(x,y) == 0 && nybuffer(x,y) == 0 && nzbuffer(x,y) == 0) { |
| 1363 | ! | continue; |
| 1364 | } | |
| 1365 | ! | vec3 origin(xxbuffer(x,y), yybuffer(x,y), zzbuffer(x,y)); |
| 1366 | ! | vec3 normal(nxbuffer(x,y), nybuffer(x,y), nzbuffer(x,y)); |
| 1367 | ! | normal = normalize(normal); |
| 1368 | ! | normal *= dot(normal, vec3(0,0,1)) < 0 ? -1 : 1; |
| 1369 | ! | int noisex = x % 4; |
| 1370 | ! | int noisey = y % 4; |
| 1371 | ! | vec3 rvec = noise[noisex + 8*noisey]; |
| 1372 | ! | vec3 tangent = normalize(rvec - normal * dot(rvec, normal)); |
| 1373 | ! | vec3 bitangent = cross(normal, tangent); |
| 1374 | ! | glm::mat3 tbn{tangent, bitangent, normal}; |
| 1375 | ! | Float occlusion = 0.0; |
| 1376 | ! | for (unsigned int i = 0; i < kernelSize; ++i) { |
| 1377 | // get sample position: | |
| 1378 | ! | vec3 sample = tbn * kernel[i]; |
| 1379 | ! | sample = sample * (Float)ambient_radius + origin; |
| 1380 | // project sample position: | |
| 1381 | ! | vec4 offset = vec4(sample, 1.0); |
| 1382 | ! | offset = vp * Projection * offset; |
| 1383 | ! | offset /= offset.w; |
| 1384 | ||
| 1385 | ! | if((int)offset.x >= 0 && (int)offset.x < nx && (int)offset.y >= 0 && (int)offset.y < ny) { |
| 1386 | ! | Float sampleDepth = zzbuffer((int)offset.x, (int)offset.y); |
| 1387 | // range check & accumulate: | |
| 1388 | ! | Float rangeCheck= std::fabs(origin.z - sampleDepth) < (Float)ambient_radius ? 1.0 : 0.0; |
| 1389 | ! | occlusion += (sampleDepth >= sample.z ? 1.0 : 0.0) * rangeCheck; |
| 1390 | } | |
| 1391 | } | |
| 1392 | ! | occlusion = 1.0 - (occlusion / (Float)kernelSize); |
| 1393 | ! | abuffer(x,y) = occlusion; |
| 1394 | } | |
| 1395 | } | |
| 1396 | ! | NumericMatrix abuffer_noblur = abuffer; |
| 1397 | ! | for (int x = 0; x < nx; x++) { |
| 1398 | ! | for (int y = 0; y < ny; y++) { |
| 1399 | ! | int uBlurSize = 4; |
| 1400 | ! | Float result = 0.0; |
| 1401 | ! | int counter = 0; |
| 1402 | ! | vec2 hlim = vec2(Float(-uBlurSize) * 0.5); |
| 1403 | ! | for (int i = 0; i < uBlurSize; ++i) { |
| 1404 | ! | for (int j = 0; j < uBlurSize; ++j) { |
| 1405 | ! | vec2 offset = (hlim + vec2((Float)i,(Float)j) + vec2(Float(x), Float(y))); |
| 1406 | ! | if((int)offset.x >= 0 && (int)offset.x < nx && (int)offset.y >= 0 && (int)offset.y < ny) { |
| 1407 | ! | result += abuffer_noblur((int)offset.x,(int)offset.y); |
| 1408 | ! | counter++; |
| 1409 | } | |
| 1410 | } | |
| 1411 | } | |
| 1412 | ! | if(counter > 0) { |
| 1413 | ! | abuffer(x,y) = result / Float(counter); |
| 1414 | } | |
| 1415 | } | |
| 1416 | } | |
| 1417 | ! | print_time(verbose, "Calculated AO" ); |
| 1418 | ||
| 1419 | } | |
| 1420 | ||
| 1421 | ||
| 1422 | 5x | std::vector<vec3> ndc_line_verts_start; |
| 1423 | 5x | std::vector<vec3> ndc_line_verts_end; |
| 1424 | 5x | std::vector<vec3> line_verts_cols; |
| 1425 | ||
| 1426 | //Lines go here (no light) | |
| 1427 | 5x | Mat vpMVP = vp * Projection * View * Model; |
| 1428 | 5x | for(int i = 0; i < line_mat.nrow(); i++) { |
| 1429 | ! | vec4 temp_line_vertex_start = vpMVP * vec4(line_mat(i,0),line_mat(i,1),line_mat(i,2),1.0f); |
| 1430 | ! | temp_line_vertex_start /= temp_line_vertex_start.w; |
| 1431 | ! | vec4 temp_line_vertex_end = vpMVP * vec4(line_mat(i,3),line_mat(i,4),line_mat(i,5),1.0f); |
| 1432 | ! | temp_line_vertex_end /= temp_line_vertex_end.w; |
| 1433 | ! | ndc_line_verts_start.push_back(temp_line_vertex_start); |
| 1434 | ! | ndc_line_verts_end.push_back(temp_line_vertex_end); |
| 1435 | ! | line_verts_cols.push_back(vec3(line_mat(i,6),line_mat(i,7),line_mat(i,8))); |
| 1436 | } | |
| 1437 | ||
| 1438 | 5x | if(line_mat.nrow() > 0) { |
| 1439 | ! | if(aa_lines) { |
| 1440 | ! | aa_line(ndc_line_verts_start, ndc_line_verts_end, line_verts_cols, zbuffer, alpha_depths, alpha_line, line_offset); |
| 1441 | } else { | |
| 1442 | ! | noaa_line(ndc_line_verts_start, ndc_line_verts_end, line_verts_cols, zbuffer, alpha_depths, alpha_line, line_offset); |
| 1443 | } | |
| 1444 | } | |
| 1445 | ||
| 1446 | 933x | for(int i = 0; i < nx; i++) { |
| 1447 | 645024x | for(int j = 0; j < ny; j++) { |
| 1448 | 644096x | for(std::map<Float, alpha_info>::reverse_iterator it = alpha_depths[j + ny*i].rbegin(); |
| 1449 | 644096x | it != alpha_depths[j + ny*i].rend(); ++it) { |
| 1450 | ! | if(it->first <= zbuffer(i,j)) { |
| 1451 | ! | zbuffer(i,j) = it->first; |
| 1452 | ! | vec4 temp_col = it->second.color; |
| 1453 | ! | vec3 old_color = image.get_color(i,j); |
| 1454 | ! | vec3 new_color = vec3(temp_col)*temp_col.w + vec3(old_color)*(1-temp_col.w); |
| 1455 | ! | image.set_color(i,j,new_color); |
| 1456 | ! | normalbuffer.set_color(i,j,it->second.normal); |
| 1457 | ! | positionbuffer.set_color(i,j,it->second.position); |
| 1458 | ! | uvbuffer.set_color(i,j,it->second.uv); |
| 1459 | } | |
| 1460 | } | |
| 1461 | } | |
| 1462 | } | |
| 1463 | ||
| 1464 | //Load/blur environment image | |
| 1465 | 5x | if(has_environment_map) { |
| 1466 | ! | if(background_sharpness != 1.0) { |
| 1467 | ! | int nx_r_resize = (double)nx_r * background_sharpness; |
| 1468 | ! | int ny_r_resize = (double)ny_r * background_sharpness; |
| 1469 | ||
| 1470 | ! | float* reflection_map_data_temp = new float[nx_r_resize * ny_r_resize * nn_r]; |
| 1471 | ||
| 1472 | ! | resize_reflection_map(main_reflection_map.reflection, nx_r, ny_r, |
| 1473 | reflection_map_data_temp, nx_r_resize, ny_r_resize, | |
| 1474 | nn_r); | |
| 1475 | ||
| 1476 | ! | resize_reflection_map(reflection_map_data_temp, nx_r_resize, ny_r_resize, |
| 1477 | main_reflection_map.reflection, nx_r, ny_r, | |
| 1478 | nn_r); | |
| 1479 | ! | delete[] reflection_map_data_temp; |
| 1480 | } | |
| 1481 | ! | Float theta = fov * M_PI/180; |
| 1482 | ! | Float half_height = tan(theta/2); |
| 1483 | ! | Float half_width = Float(nx)/Float(ny) * half_height; |
| 1484 | ! | vec3 origin = eye; |
| 1485 | ! | vec3 w = glm::normalize(eye - center); |
| 1486 | ! | vec3 u = glm::normalize(glm::cross(cam_up, w)); |
| 1487 | ! | vec3 v = glm::cross(w, u); |
| 1488 | ! | vec3 lower_left_corner = origin - half_width * u - half_height * v - w; |
| 1489 | ! | vec3 horizontal = 2.0f * half_width * u; |
| 1490 | ! | vec3 vertical = 2.0f * half_height * v; |
| 1491 | ! | for(int i = 0; i < nx; i++) { |
| 1492 | ! | for(int j = 0; j < ny; j++) { |
| 1493 | ! | if(std::isinf(zbuffer(i,j))) { |
| 1494 | ! | Float s = (Float(i)) / Float(nx); |
| 1495 | ! | Float t = (Float(j)) / Float(ny); |
| 1496 | vec2 uv; | |
| 1497 | ! | vec3 dir = glm::normalize(lower_left_corner + s * horizontal + t * vertical - origin); |
| 1498 | ! | get_sphere_uv(dir,uv); |
| 1499 | ! | uv.x = 1 - uv.x; |
| 1500 | ! | uv.x += 0.25; |
| 1501 | ! | vec3 ref_color = trivalue(uv.x,uv.y,main_reflection_map); |
| 1502 | ! | image.set_color(i,j,ref_color); |
| 1503 | } | |
| 1504 | } | |
| 1505 | } | |
| 1506 | ! | print_time(verbose, "Blurred environment map" ); |
| 1507 | } | |
| 1508 | ||
| 1509 | 5x | if(has_environment_map) { |
| 1510 | ! | stbi_image_free(main_reflection_map.reflection); |
| 1511 | } | |
| 1512 | ||
| 1513 | 10x | for(unsigned int j = 0; j < directional_lights.size(); j++) { |
| 1514 | 16x | for(int i = 0; i < depthshaders[j].size(); i++) { |
| 1515 | 11x | delete depthshaders[j][i]; |
| 1516 | } | |
| 1517 | } | |
| 1518 | 16x | for(unsigned int i = 0; i < shaders.size(); i++) { |
| 1519 | 11x | delete shaders[i]; |
| 1520 | } | |
| 1521 | ||
| 1522 | 11x | for(unsigned int i = 0; i < has_reflection_map.size(); i++) { |
| 1523 | 6x | if(has_reflection_map(i)) { |
| 1524 | ! | delete[] reflection_maps[i].reflection; |
| 1525 | } | |
| 1526 | } | |
| 1527 | ||
| 1528 | 5x | NumericMatrix linear_depth = zbuffer; |
| 1529 | 933x | for(unsigned int i = 0; i < linear_depth.nrow(); i++) { |
| 1530 | 645024x | for(unsigned int j= 0; j < linear_depth.ncol(); j++) { |
| 1531 | 644096x | if(std::isinf(linear_depth(i,j))) { |
| 1532 | 2130x | linear_depth(i,j) = 1; |
| 1533 | } | |
| 1534 | 644096x | linear_depth(i,j) = 2*linear_depth(i,j) - 1; |
| 1535 | } | |
| 1536 | } | |
| 1537 | 5x | linear_depth = 2*near_clip*far_clip/(far_clip + near_clip - linear_depth * (far_clip-near_clip)); |
| 1538 | 5x | print_time(verbose, "Calculated linear depth" ); |
| 1539 | ||
| 1540 | // Build color buffer and outline g-buffer for JFA | |
| 1541 | 5x | std::size_t pix_count = |
| 1542 | 5x | static_cast<std::size_t>(nx) * static_cast<std::size_t>(ny); |
| 1543 | 10x | std::vector<vec3> toon_color_buffer(pix_count); |
| 1544 | 5x | std::vector<OutlineGBufferPixel> outline_gbuffer(pix_count); |
| 1545 | ||
| 1546 | 933x | for (int x = 0; x < nx; ++x) { |
| 1547 | 645024x | for (int y = 0; y < ny; ++y) { |
| 1548 | 644096x | std::size_t idx = |
| 1549 | 644096x | static_cast<std::size_t>(y) * static_cast<std::size_t>(nx) + x; |
| 1550 | ||
| 1551 | 644096x | toon_color_buffer[idx] = image.get_color(x, y); |
| 1552 | 644096x | OutlineGBufferPixel &px = outline_gbuffer[idx]; |
| 1553 | ||
| 1554 | // --- Decide if this pixel has geometry --- | |
| 1555 | 644096x | bool z_is_inf = std::isinf(zbuffer(x, y)); |
| 1556 | ||
| 1557 | 644096x | int raw_mat_id = -1; |
| 1558 | 644096x | if (material_id_buffer.nrow() == nx && material_id_buffer.ncol() == ny) { |
| 1559 | 644096x | raw_mat_id = material_id_buffer(x, y); |
| 1560 | } | |
| 1561 | bool has_material = | |
| 1562 | 644096x | (raw_mat_id >= 0 && raw_mat_id < (int)mat_info.size()); |
| 1563 | ||
| 1564 | 646307x | bool has_normal = (nxbuffer(x, y) != 0.0 || nybuffer(x, y) != 0.0 || |
| 1565 | 2211x | nzbuffer(x, y) != 0.0); |
| 1566 | ||
| 1567 | 644096x | bool has_geom = !z_is_inf && has_material && has_normal; |
| 1568 | ||
| 1569 | 644096x | if (!has_geom) { |
| 1570 | // Background: no geometry | |
| 1571 | 2130x | px.normal_view = vec3(0.0); |
| 1572 | 2130x | px.depth_view = std::numeric_limits<Float>::infinity(); |
| 1573 | 2130x | px.material_id = 0u; |
| 1574 | 2130x | px.outline_width = 0.0; |
| 1575 | 2130x | px.outline_color = vec3(0.0); |
| 1576 | 2130x | px.has_outline = false; |
| 1577 | 2130x | continue; |
| 1578 | } | |
| 1579 | ||
| 1580 | 641966x | int mat_id = raw_mat_id; |
| 1581 | 641966x | if (mat_id < 0 || mat_id >= (int)mat_info.size()) { |
| 1582 | ! | mat_id = 0; |
| 1583 | } | |
| 1584 | ||
| 1585 | 641966x | px.normal_view = vec3(nxbuffer(x, y), nybuffer(x, y), nzbuffer(x, y)); |
| 1586 | 641966x | px.depth_view = linear_depth(x, y); |
| 1587 | 641966x | px.material_id = static_cast<std::uint32_t>(mat_id); |
| 1588 | ||
| 1589 | 641966x | const material_info &m = mat_info[mat_id]; |
| 1590 | ||
| 1591 | 641966x | Float outline_width = m.toon_outline_width; |
| 1592 | 641966x | vec3 outline_color = m.toon_outline_color; |
| 1593 | ||
| 1594 | 641966x | px.outline_width = outline_width; |
| 1595 | 641966x | px.outline_color = outline_color; |
| 1596 | 641966x | px.has_outline = (outline_width > (Float)0.0); |
| 1597 | } | |
| 1598 | } | |
| 1599 | ||
| 1600 | // Check if we even have any toon materials that want outlines | |
| 1601 | 5x | bool any_toon_outline = false; |
| 1602 | 16x | for (std::size_t i = 0; i < mat_info.size(); ++i) { |
| 1603 | 11x | if (mat_info[i].toon_outline_width > (Float)0.0) { |
| 1604 | ! | any_toon_outline = true; |
| 1605 | ! | break; |
| 1606 | } | |
| 1607 | } | |
| 1608 | ||
| 1609 | 5x | if (any_toon_outline) { |
| 1610 | ! | Float camera_fov_y = fov != 0.0 ? glm::radians((Float)fov) : (Float)0.0; |
| 1611 | ! | Float ortho_view_height = 0.0; |
| 1612 | ! | if (fov == 0.0 && ortho_dims.size() > 1) { |
| 1613 | ! | ortho_view_height = static_cast<Float>(ortho_dims(1)); |
| 1614 | } | |
| 1615 | ||
| 1616 | ! | apply_toon_outlines_jfa(toon_color_buffer, outline_gbuffer, nx, ny, |
| 1617 | camera_fov_y, ortho_view_height, zbuffer, linear_depth); | |
| 1618 | ||
| 1619 | // Copy the modified colors back into the rayimage | |
| 1620 | ! | for (int x = 0; x < nx; ++x) { |
| 1621 | ! | for (int y = 0; y < ny; ++y) { |
| 1622 | ! | std::size_t idx = |
| 1623 | ! | static_cast<std::size_t>(y) * static_cast<std::size_t>(nx) + x; |
| 1624 | ! | image.set_color(x, y, toon_color_buffer[idx]); |
| 1625 | } | |
| 1626 | } | |
| 1627 | ||
| 1628 | ! | print_time(verbose, "Applied toon outline JFA pass"); |
| 1629 | } | |
| 1630 | ||
| 1631 | 40x | return(List::create(_["r"] = r, _["g"] = g, _["b"] = b, _["a"] = a, |
| 1632 | 30x | _["amb"] = abuffer, _["depth"] = zbuffer, _["linear_depth"] = linear_depth, |
| 1633 | 30x | _["normalx"] = nxbuffer, _["normaly"] = nybuffer, _["normalz"] = nzbuffer, |
| 1634 | 30x | _["positionx"] = xxbuffer, _["positiony"] = yybuffer, _["positionz"] = zzbuffer, |
| 1635 | 40x | _["uvx"] = uvxbuffer, _["uvy"] = uvybuffer, _["uvz"] = uvzbuffer)); |
| 1636 | } | |
| 1637 | ||
| 1638 | #endif |
| 1 | #ifndef MODELH | |
| 2 | #define MODELH | |
| 3 | ||
| 4 | #include "glm.hpp" | |
| 5 | #include "Rcpp.h" | |
| 6 | #include "rayimage.h" | |
| 7 | #include "defines.h" | |
| 8 | ||
| 9 | class ModelInfo { | |
| 10 | public: | |
| 11 | 5x | ModelInfo(Rcpp::NumericMatrix &verts, Rcpp::NumericMatrix &texcoords, Rcpp::NumericMatrix &normals, |
| 12 | Rcpp::IntegerMatrix inds, Rcpp::IntegerMatrix tex_inds, Rcpp::IntegerMatrix norm_inds, | |
| 13 | Rcpp::LogicalVector has_vertex_tex, Rcpp::LogicalVector has_vertex_normals, | |
| 14 | Rcpp::IntegerVector &materials, | |
| 15 | bool has_normals_, bool has_texcoords_, | |
| 16 | bool tbn, | |
| 17 | 5x | int index_offset = 0) : |
| 18 | 5x | verts(verts), texcoords(texcoords), normals(normals), |
| 19 | 5x | inds(inds), tex_inds(tex_inds), norm_inds(norm_inds), |
| 20 | 5x | materials(materials), has_vertex_tex(has_vertex_tex), has_vertex_normals(has_vertex_normals), |
| 21 | 5x | tbn(tbn), has_normals(has_normals_), has_texcoords(has_texcoords_), index_offset(index_offset) { |
| 22 | 5x | num_indices = inds.nrow(); |
| 23 | } | |
| 24 | ||
| 25 | 18252x | vec3 vertex(int iface, int nthvert) { |
| 26 | 18252x | return(vec3(verts(inds(iface,nthvert), 0), |
| 27 | 18252x | verts(inds(iface,nthvert), 1), |
| 28 | 54756x | verts(inds(iface,nthvert), 2))); |
| 29 | } | |
| 30 | 4488x | vec3 normal(int iface, int nthvert) { |
| 31 | 4488x | return(vec3(normals(norm_inds(iface,nthvert), 0), |
| 32 | 4488x | normals(norm_inds(iface,nthvert), 1), |
| 33 | 13464x | normals(norm_inds(iface,nthvert), 2))); |
| 34 | } | |
| 35 | 10344x | vec3 tex(int iface, int nthvert) { |
| 36 | // Trust provided tex indices; fall back only if index invalid | |
| 37 | 10344x | if(tex_inds(iface, nthvert) != -1) { |
| 38 | 10152x | return(vec3(texcoords(tex_inds(iface,nthvert), 0), |
| 39 | 20304x | texcoords(tex_inds(iface,nthvert), 1), |
| 40 | 20304x | 0.0f)); |
| 41 | } | |
| 42 | 192x | return(vec3(1.0)); |
| 43 | } | |
| 44 | 5172x | bool model_vertex_normals(int iface) { |
| 45 | 5172x | if(has_vertex_normals.size() == num_indices) { |
| 46 | 5172x | return(has_vertex_normals(iface)); |
| 47 | } | |
| 48 | ! | int global_face = index_offset + iface; |
| 49 | ! | if(global_face >= 0 && global_face < has_vertex_normals.size()) { |
| 50 | ! | return(has_vertex_normals(global_face)); |
| 51 | } | |
| 52 | ! | return(has_normals); |
| 53 | } | |
| 54 | bool model_vertex_texcoords(int iface) { | |
| 55 | if(has_vertex_tex.size() == num_indices) { | |
| 56 | return(has_vertex_tex(iface)); | |
| 57 | } | |
| 58 | int global_face = index_offset + iface; | |
| 59 | if(global_face >= 0 && global_face < has_vertex_tex.size()) { | |
| 60 | return(has_vertex_tex(global_face)); | |
| 61 | } | |
| 62 | return(has_texcoords); | |
| 63 | } | |
| 64 | ||
| 65 | Rcpp::NumericMatrix verts; | |
| 66 | Rcpp::NumericMatrix texcoords; | |
| 67 | Rcpp::NumericMatrix normals; | |
| 68 | ||
| 69 | Rcpp::IntegerMatrix inds; | |
| 70 | Rcpp::IntegerMatrix tex_inds; | |
| 71 | Rcpp::IntegerMatrix norm_inds; | |
| 72 | Rcpp::IntegerVector materials; | |
| 73 | ||
| 74 | Rcpp::LogicalVector has_vertex_tex; | |
| 75 | Rcpp::LogicalVector has_vertex_normals; | |
| 76 | ||
| 77 | bool tbn; | |
| 78 | bool has_normals; | |
| 79 | bool has_texcoords; | |
| 80 | int num_indices; | |
| 81 | int index_offset; | |
| 82 | }; | |
| 83 | ||
| 84 | ||
| 85 | ||
| 86 | ||
| 87 | #endif |
| 1 | #include "../matrix.hpp" | |
| 2 | ||
| 3 | namespace glm | |
| 4 | { | |
| 5 | // -- Constructors -- | |
| 6 | ||
| 7 | # if GLM_CONFIG_DEFAULTED_FUNCTIONS == GLM_DISABLE | |
| 8 | template<typename T, qualifier Q> | |
| 9 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<3, 3, T, Q>::mat() | |
| 10 | # if GLM_CONFIG_CTOR_INIT == GLM_CTOR_INITIALIZER_LIST | |
| 11 | : value{col_type(1, 0, 0), col_type(0, 1, 0), col_type(0, 0, 1)} | |
| 12 | # endif | |
| 13 | { | |
| 14 | # if GLM_CONFIG_CTOR_INIT == GLM_CTOR_INITIALISATION | |
| 15 | this->value[0] = col_type(1, 0, 0); | |
| 16 | this->value[1] = col_type(0, 1, 0); | |
| 17 | this->value[2] = col_type(0, 0, 1); | |
| 18 | # endif | |
| 19 | } | |
| 20 | # endif | |
| 21 | ||
| 22 | template<typename T, qualifier Q> | |
| 23 | template<qualifier P> | |
| 24 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<3, 3, T, Q>::mat(mat<3, 3, T, P> const& m) | |
| 25 | # if GLM_HAS_INITIALIZER_LISTS | |
| 26 | : value{col_type(m[0]), col_type(m[1]), col_type(m[2])} | |
| 27 | # endif | |
| 28 | { | |
| 29 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 30 | this->value[0] = col_type(m[0]); | |
| 31 | this->value[1] = col_type(m[1]); | |
| 32 | this->value[2] = col_type(m[2]); | |
| 33 | # endif | |
| 34 | } | |
| 35 | ||
| 36 | template<typename T, qualifier Q> | |
| 37 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<3, 3, T, Q>::mat(T s) | |
| 38 | # if GLM_HAS_INITIALIZER_LISTS | |
| 39 | : value{col_type(s, 0, 0), col_type(0, s, 0), col_type(0, 0, s)} | |
| 40 | # endif | |
| 41 | { | |
| 42 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 43 | this->value[0] = col_type(s, 0, 0); | |
| 44 | this->value[1] = col_type(0, s, 0); | |
| 45 | this->value[2] = col_type(0, 0, s); | |
| 46 | # endif | |
| 47 | } | |
| 48 | ||
| 49 | template<typename T, qualifier Q> | |
| 50 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<3, 3, T, Q>::mat | |
| 51 | ( | |
| 52 | T x0, T y0, T z0, | |
| 53 | T x1, T y1, T z1, | |
| 54 | T x2, T y2, T z2 | |
| 55 | ) | |
| 56 | # if GLM_HAS_INITIALIZER_LISTS | |
| 57 | : value{col_type(x0, y0, z0), col_type(x1, y1, z1), col_type(x2, y2, z2)} | |
| 58 | # endif | |
| 59 | { | |
| 60 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 61 | this->value[0] = col_type(x0, y0, z0); | |
| 62 | this->value[1] = col_type(x1, y1, z1); | |
| 63 | this->value[2] = col_type(x2, y2, z2); | |
| 64 | # endif | |
| 65 | } | |
| 66 | ||
| 67 | template<typename T, qualifier Q> | |
| 68 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<3, 3, T, Q>::mat(col_type const& v0, col_type const& v1, col_type const& v2) | |
| 69 | # if GLM_HAS_INITIALIZER_LISTS | |
| 70 | : value{col_type(v0), col_type(v1), col_type(v2)} | |
| 71 | # endif | |
| 72 | { | |
| 73 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 74 | this->value[0] = col_type(v0); | |
| 75 | this->value[1] = col_type(v1); | |
| 76 | this->value[2] = col_type(v2); | |
| 77 | # endif | |
| 78 | } | |
| 79 | ||
| 80 | // -- Conversion constructors -- | |
| 81 | ||
| 82 | template<typename T, qualifier Q> | |
| 83 | template< | |
| 84 | typename X1, typename Y1, typename Z1, | |
| 85 | typename X2, typename Y2, typename Z2, | |
| 86 | typename X3, typename Y3, typename Z3> | |
| 87 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<3, 3, T, Q>::mat | |
| 88 | ( | |
| 89 | X1 x1, Y1 y1, Z1 z1, | |
| 90 | X2 x2, Y2 y2, Z2 z2, | |
| 91 | X3 x3, Y3 y3, Z3 z3 | |
| 92 | ) | |
| 93 | # if GLM_HAS_INITIALIZER_LISTS | |
| 94 | : value{col_type(x1, y1, z1), col_type(x2, y2, z2), col_type(x3, y3, z3)} | |
| 95 | # endif | |
| 96 | { | |
| 97 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 98 | this->value[0] = col_type(x1, y1, z1); | |
| 99 | this->value[1] = col_type(x2, y2, z2); | |
| 100 | this->value[2] = col_type(x3, y3, z3); | |
| 101 | # endif | |
| 102 | } | |
| 103 | ||
| 104 | template<typename T, qualifier Q> | |
| 105 | template<typename V1, typename V2, typename V3> | |
| 106 | ! | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<3, 3, T, Q>::mat(vec<3, V1, Q> const& v1, vec<3, V2, Q> const& v2, vec<3, V3, Q> const& v3) |
| 107 | # if GLM_HAS_INITIALIZER_LISTS | |
| 108 | ! | : value{col_type(v1), col_type(v2), col_type(v3)} |
| 109 | # endif | |
| 110 | { | |
| 111 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 112 | this->value[0] = col_type(v1); | |
| 113 | this->value[1] = col_type(v2); | |
| 114 | this->value[2] = col_type(v3); | |
| 115 | # endif | |
| 116 | } | |
| 117 | ||
| 118 | // -- Matrix conversions -- | |
| 119 | ||
| 120 | template<typename T, qualifier Q> | |
| 121 | template<typename U, qualifier P> | |
| 122 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<3, 3, T, Q>::mat(mat<3, 3, U, P> const& m) | |
| 123 | # if GLM_HAS_INITIALIZER_LISTS | |
| 124 | : value{col_type(m[0]), col_type(m[1]), col_type(m[2])} | |
| 125 | # endif | |
| 126 | { | |
| 127 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 128 | this->value[0] = col_type(m[0]); | |
| 129 | this->value[1] = col_type(m[1]); | |
| 130 | this->value[2] = col_type(m[2]); | |
| 131 | # endif | |
| 132 | } | |
| 133 | ||
| 134 | template<typename T, qualifier Q> | |
| 135 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<3, 3, T, Q>::mat(mat<2, 2, T, Q> const& m) | |
| 136 | # if GLM_HAS_INITIALIZER_LISTS | |
| 137 | : value{col_type(m[0], 0), col_type(m[1], 0), col_type(0, 0, 1)} | |
| 138 | # endif | |
| 139 | { | |
| 140 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 141 | this->value[0] = col_type(m[0], 0); | |
| 142 | this->value[1] = col_type(m[1], 0); | |
| 143 | this->value[2] = col_type(0, 0, 1); | |
| 144 | # endif | |
| 145 | } | |
| 146 | ||
| 147 | template<typename T, qualifier Q> | |
| 148 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<3, 3, T, Q>::mat(mat<4, 4, T, Q> const& m) | |
| 149 | # if GLM_HAS_INITIALIZER_LISTS | |
| 150 | : value{col_type(m[0]), col_type(m[1]), col_type(m[2])} | |
| 151 | # endif | |
| 152 | { | |
| 153 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 154 | this->value[0] = col_type(m[0]); | |
| 155 | this->value[1] = col_type(m[1]); | |
| 156 | this->value[2] = col_type(m[2]); | |
| 157 | # endif | |
| 158 | } | |
| 159 | ||
| 160 | template<typename T, qualifier Q> | |
| 161 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<3, 3, T, Q>::mat(mat<2, 3, T, Q> const& m) | |
| 162 | # if GLM_HAS_INITIALIZER_LISTS | |
| 163 | : value{col_type(m[0]), col_type(m[1]), col_type(0, 0, 1)} | |
| 164 | # endif | |
| 165 | { | |
| 166 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 167 | this->value[0] = col_type(m[0]); | |
| 168 | this->value[1] = col_type(m[1]); | |
| 169 | this->value[2] = col_type(0, 0, 1); | |
| 170 | # endif | |
| 171 | } | |
| 172 | ||
| 173 | template<typename T, qualifier Q> | |
| 174 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<3, 3, T, Q>::mat(mat<3, 2, T, Q> const& m) | |
| 175 | # if GLM_HAS_INITIALIZER_LISTS | |
| 176 | : value{col_type(m[0], 0), col_type(m[1], 0), col_type(m[2], 1)} | |
| 177 | # endif | |
| 178 | { | |
| 179 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 180 | this->value[0] = col_type(m[0], 0); | |
| 181 | this->value[1] = col_type(m[1], 0); | |
| 182 | this->value[2] = col_type(m[2], 1); | |
| 183 | # endif | |
| 184 | } | |
| 185 | ||
| 186 | template<typename T, qualifier Q> | |
| 187 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<3, 3, T, Q>::mat(mat<2, 4, T, Q> const& m) | |
| 188 | # if GLM_HAS_INITIALIZER_LISTS | |
| 189 | : value{col_type(m[0]), col_type(m[1]), col_type(0, 0, 1)} | |
| 190 | # endif | |
| 191 | { | |
| 192 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 193 | this->value[0] = col_type(m[0]); | |
| 194 | this->value[1] = col_type(m[1]); | |
| 195 | this->value[2] = col_type(0, 0, 1); | |
| 196 | # endif | |
| 197 | } | |
| 198 | ||
| 199 | template<typename T, qualifier Q> | |
| 200 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<3, 3, T, Q>::mat(mat<4, 2, T, Q> const& m) | |
| 201 | # if GLM_HAS_INITIALIZER_LISTS | |
| 202 | : value{col_type(m[0], 0), col_type(m[1], 0), col_type(m[2], 1)} | |
| 203 | # endif | |
| 204 | { | |
| 205 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 206 | this->value[0] = col_type(m[0], 0); | |
| 207 | this->value[1] = col_type(m[1], 0); | |
| 208 | this->value[2] = col_type(m[2], 1); | |
| 209 | # endif | |
| 210 | } | |
| 211 | ||
| 212 | template<typename T, qualifier Q> | |
| 213 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<3, 3, T, Q>::mat(mat<3, 4, T, Q> const& m) | |
| 214 | # if GLM_HAS_INITIALIZER_LISTS | |
| 215 | : value{col_type(m[0]), col_type(m[1]), col_type(m[2])} | |
| 216 | # endif | |
| 217 | { | |
| 218 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 219 | this->value[0] = col_type(m[0]); | |
| 220 | this->value[1] = col_type(m[1]); | |
| 221 | this->value[2] = col_type(m[2]); | |
| 222 | # endif | |
| 223 | } | |
| 224 | ||
| 225 | template<typename T, qualifier Q> | |
| 226 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR mat<3, 3, T, Q>::mat(mat<4, 3, T, Q> const& m) | |
| 227 | # if GLM_HAS_INITIALIZER_LISTS | |
| 228 | : value{col_type(m[0]), col_type(m[1]), col_type(m[2])} | |
| 229 | # endif | |
| 230 | { | |
| 231 | # if !GLM_HAS_INITIALIZER_LISTS | |
| 232 | this->value[0] = col_type(m[0]); | |
| 233 | this->value[1] = col_type(m[1]); | |
| 234 | this->value[2] = col_type(m[2]); | |
| 235 | # endif | |
| 236 | } | |
| 237 | ||
| 238 | // -- Accesses -- | |
| 239 | ||
| 240 | template<typename T, qualifier Q> | |
| 241 | ! | GLM_FUNC_QUALIFIER typename mat<3, 3, T, Q>::col_type & mat<3, 3, T, Q>::operator[](typename mat<3, 3, T, Q>::length_type i) |
| 242 | { | |
| 243 | assert(i < this->length()); | |
| 244 | ! | return this->value[i]; |
| 245 | } | |
| 246 | ||
| 247 | template<typename T, qualifier Q> | |
| 248 | ! | GLM_FUNC_QUALIFIER GLM_CONSTEXPR typename mat<3, 3, T, Q>::col_type const& mat<3, 3, T, Q>::operator[](typename mat<3, 3, T, Q>::length_type i) const |
| 249 | { | |
| 250 | assert(i < this->length()); | |
| 251 | ! | return this->value[i]; |
| 252 | } | |
| 253 | ||
| 254 | // -- Unary updatable operators -- | |
| 255 | ||
| 256 | template<typename T, qualifier Q> | |
| 257 | template<typename U> | |
| 258 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> & mat<3, 3, T, Q>::operator=(mat<3, 3, U, Q> const& m) | |
| 259 | { | |
| 260 | this->value[0] = m[0]; | |
| 261 | this->value[1] = m[1]; | |
| 262 | this->value[2] = m[2]; | |
| 263 | return *this; | |
| 264 | } | |
| 265 | ||
| 266 | template<typename T, qualifier Q> | |
| 267 | template<typename U> | |
| 268 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> & mat<3, 3, T, Q>::operator+=(U s) | |
| 269 | { | |
| 270 | this->value[0] += s; | |
| 271 | this->value[1] += s; | |
| 272 | this->value[2] += s; | |
| 273 | return *this; | |
| 274 | } | |
| 275 | ||
| 276 | template<typename T, qualifier Q> | |
| 277 | template<typename U> | |
| 278 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> & mat<3, 3, T, Q>::operator+=(mat<3, 3, U, Q> const& m) | |
| 279 | { | |
| 280 | this->value[0] += m[0]; | |
| 281 | this->value[1] += m[1]; | |
| 282 | this->value[2] += m[2]; | |
| 283 | return *this; | |
| 284 | } | |
| 285 | ||
| 286 | template<typename T, qualifier Q> | |
| 287 | template<typename U> | |
| 288 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> & mat<3, 3, T, Q>::operator-=(U s) | |
| 289 | { | |
| 290 | this->value[0] -= s; | |
| 291 | this->value[1] -= s; | |
| 292 | this->value[2] -= s; | |
| 293 | return *this; | |
| 294 | } | |
| 295 | ||
| 296 | template<typename T, qualifier Q> | |
| 297 | template<typename U> | |
| 298 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> & mat<3, 3, T, Q>::operator-=(mat<3, 3, U, Q> const& m) | |
| 299 | { | |
| 300 | this->value[0] -= m[0]; | |
| 301 | this->value[1] -= m[1]; | |
| 302 | this->value[2] -= m[2]; | |
| 303 | return *this; | |
| 304 | } | |
| 305 | ||
| 306 | template<typename T, qualifier Q> | |
| 307 | template<typename U> | |
| 308 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> & mat<3, 3, T, Q>::operator*=(U s) | |
| 309 | { | |
| 310 | this->value[0] *= s; | |
| 311 | this->value[1] *= s; | |
| 312 | this->value[2] *= s; | |
| 313 | return *this; | |
| 314 | } | |
| 315 | ||
| 316 | template<typename T, qualifier Q> | |
| 317 | template<typename U> | |
| 318 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> & mat<3, 3, T, Q>::operator*=(mat<3, 3, U, Q> const& m) | |
| 319 | { | |
| 320 | return (*this = *this * m); | |
| 321 | } | |
| 322 | ||
| 323 | template<typename T, qualifier Q> | |
| 324 | template<typename U> | |
| 325 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> & mat<3, 3, T, Q>::operator/=(U s) | |
| 326 | { | |
| 327 | this->value[0] /= s; | |
| 328 | this->value[1] /= s; | |
| 329 | this->value[2] /= s; | |
| 330 | return *this; | |
| 331 | } | |
| 332 | ||
| 333 | template<typename T, qualifier Q> | |
| 334 | template<typename U> | |
| 335 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> & mat<3, 3, T, Q>::operator/=(mat<3, 3, U, Q> const& m) | |
| 336 | { | |
| 337 | return *this *= inverse(m); | |
| 338 | } | |
| 339 | ||
| 340 | // -- Increment and decrement operators -- | |
| 341 | ||
| 342 | template<typename T, qualifier Q> | |
| 343 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> & mat<3, 3, T, Q>::operator++() | |
| 344 | { | |
| 345 | ++this->value[0]; | |
| 346 | ++this->value[1]; | |
| 347 | ++this->value[2]; | |
| 348 | return *this; | |
| 349 | } | |
| 350 | ||
| 351 | template<typename T, qualifier Q> | |
| 352 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> & mat<3, 3, T, Q>::operator--() | |
| 353 | { | |
| 354 | --this->value[0]; | |
| 355 | --this->value[1]; | |
| 356 | --this->value[2]; | |
| 357 | return *this; | |
| 358 | } | |
| 359 | ||
| 360 | template<typename T, qualifier Q> | |
| 361 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> mat<3, 3, T, Q>::operator++(int) | |
| 362 | { | |
| 363 | mat<3, 3, T, Q> Result(*this); | |
| 364 | ++*this; | |
| 365 | return Result; | |
| 366 | } | |
| 367 | ||
| 368 | template<typename T, qualifier Q> | |
| 369 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> mat<3, 3, T, Q>::operator--(int) | |
| 370 | { | |
| 371 | mat<3, 3, T, Q> Result(*this); | |
| 372 | --*this; | |
| 373 | return Result; | |
| 374 | } | |
| 375 | ||
| 376 | // -- Unary arithmetic operators -- | |
| 377 | ||
| 378 | template<typename T, qualifier Q> | |
| 379 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> operator+(mat<3, 3, T, Q> const& m) | |
| 380 | { | |
| 381 | return m; | |
| 382 | } | |
| 383 | ||
| 384 | template<typename T, qualifier Q> | |
| 385 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> operator-(mat<3, 3, T, Q> const& m) | |
| 386 | { | |
| 387 | return mat<3, 3, T, Q>( | |
| 388 | -m[0], | |
| 389 | -m[1], | |
| 390 | -m[2]); | |
| 391 | } | |
| 392 | ||
| 393 | // -- Binary arithmetic operators -- | |
| 394 | ||
| 395 | template<typename T, qualifier Q> | |
| 396 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> operator+(mat<3, 3, T, Q> const& m, T scalar) | |
| 397 | { | |
| 398 | return mat<3, 3, T, Q>( | |
| 399 | m[0] + scalar, | |
| 400 | m[1] + scalar, | |
| 401 | m[2] + scalar); | |
| 402 | } | |
| 403 | ||
| 404 | template<typename T, qualifier Q> | |
| 405 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> operator+(T scalar, mat<3, 3, T, Q> const& m) | |
| 406 | { | |
| 407 | return mat<3, 3, T, Q>( | |
| 408 | m[0] + scalar, | |
| 409 | m[1] + scalar, | |
| 410 | m[2] + scalar); | |
| 411 | } | |
| 412 | ||
| 413 | template<typename T, qualifier Q> | |
| 414 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> operator+(mat<3, 3, T, Q> const& m1, mat<3, 3, T, Q> const& m2) | |
| 415 | { | |
| 416 | return mat<3, 3, T, Q>( | |
| 417 | m1[0] + m2[0], | |
| 418 | m1[1] + m2[1], | |
| 419 | m1[2] + m2[2]); | |
| 420 | } | |
| 421 | ||
| 422 | template<typename T, qualifier Q> | |
| 423 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> operator-(mat<3, 3, T, Q> const& m, T scalar) | |
| 424 | { | |
| 425 | return mat<3, 3, T, Q>( | |
| 426 | m[0] - scalar, | |
| 427 | m[1] - scalar, | |
| 428 | m[2] - scalar); | |
| 429 | } | |
| 430 | ||
| 431 | template<typename T, qualifier Q> | |
| 432 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> operator-(T scalar, mat<3, 3, T, Q> const& m) | |
| 433 | { | |
| 434 | return mat<3, 3, T, Q>( | |
| 435 | scalar - m[0], | |
| 436 | scalar - m[1], | |
| 437 | scalar - m[2]); | |
| 438 | } | |
| 439 | ||
| 440 | template<typename T, qualifier Q> | |
| 441 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> operator-(mat<3, 3, T, Q> const& m1, mat<3, 3, T, Q> const& m2) | |
| 442 | { | |
| 443 | return mat<3, 3, T, Q>( | |
| 444 | m1[0] - m2[0], | |
| 445 | m1[1] - m2[1], | |
| 446 | m1[2] - m2[2]); | |
| 447 | } | |
| 448 | ||
| 449 | template<typename T, qualifier Q> | |
| 450 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> operator*(mat<3, 3, T, Q> const& m, T scalar) | |
| 451 | { | |
| 452 | return mat<3, 3, T, Q>( | |
| 453 | m[0] * scalar, | |
| 454 | m[1] * scalar, | |
| 455 | m[2] * scalar); | |
| 456 | } | |
| 457 | ||
| 458 | template<typename T, qualifier Q> | |
| 459 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> operator*(T scalar, mat<3, 3, T, Q> const& m) | |
| 460 | { | |
| 461 | return mat<3, 3, T, Q>( | |
| 462 | m[0] * scalar, | |
| 463 | m[1] * scalar, | |
| 464 | m[2] * scalar); | |
| 465 | } | |
| 466 | ||
| 467 | template<typename T, qualifier Q> | |
| 468 | ! | GLM_FUNC_QUALIFIER typename mat<3, 3, T, Q>::col_type operator*(mat<3, 3, T, Q> const& m, typename mat<3, 3, T, Q>::row_type const& v) |
| 469 | { | |
| 470 | ! | return typename mat<3, 3, T, Q>::col_type( |
| 471 | ! | m[0][0] * v.x + m[1][0] * v.y + m[2][0] * v.z, |
| 472 | ! | m[0][1] * v.x + m[1][1] * v.y + m[2][1] * v.z, |
| 473 | ! | m[0][2] * v.x + m[1][2] * v.y + m[2][2] * v.z); |
| 474 | } | |
| 475 | ||
| 476 | template<typename T, qualifier Q> | |
| 477 | GLM_FUNC_QUALIFIER typename mat<3, 3, T, Q>::row_type operator*(typename mat<3, 3, T, Q>::col_type const& v, mat<3, 3, T, Q> const& m) | |
| 478 | { | |
| 479 | return typename mat<3, 3, T, Q>::row_type( | |
| 480 | m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z, | |
| 481 | m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z, | |
| 482 | m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z); | |
| 483 | } | |
| 484 | ||
| 485 | template<typename T, qualifier Q> | |
| 486 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> operator*(mat<3, 3, T, Q> const& m1, mat<3, 3, T, Q> const& m2) | |
| 487 | { | |
| 488 | T const SrcA00 = m1[0][0]; | |
| 489 | T const SrcA01 = m1[0][1]; | |
| 490 | T const SrcA02 = m1[0][2]; | |
| 491 | T const SrcA10 = m1[1][0]; | |
| 492 | T const SrcA11 = m1[1][1]; | |
| 493 | T const SrcA12 = m1[1][2]; | |
| 494 | T const SrcA20 = m1[2][0]; | |
| 495 | T const SrcA21 = m1[2][1]; | |
| 496 | T const SrcA22 = m1[2][2]; | |
| 497 | ||
| 498 | T const SrcB00 = m2[0][0]; | |
| 499 | T const SrcB01 = m2[0][1]; | |
| 500 | T const SrcB02 = m2[0][2]; | |
| 501 | T const SrcB10 = m2[1][0]; | |
| 502 | T const SrcB11 = m2[1][1]; | |
| 503 | T const SrcB12 = m2[1][2]; | |
| 504 | T const SrcB20 = m2[2][0]; | |
| 505 | T const SrcB21 = m2[2][1]; | |
| 506 | T const SrcB22 = m2[2][2]; | |
| 507 | ||
| 508 | mat<3, 3, T, Q> Result; | |
| 509 | Result[0][0] = SrcA00 * SrcB00 + SrcA10 * SrcB01 + SrcA20 * SrcB02; | |
| 510 | Result[0][1] = SrcA01 * SrcB00 + SrcA11 * SrcB01 + SrcA21 * SrcB02; | |
| 511 | Result[0][2] = SrcA02 * SrcB00 + SrcA12 * SrcB01 + SrcA22 * SrcB02; | |
| 512 | Result[1][0] = SrcA00 * SrcB10 + SrcA10 * SrcB11 + SrcA20 * SrcB12; | |
| 513 | Result[1][1] = SrcA01 * SrcB10 + SrcA11 * SrcB11 + SrcA21 * SrcB12; | |
| 514 | Result[1][2] = SrcA02 * SrcB10 + SrcA12 * SrcB11 + SrcA22 * SrcB12; | |
| 515 | Result[2][0] = SrcA00 * SrcB20 + SrcA10 * SrcB21 + SrcA20 * SrcB22; | |
| 516 | Result[2][1] = SrcA01 * SrcB20 + SrcA11 * SrcB21 + SrcA21 * SrcB22; | |
| 517 | Result[2][2] = SrcA02 * SrcB20 + SrcA12 * SrcB21 + SrcA22 * SrcB22; | |
| 518 | return Result; | |
| 519 | } | |
| 520 | ||
| 521 | template<typename T, qualifier Q> | |
| 522 | GLM_FUNC_QUALIFIER mat<2, 3, T, Q> operator*(mat<3, 3, T, Q> const& m1, mat<2, 3, T, Q> const& m2) | |
| 523 | { | |
| 524 | return mat<2, 3, T, Q>( | |
| 525 | m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2], | |
| 526 | m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2], | |
| 527 | m1[0][2] * m2[0][0] + m1[1][2] * m2[0][1] + m1[2][2] * m2[0][2], | |
| 528 | m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2], | |
| 529 | m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2], | |
| 530 | m1[0][2] * m2[1][0] + m1[1][2] * m2[1][1] + m1[2][2] * m2[1][2]); | |
| 531 | } | |
| 532 | ||
| 533 | template<typename T, qualifier Q> | |
| 534 | GLM_FUNC_QUALIFIER mat<4, 3, T, Q> operator*(mat<3, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2) | |
| 535 | { | |
| 536 | return mat<4, 3, T, Q>( | |
| 537 | m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2], | |
| 538 | m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2], | |
| 539 | m1[0][2] * m2[0][0] + m1[1][2] * m2[0][1] + m1[2][2] * m2[0][2], | |
| 540 | m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2], | |
| 541 | m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2], | |
| 542 | m1[0][2] * m2[1][0] + m1[1][2] * m2[1][1] + m1[2][2] * m2[1][2], | |
| 543 | m1[0][0] * m2[2][0] + m1[1][0] * m2[2][1] + m1[2][0] * m2[2][2], | |
| 544 | m1[0][1] * m2[2][0] + m1[1][1] * m2[2][1] + m1[2][1] * m2[2][2], | |
| 545 | m1[0][2] * m2[2][0] + m1[1][2] * m2[2][1] + m1[2][2] * m2[2][2], | |
| 546 | m1[0][0] * m2[3][0] + m1[1][0] * m2[3][1] + m1[2][0] * m2[3][2], | |
| 547 | m1[0][1] * m2[3][0] + m1[1][1] * m2[3][1] + m1[2][1] * m2[3][2], | |
| 548 | m1[0][2] * m2[3][0] + m1[1][2] * m2[3][1] + m1[2][2] * m2[3][2]); | |
| 549 | } | |
| 550 | ||
| 551 | template<typename T, qualifier Q> | |
| 552 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> operator/(mat<3, 3, T, Q> const& m, T scalar) | |
| 553 | { | |
| 554 | return mat<3, 3, T, Q>( | |
| 555 | m[0] / scalar, | |
| 556 | m[1] / scalar, | |
| 557 | m[2] / scalar); | |
| 558 | } | |
| 559 | ||
| 560 | template<typename T, qualifier Q> | |
| 561 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> operator/(T scalar, mat<3, 3, T, Q> const& m) | |
| 562 | { | |
| 563 | return mat<3, 3, T, Q>( | |
| 564 | scalar / m[0], | |
| 565 | scalar / m[1], | |
| 566 | scalar / m[2]); | |
| 567 | } | |
| 568 | ||
| 569 | template<typename T, qualifier Q> | |
| 570 | GLM_FUNC_QUALIFIER typename mat<3, 3, T, Q>::col_type operator/(mat<3, 3, T, Q> const& m, typename mat<3, 3, T, Q>::row_type const& v) | |
| 571 | { | |
| 572 | return inverse(m) * v; | |
| 573 | } | |
| 574 | ||
| 575 | template<typename T, qualifier Q> | |
| 576 | GLM_FUNC_QUALIFIER typename mat<3, 3, T, Q>::row_type operator/(typename mat<3, 3, T, Q>::col_type const& v, mat<3, 3, T, Q> const& m) | |
| 577 | { | |
| 578 | return v * inverse(m); | |
| 579 | } | |
| 580 | ||
| 581 | template<typename T, qualifier Q> | |
| 582 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> operator/(mat<3, 3, T, Q> const& m1, mat<3, 3, T, Q> const& m2) | |
| 583 | { | |
| 584 | mat<3, 3, T, Q> m1_copy(m1); | |
| 585 | return m1_copy /= m2; | |
| 586 | } | |
| 587 | ||
| 588 | // -- Boolean operators -- | |
| 589 | ||
| 590 | template<typename T, qualifier Q> | |
| 591 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR bool operator==(mat<3, 3, T, Q> const& m1, mat<3, 3, T, Q> const& m2) | |
| 592 | { | |
| 593 | return (m1[0] == m2[0]) && (m1[1] == m2[1]) && (m1[2] == m2[2]); | |
| 594 | } | |
| 595 | ||
| 596 | template<typename T, qualifier Q> | |
| 597 | GLM_FUNC_QUALIFIER bool operator!=(mat<3, 3, T, Q> const& m1, mat<3, 3, T, Q> const& m2) | |
| 598 | { | |
| 599 | return (m1[0] != m2[0]) || (m1[1] != m2[1]) || (m1[2] != m2[2]); | |
| 600 | } | |
| 601 | } //namespace glm |
| 1 | #include "../geometric.hpp" | |
| 2 | #include <limits> | |
| 3 | ||
| 4 | namespace glm{ | |
| 5 | namespace detail | |
| 6 | { | |
| 7 | template<length_t C, length_t R, typename T, qualifier Q, bool Aligned> | |
| 8 | struct compute_matrixCompMult | |
| 9 | { | |
| 10 | GLM_FUNC_QUALIFIER static mat<C, R, T, Q> call(mat<C, R, T, Q> const& x, mat<C, R, T, Q> const& y) | |
| 11 | { | |
| 12 | mat<C, R, T, Q> Result; | |
| 13 | for(length_t i = 0; i < Result.length(); ++i) | |
| 14 | Result[i] = x[i] * y[i]; | |
| 15 | return Result; | |
| 16 | } | |
| 17 | }; | |
| 18 | ||
| 19 | template<length_t C, length_t R, typename T, qualifier Q, bool Aligned> | |
| 20 | struct compute_transpose{}; | |
| 21 | ||
| 22 | template<typename T, qualifier Q, bool Aligned> | |
| 23 | struct compute_transpose<2, 2, T, Q, Aligned> | |
| 24 | { | |
| 25 | GLM_FUNC_QUALIFIER static mat<2, 2, T, Q> call(mat<2, 2, T, Q> const& m) | |
| 26 | { | |
| 27 | mat<2, 2, T, Q> Result; | |
| 28 | Result[0][0] = m[0][0]; | |
| 29 | Result[0][1] = m[1][0]; | |
| 30 | Result[1][0] = m[0][1]; | |
| 31 | Result[1][1] = m[1][1]; | |
| 32 | return Result; | |
| 33 | } | |
| 34 | }; | |
| 35 | ||
| 36 | template<typename T, qualifier Q, bool Aligned> | |
| 37 | struct compute_transpose<2, 3, T, Q, Aligned> | |
| 38 | { | |
| 39 | GLM_FUNC_QUALIFIER static mat<3, 2, T, Q> call(mat<2, 3, T, Q> const& m) | |
| 40 | { | |
| 41 | mat<3,2, T, Q> Result; | |
| 42 | Result[0][0] = m[0][0]; | |
| 43 | Result[0][1] = m[1][0]; | |
| 44 | Result[1][0] = m[0][1]; | |
| 45 | Result[1][1] = m[1][1]; | |
| 46 | Result[2][0] = m[0][2]; | |
| 47 | Result[2][1] = m[1][2]; | |
| 48 | return Result; | |
| 49 | } | |
| 50 | }; | |
| 51 | ||
| 52 | template<typename T, qualifier Q, bool Aligned> | |
| 53 | struct compute_transpose<2, 4, T, Q, Aligned> | |
| 54 | { | |
| 55 | GLM_FUNC_QUALIFIER static mat<4, 2, T, Q> call(mat<2, 4, T, Q> const& m) | |
| 56 | { | |
| 57 | mat<4, 2, T, Q> Result; | |
| 58 | Result[0][0] = m[0][0]; | |
| 59 | Result[0][1] = m[1][0]; | |
| 60 | Result[1][0] = m[0][1]; | |
| 61 | Result[1][1] = m[1][1]; | |
| 62 | Result[2][0] = m[0][2]; | |
| 63 | Result[2][1] = m[1][2]; | |
| 64 | Result[3][0] = m[0][3]; | |
| 65 | Result[3][1] = m[1][3]; | |
| 66 | return Result; | |
| 67 | } | |
| 68 | }; | |
| 69 | ||
| 70 | template<typename T, qualifier Q, bool Aligned> | |
| 71 | struct compute_transpose<3, 2, T, Q, Aligned> | |
| 72 | { | |
| 73 | GLM_FUNC_QUALIFIER static mat<2, 3, T, Q> call(mat<3, 2, T, Q> const& m) | |
| 74 | { | |
| 75 | mat<2, 3, T, Q> Result; | |
| 76 | Result[0][0] = m[0][0]; | |
| 77 | Result[0][1] = m[1][0]; | |
| 78 | Result[0][2] = m[2][0]; | |
| 79 | Result[1][0] = m[0][1]; | |
| 80 | Result[1][1] = m[1][1]; | |
| 81 | Result[1][2] = m[2][1]; | |
| 82 | return Result; | |
| 83 | } | |
| 84 | }; | |
| 85 | ||
| 86 | template<typename T, qualifier Q, bool Aligned> | |
| 87 | struct compute_transpose<3, 3, T, Q, Aligned> | |
| 88 | { | |
| 89 | ! | GLM_FUNC_QUALIFIER static mat<3, 3, T, Q> call(mat<3, 3, T, Q> const& m) |
| 90 | { | |
| 91 | mat<3, 3, T, Q> Result; | |
| 92 | ! | Result[0][0] = m[0][0]; |
| 93 | ! | Result[0][1] = m[1][0]; |
| 94 | ! | Result[0][2] = m[2][0]; |
| 95 | ||
| 96 | ! | Result[1][0] = m[0][1]; |
| 97 | ! | Result[1][1] = m[1][1]; |
| 98 | ! | Result[1][2] = m[2][1]; |
| 99 | ||
| 100 | ! | Result[2][0] = m[0][2]; |
| 101 | ! | Result[2][1] = m[1][2]; |
| 102 | ! | Result[2][2] = m[2][2]; |
| 103 | ! | return Result; |
| 104 | } | |
| 105 | }; | |
| 106 | ||
| 107 | template<typename T, qualifier Q, bool Aligned> | |
| 108 | struct compute_transpose<3, 4, T, Q, Aligned> | |
| 109 | { | |
| 110 | GLM_FUNC_QUALIFIER static mat<4, 3, T, Q> call(mat<3, 4, T, Q> const& m) | |
| 111 | { | |
| 112 | mat<4, 3, T, Q> Result; | |
| 113 | Result[0][0] = m[0][0]; | |
| 114 | Result[0][1] = m[1][0]; | |
| 115 | Result[0][2] = m[2][0]; | |
| 116 | Result[1][0] = m[0][1]; | |
| 117 | Result[1][1] = m[1][1]; | |
| 118 | Result[1][2] = m[2][1]; | |
| 119 | Result[2][0] = m[0][2]; | |
| 120 | Result[2][1] = m[1][2]; | |
| 121 | Result[2][2] = m[2][2]; | |
| 122 | Result[3][0] = m[0][3]; | |
| 123 | Result[3][1] = m[1][3]; | |
| 124 | Result[3][2] = m[2][3]; | |
| 125 | return Result; | |
| 126 | } | |
| 127 | }; | |
| 128 | ||
| 129 | template<typename T, qualifier Q, bool Aligned> | |
| 130 | struct compute_transpose<4, 2, T, Q, Aligned> | |
| 131 | { | |
| 132 | GLM_FUNC_QUALIFIER static mat<2, 4, T, Q> call(mat<4, 2, T, Q> const& m) | |
| 133 | { | |
| 134 | mat<2, 4, T, Q> Result; | |
| 135 | Result[0][0] = m[0][0]; | |
| 136 | Result[0][1] = m[1][0]; | |
| 137 | Result[0][2] = m[2][0]; | |
| 138 | Result[0][3] = m[3][0]; | |
| 139 | Result[1][0] = m[0][1]; | |
| 140 | Result[1][1] = m[1][1]; | |
| 141 | Result[1][2] = m[2][1]; | |
| 142 | Result[1][3] = m[3][1]; | |
| 143 | return Result; | |
| 144 | } | |
| 145 | }; | |
| 146 | ||
| 147 | template<typename T, qualifier Q, bool Aligned> | |
| 148 | struct compute_transpose<4, 3, T, Q, Aligned> | |
| 149 | { | |
| 150 | GLM_FUNC_QUALIFIER static mat<3, 4, T, Q> call(mat<4, 3, T, Q> const& m) | |
| 151 | { | |
| 152 | mat<3, 4, T, Q> Result; | |
| 153 | Result[0][0] = m[0][0]; | |
| 154 | Result[0][1] = m[1][0]; | |
| 155 | Result[0][2] = m[2][0]; | |
| 156 | Result[0][3] = m[3][0]; | |
| 157 | Result[1][0] = m[0][1]; | |
| 158 | Result[1][1] = m[1][1]; | |
| 159 | Result[1][2] = m[2][1]; | |
| 160 | Result[1][3] = m[3][1]; | |
| 161 | Result[2][0] = m[0][2]; | |
| 162 | Result[2][1] = m[1][2]; | |
| 163 | Result[2][2] = m[2][2]; | |
| 164 | Result[2][3] = m[3][2]; | |
| 165 | return Result; | |
| 166 | } | |
| 167 | }; | |
| 168 | ||
| 169 | template<typename T, qualifier Q, bool Aligned> | |
| 170 | struct compute_transpose<4, 4, T, Q, Aligned> | |
| 171 | { | |
| 172 | ! | GLM_FUNC_QUALIFIER static mat<4, 4, T, Q> call(mat<4, 4, T, Q> const& m) |
| 173 | { | |
| 174 | mat<4, 4, T, Q> Result; | |
| 175 | ! | Result[0][0] = m[0][0]; |
| 176 | ! | Result[0][1] = m[1][0]; |
| 177 | ! | Result[0][2] = m[2][0]; |
| 178 | ! | Result[0][3] = m[3][0]; |
| 179 | ||
| 180 | ! | Result[1][0] = m[0][1]; |
| 181 | ! | Result[1][1] = m[1][1]; |
| 182 | ! | Result[1][2] = m[2][1]; |
| 183 | ! | Result[1][3] = m[3][1]; |
| 184 | ||
| 185 | ! | Result[2][0] = m[0][2]; |
| 186 | ! | Result[2][1] = m[1][2]; |
| 187 | ! | Result[2][2] = m[2][2]; |
| 188 | ! | Result[2][3] = m[3][2]; |
| 189 | ||
| 190 | ! | Result[3][0] = m[0][3]; |
| 191 | ! | Result[3][1] = m[1][3]; |
| 192 | ! | Result[3][2] = m[2][3]; |
| 193 | ! | Result[3][3] = m[3][3]; |
| 194 | ! | return Result; |
| 195 | } | |
| 196 | }; | |
| 197 | ||
| 198 | template<length_t C, length_t R, typename T, qualifier Q, bool Aligned> | |
| 199 | struct compute_determinant{}; | |
| 200 | ||
| 201 | template<typename T, qualifier Q, bool Aligned> | |
| 202 | struct compute_determinant<2, 2, T, Q, Aligned> | |
| 203 | { | |
| 204 | GLM_FUNC_QUALIFIER static T call(mat<2, 2, T, Q> const& m) | |
| 205 | { | |
| 206 | return m[0][0] * m[1][1] - m[1][0] * m[0][1]; | |
| 207 | } | |
| 208 | }; | |
| 209 | ||
| 210 | template<typename T, qualifier Q, bool Aligned> | |
| 211 | struct compute_determinant<3, 3, T, Q, Aligned> | |
| 212 | { | |
| 213 | GLM_FUNC_QUALIFIER static T call(mat<3, 3, T, Q> const& m) | |
| 214 | { | |
| 215 | return | |
| 216 | + m[0][0] * (m[1][1] * m[2][2] - m[2][1] * m[1][2]) | |
| 217 | - m[1][0] * (m[0][1] * m[2][2] - m[2][1] * m[0][2]) | |
| 218 | + m[2][0] * (m[0][1] * m[1][2] - m[1][1] * m[0][2]); | |
| 219 | } | |
| 220 | }; | |
| 221 | ||
| 222 | template<typename T, qualifier Q, bool Aligned> | |
| 223 | struct compute_determinant<4, 4, T, Q, Aligned> | |
| 224 | { | |
| 225 | GLM_FUNC_QUALIFIER static T call(mat<4, 4, T, Q> const& m) | |
| 226 | { | |
| 227 | T SubFactor00 = m[2][2] * m[3][3] - m[3][2] * m[2][3]; | |
| 228 | T SubFactor01 = m[2][1] * m[3][3] - m[3][1] * m[2][3]; | |
| 229 | T SubFactor02 = m[2][1] * m[3][2] - m[3][1] * m[2][2]; | |
| 230 | T SubFactor03 = m[2][0] * m[3][3] - m[3][0] * m[2][3]; | |
| 231 | T SubFactor04 = m[2][0] * m[3][2] - m[3][0] * m[2][2]; | |
| 232 | T SubFactor05 = m[2][0] * m[3][1] - m[3][0] * m[2][1]; | |
| 233 | ||
| 234 | vec<4, T, Q> DetCof( | |
| 235 | + (m[1][1] * SubFactor00 - m[1][2] * SubFactor01 + m[1][3] * SubFactor02), | |
| 236 | - (m[1][0] * SubFactor00 - m[1][2] * SubFactor03 + m[1][3] * SubFactor04), | |
| 237 | + (m[1][0] * SubFactor01 - m[1][1] * SubFactor03 + m[1][3] * SubFactor05), | |
| 238 | - (m[1][0] * SubFactor02 - m[1][1] * SubFactor04 + m[1][2] * SubFactor05)); | |
| 239 | ||
| 240 | return | |
| 241 | m[0][0] * DetCof[0] + m[0][1] * DetCof[1] + | |
| 242 | m[0][2] * DetCof[2] + m[0][3] * DetCof[3]; | |
| 243 | } | |
| 244 | }; | |
| 245 | ||
| 246 | template<length_t C, length_t R, typename T, qualifier Q, bool Aligned> | |
| 247 | struct compute_inverse{}; | |
| 248 | ||
| 249 | template<typename T, qualifier Q, bool Aligned> | |
| 250 | struct compute_inverse<2, 2, T, Q, Aligned> | |
| 251 | { | |
| 252 | GLM_FUNC_QUALIFIER static mat<2, 2, T, Q> call(mat<2, 2, T, Q> const& m) | |
| 253 | { | |
| 254 | T OneOverDeterminant = static_cast<T>(1) / ( | |
| 255 | + m[0][0] * m[1][1] | |
| 256 | - m[1][0] * m[0][1]); | |
| 257 | ||
| 258 | mat<2, 2, T, Q> Inverse( | |
| 259 | + m[1][1] * OneOverDeterminant, | |
| 260 | - m[0][1] * OneOverDeterminant, | |
| 261 | - m[1][0] * OneOverDeterminant, | |
| 262 | + m[0][0] * OneOverDeterminant); | |
| 263 | ||
| 264 | return Inverse; | |
| 265 | } | |
| 266 | }; | |
| 267 | ||
| 268 | template<typename T, qualifier Q, bool Aligned> | |
| 269 | struct compute_inverse<3, 3, T, Q, Aligned> | |
| 270 | { | |
| 271 | ! | GLM_FUNC_QUALIFIER static mat<3, 3, T, Q> call(mat<3, 3, T, Q> const& m) |
| 272 | { | |
| 273 | ! | T OneOverDeterminant = static_cast<T>(1) / ( |
| 274 | ! | + m[0][0] * (m[1][1] * m[2][2] - m[2][1] * m[1][2]) |
| 275 | ! | - m[1][0] * (m[0][1] * m[2][2] - m[2][1] * m[0][2]) |
| 276 | ! | + m[2][0] * (m[0][1] * m[1][2] - m[1][1] * m[0][2])); |
| 277 | ||
| 278 | mat<3, 3, T, Q> Inverse; | |
| 279 | ! | Inverse[0][0] = + (m[1][1] * m[2][2] - m[2][1] * m[1][2]) * OneOverDeterminant; |
| 280 | ! | Inverse[1][0] = - (m[1][0] * m[2][2] - m[2][0] * m[1][2]) * OneOverDeterminant; |
| 281 | ! | Inverse[2][0] = + (m[1][0] * m[2][1] - m[2][0] * m[1][1]) * OneOverDeterminant; |
| 282 | ! | Inverse[0][1] = - (m[0][1] * m[2][2] - m[2][1] * m[0][2]) * OneOverDeterminant; |
| 283 | ! | Inverse[1][1] = + (m[0][0] * m[2][2] - m[2][0] * m[0][2]) * OneOverDeterminant; |
| 284 | ! | Inverse[2][1] = - (m[0][0] * m[2][1] - m[2][0] * m[0][1]) * OneOverDeterminant; |
| 285 | ! | Inverse[0][2] = + (m[0][1] * m[1][2] - m[1][1] * m[0][2]) * OneOverDeterminant; |
| 286 | ! | Inverse[1][2] = - (m[0][0] * m[1][2] - m[1][0] * m[0][2]) * OneOverDeterminant; |
| 287 | ! | Inverse[2][2] = + (m[0][0] * m[1][1] - m[1][0] * m[0][1]) * OneOverDeterminant; |
| 288 | ||
| 289 | ! | return Inverse; |
| 290 | } | |
| 291 | }; | |
| 292 | ||
| 293 | template<typename T, qualifier Q, bool Aligned> | |
| 294 | struct compute_inverse<4, 4, T, Q, Aligned> | |
| 295 | { | |
| 296 | 27x | GLM_FUNC_QUALIFIER static mat<4, 4, T, Q> call(mat<4, 4, T, Q> const& m) |
| 297 | { | |
| 298 | 27x | T Coef00 = m[2][2] * m[3][3] - m[3][2] * m[2][3]; |
| 299 | 27x | T Coef02 = m[1][2] * m[3][3] - m[3][2] * m[1][3]; |
| 300 | 27x | T Coef03 = m[1][2] * m[2][3] - m[2][2] * m[1][3]; |
| 301 | ||
| 302 | 27x | T Coef04 = m[2][1] * m[3][3] - m[3][1] * m[2][3]; |
| 303 | 27x | T Coef06 = m[1][1] * m[3][3] - m[3][1] * m[1][3]; |
| 304 | 27x | T Coef07 = m[1][1] * m[2][3] - m[2][1] * m[1][3]; |
| 305 | ||
| 306 | 27x | T Coef08 = m[2][1] * m[3][2] - m[3][1] * m[2][2]; |
| 307 | 27x | T Coef10 = m[1][1] * m[3][2] - m[3][1] * m[1][2]; |
| 308 | 27x | T Coef11 = m[1][1] * m[2][2] - m[2][1] * m[1][2]; |
| 309 | ||
| 310 | 27x | T Coef12 = m[2][0] * m[3][3] - m[3][0] * m[2][3]; |
| 311 | 27x | T Coef14 = m[1][0] * m[3][3] - m[3][0] * m[1][3]; |
| 312 | 27x | T Coef15 = m[1][0] * m[2][3] - m[2][0] * m[1][3]; |
| 313 | ||
| 314 | 27x | T Coef16 = m[2][0] * m[3][2] - m[3][0] * m[2][2]; |
| 315 | 27x | T Coef18 = m[1][0] * m[3][2] - m[3][0] * m[1][2]; |
| 316 | 27x | T Coef19 = m[1][0] * m[2][2] - m[2][0] * m[1][2]; |
| 317 | ||
| 318 | 27x | T Coef20 = m[2][0] * m[3][1] - m[3][0] * m[2][1]; |
| 319 | 27x | T Coef22 = m[1][0] * m[3][1] - m[3][0] * m[1][1]; |
| 320 | 27x | T Coef23 = m[1][0] * m[2][1] - m[2][0] * m[1][1]; |
| 321 | ||
| 322 | 27x | vec<4, T, Q> Fac0(Coef00, Coef00, Coef02, Coef03); |
| 323 | 27x | vec<4, T, Q> Fac1(Coef04, Coef04, Coef06, Coef07); |
| 324 | 27x | vec<4, T, Q> Fac2(Coef08, Coef08, Coef10, Coef11); |
| 325 | 27x | vec<4, T, Q> Fac3(Coef12, Coef12, Coef14, Coef15); |
| 326 | 27x | vec<4, T, Q> Fac4(Coef16, Coef16, Coef18, Coef19); |
| 327 | 27x | vec<4, T, Q> Fac5(Coef20, Coef20, Coef22, Coef23); |
| 328 | ||
| 329 | 27x | vec<4, T, Q> Vec0(m[1][0], m[0][0], m[0][0], m[0][0]); |
| 330 | 27x | vec<4, T, Q> Vec1(m[1][1], m[0][1], m[0][1], m[0][1]); |
| 331 | 27x | vec<4, T, Q> Vec2(m[1][2], m[0][2], m[0][2], m[0][2]); |
| 332 | 27x | vec<4, T, Q> Vec3(m[1][3], m[0][3], m[0][3], m[0][3]); |
| 333 | ||
| 334 | 27x | vec<4, T, Q> Inv0(Vec1 * Fac0 - Vec2 * Fac1 + Vec3 * Fac2); |
| 335 | 27x | vec<4, T, Q> Inv1(Vec0 * Fac0 - Vec2 * Fac3 + Vec3 * Fac4); |
| 336 | 27x | vec<4, T, Q> Inv2(Vec0 * Fac1 - Vec1 * Fac3 + Vec3 * Fac5); |
| 337 | 27x | vec<4, T, Q> Inv3(Vec0 * Fac2 - Vec1 * Fac4 + Vec2 * Fac5); |
| 338 | ||
| 339 | 27x | vec<4, T, Q> SignA(+1, -1, +1, -1); |
| 340 | 27x | vec<4, T, Q> SignB(-1, +1, -1, +1); |
| 341 | 27x | mat<4, 4, T, Q> Inverse(Inv0 * SignA, Inv1 * SignB, Inv2 * SignA, Inv3 * SignB); |
| 342 | ||
| 343 | 27x | vec<4, T, Q> Row0(Inverse[0][0], Inverse[1][0], Inverse[2][0], Inverse[3][0]); |
| 344 | ||
| 345 | 27x | vec<4, T, Q> Dot0(m[0] * Row0); |
| 346 | 27x | T Dot1 = (Dot0.x + Dot0.y) + (Dot0.z + Dot0.w); |
| 347 | ||
| 348 | 27x | T OneOverDeterminant = static_cast<T>(1) / Dot1; |
| 349 | ||
| 350 | 54x | return Inverse * OneOverDeterminant; |
| 351 | } | |
| 352 | }; | |
| 353 | }//namespace detail | |
| 354 | ||
| 355 | template<length_t C, length_t R, typename T, qualifier Q> | |
| 356 | GLM_FUNC_QUALIFIER mat<C, R, T, Q> matrixCompMult(mat<C, R, T, Q> const& x, mat<C, R, T, Q> const& y) | |
| 357 | { | |
| 358 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559 || GLM_CONFIG_UNRESTRICTED_GENTYPE, "'matrixCompMult' only accept floating-point inputs"); | |
| 359 | return detail::compute_matrixCompMult<C, R, T, Q, detail::is_aligned<Q>::value>::call(x, y); | |
| 360 | } | |
| 361 | ||
| 362 | template<length_t DA, length_t DB, typename T, qualifier Q> | |
| 363 | GLM_FUNC_QUALIFIER typename detail::outerProduct_trait<DA, DB, T, Q>::type outerProduct(vec<DA, T, Q> const& c, vec<DB, T, Q> const& r) | |
| 364 | { | |
| 365 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559 || GLM_CONFIG_UNRESTRICTED_GENTYPE, "'outerProduct' only accept floating-point inputs"); | |
| 366 | ||
| 367 | typename detail::outerProduct_trait<DA, DB, T, Q>::type m; | |
| 368 | for(length_t i = 0; i < m.length(); ++i) | |
| 369 | m[i] = c * r[i]; | |
| 370 | return m; | |
| 371 | } | |
| 372 | ||
| 373 | template<length_t C, length_t R, typename T, qualifier Q> | |
| 374 | ! | GLM_FUNC_QUALIFIER typename mat<C, R, T, Q>::transpose_type transpose(mat<C, R, T, Q> const& m) |
| 375 | { | |
| 376 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559 || GLM_CONFIG_UNRESTRICTED_GENTYPE, "'transpose' only accept floating-point inputs"); | |
| 377 | ! | return detail::compute_transpose<C, R, T, Q, detail::is_aligned<Q>::value>::call(m); |
| 378 | } | |
| 379 | ||
| 380 | template<length_t C, length_t R, typename T, qualifier Q> | |
| 381 | GLM_FUNC_QUALIFIER T determinant(mat<C, R, T, Q> const& m) | |
| 382 | { | |
| 383 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559 || GLM_CONFIG_UNRESTRICTED_GENTYPE, "'determinant' only accept floating-point inputs"); | |
| 384 | return detail::compute_determinant<C, R, T, Q, detail::is_aligned<Q>::value>::call(m); | |
| 385 | } | |
| 386 | ||
| 387 | template<length_t C, length_t R, typename T, qualifier Q> | |
| 388 | 27x | GLM_FUNC_QUALIFIER mat<C, R, T, Q> inverse(mat<C, R, T, Q> const& m) |
| 389 | { | |
| 390 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559 || GLM_CONFIG_UNRESTRICTED_GENTYPE, "'inverse' only accept floating-point inputs"); | |
| 391 | 27x | return detail::compute_inverse<C, R, T, Q, detail::is_aligned<Q>::value>::call(m); |
| 392 | } | |
| 393 | }//namespace glm | |
| 394 | ||
| 395 | #if GLM_CONFIG_SIMD == GLM_ENABLE | |
| 396 | # include "func_matrix_simd.inl" | |
| 397 | #endif | |
| 398 |
| 1 | #ifndef LIGHTH | |
| 2 | #define LIGHTH | |
| 3 | ||
| 4 | #include "glm.hpp" | |
| 5 | #include "defines.h" | |
| 6 | #include "gtc/matrix_transform.hpp" | |
| 7 | ||
| 8 | class Light { | |
| 9 | public: | |
| 10 | ! | Light(vec3 position, vec3 color, |
| 11 | Float constant, Float linear, Float quadratic, | |
| 12 | ! | Float intensity) : |
| 13 | ! | position(position), color(color*intensity), constant(constant), |
| 14 | ! | linear(linear), quadratic(quadratic) {} |
| 15 | ||
| 16 | vec3 position; | |
| 17 | vec3 color; | |
| 18 | Float constant; | |
| 19 | Float linear; | |
| 20 | Float quadratic; | |
| 21 | Float intensity; | |
| 22 | ||
| 23 | vec3 CalcPointLightAtten(vec3 fragPos); | |
| 24 | vec3 CalcLightDir(vec3 fragPos); | |
| 25 | ||
| 26 | }; | |
| 27 | ||
| 28 | class DirectionalLight { | |
| 29 | public: | |
| 30 | 5x | DirectionalLight(vec3 direction, vec3 color, vec3 scene_center, vec3 light_up, Float scene_diag, |
| 31 | Float near_plane, Float far_plane, Mat vp_shadow, Mat Model, Mat shadow_inv, | |
| 32 | 5x | Float intensity_) : |
| 33 | 5x | direction(direction), color(color) { |
| 34 | 5x | lightProjection = glm::ortho(-scene_diag/2, scene_diag/2, -scene_diag/2, scene_diag/2, |
| 35 | 0.1, scene_diag); | |
| 36 | 5x | lightView = glm::lookAt(scene_center + direction * scene_diag, |
| 37 | scene_center, | |
| 38 | light_up); | |
| 39 | 5x | M = vp_shadow * lightProjection * lightView * Model; |
| 40 | 5x | uniform_Mshadow_ = M * shadow_inv; |
| 41 | 5x | intensity = intensity_; |
| 42 | } | |
| 43 | ||
| 44 | vec3 direction; | |
| 45 | vec3 color; | |
| 46 | Float intensity; | |
| 47 | ||
| 48 | Mat lightProjection; | |
| 49 | Mat lightView; | |
| 50 | Mat M; | |
| 51 | Mat uniform_Mshadow_; | |
| 52 | }; | |
| 53 | ||
| 54 | ||
| 55 | #endif |
| 1 | #include "shaders.h" | |
| 2 | ||
| 3 | #include "RcppThread.h" | |
| 4 | #include "stbimageheaders/stb_image.h" | |
| 5 | ||
| 6 | ||
| 7 | ! | void print_vec(vec3 m) { |
| 8 | ! | RcppThread::Rcout << std::fixed << m[0] << " " << m[1] << " " << m[2] << "\n"; |
| 9 | } | |
| 10 | ||
| 11 | ! | void print_vec(vec4 m) { |
| 12 | ! | RcppThread::Rcout << std::fixed << m[0] << " " << m[1] << " " << m[2] << " " << m[3] << "\n"; |
| 13 | } | |
| 14 | ||
| 15 | ! | inline Float clamp(Float c, Float clamplow, Float clamphigh) { |
| 16 | ! | if(c > clamphigh) { |
| 17 | ! | return(clamphigh); |
| 18 | ! | } else if(c < clamplow) { |
| 19 | ! | return(clamplow); |
| 20 | } | |
| 21 | ! | return(c); |
| 22 | } | |
| 23 | ||
| 24 | 22x | IShader::~IShader() {} |
| 25 | ||
| 26 | ! | GouraudShader::GouraudShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, |
| 27 | bool has_shadow_map, Float shadow_map_bias, | |
| 28 | material_info mat_info, std::vector<Light>& point_lights, | |
| 29 | std::vector<DirectionalLight> directional_lights, | |
| 30 | std::vector<rayimage>& shadowbuffers, | |
| 31 | std::vector<rayimage>& transparency_buffers, | |
| 32 | std::vector<vec3>& vec_varying_intensity, | |
| 33 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 34 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 35 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 36 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 37 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 38 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 39 | ! | reflection_map_info reflection_map, bool has_reflection, bool has_refraction) : |
| 40 | ! | Projection(Projection), View(View), viewport(viewport), |
| 41 | ! | has_shadow_map(has_shadow_map), |
| 42 | ! | shadow_map_bias(shadow_map_bias), material(mat_info), plights(point_lights), |
| 43 | ! | directional_lights(directional_lights), shadowbuffers(shadowbuffers), transparency_buffers(transparency_buffers), |
| 44 | ! | vec_varying_intensity(vec_varying_intensity), vec_varying_uv(vec_varying_uv), |
| 45 | ! | vec_varying_tri(vec_varying_tri), vec_varying_pos(vec_varying_pos), vec_varying_world_nrm(vec_varying_world_nrm), |
| 46 | ! | reflection_map(reflection_map), has_reflection(has_reflection), has_refraction(has_refraction) { |
| 47 | ! | MVP = Projection * View * Model; |
| 48 | ! | vp = glm::scale(glm::translate(Mat(1.0f), |
| 49 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)), |
| 50 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)); |
| 51 | ||
| 52 | ! | uniform_M = View * Model; |
| 53 | ! | uniform_MIT = glm::inverseTranspose(uniform_M); |
| 54 | ! | uniform_M_inv = glm::inverse(uniform_M); |
| 55 | ! | uniform_MIT_inv = glm::inverse(uniform_MIT); |
| 56 | ||
| 57 | ! | has_texture = has_normal_texture = has_specular_texture = has_emissive_texture = false; |
| 58 | ! | if(material.has_texture) { |
| 59 | ! | has_texture = true; |
| 60 | ! | texture = stbi_loadf(material.diffuse_texname.get_cstring(), &nx_t, &ny_t, &nn_t, 0); |
| 61 | ! | if(nx_t == 0 || ny_t == 0 || nn_t == 0) { |
| 62 | ! | throw std::runtime_error("Texture loading failed"); |
| 63 | } | |
| 64 | } | |
| 65 | ! | if(material.has_ambient_texture) { |
| 66 | ! | ambient_texture = stbi_loadf(material.ambient_texname.get_cstring(), &nx_a, &ny_a, &nn_a, 0); |
| 67 | ! | if(nx_a == 0 || ny_a == 0 || nn_a == 0) { |
| 68 | ! | throw std::runtime_error("Ambient Texture loading failed"); |
| 69 | } | |
| 70 | } | |
| 71 | ! | if(material.has_normal_texture) { |
| 72 | ! | has_normal_texture = true; |
| 73 | ! | normal_texture = stbi_loadf(material.normal_texname.get_cstring(), &nx_nt, &ny_nt, &nn_nt, 0); |
| 74 | ! | if(nx_nt == 0 || ny_nt == 0 || nn_nt == 0) { |
| 75 | ! | throw std::runtime_error("Normal texture loading failed"); |
| 76 | } | |
| 77 | } | |
| 78 | ! | if(material.has_specular_texture) { |
| 79 | ! | has_specular_texture = true; |
| 80 | ! | specular_texture = stbi_loadf(material.specular_texname.get_cstring(), |
| 81 | &nx_st, &ny_st, &nn_st, 0); | |
| 82 | ! | if(nx_st == 0 || ny_st == 0 || nn_st == 0) { |
| 83 | ! | throw std::runtime_error("Specular texture loading failed"); |
| 84 | } | |
| 85 | } | |
| 86 | ! | if(material.has_emissive_texture) { |
| 87 | ! | has_emissive_texture = true; |
| 88 | ! | emissive_texture = stbi_loadf(material.emissive_texname.get_cstring(), |
| 89 | &nx_et, &ny_et, &nn_et, 0); | |
| 90 | ! | if(nx_et == 0 || ny_et == 0 || nn_et == 0) { |
| 91 | ! | throw std::runtime_error("Emissive texture loading failed"); |
| 92 | } | |
| 93 | } | |
| 94 | } | |
| 95 | ||
| 96 | ! | GouraudShader::~GouraudShader() { |
| 97 | ! | if(has_texture) { |
| 98 | ! | stbi_image_free(texture); |
| 99 | } | |
| 100 | ! | if(material.has_ambient_texture) { |
| 101 | ! | stbi_image_free(ambient_texture); |
| 102 | } | |
| 103 | ! | if(has_normal_texture) { |
| 104 | ! | stbi_image_free(normal_texture); |
| 105 | } | |
| 106 | ! | if(has_specular_texture) { |
| 107 | ! | stbi_image_free(specular_texture); |
| 108 | } | |
| 109 | ! | if(has_emissive_texture) { |
| 110 | ! | stbi_image_free(emissive_texture); |
| 111 | } | |
| 112 | } | |
| 113 | ||
| 114 | ! | vec4 GouraudShader::vertex(int iface, int nthvert, ModelInfo& model) { |
| 115 | ! | int global_face = model.index_offset + iface; |
| 116 | ! | vec_varying_intensity[global_face][nthvert] = std::fmax(0.f, dot(model.normal(iface, nthvert),light_dir)); |
| 117 | ! | vec_varying_pos[global_face][nthvert] = vec3(View * Model * vec4(model.vertex(iface, nthvert),1.0f)); |
| 118 | ! | vec_varying_world_nrm[global_face][nthvert] = vec3(uniform_MIT * vec4(model.normal(iface, nthvert),0.0f)); |
| 119 | ! | vec4 clip = vp * MVP * vec4(model.vertex(iface, nthvert),1.0f); |
| 120 | ||
| 121 | ! | vec_varying_tri[global_face][nthvert] = clip; |
| 122 | ||
| 123 | ! | return (clip); |
| 124 | } | |
| 125 | ||
| 126 | ! | bool GouraudShader::fragment(vec3& bc, vec4 &color, vec3& pos, vec3& normal, int iface) { |
| 127 | ! | normal = vec_varying_world_nrm[iface][0] * bc.x + vec_varying_world_nrm[iface][1] * bc.y + vec_varying_world_nrm[iface][2] * bc.z; |
| 128 | ! | vec4 diffuse_color = vec4(material.diffuse,material.dissolve); |
| 129 | ||
| 130 | ! | vec4 light_color(0.0); |
| 131 | ! | for(unsigned int ii = 0; ii < directional_lights.size(); ii++) { |
| 132 | ! | vec4 trans_color(0.0,0.0,0.0,0.0); |
| 133 | ||
| 134 | ! | Float shadow = 0.0f; |
| 135 | ! | Float intensity = std::fmax(dot(normal, vec3(uniform_M * vec4(directional_lights[ii].direction,0.0))),0.0); |
| 136 | ! | if(has_shadow_map && intensity != 0.0) { |
| 137 | ! | vec4 sb_p = directional_lights[ii].uniform_Mshadow_ * (vec_varying_tri[iface][0] * bc.x + vec_varying_tri[iface][1] * bc.y + vec_varying_tri[iface][2] * bc.z); |
| 138 | ! | sb_p = sb_p/sb_p.w; |
| 139 | ! | if(sb_p[0] >= 0 && sb_p[0] < shadowbuffers[ii].width() && sb_p[1] >= 0 && sb_p[1] < shadowbuffers[ii].height()) { |
| 140 | ! | Float bias = std::fmax(shadow_map_bias*10.0 * (1.0 - intensity),shadow_map_bias); |
| 141 | ||
| 142 | ! | int i = int(sb_p[0]); |
| 143 | ! | int j = int(sb_p[1]); |
| 144 | ! | for(int x = -2; x <= 2; ++x) { |
| 145 | ! | for(int y = -2; y <= 2; ++y) { |
| 146 | ! | shadow += shadowbuffers[ii].get_color_bounded(i+x,j+y).x > sb_p[2]-bias ? 1.0f : shadowbuffers[ii].get_shadow_intensity(); |
| 147 | } | |
| 148 | } | |
| 149 | ! | shadow /= 25; |
| 150 | ! | if(diffuse_color.w == 1.0) { |
| 151 | ! | for(int x = -2; x <= 2; ++x) { |
| 152 | ! | for(int y = -2; y <= 2; ++y) { |
| 153 | ! | trans_color += transparency_buffers[ii].get_color_bounded_a(i+x,j+y); |
| 154 | } | |
| 155 | } | |
| 156 | ! | trans_color /= 25; |
| 157 | } | |
| 158 | } | |
| 159 | } | |
| 160 | ! | light_color += vec4(vec3(trans_color) * trans_color.w * directional_lights[ii].intensity + |
| 161 | ! | (1-trans_color.w) * directional_lights[ii].color * directional_lights[ii].intensity,0.0) * shadow * intensity; |
| 162 | } | |
| 163 | // color = vec4(light_color * material.diffuse,1.0f); | |
| 164 | ! | color = light_color; |
| 165 | ! | pos = vec_varying_pos[iface][0] * bc.x + vec_varying_pos[iface][1] * bc.y + vec_varying_pos[iface][2] * bc.z; |
| 166 | ! | if(has_reflection && !has_refraction) { |
| 167 | ! | vec3 dir = uniform_M_inv * vec4(glm::normalize(pos),0.0f); |
| 168 | ! | vec3 normal_w = uniform_MIT_inv * vec4(glm::normalize(normal),0.0f); |
| 169 | ! | vec3 r = glm::reflect(dir,normal_w); |
| 170 | ! | color = material.reflection_intensity * reflection(r) + (1-material.reflection_intensity) * color; |
| 171 | } | |
| 172 | ! | if(has_refraction) { |
| 173 | ! | vec4 temp_col = diffuse_color; |
| 174 | ! | vec3 dir = glm::normalize(uniform_M_inv * vec4(pos,0.0f)); |
| 175 | ! | vec3 normal_w = glm::normalize(uniform_MIT_inv * vec4(normal,0.0f)); |
| 176 | ! | vec3 rl = glm::reflect(dir,normal_w); |
| 177 | ||
| 178 | ! | vec3 rf = glm::refract(dir,normal_w, 1.0/material.ior); |
| 179 | ! | vec4 reflect_col = reflection(rl); |
| 180 | ! | vec4 refract_col = reflection(rf); |
| 181 | ! | Float Ro = (material.ior - 1.0)/(material.ior + 1.0); |
| 182 | ! | Ro = Ro * Ro; |
| 183 | ! | Float c0 = 1.0-dot(dir,-normal_w); |
| 184 | ! | Float c0_5 = c0*c0*c0*c0*c0; |
| 185 | ! | Float reflect_coef = Ro + (1.0 - Ro) * c0_5; |
| 186 | ! | color = (1-reflect_coef) * refract_col * temp_col + reflect_coef * reflect_col; |
| 187 | ! | color.w = 1.0; |
| 188 | } | |
| 189 | ! | return(false); |
| 190 | } | |
| 191 | ||
| 192 | ||
| 193 | ! | ColorShader::~ColorShader() { |
| 194 | ! | if(has_texture) { |
| 195 | ! | stbi_image_free(texture); |
| 196 | } | |
| 197 | ! | if(material.has_ambient_texture) { |
| 198 | ! | stbi_image_free(ambient_texture); |
| 199 | } | |
| 200 | ! | if(has_normal_texture) { |
| 201 | ! | stbi_image_free(normal_texture); |
| 202 | } | |
| 203 | ! | if(has_specular_texture) { |
| 204 | ! | stbi_image_free(specular_texture); |
| 205 | } | |
| 206 | ! | if(has_emissive_texture) { |
| 207 | ! | stbi_image_free(emissive_texture); |
| 208 | } | |
| 209 | } | |
| 210 | ||
| 211 | ! | ColorShader::ColorShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, |
| 212 | material_info mat_info, | |
| 213 | std::vector<vec3>& vec_varying_intensity, | |
| 214 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 215 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 216 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 217 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 218 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 219 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 220 | ! | reflection_map_info reflection_map, bool has_reflection, bool has_refraction) : |
| 221 | ! | Projection(Projection), View(View), viewport(viewport), material(mat_info), |
| 222 | ! | vec_varying_uv(vec_varying_uv), |
| 223 | ! | vec_varying_tri(vec_varying_tri), vec_varying_pos(vec_varying_pos), vec_varying_world_nrm(vec_varying_world_nrm), |
| 224 | ! | reflection_map(reflection_map), has_reflection(has_reflection), has_refraction(has_refraction) { |
| 225 | ! | vp = glm::scale(glm::translate(Mat(1.0f), |
| 226 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)), |
| 227 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)); |
| 228 | ! | MVP = Projection * View * Model; |
| 229 | ! | uniform_M = View * Model; |
| 230 | ! | uniform_MIT = glm::inverseTranspose(uniform_M); |
| 231 | ! | uniform_M_inv = glm::inverse(uniform_M); |
| 232 | ! | uniform_MIT_inv = glm::inverse(uniform_MIT); |
| 233 | ||
| 234 | ! | has_texture = has_normal_texture = has_specular_texture = has_emissive_texture = false; |
| 235 | ! | if(material.has_texture) { |
| 236 | ! | has_texture = true; |
| 237 | ! | texture = stbi_loadf(material.diffuse_texname.get_cstring(), &nx_t, &ny_t, &nn_t, 0); |
| 238 | ! | if(nx_t == 0 || ny_t == 0 || nn_t == 0) { |
| 239 | ! | throw std::runtime_error("Texture loading failed"); |
| 240 | } | |
| 241 | } | |
| 242 | ! | if(material.has_ambient_texture) { |
| 243 | ! | ambient_texture = stbi_loadf(material.ambient_texname.get_cstring(), &nx_a, &ny_a, &nn_a, 0); |
| 244 | ! | if(nx_a == 0 || ny_a == 0 || nn_a == 0) { |
| 245 | ! | throw std::runtime_error("Ambient Texture loading failed"); |
| 246 | } | |
| 247 | } | |
| 248 | ! | if(material.has_normal_texture) { |
| 249 | ! | has_normal_texture = true; |
| 250 | ! | normal_texture = stbi_loadf(material.normal_texname.get_cstring(), &nx_nt, &ny_nt, &nn_nt, 0); |
| 251 | ! | if(nx_nt == 0 || ny_nt == 0 || nn_nt == 0) { |
| 252 | ! | throw std::runtime_error("Normal texture loading failed"); |
| 253 | } | |
| 254 | } | |
| 255 | ! | if(material.has_specular_texture) { |
| 256 | ! | has_specular_texture = true; |
| 257 | ! | specular_texture = stbi_loadf(material.specular_texname.get_cstring(), |
| 258 | &nx_st, &ny_st, &nn_st, 0); | |
| 259 | ! | if(nx_st == 0 || ny_st == 0 || nn_st == 0) { |
| 260 | ! | throw std::runtime_error("Specular texture loading failed"); |
| 261 | } | |
| 262 | } | |
| 263 | ! | if(material.has_emissive_texture) { |
| 264 | ! | has_emissive_texture = true; |
| 265 | ! | emissive_texture = stbi_loadf(material.emissive_texname.get_cstring(), |
| 266 | &nx_et, &ny_et, &nn_et, 0); | |
| 267 | ! | if(nx_et == 0 || ny_et == 0 || nn_et == 0) { |
| 268 | ! | throw std::runtime_error("Emissive texture loading failed"); |
| 269 | } | |
| 270 | } | |
| 271 | } | |
| 272 | ||
| 273 | ||
| 274 | ! | vec4 ColorShader::vertex(int iface, int nthvert, ModelInfo& model) { |
| 275 | ! | int global_face = model.index_offset + iface; |
| 276 | ! | vec4 clip = MVP * vec4(model.vertex(iface,nthvert),1.0f); |
| 277 | ! | vec_varying_uv[global_face][nthvert] = model.tex(iface,nthvert); |
| 278 | ! | vec_varying_tri[global_face][nthvert] = vp * clip; |
| 279 | ! | vec_varying_pos[global_face][nthvert] = uniform_M * vec4(model.vertex(iface, nthvert),1.0f); |
| 280 | ! | vec_varying_world_nrm[global_face][nthvert] = model.model_vertex_normals(iface) ? |
| 281 | ! | uniform_MIT * vec4(model.normal(iface, nthvert),0.0f) : |
| 282 | ! | uniform_MIT * normalize(vec4(glm::cross(model.vertex(iface,1)-model.vertex(iface,0), |
| 283 | ! | model.vertex(iface,2)-model.vertex(iface,0)),0.0f)); |
| 284 | ! | return (vec_varying_tri[global_face][nthvert]); |
| 285 | } | |
| 286 | ||
| 287 | ! | bool ColorShader::fragment(vec3& bc, vec4 &color, vec3& pos, vec3& normal, int iface) { |
| 288 | ! | vec3 uv = vec_varying_uv[iface][0] * bc.x + vec_varying_uv[iface][1] * bc.y + vec_varying_uv[iface][2] * bc.z; |
| 289 | ! | vec4 diffuse_color = diffuse(uv); |
| 290 | ! | if(diffuse_color.w == 0.0) return true; |
| 291 | ||
| 292 | ! | pos = vec_varying_pos[iface][0] * bc.x + vec_varying_pos[iface][1] * bc.y + vec_varying_pos[iface][2] * bc.z; |
| 293 | ! | normal = vec_varying_world_nrm[iface][0] * bc.x + vec_varying_world_nrm[iface][1] * bc.y + vec_varying_world_nrm[iface][2] * bc.z; |
| 294 | ! | bc = uv; |
| 295 | ! | color = diffuse_color; |
| 296 | //Emissive and ambient terms | |
| 297 | ! | color += emissive(uv); |
| 298 | ! | color += ambient(uv); |
| 299 | ! | if(has_reflection && !has_refraction) { |
| 300 | ! | vec3 dir = uniform_M_inv * vec4(glm::normalize(pos),0.0f); |
| 301 | ! | vec3 normal_w = uniform_MIT_inv * vec4(glm::normalize(normal),0.0f); |
| 302 | ! | vec3 r = glm::reflect(dir,normal_w); |
| 303 | ! | color = material.reflection_intensity * reflection(r) + (1-material.reflection_intensity) * color; |
| 304 | } | |
| 305 | ! | if(has_refraction) { |
| 306 | ! | vec4 temp_col = diffuse_color; |
| 307 | ! | vec3 dir = glm::normalize(uniform_M_inv * vec4(pos,0.0f)); |
| 308 | ! | vec3 normal_w = glm::normalize(uniform_MIT_inv * vec4(normal,0.0f)); |
| 309 | ! | vec3 rl = glm::reflect(dir,normal_w); |
| 310 | ||
| 311 | ! | vec3 rf = glm::refract(dir,normal_w, 1.0/material.ior); |
| 312 | ! | vec4 reflect_col = reflection(rl); |
| 313 | ! | vec4 refract_col = reflection(rf); |
| 314 | ! | Float Ro = (material.ior - 1.0)/(material.ior + 1.0); |
| 315 | ! | Ro = Ro * Ro; |
| 316 | ! | Float c0 = 1.0-dot(dir,-normal_w); |
| 317 | ! | Float c0_5 = c0*c0*c0*c0*c0; |
| 318 | ! | Float reflect_coef = Ro + (1.0 - Ro) * c0_5; |
| 319 | ! | color = (1-reflect_coef) * refract_col * temp_col + reflect_coef * reflect_col; |
| 320 | ! | color.w = 1.0; |
| 321 | } | |
| 322 | ||
| 323 | ! | return false; |
| 324 | } | |
| 325 | ||
| 326 | 22x | DiffuseShader::~DiffuseShader() { |
| 327 | 11x | if(has_texture) { |
| 328 | 1x | stbi_image_free(texture); |
| 329 | } | |
| 330 | 11x | if(material.has_ambient_texture) { |
| 331 | ! | stbi_image_free(ambient_texture); |
| 332 | } | |
| 333 | 11x | if(has_normal_texture) { |
| 334 | ! | stbi_image_free(normal_texture); |
| 335 | } | |
| 336 | 11x | if(has_specular_texture) { |
| 337 | ! | stbi_image_free(specular_texture); |
| 338 | } | |
| 339 | 11x | if(has_emissive_texture) { |
| 340 | ! | stbi_image_free(emissive_texture); |
| 341 | } | |
| 342 | } | |
| 343 | ||
| 344 | 11x | DiffuseShader::DiffuseShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, |
| 345 | ||
| 346 | bool has_shadow_map, Float shadow_map_bias, | |
| 347 | material_info mat_info, std::vector<Light>& point_lights, | |
| 348 | std::vector<DirectionalLight> directional_lights, | |
| 349 | std::vector<rayimage>& shadowbuffers, | |
| 350 | std::vector<rayimage>& transparency_buffers, | |
| 351 | std::vector<vec3>& vec_varying_intensity, | |
| 352 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 353 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 354 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 355 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 356 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 357 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 358 | reflection_map_info reflection_map, bool has_reflection, bool has_refraction, | |
| 359 | 11x | bool two_sided) : |
| 360 | 11x | Projection(Projection), View(View), viewport(viewport), |
| 361 | 11x | has_shadow_map(has_shadow_map), |
| 362 | 22x | shadow_map_bias(shadow_map_bias), material(mat_info), plights(point_lights), |
| 363 | 11x | directional_lights(directional_lights), shadowbuffers(shadowbuffers), transparency_buffers(transparency_buffers), |
| 364 | 11x | vec_varying_intensity(vec_varying_intensity), vec_varying_uv(vec_varying_uv), |
| 365 | 11x | vec_varying_tri(vec_varying_tri), vec_varying_pos(vec_varying_pos), vec_varying_world_nrm(vec_varying_world_nrm), |
| 366 | 11x | reflection_map(reflection_map), has_reflection(has_reflection), has_refraction(has_refraction), |
| 367 | 11x | two_sided(two_sided) { |
| 368 | 11x | vp = glm::scale(glm::translate(Mat(1.0f), |
| 369 | 11x | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)), |
| 370 | 11x | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)); |
| 371 | 11x | MVP = Projection * View * Model; |
| 372 | 11x | uniform_M = View * Model; |
| 373 | 11x | uniform_MIT = glm::inverseTranspose(uniform_M); |
| 374 | 11x | uniform_M_inv = glm::inverse(uniform_M); |
| 375 | 11x | uniform_MIT_inv = glm::inverse(uniform_MIT); |
| 376 | ||
| 377 | 11x | has_texture = has_normal_texture = has_specular_texture = has_emissive_texture = false; |
| 378 | 11x | if(material.has_texture) { |
| 379 | 1x | has_texture = true; |
| 380 | 1x | texture = stbi_loadf(material.diffuse_texname.get_cstring(), &nx_t, &ny_t, &nn_t, 0); |
| 381 | 1x | if(nx_t == 0 || ny_t == 0 || nn_t == 0) { |
| 382 | ! | throw std::runtime_error("Texture loading failed"); |
| 383 | } | |
| 384 | } | |
| 385 | 11x | if(material.has_ambient_texture) { |
| 386 | ! | ambient_texture = stbi_loadf(material.ambient_texname.get_cstring(), &nx_a, &ny_a, &nn_a, 0); |
| 387 | ! | if(nx_a == 0 || ny_a == 0 || nn_a == 0) { |
| 388 | ! | throw std::runtime_error("Ambient Texture loading failed"); |
| 389 | } | |
| 390 | } | |
| 391 | 11x | if(material.has_normal_texture) { |
| 392 | ! | has_normal_texture = true; |
| 393 | ! | normal_texture = stbi_loadf(material.normal_texname.get_cstring(), &nx_nt, &ny_nt, &nn_nt, 0); |
| 394 | ! | if(nx_nt == 0 || ny_nt == 0 || nn_nt == 0) { |
| 395 | ! | throw std::runtime_error("Normal texture loading failed"); |
| 396 | } | |
| 397 | } | |
| 398 | 11x | if(material.has_specular_texture) { |
| 399 | ! | has_specular_texture = true; |
| 400 | ! | specular_texture = stbi_loadf(material.specular_texname.get_cstring(), |
| 401 | &nx_st, &ny_st, &nn_st, 0); | |
| 402 | ! | if(nx_st == 0 || ny_st == 0 || nn_st == 0) { |
| 403 | ! | throw std::runtime_error("Specular texture loading failed"); |
| 404 | } | |
| 405 | } | |
| 406 | 11x | if(material.has_emissive_texture) { |
| 407 | ! | has_emissive_texture = true; |
| 408 | ! | emissive_texture = stbi_loadf(material.emissive_texname.get_cstring(), |
| 409 | &nx_et, &ny_et, &nn_et, 0); | |
| 410 | ! | if(nx_et == 0 || ny_et == 0 || nn_et == 0) { |
| 411 | ! | throw std::runtime_error("Emissive texture loading failed"); |
| 412 | } | |
| 413 | } | |
| 414 | } | |
| 415 | ||
| 416 | ||
| 417 | 5172x | vec4 DiffuseShader::vertex(int iface, int nthvert, ModelInfo& model) { |
| 418 | 5172x | int global_face = model.index_offset + iface; |
| 419 | 5172x | vec4 clip = MVP * vec4(model.vertex(iface,nthvert),1.0f); |
| 420 | 5172x | vec_varying_uv[global_face][nthvert] = model.tex(iface,nthvert); |
| 421 | 5172x | vec_varying_tri[global_face][nthvert] = vp * clip; |
| 422 | 5172x | vec_varying_pos[global_face][nthvert] = uniform_M * vec4(model.vertex(iface, nthvert),1.0f); |
| 423 | ||
| 424 | 10344x | vec_varying_world_nrm[global_face][nthvert] = model.model_vertex_normals(iface) ? |
| 425 | 4488x | uniform_MIT * vec4(model.normal(iface, nthvert),0.0f) : |
| 426 | 1368x | uniform_MIT * normalize(vec4(glm::cross(model.vertex(iface,1)-model.vertex(iface,0), |
| 427 | 2052x | model.vertex(iface,2)-model.vertex(iface,0)),0.0f)); |
| 428 | ||
| 429 | 10344x | return (vec_varying_tri[global_face][nthvert]); |
| 430 | } | |
| 431 | ||
| 432 | 666476x | bool DiffuseShader::fragment(vec3& bc, vec4 &color, vec3& pos, vec3& normal, int iface) { |
| 433 | 666476x | vec3 uv = vec_varying_uv[iface][0] * bc.x + vec_varying_uv[iface][1] * bc.y + vec_varying_uv[iface][2] * bc.z; |
| 434 | 666476x | vec4 diffuse_color = diffuse(uv); |
| 435 | ||
| 436 | 666476x | if(diffuse_color.w == 0.0) return true; |
| 437 | 666476x | normal = vec_varying_world_nrm[iface][0] * bc.x + vec_varying_world_nrm[iface][1] * bc.y + vec_varying_world_nrm[iface][2] * bc.z; |
| 438 | ||
| 439 | 666476x | vec3 light_color(0.0); |
| 440 | ||
| 441 | 1332952x | for(unsigned int ii = 0; ii < directional_lights.size(); ii++) { |
| 442 | 666476x | vec4 trans_color(0.0,0.0,0.0,0.0); |
| 443 | 666476x | Float shadow = 1.0f; |
| 444 | 666476x | Float dot_prod = dot(normal, vec3(uniform_M * vec4(directional_lights[ii].direction, 0.0))); |
| 445 | 666476x | dot_prod *= two_sided && dot_prod < 0 ? -1 : 1; |
| 446 | 666476x | Float intensity = std::fmax(dot_prod,0.0); |
| 447 | 666476x | if(has_shadow_map && intensity != 0.0) { |
| 448 | 665539x | shadow = 0.0f; |
| 449 | 665539x | vec4 sb_p = directional_lights[ii].uniform_Mshadow_ * (vec_varying_tri[iface][0] * bc.x + vec_varying_tri[iface][1] * bc.y + vec_varying_tri[iface][2] * bc.z); |
| 450 | 665539x | sb_p = sb_p/sb_p.w; |
| 451 | ||
| 452 | 665539x | if(sb_p[0] >= 0 && sb_p[0] < shadowbuffers[ii].width() && sb_p[1] >= 0 && sb_p[1] < shadowbuffers[ii].height()) { |
| 453 | 665539x | Float bias = std::fmax(shadow_map_bias*10.0 * (1.0 - intensity),shadow_map_bias); |
| 454 | ||
| 455 | 665539x | int i = int(sb_p[0]); |
| 456 | 665539x | int j = int(sb_p[1]); |
| 457 | 3993234x | for(int x = -2; x <= 2; ++x) { |
| 458 | 19966170x | for(int y = -2; y <= 2; ++y) { |
| 459 | 16638475x | shadow += shadowbuffers[ii].get_color_bounded(i+x,j+y).x > sb_p[2]-bias ? 1.0f : shadowbuffers[ii].get_shadow_intensity(); |
| 460 | } | |
| 461 | } | |
| 462 | 665539x | shadow /= 25; |
| 463 | 665539x | if(diffuse_color.w == 1.0) { |
| 464 | 3993234x | for(int x = -2; x <= 2; ++x) { |
| 465 | 19966170x | for(int y = -2; y <= 2; ++y) { |
| 466 | 16638475x | trans_color += transparency_buffers[ii].get_color_bounded_a(i+x,j+y); |
| 467 | } | |
| 468 | } | |
| 469 | 665539x | trans_color /= 25; |
| 470 | } | |
| 471 | } | |
| 472 | } | |
| 473 | 666476x | light_color += (vec3(trans_color) * trans_color.w * directional_lights[ii].intensity + |
| 474 | 1332952x | (1-trans_color.w) * directional_lights[ii].color * directional_lights[ii].intensity) * shadow * intensity; |
| 475 | } | |
| 476 | ||
| 477 | ||
| 478 | 666476x | pos = vec_varying_pos[iface][0] * bc.x + vec_varying_pos[iface][1] * bc.y + vec_varying_pos[iface][2] * bc.z; |
| 479 | //Directional light contribution | |
| 480 | 666476x | color = diffuse_color * vec4(light_color,1.0); |
| 481 | ||
| 482 | ||
| 483 | 666476x | for(unsigned int i = 0; i < plights.size(); i++) { |
| 484 | ! | color += diffuse_color * vec4(plights[i].CalcPointLightAtten(pos),0.0f) * fmax(0.0f,dot(normal, plights[i].CalcLightDir(pos))); |
| 485 | } | |
| 486 | //Emissive and ambient terms | |
| 487 | 666476x | color += emissive(uv); |
| 488 | 666476x | color += ambient(uv); |
| 489 | ||
| 490 | 666476x | if(has_reflection && !has_refraction) { |
| 491 | ! | vec3 dir = uniform_M_inv * vec4(glm::normalize(pos),0.0f); |
| 492 | ! | vec3 normal_w = uniform_MIT_inv * vec4(glm::normalize(normal),0.0f); |
| 493 | ! | vec3 r = glm::reflect(dir,normal_w); |
| 494 | ! | color = material.reflection_intensity * reflection(r) + (1-material.reflection_intensity) * color; |
| 495 | } | |
| 496 | 666476x | if(has_refraction) { |
| 497 | ! | vec4 temp_col = diffuse_color; |
| 498 | ! | vec3 dir = glm::normalize(uniform_M_inv * vec4(pos,0.0f)); |
| 499 | ! | vec3 normal_w = glm::normalize(uniform_MIT_inv * vec4(normal,0.0f)); |
| 500 | ! | vec3 rl = glm::reflect(dir,normal_w); |
| 501 | ||
| 502 | ! | vec3 rf = glm::refract(dir,normal_w, 1.0/material.ior); |
| 503 | ! | vec4 reflect_col = reflection(rl); |
| 504 | ! | vec4 refract_col = reflection(rf); |
| 505 | ! | Float Ro = (material.ior - 1.0)/(material.ior + 1.0); |
| 506 | ! | Ro = Ro * Ro; |
| 507 | ! | Float c0 = 1.0-dot(dir,-normal_w); |
| 508 | ! | Float c0_5 = c0*c0*c0*c0*c0; |
| 509 | ! | Float reflect_coef = Ro + (1.0 - Ro) * c0_5; |
| 510 | ! | color = (1-reflect_coef) * refract_col * temp_col + reflect_coef * reflect_col; |
| 511 | ! | color.w = 1.0; |
| 512 | } | |
| 513 | 666476x | bc = uv; |
| 514 | 666476x | return false; |
| 515 | } | |
| 516 | ||
| 517 | ||
| 518 | ! | OrenNayerShader::~OrenNayerShader() { |
| 519 | ! | if(has_texture) { |
| 520 | ! | stbi_image_free(texture); |
| 521 | } | |
| 522 | ! | if(material.has_ambient_texture) { |
| 523 | ! | stbi_image_free(ambient_texture); |
| 524 | } | |
| 525 | ! | if(has_normal_texture) { |
| 526 | ! | stbi_image_free(normal_texture); |
| 527 | } | |
| 528 | ! | if(has_specular_texture) { |
| 529 | ! | stbi_image_free(specular_texture); |
| 530 | } | |
| 531 | ! | if(has_emissive_texture) { |
| 532 | ! | stbi_image_free(emissive_texture); |
| 533 | } | |
| 534 | } | |
| 535 | ||
| 536 | ! | OrenNayerShader::OrenNayerShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, |
| 537 | ||
| 538 | bool has_shadow_map, Float shadow_map_bias, | |
| 539 | material_info mat_info, std::vector<Light>& point_lights, | |
| 540 | std::vector<DirectionalLight> directional_lights, | |
| 541 | std::vector<rayimage>& shadowbuffers, | |
| 542 | std::vector<rayimage>& transparency_buffers, | |
| 543 | std::vector<vec3>& vec_varying_intensity, | |
| 544 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 545 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 546 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 547 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 548 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 549 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 550 | reflection_map_info reflection_map, bool has_reflection, bool has_refraction, | |
| 551 | ! | bool two_sided) : |
| 552 | ! | Projection(Projection), View(View), viewport(viewport), |
| 553 | ! | has_shadow_map(has_shadow_map), |
| 554 | ! | shadow_map_bias(shadow_map_bias), material(mat_info), plights(point_lights), |
| 555 | ! | directional_lights(directional_lights), shadowbuffers(shadowbuffers), transparency_buffers(transparency_buffers), |
| 556 | ! | vec_varying_intensity(vec_varying_intensity), vec_varying_uv(vec_varying_uv), |
| 557 | ! | vec_varying_tri(vec_varying_tri), vec_varying_pos(vec_varying_pos), vec_varying_world_nrm(vec_varying_world_nrm), |
| 558 | ! | reflection_map(reflection_map), has_reflection(has_reflection), has_refraction(has_refraction), |
| 559 | ! | two_sided(two_sided) { |
| 560 | ! | vp = glm::scale(glm::translate(Mat(1.0f), |
| 561 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)), |
| 562 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)); |
| 563 | ! | MVP = Projection * View * Model; |
| 564 | ! | uniform_M = View * Model; |
| 565 | ! | uniform_MIT = glm::inverseTranspose(uniform_M); |
| 566 | ! | uniform_M_inv = glm::inverse(uniform_M); |
| 567 | ! | uniform_MIT_inv = glm::inverse(uniform_MIT); |
| 568 | ||
| 569 | ! | has_texture = has_normal_texture = has_specular_texture = has_emissive_texture = false; |
| 570 | ! | if(material.has_texture) { |
| 571 | ! | has_texture = true; |
| 572 | ! | texture = stbi_loadf(material.diffuse_texname.get_cstring(), &nx_t, &ny_t, &nn_t, 0); |
| 573 | ! | if(nx_t == 0 || ny_t == 0 || nn_t == 0) { |
| 574 | ! | throw std::runtime_error("Texture loading failed"); |
| 575 | } | |
| 576 | } | |
| 577 | ! | if(material.has_ambient_texture) { |
| 578 | ! | ambient_texture = stbi_loadf(material.ambient_texname.get_cstring(), &nx_a, &ny_a, &nn_a, 0); |
| 579 | ! | if(nx_a == 0 || ny_a == 0 || nn_a == 0) { |
| 580 | ! | throw std::runtime_error("Ambient Texture loading failed"); |
| 581 | } | |
| 582 | } | |
| 583 | ! | if(material.has_normal_texture) { |
| 584 | ! | has_normal_texture = true; |
| 585 | ! | normal_texture = stbi_loadf(material.normal_texname.get_cstring(), &nx_nt, &ny_nt, &nn_nt, 0); |
| 586 | ! | if(nx_nt == 0 || ny_nt == 0 || nn_nt == 0) { |
| 587 | ! | throw std::runtime_error("Normal texture loading failed"); |
| 588 | } | |
| 589 | } | |
| 590 | ! | if(material.has_specular_texture) { |
| 591 | ! | has_specular_texture = true; |
| 592 | ! | specular_texture = stbi_loadf(material.specular_texname.get_cstring(), |
| 593 | &nx_st, &ny_st, &nn_st, 0); | |
| 594 | ! | if(nx_st == 0 || ny_st == 0 || nn_st == 0) { |
| 595 | ! | throw std::runtime_error("Specular texture loading failed"); |
| 596 | } | |
| 597 | } | |
| 598 | ! | if(material.has_emissive_texture) { |
| 599 | ! | has_emissive_texture = true; |
| 600 | ! | emissive_texture = stbi_loadf(material.emissive_texname.get_cstring(), |
| 601 | &nx_et, &ny_et, &nn_et, 0); | |
| 602 | ! | if(nx_et == 0 || ny_et == 0 || nn_et == 0) { |
| 603 | ! | throw std::runtime_error("Emissive texture loading failed"); |
| 604 | } | |
| 605 | } | |
| 606 | ! | Float sigma_val = mat_info.sigma*mat_info.sigma * M_PI / 180.0; |
| 607 | ! | Float sigma2 = sigma_val*sigma_val; |
| 608 | ! | A = 1.0f - (sigma2 / (2.0f * (sigma2 + 0.33f))); |
| 609 | ! | B = 0.45f * sigma2 / (sigma2 + 0.09f); |
| 610 | } | |
| 611 | ||
| 612 | ||
| 613 | ! | vec4 OrenNayerShader::vertex(int iface, int nthvert, ModelInfo& model) { |
| 614 | ! | int global_face = model.index_offset + iface; |
| 615 | ! | vec4 clip = MVP * vec4(model.vertex(iface,nthvert),1.0f); |
| 616 | ! | vec_varying_uv[global_face][nthvert] = model.tex(iface,nthvert); |
| 617 | ! | vec_varying_tri[global_face][nthvert] = vp * clip; |
| 618 | ! | vec_varying_pos[global_face][nthvert] = uniform_M * vec4(model.vertex(iface, nthvert),1.0f); |
| 619 | ||
| 620 | ! | vec_varying_world_nrm[global_face][nthvert] = model.model_vertex_normals(iface) ? |
| 621 | ! | uniform_MIT * vec4(model.normal(iface, nthvert),0.0f) : |
| 622 | ! | uniform_MIT * normalize(vec4(glm::cross(model.vertex(iface,1)-model.vertex(iface,0), |
| 623 | ! | model.vertex(iface,2)-model.vertex(iface,0)),0.0f)); |
| 624 | ||
| 625 | ! | return (vec_varying_tri[global_face][nthvert]); |
| 626 | } | |
| 627 | ||
| 628 | // Clamp helper | |
| 629 | ! | inline Float saturate(Float x) { return clamp(x, 0.0f, 1.0f); } |
| 630 | ||
| 631 | ! | bool OrenNayerShader::fragment(vec3& bc, vec4 &color, vec3& pos, vec3& normal, int iface) { |
| 632 | // Compute Oren–Nayar factor given N (front-facing), V (to camera), L (to light) | |
| 633 | ! | auto oren_nayar = [&](const vec3& Nf, const vec3& V, const vec3& L) -> Float { |
| 634 | ! | Float cosThetaI = saturate(glm::dot(Nf, L)); |
| 635 | ! | Float cosThetaO = saturate(glm::dot(Nf, V)); |
| 636 | ! | Float sinThetaI = std::sqrt(std::max(0.0, 1.0 - cosThetaI*cosThetaI)); |
| 637 | ! | Float sinThetaO = std::sqrt(std::max(0.0, 1.0 - cosThetaO*cosThetaO)); |
| 638 | ||
| 639 | ! | Float cosPhiDiff = 0.0f; |
| 640 | ! | if (sinThetaI > 1e-4f && sinThetaO > 1e-4f) { |
| 641 | ! | vec3 vPerp = glm::normalize(V - Nf * cosThetaO); |
| 642 | ! | vec3 lPerp = glm::normalize(L - Nf * cosThetaI); |
| 643 | ! | cosPhiDiff = std::max(0.0, glm::dot(vPerp, lPerp)); |
| 644 | } | |
| 645 | ||
| 646 | Float sinAlpha, tanBeta; | |
| 647 | ! | if (std::abs(cosThetaI) > std::abs(cosThetaO)) { |
| 648 | ! | sinAlpha = sinThetaO; |
| 649 | ! | tanBeta = sinThetaI / std::max(1e-4, std::abs(cosThetaI)); |
| 650 | } else { | |
| 651 | ! | sinAlpha = sinThetaI; |
| 652 | ! | tanBeta = sinThetaO / std::max(1e-4, std::abs(cosThetaO)); |
| 653 | } | |
| 654 | ! | return (A + B * cosPhiDiff * sinAlpha * tanBeta); |
| 655 | }; | |
| 656 | ! | vec3 uv = vec_varying_uv[iface][0] * bc.x + vec_varying_uv[iface][1] * bc.y + vec_varying_uv[iface][2] * bc.z; |
| 657 | ! | vec4 diffuse_color = diffuse(uv); |
| 658 | ||
| 659 | ! | if(diffuse_color.w == 0.0) return true; |
| 660 | ||
| 661 | // Interpolate and normalize the view-space normal | |
| 662 | ! | normal = vec_varying_world_nrm[iface][0] * bc.x + |
| 663 | ! | vec_varying_world_nrm[iface][1] * bc.y + |
| 664 | ! | vec_varying_world_nrm[iface][2] * bc.z; |
| 665 | ! | normal = glm::normalize(normal); |
| 666 | ||
| 667 | // Interpolate view-space position now so we can make a view vector | |
| 668 | ! | vec3 pos_view = vec_varying_pos[iface][0] * bc.x + |
| 669 | ! | vec_varying_pos[iface][1] * bc.y + |
| 670 | ! | vec_varying_pos[iface][2] * bc.z; |
| 671 | ||
| 672 | // View vector (from surface to camera) in view space | |
| 673 | ! | vec3 V = glm::normalize(-pos_view); |
| 674 | ||
| 675 | ! | vec3 light_color(0.0); |
| 676 | ||
| 677 | ! | for (unsigned int ii = 0; ii < directional_lights.size(); ii++) { |
| 678 | ! | vec4 trans_color(0.0); |
| 679 | ! | Float shadow = 1.0f; |
| 680 | ||
| 681 | // Light direction in view space (normalize!) | |
| 682 | ! | vec3 L = glm::normalize(vec3(uniform_M * vec4(directional_lights[ii].direction, 0.0f))); |
| 683 | ||
| 684 | // Two-sided handling: flip N if needed so cosThetaI is positive when allowed | |
| 685 | ! | Float ndl_raw = glm::dot(normal, L); |
| 686 | ! | vec3 Nf = (two_sided && ndl_raw < 0.0f) ? -normal : normal; |
| 687 | ||
| 688 | // Cosine to light (used both for shadow bias and the final factor) | |
| 689 | ! | Float intensity = std::max(0.0, glm::dot(Nf, L)); |
| 690 | ||
| 691 | // --- Your existing shadow map code (unchanged except it uses 'intensity') --- | |
| 692 | ! | if (has_shadow_map && intensity != 0.0f) { |
| 693 | ! | shadow = 0.0f; |
| 694 | ! | vec4 sb_p = directional_lights[ii].uniform_Mshadow_ * |
| 695 | ! | (vec_varying_tri[iface][0] * bc.x + |
| 696 | ! | vec_varying_tri[iface][1] * bc.y + |
| 697 | ! | vec_varying_tri[iface][2] * bc.z); |
| 698 | ! | sb_p /= sb_p.w; |
| 699 | ! | if (sb_p[0] >= 0 && sb_p[0] < shadowbuffers[ii].width() && |
| 700 | ! | sb_p[1] >= 0 && sb_p[1] < shadowbuffers[ii].height()) { |
| 701 | ! | Float bias = std::fmax(shadow_map_bias*10.0f * (1.0f - intensity), shadow_map_bias); |
| 702 | ! | int i = int(sb_p[0]), j = int(sb_p[1]); |
| 703 | ! | for (int x = -2; x <= 2; ++x) { |
| 704 | ! | for (int y = -2; y <= 2; ++y) { |
| 705 | ! | shadow += shadowbuffers[ii].get_color_bounded(i+x,j+y).x > sb_p[2]-bias ? |
| 706 | ! | 1.0f : shadowbuffers[ii].get_shadow_intensity(); |
| 707 | } | |
| 708 | } | |
| 709 | ! | shadow /= 25.0f; |
| 710 | ||
| 711 | ! | if (diffuse_color.w == 1.0f) { |
| 712 | ! | for (int x = -2; x <= 2; ++x) |
| 713 | ! | for (int y = -2; y <= 2; ++y) |
| 714 | ! | trans_color += transparency_buffers[ii].get_color_bounded_a(i+x,j+y); |
| 715 | ! | trans_color /= 25.0f; |
| 716 | } | |
| 717 | } | |
| 718 | } | |
| 719 | // --------------------------------------------------------------------------- | |
| 720 | ||
| 721 | // Oren–Nayar factor | |
| 722 | ! | Float on = oren_nayar(Nf, V, L); |
| 723 | ||
| 724 | // Final per-light diffuse contribution (keeps your units: ON * cosThetaI) | |
| 725 | ! | vec3 Li = (vec3(trans_color) * trans_color.w * directional_lights[ii].intensity + |
| 726 | ! | (1.0f - trans_color.w) * directional_lights[ii].color * directional_lights[ii].intensity); |
| 727 | ||
| 728 | ! | light_color += Li * shadow * (on * intensity); |
| 729 | } | |
| 730 | ||
| 731 | ||
| 732 | ! | pos = pos_view; |
| 733 | ||
| 734 | ! | color = diffuse_color * vec4(light_color, 1.0f); |
| 735 | ||
| 736 | ! | for (unsigned int i = 0; i < plights.size(); i++) { |
| 737 | ! | vec3 L = plights[i].CalcLightDir(pos_view); // assumed normalized (as before) |
| 738 | ! | Float ndl_raw = glm::dot(normal, L); |
| 739 | ! | vec3 Nf = (two_sided && ndl_raw < 0.0f) ? -normal : normal; |
| 740 | ! | Float cosThetaI = std::max(0.0, glm::dot(Nf, L)); |
| 741 | ||
| 742 | ! | Float on = oren_nayar(Nf, V, L); |
| 743 | ||
| 744 | ! | vec3 Li = plights[i].CalcPointLightAtten(pos_view); // your existing attenuation * color |
| 745 | ! | color += diffuse_color * vec4(Li * (on * cosThetaI), 0.0f); |
| 746 | } | |
| 747 | //Emissive and ambient terms | |
| 748 | ! | color += emissive(uv); |
| 749 | ! | color += ambient(uv); |
| 750 | ||
| 751 | ! | if(has_reflection && !has_refraction) { |
| 752 | ! | vec3 dir = uniform_M_inv * vec4(glm::normalize(pos),0.0f); |
| 753 | ! | vec3 normal_w = uniform_MIT_inv * vec4(glm::normalize(normal),0.0f); |
| 754 | ! | vec3 r = glm::reflect(dir,normal_w); |
| 755 | ! | color = material.reflection_intensity * reflection(r) + (1-material.reflection_intensity) * color; |
| 756 | } | |
| 757 | ! | if(has_refraction) { |
| 758 | ! | vec4 temp_col = diffuse_color; |
| 759 | ! | vec3 dir = glm::normalize(uniform_M_inv * vec4(pos,0.0f)); |
| 760 | ! | vec3 normal_w = glm::normalize(uniform_MIT_inv * vec4(normal,0.0f)); |
| 761 | ! | vec3 rl = glm::reflect(dir,normal_w); |
| 762 | ||
| 763 | ! | vec3 rf = glm::refract(dir,normal_w, 1.0/material.ior); |
| 764 | ! | vec4 reflect_col = reflection(rl); |
| 765 | ! | vec4 refract_col = reflection(rf); |
| 766 | ! | Float Ro = (material.ior - 1.0)/(material.ior + 1.0); |
| 767 | ! | Ro = Ro * Ro; |
| 768 | ! | Float c0 = 1.0-dot(dir,-normal_w); |
| 769 | ! | Float c0_5 = c0*c0*c0*c0*c0; |
| 770 | ! | Float reflect_coef = Ro + (1.0 - Ro) * c0_5; |
| 771 | ! | color = (1-reflect_coef) * refract_col * temp_col + reflect_coef * reflect_col; |
| 772 | ! | color.w = 1.0; |
| 773 | } | |
| 774 | ! | bc = uv; |
| 775 | ! | return false; |
| 776 | } | |
| 777 | ||
| 778 | ! | DiffuseNormalShader::~DiffuseNormalShader() { |
| 779 | ! | if(has_texture) { |
| 780 | ! | stbi_image_free(texture); |
| 781 | } | |
| 782 | ! | if(material.has_ambient_texture) { |
| 783 | ! | stbi_image_free(ambient_texture); |
| 784 | } | |
| 785 | ! | if(has_normal_texture) { |
| 786 | ! | stbi_image_free(normal_texture); |
| 787 | } | |
| 788 | ! | if(has_specular_texture) { |
| 789 | ! | stbi_image_free(specular_texture); |
| 790 | } | |
| 791 | ! | if(has_emissive_texture) { |
| 792 | ! | stbi_image_free(emissive_texture); |
| 793 | } | |
| 794 | } | |
| 795 | ||
| 796 | ! | DiffuseNormalShader::DiffuseNormalShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, |
| 797 | ||
| 798 | bool has_shadow_map, Float shadow_map_bias, | |
| 799 | material_info mat_info, std::vector<Light>& point_lights, | |
| 800 | std::vector<DirectionalLight> directional_lights, | |
| 801 | std::vector<rayimage>& shadowbuffers, | |
| 802 | std::vector<rayimage>& transparency_buffers, | |
| 803 | std::vector<vec3>& vec_varying_intensity, | |
| 804 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 805 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 806 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 807 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 808 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 809 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 810 | ! | reflection_map_info reflection_map, bool has_reflection, bool has_refraction) : |
| 811 | ! | Projection(Projection), View(View), viewport(viewport), |
| 812 | ! | has_shadow_map(has_shadow_map), |
| 813 | ! | shadow_map_bias(shadow_map_bias), material(mat_info), plights(point_lights), |
| 814 | ! | directional_lights(directional_lights), shadowbuffers(shadowbuffers), transparency_buffers(transparency_buffers), |
| 815 | ! | vec_varying_uv(vec_varying_uv), |
| 816 | ! | vec_varying_tri(vec_varying_tri), vec_varying_pos(vec_varying_pos), vec_varying_world_nrm(vec_varying_world_nrm), |
| 817 | ! | reflection_map(reflection_map), has_reflection(has_reflection), has_refraction(has_refraction) { |
| 818 | ! | MVP = Projection * View * Model; |
| 819 | ! | vp = glm::scale(glm::translate(Mat(1.0f), |
| 820 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)), |
| 821 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)); |
| 822 | ||
| 823 | ! | has_texture = has_normal_texture = has_specular_texture = has_emissive_texture = false; |
| 824 | ! | if(material.has_texture) { |
| 825 | ! | has_texture = true; |
| 826 | ! | texture = stbi_loadf(material.diffuse_texname.get_cstring(), &nx_t, &ny_t, &nn_t, 0); |
| 827 | ! | if(nx_t == 0 || ny_t == 0 || nn_t == 0) { |
| 828 | ! | throw std::runtime_error("Texture loading failed"); |
| 829 | } | |
| 830 | } | |
| 831 | ! | if(material.has_ambient_texture) { |
| 832 | ! | ambient_texture = stbi_loadf(material.ambient_texname.get_cstring(), &nx_a, &ny_a, &nn_a, 0); |
| 833 | ! | if(nx_a == 0 || ny_a == 0 || nn_a == 0) { |
| 834 | ! | throw std::runtime_error("Ambient Texture loading failed"); |
| 835 | } | |
| 836 | } | |
| 837 | ! | if(material.has_normal_texture) { |
| 838 | ! | has_normal_texture = true; |
| 839 | ! | normal_texture = stbi_loadf(material.normal_texname.get_cstring(), &nx_nt, &ny_nt, &nn_nt, 0); |
| 840 | ! | if(nx_nt == 0 || ny_nt == 0 || nn_nt == 0) { |
| 841 | ! | throw std::runtime_error("Normal texture loading failed"); |
| 842 | } | |
| 843 | } | |
| 844 | ! | if(material.has_specular_texture) { |
| 845 | ! | has_specular_texture = true; |
| 846 | ! | specular_texture = stbi_loadf(material.specular_texname.get_cstring(), |
| 847 | &nx_st, &ny_st, &nn_st, 0); | |
| 848 | ! | if(nx_st == 0 || ny_st == 0 || nn_st == 0) { |
| 849 | ! | throw std::runtime_error("Specular texture loading failed"); |
| 850 | } | |
| 851 | } | |
| 852 | ! | if(material.has_emissive_texture) { |
| 853 | ! | has_emissive_texture = true; |
| 854 | ! | emissive_texture = stbi_loadf(material.emissive_texname.get_cstring(), |
| 855 | &nx_et, &ny_et, &nn_et, 0); | |
| 856 | ! | if(nx_et == 0 || ny_et == 0 || nn_et == 0) { |
| 857 | ! | throw std::runtime_error("Emissive texture loading failed"); |
| 858 | } | |
| 859 | } | |
| 860 | ||
| 861 | ||
| 862 | ! | uniform_M = View * Model; |
| 863 | ! | uniform_MIT = glm::inverseTranspose(uniform_M); |
| 864 | ! | uniform_M_inv = glm::inverse(uniform_M); |
| 865 | ! | uniform_MIT_inv = glm::inverse(uniform_MIT); |
| 866 | } | |
| 867 | ||
| 868 | ||
| 869 | ! | vec4 DiffuseNormalShader::vertex(int iface, int nthvert, ModelInfo& model) { |
| 870 | ! | int global_face = model.index_offset + iface; |
| 871 | ! | vec_varying_uv[global_face][nthvert] = model.tex(iface,nthvert); |
| 872 | ! | vec_varying_pos[global_face][nthvert] = vec3(View * Model * vec4(model.vertex(iface, nthvert),1.0f)); |
| 873 | ! | vec_varying_world_nrm[global_face][nthvert] = vec3(uniform_MIT * vec4(model.normal(iface, nthvert),0.0f)); |
| 874 | ||
| 875 | ! | vec4 clip = vp * MVP * vec4(model.vertex(iface,nthvert),1.0f); |
| 876 | ! | vec_varying_tri[global_face][nthvert] = clip; |
| 877 | ||
| 878 | ||
| 879 | ! | return (clip); |
| 880 | } | |
| 881 | ||
| 882 | ! | bool DiffuseNormalShader::fragment(vec3& bc, vec4 &color, vec3& pos, vec3& normal, int iface) { |
| 883 | ! | vec3 uv = vec_varying_uv[iface][0] * bc.x + vec_varying_uv[iface][1] * bc.y + vec_varying_uv[iface][2] * bc.z; |
| 884 | ! | vec4 diffuse_color = diffuse(uv); |
| 885 | ! | if(diffuse_color.w == 0.0) return true; |
| 886 | ! | vec3 n = normalize(vec3(uniform_MIT * vec4(normal_uv(uv), 0.0f))); |
| 887 | ||
| 888 | ! | vec3 light_color(0.0); |
| 889 | ! | for(unsigned int ii = 0; ii < directional_lights.size(); ii++) { |
| 890 | ! | vec4 trans_color(0.0,0.0,0.0,0.0); |
| 891 | ||
| 892 | ! | Float shadow = 1.0f; |
| 893 | ! | Float intensity = std::fmax(dot(n, vec3(uniform_M * vec4(directional_lights[ii].direction,0.0))),0.0); |
| 894 | ! | if(has_shadow_map && intensity != 0.0) { |
| 895 | ! | shadow = 0.0f; |
| 896 | ! | vec4 sb_p = directional_lights[ii].uniform_Mshadow_ * (vec_varying_tri[iface][0] * bc.x + vec_varying_tri[iface][1] * bc.y + vec_varying_tri[iface][2] * bc.z); |
| 897 | ! | sb_p = sb_p/sb_p.w; |
| 898 | ! | if(sb_p[0] >= 0 && sb_p[0] < shadowbuffers[ii].width() && sb_p[1] >= 0 && sb_p[1] < shadowbuffers[ii].height()) { |
| 899 | ! | Float bias = std::fmax(shadow_map_bias*10.0 * (1.0 - intensity),shadow_map_bias); |
| 900 | ||
| 901 | ! | int i = int(sb_p[0]); |
| 902 | ! | int j = int(sb_p[1]); |
| 903 | ! | for(int x = -2; x <= 2; ++x) { |
| 904 | ! | for(int y = -2; y <= 2; ++y) { |
| 905 | ! | shadow += shadowbuffers[ii].get_color_bounded(i+x,j+y).x > sb_p[2]-bias ? 1.0f : shadowbuffers[ii].get_shadow_intensity(); |
| 906 | } | |
| 907 | } | |
| 908 | ! | shadow /= 25; |
| 909 | ! | if(diffuse_color.w == 1.0) { |
| 910 | ! | for(int x = -2; x <= 2; ++x) { |
| 911 | ! | for(int y = -2; y <= 2; ++y) { |
| 912 | ! | trans_color += transparency_buffers[ii].get_color_bounded_a(i+x,j+y); |
| 913 | } | |
| 914 | } | |
| 915 | ! | trans_color /= 25; |
| 916 | } | |
| 917 | } | |
| 918 | } | |
| 919 | ! | light_color += (vec3(trans_color) * trans_color.w * directional_lights[ii].intensity + |
| 920 | ! | (1-trans_color.w) * directional_lights[ii].color * directional_lights[ii].intensity) * shadow * intensity; |
| 921 | } | |
| 922 | ||
| 923 | ! | for(unsigned int i = 0; i < plights.size(); i++) { |
| 924 | ! | color += diffuse_color * vec4(plights[i].CalcPointLightAtten(pos),0.0f) * fmax(0.0f,dot(normal, plights[i].CalcLightDir(pos))); |
| 925 | } | |
| 926 | ||
| 927 | //Emissive and ambient terms | |
| 928 | ! | color += emissive(uv); |
| 929 | ! | color += ambient(uv); |
| 930 | ||
| 931 | ! | pos = vec_varying_pos[iface][0] * bc.x + vec_varying_pos[iface][1] * bc.y + vec_varying_pos[iface][2] * bc.z; |
| 932 | ! | normal = n; |
| 933 | ! | if(has_reflection && !has_refraction) { |
| 934 | ! | vec3 dir = uniform_M_inv * vec4(glm::normalize(pos),0.0f); |
| 935 | ! | vec3 normal_w = uniform_MIT_inv * vec4(glm::normalize(normal),0.0f); |
| 936 | ! | vec3 r = glm::reflect(dir,normal_w); |
| 937 | ! | color = material.reflection_intensity * reflection(r) + (1-material.reflection_intensity) * color; |
| 938 | } | |
| 939 | ! | if(has_refraction) { |
| 940 | ! | vec4 temp_col = diffuse_color; |
| 941 | ! | vec3 dir = glm::normalize(uniform_M_inv * vec4(pos,0.0f)); |
| 942 | ! | vec3 normal_w = glm::normalize(uniform_MIT_inv * vec4(normal,0.0f)); |
| 943 | ! | vec3 rl = glm::reflect(dir,normal_w); |
| 944 | ||
| 945 | ! | vec3 rf = glm::refract(dir,normal_w, 1.0/material.ior); |
| 946 | ! | vec4 reflect_col = reflection(rl); |
| 947 | ! | vec4 refract_col = reflection(rf); |
| 948 | ! | Float Ro = (material.ior - 1.0)/(material.ior + 1.0); |
| 949 | ! | Ro = Ro * Ro; |
| 950 | ! | Float c0 = 1.0-dot(dir,-normal_w); |
| 951 | ! | Float c0_5 = c0*c0*c0*c0*c0; |
| 952 | ! | Float reflect_coef = Ro + (1.0 - Ro) * c0_5; |
| 953 | ! | color = (1-reflect_coef) * refract_col * temp_col + reflect_coef * reflect_col; |
| 954 | ! | color.w = 1.0; |
| 955 | } | |
| 956 | ! | bc = uv; |
| 957 | ! | return false; |
| 958 | } | |
| 959 | ||
| 960 | ! | DiffuseShaderTangent::~DiffuseShaderTangent() { |
| 961 | ! | if(has_texture) { |
| 962 | ! | stbi_image_free(texture); |
| 963 | } | |
| 964 | ! | if(material.has_ambient_texture) { |
| 965 | ! | stbi_image_free(ambient_texture); |
| 966 | } | |
| 967 | ! | if(has_normal_texture) { |
| 968 | ! | stbi_image_free(normal_texture); |
| 969 | } | |
| 970 | ! | if(has_specular_texture) { |
| 971 | ! | stbi_image_free(specular_texture); |
| 972 | } | |
| 973 | ! | if(has_emissive_texture) { |
| 974 | ! | stbi_image_free(emissive_texture); |
| 975 | } | |
| 976 | } | |
| 977 | ||
| 978 | ! | DiffuseShaderTangent::DiffuseShaderTangent(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, |
| 979 | ||
| 980 | bool has_shadow_map, Float shadow_map_bias, | |
| 981 | material_info mat_info, std::vector<Light>& point_lights, | |
| 982 | std::vector<DirectionalLight> directional_lights, | |
| 983 | std::vector<rayimage>& shadowbuffers, | |
| 984 | std::vector<rayimage>& transparency_buffers, | |
| 985 | std::vector<vec3>& vec_varying_intensity, | |
| 986 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 987 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 988 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 989 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 990 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 991 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 992 | ! | reflection_map_info reflection_map, bool has_reflection, bool has_refraction) : |
| 993 | ! | Projection(Projection), View(View), viewport(viewport), |
| 994 | ! | has_shadow_map(has_shadow_map), |
| 995 | ! | shadow_map_bias(shadow_map_bias), material(mat_info), plights(point_lights), |
| 996 | ! | directional_lights(directional_lights), shadowbuffers(shadowbuffers), transparency_buffers(transparency_buffers), |
| 997 | ! | vec_varying_intensity(vec_varying_intensity), vec_varying_uv(vec_varying_uv), |
| 998 | ! | vec_varying_tri(vec_varying_tri), vec_varying_pos(vec_varying_pos), |
| 999 | ! | vec_varying_ndc_tri(vec_varying_ndc_tri), vec_varying_world_nrm(vec_varying_world_nrm), |
| 1000 | ! | vec_varying_nrm(vec_varying_nrm), |
| 1001 | ! | reflection_map(reflection_map), has_reflection(has_reflection), has_refraction(has_refraction) { |
| 1002 | ! | MVP = Projection * View * Model; |
| 1003 | ! | vp = glm::scale(glm::translate(Mat(1.0f), |
| 1004 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)), |
| 1005 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)); |
| 1006 | ! | uniform_M = View * Model; |
| 1007 | ! | uniform_MIT = glm::inverseTranspose(uniform_M); |
| 1008 | ! | uniform_M_inv = glm::inverse(uniform_M); |
| 1009 | ! | uniform_MIT_inv = glm::inverse(uniform_MIT); |
| 1010 | ||
| 1011 | ! | has_texture = has_normal_texture = has_specular_texture = has_emissive_texture = false; |
| 1012 | ! | if(material.has_texture) { |
| 1013 | ! | has_texture = true; |
| 1014 | ! | texture = stbi_loadf(material.diffuse_texname.get_cstring(), &nx_t, &ny_t, &nn_t, 0); |
| 1015 | ! | if(nx_t == 0 || ny_t == 0 || nn_t == 0) { |
| 1016 | ! | throw std::runtime_error("Texture loading failed"); |
| 1017 | } | |
| 1018 | } | |
| 1019 | ! | if(material.has_ambient_texture) { |
| 1020 | ! | ambient_texture = stbi_loadf(material.ambient_texname.get_cstring(), &nx_a, &ny_a, &nn_a, 0); |
| 1021 | ! | if(nx_a == 0 || ny_a == 0 || nn_a == 0) { |
| 1022 | ! | throw std::runtime_error("Ambient Texture loading failed"); |
| 1023 | } | |
| 1024 | } | |
| 1025 | ! | if(material.has_normal_texture) { |
| 1026 | ! | has_normal_texture = true; |
| 1027 | ! | normal_texture = stbi_loadf(material.normal_texname.get_cstring(), &nx_nt, &ny_nt, &nn_nt, 0); |
| 1028 | ! | if(nx_nt == 0 || ny_nt == 0 || nn_nt == 0) { |
| 1029 | ! | throw std::runtime_error("Normal texture loading failed"); |
| 1030 | } | |
| 1031 | } | |
| 1032 | ! | if(material.has_specular_texture) { |
| 1033 | ! | has_specular_texture = true; |
| 1034 | ! | specular_texture = stbi_loadf(material.specular_texname.get_cstring(), |
| 1035 | &nx_st, &ny_st, &nn_st, 0); | |
| 1036 | ! | if(nx_st == 0 || ny_st == 0 || nn_st == 0) { |
| 1037 | ! | throw std::runtime_error("Specular texture loading failed"); |
| 1038 | } | |
| 1039 | } | |
| 1040 | ! | if(material.has_emissive_texture) { |
| 1041 | ! | has_emissive_texture = true; |
| 1042 | ! | emissive_texture = stbi_loadf(material.emissive_texname.get_cstring(), |
| 1043 | &nx_et, &ny_et, &nn_et, 0); | |
| 1044 | ! | if(nx_et == 0 || ny_et == 0 || nn_et == 0) { |
| 1045 | ! | throw std::runtime_error("Emissive texture loading failed"); |
| 1046 | } | |
| 1047 | } | |
| 1048 | } | |
| 1049 | ||
| 1050 | ! | vec4 DiffuseShaderTangent::vertex(int iface, int nthvert, ModelInfo& model) { |
| 1051 | ! | int global_face = model.index_offset + iface; |
| 1052 | ! | vec_varying_uv[global_face][nthvert] = model.tex(iface,nthvert); |
| 1053 | ! | vec_varying_nrm[global_face][nthvert] = vec3(uniform_MIT * vec4(model.normal(iface, nthvert),0.0f)); |
| 1054 | ! | vec_varying_pos[global_face][nthvert] = vec3(uniform_M * vec4(model.vertex(iface, nthvert),1.0f)); |
| 1055 | ! | vec_varying_world_nrm[global_face][nthvert] = vec3(uniform_MIT * vec4(model.normal(iface, nthvert),0.0f)); |
| 1056 | ||
| 1057 | ! | vec3 gl_Vertex = model.vertex(iface,nthvert); |
| 1058 | ||
| 1059 | ! | vec4 ndc = MVP * vec4(gl_Vertex, 1.0f); |
| 1060 | ! | vec_varying_ndc_tri[global_face][nthvert] = vec3(ndc/ndc.w); |
| 1061 | ! | vec4 clip = vp * MVP * vec4(gl_Vertex, 1.0f); |
| 1062 | ! | vec_varying_tri[global_face][nthvert] = clip; |
| 1063 | ||
| 1064 | ||
| 1065 | ! | return clip; |
| 1066 | } | |
| 1067 | ||
| 1068 | ! | bool DiffuseShaderTangent::fragment(vec3& bc, vec4 &color, vec3& pos, vec3& normal, int iface) { |
| 1069 | ! | vec3 uv = vec_varying_uv[iface][0] * bc.x + vec_varying_uv[iface][1] * bc.y + vec_varying_uv[iface][2] * bc.z; |
| 1070 | ! | vec4 diffuse_color = diffuse(uv); |
| 1071 | ! | if(diffuse_color.w == 0.0) return true; |
| 1072 | ||
| 1073 | ! | vec3 bn = normalize(vec_varying_nrm[iface][0] * bc.x + |
| 1074 | ! | vec_varying_nrm[iface][1] * bc.y + |
| 1075 | ! | vec_varying_nrm[iface][2] * bc.z); |
| 1076 | ||
| 1077 | ! | glm::mat3 A{(vec_varying_ndc_tri[iface][1] - vec_varying_ndc_tri[iface][0]), |
| 1078 | ! | (vec_varying_ndc_tri[iface][2] - vec_varying_ndc_tri[iface][0]),bn}; |
| 1079 | ! | glm::mat3 AI = inverse(transpose(A)); |
| 1080 | ! | vec3 i = AI * vec3(vec_varying_uv[iface][1].x - vec_varying_uv[iface][0].x, |
| 1081 | ! | vec_varying_uv[iface][2].x - vec_varying_uv[iface][0].x, 0.0f); |
| 1082 | ! | vec3 j = AI * vec3(vec_varying_uv[iface][1].y - vec_varying_uv[iface][0].y, |
| 1083 | ! | vec_varying_uv[iface][2].y - vec_varying_uv[iface][0].y, 0.0f); |
| 1084 | ! | glm::mat3 B = (glm::mat3{ normalize(i), normalize(j), bn }); |
| 1085 | ! | vec3 norm = normalize(B * normal_uv(uv)); |
| 1086 | ||
| 1087 | ! | vec3 light_color(0.0); |
| 1088 | ! | for(unsigned int ii = 0; ii < directional_lights.size(); ii++) { |
| 1089 | ! | vec4 trans_color(0.0,0.0,0.0,0.0); |
| 1090 | ||
| 1091 | ! | Float shadow = 1.0f; |
| 1092 | ! | Float intensity = std::fmax(dot(norm, vec3(uniform_M * vec4(directional_lights[ii].direction,0.0))),0.0); |
| 1093 | ! | if(has_shadow_map && intensity != 0.0) { |
| 1094 | ! | shadow = 0.0f; |
| 1095 | ||
| 1096 | ! | vec4 sb_p = directional_lights[ii].uniform_Mshadow_ * (vec_varying_tri[iface][0] * bc.x + vec_varying_tri[iface][1] * bc.y + vec_varying_tri[iface][2] * bc.z); |
| 1097 | ! | sb_p = sb_p/sb_p.w; |
| 1098 | ! | if(sb_p[0] >= 0 && sb_p[0] < shadowbuffers[ii].width() && sb_p[1] >= 0 && sb_p[1] < shadowbuffers[ii].height()) { |
| 1099 | ! | Float bias = std::fmax(shadow_map_bias*10.0 * (1.0 - intensity),shadow_map_bias); |
| 1100 | ||
| 1101 | ! | int i = int(sb_p[0]); |
| 1102 | ! | int j = int(sb_p[1]); |
| 1103 | ! | for(int x = -2; x <= 2; ++x) { |
| 1104 | ! | for(int y = -2; y <= 2; ++y) { |
| 1105 | ! | shadow += shadowbuffers[ii].get_color_bounded(i+x,j+y).x > sb_p[2]-bias ? 1.0f : shadowbuffers[ii].get_shadow_intensity(); |
| 1106 | } | |
| 1107 | } | |
| 1108 | ! | shadow /= 25; |
| 1109 | ! | if(diffuse_color.w == 1.0) { |
| 1110 | ! | for(int x = -2; x <= 2; ++x) { |
| 1111 | ! | for(int y = -2; y <= 2; ++y) { |
| 1112 | ! | trans_color += transparency_buffers[ii].get_color_bounded_a(i+x,j+y); |
| 1113 | } | |
| 1114 | } | |
| 1115 | ! | trans_color /= 25; |
| 1116 | } | |
| 1117 | } | |
| 1118 | } | |
| 1119 | ! | light_color += (vec3(trans_color) * trans_color.w * directional_lights[ii].intensity + |
| 1120 | ! | (1-trans_color.w) * directional_lights[ii].color * directional_lights[ii].intensity) * shadow * intensity; |
| 1121 | } | |
| 1122 | ! | pos = vec_varying_pos[iface][0] * bc.x + vec_varying_pos[iface][1] * bc.y + vec_varying_pos[iface][2] * bc.z; |
| 1123 | ||
| 1124 | ! | vec4 dir_shadow_int = vec4(light_color, 1.0f); |
| 1125 | //Directional light contribution | |
| 1126 | ! | color = diffuse_color * dir_shadow_int; |
| 1127 | ! | for(unsigned int i = 0; i < plights.size(); i++) { |
| 1128 | ! | vec3 p_light_dir = vec4(plights[i].CalcLightDir(pos),0.0f); |
| 1129 | ! | color += diffuse_color * vec4(plights[i].CalcPointLightAtten(pos),0.0f) * fmax(0.0f, dot(norm, p_light_dir)); |
| 1130 | } | |
| 1131 | ||
| 1132 | ||
| 1133 | //Emissive and ambient terms | |
| 1134 | ! | color += emissive(uv); |
| 1135 | ! | color += ambient(uv); |
| 1136 | ! | normal = norm; |
| 1137 | ! | if(has_reflection && !has_refraction) { |
| 1138 | ! | vec3 dir = uniform_M_inv * vec4(glm::normalize(pos),0.0f); |
| 1139 | ! | vec3 normal_w = uniform_MIT_inv * vec4(glm::normalize(normal),0.0f); |
| 1140 | ! | vec3 r = glm::reflect(dir,normal_w); |
| 1141 | ! | color = material.reflection_intensity * reflection(r) + (1-material.reflection_intensity) * color; |
| 1142 | } | |
| 1143 | ! | if(has_refraction) { |
| 1144 | ! | vec4 temp_col = diffuse_color; |
| 1145 | ! | vec3 dir = glm::normalize(uniform_M_inv * vec4(pos,0.0f)); |
| 1146 | ! | vec3 normal_w = glm::normalize(uniform_MIT_inv * vec4(normal,0.0f)); |
| 1147 | ! | vec3 rl = glm::reflect(dir,normal_w); |
| 1148 | ||
| 1149 | ! | vec3 rf = glm::refract(dir,normal_w, 1.0/material.ior); |
| 1150 | ! | vec4 reflect_col = reflection(rl); |
| 1151 | ! | vec4 refract_col = reflection(rf); |
| 1152 | ! | Float Ro = (material.ior - 1.0)/(material.ior + 1.0); |
| 1153 | ! | Ro = Ro * Ro; |
| 1154 | ! | Float c0 = 1.0-dot(dir,-normal_w); |
| 1155 | ! | Float c0_5 = c0*c0*c0*c0*c0; |
| 1156 | ! | Float reflect_coef = Ro + (1.0 - Ro) * c0_5; |
| 1157 | ! | color = (1-reflect_coef) * refract_col * temp_col + reflect_coef * reflect_col; |
| 1158 | ! | color.w = 1.0; |
| 1159 | } | |
| 1160 | ! | bc = uv; |
| 1161 | ! | return false; |
| 1162 | } | |
| 1163 | ||
| 1164 | ! | PhongShader::~PhongShader() { |
| 1165 | ! | if(has_texture) { |
| 1166 | ! | stbi_image_free(texture); |
| 1167 | } | |
| 1168 | ! | if(material.has_ambient_texture) { |
| 1169 | ! | stbi_image_free(ambient_texture); |
| 1170 | } | |
| 1171 | ! | if(has_normal_texture) { |
| 1172 | ! | stbi_image_free(normal_texture); |
| 1173 | } | |
| 1174 | ! | if(has_specular_texture) { |
| 1175 | ! | stbi_image_free(specular_texture); |
| 1176 | } | |
| 1177 | ! | if(has_emissive_texture) { |
| 1178 | ! | stbi_image_free(emissive_texture); |
| 1179 | } | |
| 1180 | } | |
| 1181 | ||
| 1182 | ! | PhongShader::PhongShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, |
| 1183 | bool has_shadow_map, Float shadow_map_bias, | |
| 1184 | material_info mat_info, std::vector<Light>& point_lights, | |
| 1185 | std::vector<DirectionalLight> directional_lights, | |
| 1186 | std::vector<rayimage>& shadowbuffers, | |
| 1187 | std::vector<rayimage>& transparency_buffers, | |
| 1188 | std::vector<vec3>& vec_varying_intensity, | |
| 1189 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 1190 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 1191 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 1192 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 1193 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 1194 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 1195 | ! | reflection_map_info reflection_map, bool has_reflection, bool has_refraction) : |
| 1196 | ! | Projection(Projection), View(View), viewport(viewport), |
| 1197 | ! | has_shadow_map(has_shadow_map), |
| 1198 | ! | shadow_map_bias(shadow_map_bias), material(mat_info), plights(point_lights), |
| 1199 | ! | directional_lights(directional_lights), shadowbuffers(shadowbuffers), transparency_buffers(transparency_buffers), |
| 1200 | ! | vec_varying_intensity(vec_varying_intensity), vec_varying_uv(vec_varying_uv), |
| 1201 | ! | vec_varying_tri(vec_varying_tri), |
| 1202 | ! | vec_varying_nrm(vec_varying_nrm), vec_varying_pos(vec_varying_pos), |
| 1203 | ! | vec_varying_world_nrm(vec_varying_world_nrm), |
| 1204 | ! | reflection_map(reflection_map), has_reflection(has_reflection), has_refraction(has_refraction) { |
| 1205 | ! | MVP = Projection * View * Model; |
| 1206 | ! | vp = glm::scale(glm::translate(Mat(1.0f), |
| 1207 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)), |
| 1208 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)); |
| 1209 | ||
| 1210 | ! | has_texture = has_normal_texture = has_specular_texture = has_emissive_texture = false; |
| 1211 | ! | if(material.has_texture) { |
| 1212 | ! | has_texture = true; |
| 1213 | ! | texture = stbi_loadf(material.diffuse_texname.get_cstring(), &nx_t, &ny_t, &nn_t, 0); |
| 1214 | ! | if(nx_t == 0 || ny_t == 0 || nn_t == 0) { |
| 1215 | ! | throw std::runtime_error("Texture loading failed"); |
| 1216 | } | |
| 1217 | } | |
| 1218 | ! | if(material.has_ambient_texture) { |
| 1219 | ! | ambient_texture = stbi_loadf(material.ambient_texname.get_cstring(), &nx_a, &ny_a, &nn_a, 0); |
| 1220 | ! | if(nx_a == 0 || ny_a == 0 || nn_a == 0) { |
| 1221 | ! | throw std::runtime_error("Ambient Texture loading failed"); |
| 1222 | } | |
| 1223 | } | |
| 1224 | ! | if(material.has_normal_texture) { |
| 1225 | ! | has_normal_texture = true; |
| 1226 | ! | normal_texture = stbi_loadf(material.normal_texname.get_cstring(), &nx_nt, &ny_nt, &nn_nt, 0); |
| 1227 | ! | if(nx_nt == 0 || ny_nt == 0 || nn_nt == 0) { |
| 1228 | ! | throw std::runtime_error("Normal texture loading failed"); |
| 1229 | } | |
| 1230 | } | |
| 1231 | ! | if(material.has_specular_texture) { |
| 1232 | ! | has_specular_texture = true; |
| 1233 | ! | specular_texture = stbi_loadf(material.specular_texname.get_cstring(), |
| 1234 | &nx_st, &ny_st, &nn_st, 0); | |
| 1235 | ! | if(nx_st == 0 || ny_st == 0 || nn_st == 0) { |
| 1236 | ! | throw std::runtime_error("Specular texture loading failed"); |
| 1237 | } | |
| 1238 | } | |
| 1239 | ! | if(material.has_emissive_texture) { |
| 1240 | ! | has_emissive_texture = true; |
| 1241 | ! | emissive_texture = stbi_loadf(material.emissive_texname.get_cstring(), |
| 1242 | &nx_et, &ny_et, &nn_et, 0); | |
| 1243 | ! | if(nx_et == 0 || ny_et == 0 || nn_et == 0) { |
| 1244 | ! | throw std::runtime_error("Emissive texture loading failed"); |
| 1245 | } | |
| 1246 | } | |
| 1247 | ! | uniform_M = View * Model; |
| 1248 | ! | uniform_MIT = glm::inverse(glm::transpose(uniform_M)); |
| 1249 | ! | uniform_M_inv = glm::inverse(uniform_M); |
| 1250 | ! | uniform_MIT_inv = glm::inverse(uniform_MIT); |
| 1251 | } | |
| 1252 | ||
| 1253 | ! | vec4 PhongShader::vertex(int iface, int nthvert, ModelInfo& model) { |
| 1254 | ! | int global_face = model.index_offset + iface; |
| 1255 | ! | vec_varying_uv[global_face][nthvert] = model.tex(iface,nthvert); |
| 1256 | ! | vec_varying_pos[global_face][nthvert] = uniform_M * vec4(model.vertex(iface, nthvert),1.0f); |
| 1257 | ! | vec4 clip = vp * MVP * vec4(model.vertex(iface,nthvert),1.0f); |
| 1258 | ! | vec_varying_tri[global_face][nthvert] = clip; |
| 1259 | ||
| 1260 | ! | vec_varying_world_nrm[global_face][nthvert] = model.model_vertex_normals(iface) ? |
| 1261 | ! | uniform_MIT * normalize(vec4(model.normal(iface, nthvert),0.0f)) : |
| 1262 | ! | uniform_MIT * normalize(vec4(glm::cross(model.vertex(iface,1)-model.vertex(iface,0), |
| 1263 | ! | model.vertex(iface,2)-model.vertex(iface,0)),0.0f)); |
| 1264 | ||
| 1265 | ! | return clip; |
| 1266 | } | |
| 1267 | ||
| 1268 | ! | bool PhongShader::fragment(vec3& bc, vec4 &color, vec3& pos, vec3& normal, int iface) { |
| 1269 | ! | vec3 uv = vec_varying_uv[iface][0] * bc.x + vec_varying_uv[iface][1] * bc.y + vec_varying_uv[iface][2] * bc.z; |
| 1270 | ! | vec4 diffuse_color = diffuse(uv); |
| 1271 | ! | if(diffuse_color.w == 0.0) return true; |
| 1272 | ! | normal = (vec_varying_world_nrm[iface][0] * bc.x + vec_varying_world_nrm[iface][1] * bc.y + vec_varying_world_nrm[iface][2] * bc.z); |
| 1273 | ||
| 1274 | ! | vec3 spec_uv = specular(uv); |
| 1275 | ! | vec3 light_color(0.0); |
| 1276 | ! | vec4 spec_total(0.0); |
| 1277 | ! | for(unsigned int ii = 0; ii < directional_lights.size(); ii++) { |
| 1278 | ! | vec4 trans_color(0.0,0.0,0.0,0.0); |
| 1279 | ||
| 1280 | ! | Float shadow = 1.0f; |
| 1281 | ! | vec3 l_dir = vec3(uniform_M * vec4(directional_lights[ii].direction, 0.0)); |
| 1282 | ! | Float intensity = std::fmax(dot(normal, l_dir),0.0); |
| 1283 | ! | Float shadow_int = shadowbuffers[ii].get_shadow_intensity(); |
| 1284 | ! | if(has_shadow_map && intensity != 0.0) { |
| 1285 | ! | shadow = 0.0f; |
| 1286 | ! | vec4 sb_p = directional_lights[ii].uniform_Mshadow_ * (vec_varying_tri[iface][0] * bc.x + vec_varying_tri[iface][1] * bc.y + vec_varying_tri[iface][2] * bc.z); |
| 1287 | ! | sb_p = sb_p/sb_p.w; |
| 1288 | ! | if(sb_p[0] >= 0 && sb_p[0] < shadowbuffers[ii].width() && sb_p[1] >= 0 && sb_p[1] < shadowbuffers[ii].height()) { |
| 1289 | ! | Float bias = std::fmax(shadow_map_bias*10.0 * (1.0 - intensity),shadow_map_bias); |
| 1290 | ||
| 1291 | ! | int i = int(sb_p[0]); |
| 1292 | ! | int j = int(sb_p[1]); |
| 1293 | ! | for(int x = -2; x <= 2; ++x) { |
| 1294 | ! | for(int y = -2; y <= 2; ++y) { |
| 1295 | ! | shadow += shadowbuffers[ii].get_color_bounded(i+x,j+y).x > sb_p[2]-bias ? 1.0 : shadow_int; |
| 1296 | } | |
| 1297 | } | |
| 1298 | ! | shadow /= 25; |
| 1299 | ! | if(diffuse_color.w == 1.0) { |
| 1300 | ! | for(int x = -2; x <= 2; ++x) { |
| 1301 | ! | for(int y = -2; y <= 2; ++y) { |
| 1302 | ! | trans_color += transparency_buffers[ii].get_color_bounded_a(i+x,j+y); |
| 1303 | } | |
| 1304 | } | |
| 1305 | ! | trans_color /= 25; |
| 1306 | } | |
| 1307 | } | |
| 1308 | } | |
| 1309 | ! | light_color += (vec3(trans_color) * trans_color.w * directional_lights[ii].intensity + |
| 1310 | ! | (1-trans_color.w) * directional_lights[ii].color * directional_lights[ii].intensity) * shadow * intensity; |
| 1311 | ! | vec3 r = normalize(2.0f*dot(normal,l_dir)*normal - l_dir); |
| 1312 | ! | spec_total += vec4(spec_uv * std::pow(std::fmax(r.z, 0.0f), material.shininess),0.0f) * (shadow) * directional_lights[ii].intensity; |
| 1313 | } | |
| 1314 | ! | pos = vec_varying_pos[iface][0] * bc.x + vec_varying_pos[iface][1] * bc.y + vec_varying_pos[iface][2] * bc.z; |
| 1315 | ||
| 1316 | ! | vec4 amb = ambient(uv); |
| 1317 | ! | vec4 emit = emissive(uv); |
| 1318 | ! | vec4 shadow_vec = vec4(light_color,1.0f); |
| 1319 | ! | color = clamp( diffuse_color*shadow_vec + spec_total,(Float)0.0,(Float)1.0); |
| 1320 | ||
| 1321 | ! | for(unsigned int i = 0; i < plights.size(); i++) { |
| 1322 | ! | vec3 l_p = vec4(plights[i].CalcLightDir(pos),0.0f); |
| 1323 | ! | vec3 r = normalize(2.0f*dot(normal,l_p)*normal - l_p); |
| 1324 | ! | vec4 spec = vec4(spec_uv * std::pow(std::fmax(r.z, 0.0f), material.shininess),0.0f); |
| 1325 | ! | color += clamp(diffuse_color * vec4(plights[i].CalcPointLightAtten(pos),(Float)0.0) * fmax(0.0f, dot(normal, l_p)) + |
| 1326 | ! | vec4(plights[i].CalcPointLightAtten(pos),0.0f) * spec, (Float)0.0,(Float)1.0); |
| 1327 | } | |
| 1328 | ! | color += amb; |
| 1329 | ! | color += emit; |
| 1330 | ! | if(has_reflection && !has_refraction) { |
| 1331 | ! | vec3 dir = uniform_M_inv * vec4(glm::normalize(pos),0.0f); |
| 1332 | ! | vec3 normal_w = uniform_MIT_inv * vec4(glm::normalize(normal),0.0f); |
| 1333 | ! | vec3 r = glm::reflect(dir,normal_w); |
| 1334 | ! | color = material.reflection_intensity * reflection(r) + (1-material.reflection_intensity) * color; |
| 1335 | } | |
| 1336 | ! | if(has_refraction) { |
| 1337 | ! | vec4 temp_col = diffuse_color; |
| 1338 | ! | vec3 dir = glm::normalize(uniform_M_inv * vec4(pos,0.0f)); |
| 1339 | ! | vec3 normal_w = glm::normalize(uniform_MIT_inv * vec4(normal,0.0f)); |
| 1340 | ! | vec3 rl = glm::reflect(dir,normal_w); |
| 1341 | ||
| 1342 | ! | vec3 rf = glm::refract(dir,normal_w, 1.0/material.ior); |
| 1343 | ! | vec4 reflect_col = reflection(rl); |
| 1344 | ! | vec4 refract_col = reflection(rf); |
| 1345 | ! | Float Ro = (material.ior - 1.0)/(material.ior + 1.0); |
| 1346 | ! | Ro = Ro * Ro; |
| 1347 | ! | Float c0 = 1.0-dot(dir,-normal_w); |
| 1348 | ! | Float c0_5 = c0*c0*c0*c0*c0; |
| 1349 | ! | Float reflect_coef = Ro + (1.0 - Ro) * c0_5; |
| 1350 | ! | color = (1-reflect_coef) * refract_col * temp_col + reflect_coef * reflect_col; |
| 1351 | ! | color.w = 1.0; |
| 1352 | } | |
| 1353 | ! | bc = uv; |
| 1354 | ! | return false; |
| 1355 | } | |
| 1356 | ||
| 1357 | ! | PhongNormalShader::~PhongNormalShader() { |
| 1358 | ! | if(has_texture) { |
| 1359 | ! | stbi_image_free(texture); |
| 1360 | } | |
| 1361 | ! | if(material.has_ambient_texture) { |
| 1362 | ! | stbi_image_free(ambient_texture); |
| 1363 | } | |
| 1364 | ! | if(has_normal_texture) { |
| 1365 | ! | stbi_image_free(normal_texture); |
| 1366 | } | |
| 1367 | ! | if(has_specular_texture) { |
| 1368 | ! | stbi_image_free(specular_texture); |
| 1369 | } | |
| 1370 | ! | if(has_emissive_texture) { |
| 1371 | ! | stbi_image_free(emissive_texture); |
| 1372 | } | |
| 1373 | } | |
| 1374 | ||
| 1375 | ! | PhongNormalShader::PhongNormalShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, |
| 1376 | bool has_shadow_map, Float shadow_map_bias, | |
| 1377 | material_info mat_info, std::vector<Light>& point_lights, | |
| 1378 | std::vector<DirectionalLight> directional_lights, | |
| 1379 | std::vector<rayimage>& shadowbuffers, | |
| 1380 | std::vector<rayimage>& transparency_buffers, | |
| 1381 | std::vector<vec3>& vec_varying_intensity, | |
| 1382 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 1383 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 1384 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 1385 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 1386 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 1387 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 1388 | ! | reflection_map_info reflection_map, bool has_reflection, bool has_refraction) : |
| 1389 | ! | Projection(Projection), View(View), viewport(viewport), |
| 1390 | ! | has_shadow_map(has_shadow_map), |
| 1391 | ! | shadow_map_bias(shadow_map_bias), material(mat_info), plights(point_lights), |
| 1392 | ! | directional_lights(directional_lights), shadowbuffers(shadowbuffers), transparency_buffers(transparency_buffers), |
| 1393 | ! | vec_varying_uv(vec_varying_uv), |
| 1394 | ! | vec_varying_tri(vec_varying_tri), vec_varying_pos(vec_varying_pos), vec_varying_world_nrm(vec_varying_world_nrm), |
| 1395 | ! | reflection_map(reflection_map), has_reflection(has_reflection), has_refraction(has_refraction) { |
| 1396 | ! | MVP = Projection * View * Model; |
| 1397 | ! | vp = glm::scale(glm::translate(Mat(1.0f), |
| 1398 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)), |
| 1399 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)); |
| 1400 | ! | uniform_M = View * Model; |
| 1401 | ! | uniform_MIT = glm::transpose(glm::inverse(uniform_M)); |
| 1402 | ! | uniform_M_inv = glm::inverse(uniform_M); |
| 1403 | ! | uniform_MIT_inv = glm::inverse(uniform_MIT); |
| 1404 | ||
| 1405 | ! | has_texture = has_normal_texture = has_specular_texture = has_emissive_texture = false; |
| 1406 | ! | if(material.has_texture) { |
| 1407 | ! | has_texture = true; |
| 1408 | ! | texture = stbi_loadf(material.diffuse_texname.get_cstring(), &nx_t, &ny_t, &nn_t, 0); |
| 1409 | ! | if(nx_t == 0 || ny_t == 0 || nn_t == 0) { |
| 1410 | ! | throw std::runtime_error("Texture loading failed"); |
| 1411 | } | |
| 1412 | } | |
| 1413 | ! | if(material.has_ambient_texture) { |
| 1414 | ! | ambient_texture = stbi_loadf(material.ambient_texname.get_cstring(), &nx_a, &ny_a, &nn_a, 0); |
| 1415 | ! | if(nx_a == 0 || ny_a == 0 || nn_a == 0) { |
| 1416 | ! | throw std::runtime_error("Ambient Texture loading failed"); |
| 1417 | } | |
| 1418 | } | |
| 1419 | ! | if(material.has_normal_texture) { |
| 1420 | ! | has_normal_texture = true; |
| 1421 | ! | normal_texture = stbi_loadf(material.normal_texname.get_cstring(), &nx_nt, &ny_nt, &nn_nt, 0); |
| 1422 | ! | if(nx_nt == 0 || ny_nt == 0 || nn_nt == 0) { |
| 1423 | ! | throw std::runtime_error("Normal texture loading failed"); |
| 1424 | } | |
| 1425 | } | |
| 1426 | ! | if(material.has_specular_texture) { |
| 1427 | ! | has_specular_texture = true; |
| 1428 | ! | specular_texture = stbi_loadf(material.specular_texname.get_cstring(), |
| 1429 | &nx_st, &ny_st, &nn_st, 0); | |
| 1430 | ! | if(nx_st == 0 || ny_st == 0 || nn_st == 0) { |
| 1431 | ! | throw std::runtime_error("Specular texture loading failed"); |
| 1432 | } | |
| 1433 | } | |
| 1434 | ! | if(material.has_emissive_texture) { |
| 1435 | ! | has_emissive_texture = true; |
| 1436 | ! | emissive_texture = stbi_loadf(material.emissive_texname.get_cstring(), |
| 1437 | &nx_et, &ny_et, &nn_et, 0); | |
| 1438 | ! | if(nx_et == 0 || ny_et == 0 || nn_et == 0) { |
| 1439 | ! | throw std::runtime_error("Emissive texture loading failed"); |
| 1440 | } | |
| 1441 | } | |
| 1442 | } | |
| 1443 | ||
| 1444 | ! | vec4 PhongNormalShader::vertex(int iface, int nthvert, ModelInfo& model) { |
| 1445 | ! | int global_face = model.index_offset + iface; |
| 1446 | ! | vec_varying_uv[global_face][nthvert] = model.tex(iface,nthvert); |
| 1447 | ! | vec_varying_pos[global_face][nthvert] = vec3(View * Model * vec4(model.vertex(iface, nthvert),1.0f)); |
| 1448 | ! | vec_varying_world_nrm[global_face][nthvert] = vec3(uniform_MIT * vec4(model.normal(iface, nthvert),0.0f)); |
| 1449 | ||
| 1450 | ! | vec3 gl_Vertex = model.vertex(iface,nthvert); |
| 1451 | ! | vec4 clip = vp * MVP * vec4(gl_Vertex, 1.0f); |
| 1452 | ! | vec_varying_tri[global_face][nthvert] = clip; |
| 1453 | ||
| 1454 | ||
| 1455 | ! | return clip; |
| 1456 | } | |
| 1457 | ||
| 1458 | ! | bool PhongNormalShader::fragment(vec3& bc, vec4 &color, vec3& pos, vec3& normal, int iface) { |
| 1459 | ! | vec3 uv = vec_varying_uv[iface][0] * bc.x + vec_varying_uv[iface][1] * bc.y + vec_varying_uv[iface][2] * bc.z; |
| 1460 | ! | vec4 diffuse_color = diffuse(uv); |
| 1461 | ! | if(diffuse_color.w == 0.0) return true; |
| 1462 | ! | normal = normalize(vec3(uniform_MIT * vec4(normal_uv(uv),0.0f))); |
| 1463 | ||
| 1464 | ! | vec3 spec_uv = specular(uv); |
| 1465 | ! | vec3 light_color(0.0); |
| 1466 | ! | vec4 spec_total(0.0); |
| 1467 | ! | for(unsigned int ii = 0; ii < directional_lights.size(); ii++) { |
| 1468 | ! | vec4 trans_color(0.0,0.0,0.0,0.0); |
| 1469 | ||
| 1470 | ! | Float shadow = 1.0f; |
| 1471 | ! | vec3 l_dir = vec3(uniform_M * vec4(directional_lights[ii].direction, 0.0)); |
| 1472 | ! | Float intensity = std::fmax(dot(normal, l_dir),0.0); |
| 1473 | ! | Float shadow_int = shadowbuffers[ii].get_shadow_intensity(); |
| 1474 | ! | if(has_shadow_map && intensity != 0.0) { |
| 1475 | ! | shadow = 0.0f; |
| 1476 | ! | vec4 sb_p = directional_lights[ii].uniform_Mshadow_ * (vec_varying_tri[iface][0] * bc.x + vec_varying_tri[iface][1] * bc.y + vec_varying_tri[iface][2] * bc.z); |
| 1477 | ! | sb_p = sb_p/sb_p.w; |
| 1478 | ! | if(sb_p[0] >= 0 && sb_p[0] < shadowbuffers[ii].width() && sb_p[1] >= 0 && sb_p[1] < shadowbuffers[ii].height()) { |
| 1479 | ! | Float bias = std::fmax(shadow_map_bias*10.0 * (1.0 - intensity),shadow_map_bias); |
| 1480 | ||
| 1481 | ! | int i = int(sb_p[0]); |
| 1482 | ! | int j = int(sb_p[1]); |
| 1483 | ! | for(int x = -2; x <= 2; ++x) { |
| 1484 | ! | for(int y = -2; y <= 2; ++y) { |
| 1485 | ! | shadow += shadowbuffers[ii].get_color_bounded(i+x,j+y).x > sb_p[2]-bias ? 1.0 : shadow_int; |
| 1486 | } | |
| 1487 | } | |
| 1488 | ! | shadow /= 25; |
| 1489 | ! | if(diffuse_color.w == 1.0) { |
| 1490 | ! | for(int x = -2; x <= 2; ++x) { |
| 1491 | ! | for(int y = -2; y <= 2; ++y) { |
| 1492 | ! | trans_color += transparency_buffers[ii].get_color_bounded_a(i+x,j+y); |
| 1493 | } | |
| 1494 | } | |
| 1495 | ! | trans_color /= 25; |
| 1496 | } | |
| 1497 | } | |
| 1498 | } | |
| 1499 | ! | light_color += (vec3(trans_color) * trans_color.w * directional_lights[ii].intensity + |
| 1500 | ! | (1-trans_color.w) * directional_lights[ii].color * directional_lights[ii].intensity) * shadow * intensity; |
| 1501 | ! | vec3 r = normalize(2.0f*dot(normal,l_dir)*normal - l_dir); |
| 1502 | ! | spec_total += vec4(spec_uv * std::pow(std::fmax(r.z, 0.0f), material.shininess),0.0f) * (shadow) * directional_lights[ii].intensity; |
| 1503 | } | |
| 1504 | ! | pos = vec_varying_pos[iface][0] * bc.x + vec_varying_pos[iface][1] * bc.y + vec_varying_pos[iface][2] * bc.z; |
| 1505 | ||
| 1506 | ! | vec3 ambient = material.ambient; |
| 1507 | ! | vec4 emit = emissive(uv); |
| 1508 | ! | vec4 shadow_vec = vec4(light_color,1.0f); |
| 1509 | ! | color = clamp( diffuse_color*shadow_vec + spec_total,(Float)0.0,(Float)1.0); |
| 1510 | ||
| 1511 | ||
| 1512 | ! | for(unsigned int i = 0; i < plights.size(); i++) { |
| 1513 | ! | vec3 l_p = vec4(plights[i].CalcLightDir(pos),0.0f); |
| 1514 | ! | vec3 r = normalize(2.0f*dot(normal,l_p)*normal - l_p); |
| 1515 | ! | vec4 spec = vec4(spec_uv * std::pow(std::fmax(r.z, 0.0f), material.shininess),0.0f); |
| 1516 | ! | color += clamp(diffuse_color * vec4(plights[i].CalcPointLightAtten(pos),(Float)0.0) * fmax(0.0f, dot(normal, l_p)) + |
| 1517 | ! | vec4(plights[i].CalcPointLightAtten(pos),0.0f) * spec, (Float)0.0,(Float)1.0); |
| 1518 | } | |
| 1519 | ! | color += vec4(ambient,0.0f); |
| 1520 | ! | color += emit; |
| 1521 | ! | if(has_reflection && !has_refraction) { |
| 1522 | ! | vec3 dir = uniform_M_inv * vec4(glm::normalize(pos),0.0f); |
| 1523 | ! | vec3 normal_w = uniform_MIT_inv * vec4(glm::normalize(normal),0.0f); |
| 1524 | ! | vec3 r = glm::reflect(dir,normal_w); |
| 1525 | ! | color = material.reflection_intensity * reflection(r) + (1-material.reflection_intensity) * color; |
| 1526 | } | |
| 1527 | ! | if(has_refraction) { |
| 1528 | ! | vec4 temp_col = diffuse_color; |
| 1529 | ! | vec3 dir = glm::normalize(uniform_M_inv * vec4(pos,0.0f)); |
| 1530 | ! | vec3 normal_w = glm::normalize(uniform_MIT_inv * vec4(normal,0.0f)); |
| 1531 | ! | vec3 rl = glm::reflect(dir,normal_w); |
| 1532 | ||
| 1533 | ! | vec3 rf = glm::refract(dir,normal_w, 1.0/material.ior); |
| 1534 | ! | vec4 reflect_col = reflection(rl); |
| 1535 | ! | vec4 refract_col = reflection(rf); |
| 1536 | ! | Float Ro = (material.ior - 1.0)/(material.ior + 1.0); |
| 1537 | ! | Ro = Ro * Ro; |
| 1538 | ! | Float c0 = 1.0-dot(dir,-normal_w); |
| 1539 | ! | Float c0_5 = c0*c0*c0*c0*c0; |
| 1540 | ! | Float reflect_coef = Ro + (1.0 - Ro) * c0_5; |
| 1541 | ! | color = (1-reflect_coef) * refract_col * temp_col + reflect_coef * reflect_col; |
| 1542 | ! | color.w = 1.0; |
| 1543 | } | |
| 1544 | ! | bc = uv; |
| 1545 | ! | return false; |
| 1546 | } | |
| 1547 | ||
| 1548 | ! | PhongShaderTangent::~PhongShaderTangent() { |
| 1549 | ! | if(has_texture) { |
| 1550 | ! | stbi_image_free(texture); |
| 1551 | } | |
| 1552 | ! | if(material.has_ambient_texture) { |
| 1553 | ! | stbi_image_free(ambient_texture); |
| 1554 | } | |
| 1555 | ! | if(has_normal_texture) { |
| 1556 | ! | stbi_image_free(normal_texture); |
| 1557 | } | |
| 1558 | ! | if(has_specular_texture) { |
| 1559 | ! | stbi_image_free(specular_texture); |
| 1560 | } | |
| 1561 | ! | if(has_emissive_texture) { |
| 1562 | ! | stbi_image_free(emissive_texture); |
| 1563 | } | |
| 1564 | } | |
| 1565 | ||
| 1566 | ! | PhongShaderTangent::PhongShaderTangent(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, |
| 1567 | ||
| 1568 | bool has_shadow_map, Float shadow_map_bias, | |
| 1569 | material_info mat_info, std::vector<Light>& point_lights, | |
| 1570 | std::vector<DirectionalLight> directional_lights, | |
| 1571 | std::vector<rayimage>& shadowbuffers, | |
| 1572 | std::vector<rayimage>& transparency_buffers, | |
| 1573 | std::vector<vec3>& vec_varying_intensity, | |
| 1574 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 1575 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 1576 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 1577 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 1578 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 1579 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 1580 | ! | reflection_map_info reflection_map, bool has_reflection, bool has_refraction) : |
| 1581 | ! | Projection(Projection), View(View), viewport(viewport), |
| 1582 | ! | has_shadow_map(has_shadow_map), |
| 1583 | ! | shadow_map_bias(shadow_map_bias), material(mat_info), plights(point_lights), |
| 1584 | ! | directional_lights(directional_lights), shadowbuffers(shadowbuffers), transparency_buffers(transparency_buffers), |
| 1585 | ! | vec_varying_uv(vec_varying_uv), |
| 1586 | ! | vec_varying_tri(vec_varying_tri), vec_varying_pos(vec_varying_pos), |
| 1587 | ! | vec_varying_ndc_tri(vec_varying_ndc_tri), vec_varying_world_nrm(vec_varying_world_nrm), |
| 1588 | ! | vec_varying_nrm(vec_varying_nrm), |
| 1589 | ! | reflection_map(reflection_map), has_reflection(has_reflection), has_refraction(has_refraction) { |
| 1590 | ! | MVP = Projection * View * Model; |
| 1591 | ! | vp = glm::scale(glm::translate(Mat(1.0f), |
| 1592 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)), |
| 1593 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)); |
| 1594 | ! | uniform_M = View * Model; |
| 1595 | ! | uniform_MIT = glm::inverseTranspose(uniform_M); |
| 1596 | ! | uniform_M_inv = glm::inverse(uniform_M); |
| 1597 | ! | uniform_MIT_inv = glm::inverse(uniform_MIT); |
| 1598 | ||
| 1599 | ! | has_texture = has_normal_texture = has_specular_texture = has_emissive_texture = false; |
| 1600 | ! | if(material.has_texture) { |
| 1601 | ! | has_texture = true; |
| 1602 | ! | texture = stbi_loadf(material.diffuse_texname.get_cstring(), &nx_t, &ny_t, &nn_t, 0); |
| 1603 | ! | if(nx_t == 0 || ny_t == 0 || nn_t == 0) { |
| 1604 | ! | throw std::runtime_error("Texture loading failed"); |
| 1605 | } | |
| 1606 | } | |
| 1607 | ! | if(material.has_ambient_texture) { |
| 1608 | ! | ambient_texture = stbi_loadf(material.ambient_texname.get_cstring(), &nx_a, &ny_a, &nn_a, 0); |
| 1609 | ! | if(nx_a == 0 || ny_a == 0 || nn_a == 0) { |
| 1610 | ! | throw std::runtime_error("Ambient Texture loading failed"); |
| 1611 | } | |
| 1612 | } | |
| 1613 | ! | if(material.has_normal_texture) { |
| 1614 | ! | has_normal_texture = true; |
| 1615 | ! | normal_texture = stbi_loadf(material.normal_texname.get_cstring(), &nx_nt, &ny_nt, &nn_nt, 0); |
| 1616 | ! | if(nx_nt == 0 || ny_nt == 0 || nn_nt == 0) { |
| 1617 | ! | throw std::runtime_error("Normal texture loading failed"); |
| 1618 | } | |
| 1619 | } | |
| 1620 | ! | if(material.has_specular_texture) { |
| 1621 | ! | has_specular_texture = true; |
| 1622 | ! | specular_texture = stbi_loadf(material.specular_texname.get_cstring(), |
| 1623 | &nx_st, &ny_st, &nn_st, 0); | |
| 1624 | ! | if(nx_st == 0 || ny_st == 0 || nn_st == 0) { |
| 1625 | ! | throw std::runtime_error("Specular texture loading failed"); |
| 1626 | } | |
| 1627 | } | |
| 1628 | ! | if(material.has_emissive_texture) { |
| 1629 | ! | has_emissive_texture = true; |
| 1630 | ! | emissive_texture = stbi_loadf(material.emissive_texname.get_cstring(), |
| 1631 | &nx_et, &ny_et, &nn_et, 0); | |
| 1632 | ! | if(nx_et == 0 || ny_et == 0 || nn_et == 0) { |
| 1633 | ! | throw std::runtime_error("Emissive texture loading failed"); |
| 1634 | } | |
| 1635 | } | |
| 1636 | } | |
| 1637 | ||
| 1638 | ! | vec4 PhongShaderTangent::vertex(int iface, int nthvert, ModelInfo& model) { |
| 1639 | ! | int global_face = model.index_offset + iface; |
| 1640 | ! | vec_varying_uv[global_face][nthvert] = model.tex(iface,nthvert); |
| 1641 | ! | vec_varying_nrm[global_face][nthvert] = vec3(uniform_MIT * vec4(model.normal(iface, nthvert),0.0f)); |
| 1642 | ! | vec_varying_pos[global_face][nthvert] = vec3(uniform_M * vec4(model.vertex(iface, nthvert),1.0f)); |
| 1643 | ! | vec_varying_world_nrm[global_face][nthvert] = vec3(uniform_MIT * vec4(model.normal(iface, nthvert),0.0f)); |
| 1644 | ||
| 1645 | ! | vec3 gl_Vertex = model.vertex(iface,nthvert); |
| 1646 | ! | vec4 clip = MVP * vec4(gl_Vertex,1.0f); |
| 1647 | ! | vec_varying_ndc_tri[global_face][nthvert] = clip/clip.w; |
| 1648 | ! | clip = vp * clip; |
| 1649 | ! | vec_varying_tri[global_face][nthvert] = clip; |
| 1650 | ||
| 1651 | ||
| 1652 | ! | return clip; |
| 1653 | } | |
| 1654 | ||
| 1655 | ! | bool PhongShaderTangent::fragment(vec3& bc, vec4 &color, vec3& pos, vec3& normal, int iface) { |
| 1656 | ! | vec3 uv = vec_varying_uv[iface][0] * bc.x + vec_varying_uv[iface][1] * bc.y + vec_varying_uv[iface][2] * bc.z; |
| 1657 | ! | vec4 diffuse_color = diffuse(uv); |
| 1658 | ! | if(diffuse_color.w == 0.0) return true; |
| 1659 | ||
| 1660 | ! | vec3 bn = (vec_varying_nrm[iface][0] * bc.x + |
| 1661 | ! | vec_varying_nrm[iface][1] * bc.y + |
| 1662 | ! | vec_varying_nrm[iface][2] * bc.z); |
| 1663 | ||
| 1664 | ! | glm::mat3 A{(vec_varying_ndc_tri[iface][1] - vec_varying_ndc_tri[iface][0]), |
| 1665 | ! | (vec_varying_ndc_tri[iface][2] - vec_varying_ndc_tri[iface][0]),bn}; |
| 1666 | ! | glm::mat3 AI = inverse(transpose(A)); |
| 1667 | ! | vec3 i = AI * vec3(vec_varying_uv[iface][1].x - vec_varying_uv[iface][0].x, |
| 1668 | ! | vec_varying_uv[iface][2].x - vec_varying_uv[iface][0].x, 0.0f); |
| 1669 | ! | vec3 j = AI * vec3(vec_varying_uv[iface][1].y - vec_varying_uv[iface][0].y, |
| 1670 | ! | vec_varying_uv[iface][2].y - vec_varying_uv[iface][0].y, 0.0f); |
| 1671 | ! | glm::mat3 B = (glm::mat3{ normalize(i), normalize(j), bn }); |
| 1672 | ! | normal = normalize(B * normal_uv(uv)); |
| 1673 | ||
| 1674 | ! | vec3 spec_uv = specular(uv); |
| 1675 | ! | vec3 light_color(0.0); |
| 1676 | ! | vec4 spec_total(0.0); |
| 1677 | ! | for(unsigned int ii = 0; ii < directional_lights.size(); ii++) { |
| 1678 | ! | vec4 trans_color(0.0,0.0,0.0,0.0); |
| 1679 | ||
| 1680 | ! | Float shadow = 1.0f; |
| 1681 | ! | vec3 l_dir = vec3(uniform_M * vec4(directional_lights[ii].direction, 0.0)); |
| 1682 | ! | Float intensity = std::fmax(dot(normal, l_dir),0.0); |
| 1683 | ! | Float shadow_int = shadowbuffers[ii].get_shadow_intensity(); |
| 1684 | ! | if(has_shadow_map && intensity != 0.0) { |
| 1685 | ! | shadow = 0.0f; |
| 1686 | ! | vec4 sb_p = directional_lights[ii].uniform_Mshadow_ * (vec_varying_tri[iface][0] * bc.x + vec_varying_tri[iface][1] * bc.y + vec_varying_tri[iface][2] * bc.z); |
| 1687 | ! | sb_p = sb_p/sb_p.w; |
| 1688 | ! | if(sb_p[0] >= 0 && sb_p[0] < shadowbuffers[ii].width() && sb_p[1] >= 0 && sb_p[1] < shadowbuffers[ii].height()) { |
| 1689 | ! | Float bias = std::fmax(shadow_map_bias*10.0 * (1.0 - intensity),shadow_map_bias); |
| 1690 | ||
| 1691 | ! | int i = int(sb_p[0]); |
| 1692 | ! | int j = int(sb_p[1]); |
| 1693 | ! | for(int x = -2; x <= 2; ++x) { |
| 1694 | ! | for(int y = -2; y <= 2; ++y) { |
| 1695 | ! | shadow += shadowbuffers[ii].get_color_bounded(i+x,j+y).x > sb_p[2]-bias ? 1.0 : shadow_int; |
| 1696 | } | |
| 1697 | } | |
| 1698 | ! | shadow /= 25; |
| 1699 | ! | if(diffuse_color.w == 1.0) { |
| 1700 | ! | for(int x = -2; x <= 2; ++x) { |
| 1701 | ! | for(int y = -2; y <= 2; ++y) { |
| 1702 | ! | trans_color += transparency_buffers[ii].get_color_bounded_a(i+x,j+y); |
| 1703 | } | |
| 1704 | } | |
| 1705 | ! | trans_color /= 25; |
| 1706 | } | |
| 1707 | } | |
| 1708 | } | |
| 1709 | ! | light_color += (vec3(trans_color) * trans_color.w * directional_lights[ii].intensity + |
| 1710 | ! | (1-trans_color.w) * directional_lights[ii].color * directional_lights[ii].intensity) * shadow * intensity; |
| 1711 | ! | vec3 r = normalize(2.0f*dot(normal,l_dir)*normal - l_dir); |
| 1712 | ! | spec_total += vec4(spec_uv * std::pow(std::fmax(r.z, 0.0f), material.shininess),0.0f) * (shadow) * directional_lights[ii].intensity; |
| 1713 | } | |
| 1714 | ||
| 1715 | ! | pos = vec_varying_pos[iface][0] * bc.x + vec_varying_pos[iface][1] * bc.y + vec_varying_pos[iface][2] * bc.z; |
| 1716 | ||
| 1717 | ! | vec4 amb = ambient(uv); |
| 1718 | ! | vec4 emit = emissive(uv); |
| 1719 | ! | vec4 shadow_vec = vec4(light_color,1.0f); |
| 1720 | ! | color = clamp( diffuse_color*shadow_vec + spec_total,(Float)0.0,(Float)1.0); |
| 1721 | ||
| 1722 | ||
| 1723 | ! | for(unsigned int i = 0; i < plights.size(); i++) { |
| 1724 | ! | vec3 l_p = vec4(plights[i].CalcLightDir(pos),0.0f); |
| 1725 | ! | vec3 r = normalize(2.0f*dot(normal,l_p)*normal - l_p); |
| 1726 | ! | vec4 spec = vec4(spec_uv * std::pow(std::fmax(r.z, 0.0f), material.shininess),0.0f); |
| 1727 | ! | color += clamp(diffuse_color * vec4(plights[i].CalcPointLightAtten(pos),(Float)0.0) * fmax(0.0f, dot(normal, l_p)) + |
| 1728 | ! | vec4(plights[i].CalcPointLightAtten(pos),0.0f) * spec, (Float)0.0,(Float)1.0); |
| 1729 | } | |
| 1730 | ! | color += amb; |
| 1731 | ! | color += emit; |
| 1732 | ! | if(has_reflection && !has_refraction) { |
| 1733 | ! | vec3 dir = uniform_M_inv * vec4(glm::normalize(pos),0.0f); |
| 1734 | ! | vec3 normal_w = uniform_MIT_inv * vec4(glm::normalize(normal),0.0f); |
| 1735 | ! | vec3 r = glm::reflect(dir,normal_w); |
| 1736 | ! | color = material.reflection_intensity * reflection(r) + (1-material.reflection_intensity) * color; |
| 1737 | } | |
| 1738 | ! | if(has_refraction) { |
| 1739 | ! | vec4 temp_col = diffuse_color; |
| 1740 | ! | vec3 dir = glm::normalize(uniform_M_inv * vec4(pos,0.0f)); |
| 1741 | ! | vec3 normal_w = glm::normalize(uniform_MIT_inv * vec4(normal,0.0f)); |
| 1742 | ! | vec3 rl = glm::reflect(dir,normal_w); |
| 1743 | ||
| 1744 | ! | vec3 rf = glm::refract(dir,normal_w, 1.0/material.ior); |
| 1745 | ! | vec4 reflect_col = reflection(rl); |
| 1746 | ! | vec4 refract_col = reflection(rf); |
| 1747 | ! | Float Ro = (material.ior - 1.0)/(material.ior + 1.0); |
| 1748 | ! | Ro = Ro * Ro; |
| 1749 | ! | Float c0 = 1.0-dot(dir,-normal_w); |
| 1750 | ! | Float c0_5 = c0*c0*c0*c0*c0; |
| 1751 | ! | Float reflect_coef = Ro + (1.0 - Ro) * c0_5; |
| 1752 | ! | color = (1-reflect_coef) * refract_col * temp_col + reflect_coef * reflect_col; |
| 1753 | ! | color.w = 1.0; |
| 1754 | } | |
| 1755 | ! | bc = uv; |
| 1756 | ! | return false; |
| 1757 | } | |
| 1758 | ||
| 1759 | 22x | DepthShader::~DepthShader() { |
| 1760 | 11x | if(material.has_texture) { |
| 1761 | 1x | stbi_image_free(texture); |
| 1762 | } | |
| 1763 | } | |
| 1764 | ||
| 1765 | 11x | DepthShader::DepthShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, |
| 1766 | material_info mat_info, int mat_ind, | |
| 1767 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 1768 | std::vector<std::vector<vec4> >& vec_varying_tri | |
| 1769 | ) : | |
| 1770 | 11x | Projection(Projection), View(View), viewport(viewport), |
| 1771 | 11x | material(mat_info), vec_varying_uv(vec_varying_uv), vec_varying_tri(vec_varying_tri) |
| 1772 | { | |
| 1773 | 11x | MVP = Projection * View * Model; |
| 1774 | 11x | vp = glm::scale(glm::translate(Mat(1.0f), |
| 1775 | 11x | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)), |
| 1776 | 11x | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)); |
| 1777 | 11x | has_texture = false; |
| 1778 | 11x | if(mat_info.has_texture) { |
| 1779 | 1x | has_texture = true; |
| 1780 | 1x | texture = stbi_loadf(mat_info.diffuse_texname.get_cstring(), &nx_t, &ny_t, &nn_t, 0); |
| 1781 | 1x | if(nx_t == 0 || ny_t == 0 || nn_t == 0) { |
| 1782 | ! | throw std::runtime_error("Texture loading failed"); |
| 1783 | } | |
| 1784 | } | |
| 1785 | } | |
| 1786 | ||
| 1787 | 5172x | vec4 DepthShader::vertex(int iface, int nthvert, ModelInfo& model) { |
| 1788 | 5172x | int global_face = model.index_offset + iface; |
| 1789 | 5172x | vec3 gl_Vertex = model.vertex(iface,nthvert); |
| 1790 | 5172x | vec4 clip = vp * MVP * vec4(gl_Vertex,1.0); |
| 1791 | 5172x | vec_varying_tri[global_face][nthvert] = clip; |
| 1792 | 5172x | vec_varying_uv[global_face][nthvert] = model.tex(iface,nthvert); |
| 1793 | ||
| 1794 | 10344x | return clip; |
| 1795 | } | |
| 1796 | ||
| 1797 | 166395x | bool DepthShader::fragment(vec3& bc, vec4 &color, vec3& pos, vec3& normal, int iface) { |
| 1798 | 166395x | vec3 uv = vec_varying_uv[iface][0] * bc.x + vec_varying_uv[iface][1] * bc.y + vec_varying_uv[iface][2] * bc.z; |
| 1799 | 166395x | vec4 diffuse_color = diffuse(uv); |
| 1800 | 166395x | if(diffuse_color.w == 0.0) return true; |
| 1801 | ||
| 1802 | 166395x | vec4 p = vec_varying_tri[iface][0] * bc.x + vec_varying_tri[iface][1] * bc.y + vec_varying_tri[iface][2] * bc.z; |
| 1803 | 166395x | color = diffuse_color; |
| 1804 | 166395x | pos = p; |
| 1805 | 166395x | bc = uv; |
| 1806 | 166395x | return false; |
| 1807 | } | |
| 1808 | ||
| 1809 | ||
| 1810 | ! | ToonShader::ToonShader(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, |
| 1811 | ||
| 1812 | bool has_shadow_map, Float shadow_map_bias, | |
| 1813 | material_info mat_info, std::vector<Light>& point_lights, | |
| 1814 | std::vector<DirectionalLight> directional_lights, | |
| 1815 | std::vector<rayimage>& shadowbuffers, | |
| 1816 | std::vector<rayimage>& transparency_buffers, | |
| 1817 | std::vector<vec3>& vec_varying_intensity, | |
| 1818 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 1819 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 1820 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 1821 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 1822 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 1823 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 1824 | ! | reflection_map_info reflection_map, bool has_reflection, bool has_refraction) : |
| 1825 | ! | Projection(Projection), View(View), viewport(viewport), |
| 1826 | ! | has_shadow_map(has_shadow_map), |
| 1827 | ! | shadow_map_bias(shadow_map_bias), material(mat_info), plights(point_lights), |
| 1828 | ! | directional_lights(directional_lights), shadowbuffers(shadowbuffers), transparency_buffers(transparency_buffers), |
| 1829 | ! | vec_varying_intensity(vec_varying_intensity), vec_varying_uv(vec_varying_uv), |
| 1830 | ! | vec_varying_tri(vec_varying_tri), vec_varying_pos(vec_varying_pos), vec_varying_world_nrm(vec_varying_world_nrm), |
| 1831 | ! | reflection_map(reflection_map), has_reflection(has_reflection), has_refraction(has_refraction) { |
| 1832 | ! | vp = glm::scale(glm::translate(Mat(1.0f), |
| 1833 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)), |
| 1834 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)); |
| 1835 | ! | MVP = Projection * View * Model; |
| 1836 | ! | uniform_M = View * Model; |
| 1837 | ! | uniform_MIT = glm::inverseTranspose(uniform_M); |
| 1838 | ! | uniform_M_inv = glm::inverse(uniform_M); |
| 1839 | ! | uniform_MIT_inv = glm::inverse(uniform_MIT); |
| 1840 | ||
| 1841 | ! | has_texture = has_normal_texture = has_specular_texture = has_emissive_texture = false; |
| 1842 | ! | if(material.has_texture) { |
| 1843 | ! | has_texture = true; |
| 1844 | ! | texture = stbi_loadf(material.diffuse_texname.get_cstring(), &nx_t, &ny_t, &nn_t, 0); |
| 1845 | ! | if(nx_t == 0 || ny_t == 0 || nn_t == 0) { |
| 1846 | ! | throw std::runtime_error("Texture loading failed"); |
| 1847 | } | |
| 1848 | } | |
| 1849 | ! | if(material.has_ambient_texture) { |
| 1850 | ! | ambient_texture = stbi_loadf(material.ambient_texname.get_cstring(), &nx_a, &ny_a, &nn_a, 0); |
| 1851 | ! | if(nx_a == 0 || ny_a == 0 || nn_a == 0) { |
| 1852 | ! | throw std::runtime_error("Ambient Texture loading failed"); |
| 1853 | } | |
| 1854 | } | |
| 1855 | ! | if(material.has_normal_texture) { |
| 1856 | ! | has_normal_texture = true; |
| 1857 | ! | normal_texture = stbi_loadf(material.normal_texname.get_cstring(), &nx_nt, &ny_nt, &nn_nt, 0); |
| 1858 | ! | if(nx_nt == 0 || ny_nt == 0 || nn_nt == 0) { |
| 1859 | ! | throw std::runtime_error("Normal texture loading failed"); |
| 1860 | } | |
| 1861 | } | |
| 1862 | ! | if(material.has_specular_texture) { |
| 1863 | ! | has_specular_texture = true; |
| 1864 | ! | specular_texture = stbi_loadf(material.specular_texname.get_cstring(), |
| 1865 | &nx_st, &ny_st, &nn_st, 0); | |
| 1866 | ! | if(nx_st == 0 || ny_st == 0 || nn_st == 0) { |
| 1867 | ! | throw std::runtime_error("Specular texture loading failed"); |
| 1868 | } | |
| 1869 | } | |
| 1870 | ! | if(material.has_emissive_texture) { |
| 1871 | ! | has_emissive_texture = true; |
| 1872 | ! | emissive_texture = stbi_loadf(material.emissive_texname.get_cstring(), |
| 1873 | &nx_et, &ny_et, &nn_et, 0); | |
| 1874 | ! | if(nx_et == 0 || ny_et == 0 || nn_et == 0) { |
| 1875 | ! | throw std::runtime_error("Emissive texture loading failed"); |
| 1876 | } | |
| 1877 | } | |
| 1878 | } | |
| 1879 | ||
| 1880 | ! | ToonShader::~ToonShader() { |
| 1881 | ! | if(has_texture) { |
| 1882 | ! | stbi_image_free(texture); |
| 1883 | } | |
| 1884 | ! | if(material.has_ambient_texture) { |
| 1885 | ! | stbi_image_free(ambient_texture); |
| 1886 | } | |
| 1887 | ! | if(has_normal_texture) { |
| 1888 | ! | stbi_image_free(normal_texture); |
| 1889 | } | |
| 1890 | ! | if(has_specular_texture) { |
| 1891 | ! | stbi_image_free(specular_texture); |
| 1892 | } | |
| 1893 | ! | if(has_emissive_texture) { |
| 1894 | ! | stbi_image_free(emissive_texture); |
| 1895 | } | |
| 1896 | } | |
| 1897 | ||
| 1898 | ||
| 1899 | ! | vec4 ToonShader::vertex(int iface, int nthvert, ModelInfo& model) { |
| 1900 | ! | int global_face = model.index_offset + iface; |
| 1901 | ! | vec4 clip = MVP * vec4(model.vertex(iface,nthvert),1.0f); |
| 1902 | ! | vec_varying_uv[global_face][nthvert] = model.tex(iface,nthvert); |
| 1903 | ! | vec_varying_tri[global_face][nthvert] = vp * clip; |
| 1904 | ! | vec_varying_pos[global_face][nthvert] = uniform_M * vec4(model.vertex(iface, nthvert),1.0f); |
| 1905 | ||
| 1906 | ! | vec_varying_world_nrm[global_face][nthvert] = model.model_vertex_normals(iface) ? |
| 1907 | ! | uniform_MIT * vec4(model.normal(iface, nthvert),0.0f) : |
| 1908 | ! | uniform_MIT * normalize(vec4(glm::cross(model.vertex(iface,1)-model.vertex(iface,0), |
| 1909 | ! | model.vertex(iface,2)-model.vertex(iface,0)),0.0f)); |
| 1910 | ||
| 1911 | ||
| 1912 | ! | return (vec_varying_tri[global_face][nthvert]); |
| 1913 | } | |
| 1914 | ||
| 1915 | ! | bool ToonShader::fragment(vec3& bc, vec4 &color, vec3& pos, vec3& normal, int iface) { |
| 1916 | ! | vec3 uv = vec_varying_uv[iface][0] * bc.x + vec_varying_uv[iface][1] * bc.y + vec_varying_uv[iface][2] * bc.z; |
| 1917 | ! | vec4 diffuse_color = diffuse(uv); |
| 1918 | ! | if(diffuse_color.w == 0.0) return true; |
| 1919 | ! | normal = vec_varying_world_nrm[iface][0] * bc.x + vec_varying_world_nrm[iface][1] * bc.y + vec_varying_world_nrm[iface][2] * bc.z; |
| 1920 | ||
| 1921 | ! | vec3 light_color(0.0); |
| 1922 | ||
| 1923 | ! | for(unsigned int ii = 0; ii < directional_lights.size(); ii++) { |
| 1924 | ! | vec4 trans_color(0.0,0.0,0.0,0.0); |
| 1925 | ! | Float shadow = 1.0f; |
| 1926 | ! | Float intensity = std::fmax(dot(normal, vec3(uniform_M * vec4(directional_lights[ii].direction, 0.0))),0.0); |
| 1927 | ! | if(has_shadow_map && intensity != 0.0) { |
| 1928 | ! | shadow = 0.0f; |
| 1929 | ||
| 1930 | ! | vec4 sb_p = directional_lights[ii].uniform_Mshadow_ * (vec_varying_tri[iface][0] * bc.x + vec_varying_tri[iface][1] * bc.y + vec_varying_tri[iface][2] * bc.z); |
| 1931 | ! | sb_p = sb_p/sb_p.w; |
| 1932 | ! | if(sb_p[0] >= 0 && sb_p[0] < shadowbuffers[ii].width() && sb_p[1] >= 0 && sb_p[1] < shadowbuffers[ii].height()) { |
| 1933 | ! | Float bias = std::fmax(shadow_map_bias*10.0 * (1.0 - intensity),shadow_map_bias); |
| 1934 | ||
| 1935 | ! | int i = int(sb_p[0]); |
| 1936 | ! | int j = int(sb_p[1]); |
| 1937 | ! | for(int x = -2; x <= 2; ++x) { |
| 1938 | ! | for(int y = -2; y <= 2; ++y) { |
| 1939 | ! | shadow += shadowbuffers[ii].get_color_bounded(i+x,j+y).x > sb_p[2]-bias ? 1.0f : shadowbuffers[ii].get_shadow_intensity(); |
| 1940 | } | |
| 1941 | } | |
| 1942 | ! | shadow /= 25; |
| 1943 | ! | if(diffuse_color.w == 1.0) { |
| 1944 | ! | for(int x = -2; x <= 2; ++x) { |
| 1945 | ! | for(int y = -2; y <= 2; ++y) { |
| 1946 | ! | trans_color += transparency_buffers[ii].get_color_bounded_a(i+x,j+y); |
| 1947 | } | |
| 1948 | } | |
| 1949 | ! | trans_color /= 25; |
| 1950 | } | |
| 1951 | } | |
| 1952 | } | |
| 1953 | ! | light_color += (vec3(trans_color) * trans_color.w + |
| 1954 | ! | (1-trans_color.w) * directional_lights[ii].color) * |
| 1955 | ! | (Float)round(material.toon_levels * directional_lights[ii].intensity * shadow * intensity)/material.toon_levels; |
| 1956 | } | |
| 1957 | ! | pos = vec_varying_pos[iface][0] * bc.x + vec_varying_pos[iface][1] * bc.y + vec_varying_pos[iface][2] * bc.z; |
| 1958 | //Directional light contribution | |
| 1959 | ! | color = diffuse_color * vec4(light_color,1.0); |
| 1960 | ||
| 1961 | ||
| 1962 | ! | for(unsigned int i = 0; i < plights.size(); i++) { |
| 1963 | ! | color += diffuse_color * vec4(plights[i].CalcPointLightAtten(pos),0.0f) * fmax(0.0f,dot(normal, plights[i].CalcLightDir(pos))); |
| 1964 | } | |
| 1965 | //Emissive and ambient terms | |
| 1966 | ! | color += emissive(uv); |
| 1967 | ! | color += ambient(uv); |
| 1968 | ! | bc = uv; |
| 1969 | ! | return false; |
| 1970 | } | |
| 1971 | ||
| 1972 | ! | ToonShaderPhong::ToonShaderPhong(Mat& Model, Mat& Projection, Mat& View, vec4& viewport, |
| 1973 | ||
| 1974 | bool has_shadow_map, Float shadow_map_bias, | |
| 1975 | material_info mat_info, std::vector<Light>& point_lights, | |
| 1976 | std::vector<DirectionalLight> directional_lights, | |
| 1977 | std::vector<rayimage>& shadowbuffers, | |
| 1978 | std::vector<rayimage>& transparency_buffers, | |
| 1979 | std::vector<vec3>& vec_varying_intensity, | |
| 1980 | std::vector<std::vector<vec3> >& vec_varying_uv, | |
| 1981 | std::vector<std::vector<vec4> >& vec_varying_tri, | |
| 1982 | std::vector<std::vector<vec3> >& vec_varying_pos, | |
| 1983 | std::vector<std::vector<vec3> >& vec_varying_world_nrm, | |
| 1984 | std::vector<std::vector<vec3> >& vec_varying_ndc_tri, | |
| 1985 | std::vector<std::vector<vec3> >& vec_varying_nrm, | |
| 1986 | ! | reflection_map_info reflection_map, bool has_reflection, bool has_refraction) : |
| 1987 | ! | Projection(Projection), View(View), viewport(viewport), |
| 1988 | ! | has_shadow_map(has_shadow_map), |
| 1989 | ! | shadow_map_bias(shadow_map_bias), material(mat_info), plights(point_lights), |
| 1990 | ! | directional_lights(directional_lights), shadowbuffers(shadowbuffers), transparency_buffers(transparency_buffers), |
| 1991 | ! | vec_varying_intensity(vec_varying_intensity), vec_varying_uv(vec_varying_uv), |
| 1992 | ! | vec_varying_tri(vec_varying_tri), vec_varying_pos(vec_varying_pos), vec_varying_world_nrm(vec_varying_world_nrm), |
| 1993 | ! | reflection_map(reflection_map), has_reflection(has_reflection), has_refraction(has_refraction) { |
| 1994 | ! | vp = glm::scale(glm::translate(Mat(1.0f), |
| 1995 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)), |
| 1996 | ! | vec3(viewport[2]/2.0f,viewport[3]/2.0f,1.0f/2.0f)); |
| 1997 | ! | MVP = Projection * View * Model; |
| 1998 | ! | uniform_M = View * Model; |
| 1999 | ! | uniform_MIT = glm::inverseTranspose(uniform_M); |
| 2000 | ! | uniform_M_inv = glm::inverse(uniform_M); |
| 2001 | ! | uniform_MIT_inv = glm::inverse(uniform_MIT); |
| 2002 | ||
| 2003 | ! | has_texture = has_normal_texture = has_specular_texture = has_emissive_texture = false; |
| 2004 | ! | if(material.has_texture) { |
| 2005 | ! | has_texture = true; |
| 2006 | ! | texture = stbi_loadf(material.diffuse_texname.get_cstring(), &nx_t, &ny_t, &nn_t, 0); |
| 2007 | ! | if(nx_t == 0 || ny_t == 0 || nn_t == 0) { |
| 2008 | ! | throw std::runtime_error("Texture loading failed"); |
| 2009 | } | |
| 2010 | } | |
| 2011 | ! | if(material.has_ambient_texture) { |
| 2012 | ! | ambient_texture = stbi_loadf(material.ambient_texname.get_cstring(), &nx_a, &ny_a, &nn_a, 0); |
| 2013 | ! | if(nx_a == 0 || ny_a == 0 || nn_a == 0) { |
| 2014 | ! | throw std::runtime_error("Ambient Texture loading failed"); |
| 2015 | } | |
| 2016 | } | |
| 2017 | ! | if(material.has_normal_texture) { |
| 2018 | ! | has_normal_texture = true; |
| 2019 | ! | normal_texture = stbi_loadf(material.normal_texname.get_cstring(), &nx_nt, &ny_nt, &nn_nt, 0); |
| 2020 | ! | if(nx_nt == 0 || ny_nt == 0 || nn_nt == 0) { |
| 2021 | ! | throw std::runtime_error("Normal texture loading failed"); |
| 2022 | } | |
| 2023 | } | |
| 2024 | ! | if(material.has_specular_texture) { |
| 2025 | ! | has_specular_texture = true; |
| 2026 | ! | specular_texture = stbi_loadf(material.specular_texname.get_cstring(), |
| 2027 | &nx_st, &ny_st, &nn_st, 0); | |
| 2028 | ! | if(nx_st == 0 || ny_st == 0 || nn_st == 0) { |
| 2029 | ! | throw std::runtime_error("Specular texture loading failed"); |
| 2030 | } | |
| 2031 | } | |
| 2032 | ! | if(material.has_emissive_texture) { |
| 2033 | ! | has_emissive_texture = true; |
| 2034 | ! | emissive_texture = stbi_loadf(material.emissive_texname.get_cstring(), |
| 2035 | &nx_et, &ny_et, &nn_et, 0); | |
| 2036 | ! | if(nx_et == 0 || ny_et == 0 || nn_et == 0) { |
| 2037 | ! | throw std::runtime_error("Emissive texture loading failed"); |
| 2038 | } | |
| 2039 | } | |
| 2040 | } | |
| 2041 | ||
| 2042 | ! | ToonShaderPhong::~ToonShaderPhong() { |
| 2043 | ! | if(has_texture) { |
| 2044 | ! | stbi_image_free(texture); |
| 2045 | } | |
| 2046 | ! | if(material.has_ambient_texture) { |
| 2047 | ! | stbi_image_free(ambient_texture); |
| 2048 | } | |
| 2049 | ! | if(has_normal_texture) { |
| 2050 | ! | stbi_image_free(normal_texture); |
| 2051 | } | |
| 2052 | ! | if(has_specular_texture) { |
| 2053 | ! | stbi_image_free(specular_texture); |
| 2054 | } | |
| 2055 | ! | if(has_emissive_texture) { |
| 2056 | ! | stbi_image_free(emissive_texture); |
| 2057 | } | |
| 2058 | } | |
| 2059 | ||
| 2060 | ||
| 2061 | ! | vec4 ToonShaderPhong::vertex(int iface, int nthvert, ModelInfo& model) { |
| 2062 | ! | int global_face = model.index_offset + iface; |
| 2063 | ! | vec_varying_uv[global_face][nthvert] = model.tex(iface,nthvert); |
| 2064 | ! | vec_varying_pos[global_face][nthvert] = uniform_M * vec4(model.vertex(iface, nthvert),1.0f); |
| 2065 | ! | vec4 clip = vp * MVP * vec4(model.vertex(iface,nthvert),1.0f); |
| 2066 | ! | vec_varying_tri[global_face][nthvert] = clip; |
| 2067 | ||
| 2068 | ! | vec_varying_world_nrm[global_face][nthvert] = model.model_vertex_normals(iface) ? |
| 2069 | ! | uniform_MIT * normalize(vec4(model.normal(iface, nthvert),0.0f)) : |
| 2070 | ! | uniform_MIT * normalize(vec4(glm::cross(model.vertex(iface,1)-model.vertex(iface,0), |
| 2071 | ! | model.vertex(iface,2)-model.vertex(iface,0)),0.0f)); |
| 2072 | ||
| 2073 | ! | return clip; |
| 2074 | } | |
| 2075 | ||
| 2076 | ! | bool ToonShaderPhong::fragment(vec3& bc, vec4 &color, vec3& pos, vec3& normal, int iface) { |
| 2077 | ! | vec3 uv = vec_varying_uv[iface][0] * bc.x + vec_varying_uv[iface][1] * bc.y + vec_varying_uv[iface][2] * bc.z; |
| 2078 | ! | vec4 diffuse_color = diffuse(uv); |
| 2079 | ! | if(diffuse_color.w == 0.0) return true; |
| 2080 | ! | normal = (vec_varying_world_nrm[iface][0] * bc.x + vec_varying_world_nrm[iface][1] * bc.y + vec_varying_world_nrm[iface][2] * bc.z); |
| 2081 | ||
| 2082 | ! | vec3 spec_uv = specular(uv); |
| 2083 | ! | vec3 light_color(0.0); |
| 2084 | ! | vec4 spec_total(0.0); |
| 2085 | ! | for(unsigned int ii = 0; ii < directional_lights.size(); ii++) { |
| 2086 | ! | vec4 trans_color(0.0,0.0,0.0,0.0); |
| 2087 | ||
| 2088 | ! | Float shadow = 1.0f; |
| 2089 | ! | vec3 l_dir = vec3(uniform_M * vec4(directional_lights[ii].direction, 0.0)); |
| 2090 | ! | Float intensity = std::fmax(dot(normal, l_dir),0.0); |
| 2091 | ! | Float shadow_int = shadowbuffers[ii].get_shadow_intensity(); |
| 2092 | ! | if(has_shadow_map && intensity != 0.0) { |
| 2093 | ! | shadow = 0.0f; |
| 2094 | ||
| 2095 | ! | vec4 sb_p = directional_lights[ii].uniform_Mshadow_ * (vec_varying_tri[iface][0] * bc.x + vec_varying_tri[iface][1] * bc.y + vec_varying_tri[iface][2] * bc.z); |
| 2096 | ! | sb_p = sb_p/sb_p.w; |
| 2097 | ! | if(sb_p[0] >= 0 && sb_p[0] < shadowbuffers[ii].width() && sb_p[1] >= 0 && sb_p[1] < shadowbuffers[ii].height()) { |
| 2098 | ! | Float bias = std::fmax(shadow_map_bias*10.0 * (1.0 - intensity),shadow_map_bias); |
| 2099 | ||
| 2100 | ! | int i = int(sb_p[0]); |
| 2101 | ! | int j = int(sb_p[1]); |
| 2102 | ! | for(int x = -2; x <= 2; ++x) { |
| 2103 | ! | for(int y = -2; y <= 2; ++y) { |
| 2104 | ! | shadow += shadowbuffers[ii].get_color_bounded(i+x,j+y).x > sb_p[2]-bias ? 1.0 : shadow_int; |
| 2105 | } | |
| 2106 | } | |
| 2107 | ! | shadow /= 25; |
| 2108 | ! | if(diffuse_color.w == 1.0) { |
| 2109 | ! | for(int x = -2; x <= 2; ++x) { |
| 2110 | ! | for(int y = -2; y <= 2; ++y) { |
| 2111 | ! | trans_color += transparency_buffers[ii].get_color_bounded_a(i+x,j+y); |
| 2112 | } | |
| 2113 | } | |
| 2114 | ! | trans_color /= 25; |
| 2115 | } | |
| 2116 | } | |
| 2117 | } | |
| 2118 | ! | light_color += (vec3(trans_color) * trans_color.w + |
| 2119 | ! | (1-trans_color.w) * directional_lights[ii].color) * |
| 2120 | ! | (Float)round(material.toon_levels * directional_lights[ii].intensity * shadow * intensity)/material.toon_levels; |
| 2121 | ! | vec3 r = normalize(2.0f*dot(normal,l_dir)*normal - l_dir); |
| 2122 | ! | spec_total += vec4(spec_uv * |
| 2123 | ! | (Float)round(material.toon_levels * std::pow(std::fmax(r.z, 0.0f), material.shininess) * shadow * directional_lights[ii].intensity)/material.toon_levels,0.0f); |
| 2124 | } | |
| 2125 | ! | pos = vec_varying_pos[iface][0] * bc.x + vec_varying_pos[iface][1] * bc.y + vec_varying_pos[iface][2] * bc.z; |
| 2126 | ||
| 2127 | ! | vec4 amb = ambient(uv); |
| 2128 | ! | vec4 emit = emissive(uv); |
| 2129 | ! | vec4 shadow_vec = vec4(light_color,1.0f); |
| 2130 | ! | color = clamp( diffuse_color*shadow_vec + spec_total,(Float)0.0,(Float)1.0); |
| 2131 | ||
| 2132 | ! | for(unsigned int i = 0; i < plights.size(); i++) { |
| 2133 | ! | vec3 l_p = vec4(plights[i].CalcLightDir(pos),0.0f); |
| 2134 | ! | vec3 r = normalize(2.0f*dot(normal,l_p)*normal - l_p); |
| 2135 | ! | vec4 spec = vec4(spec_uv * std::pow(std::fmax(r.z, 0.0f), material.shininess),0.0f); |
| 2136 | ! | color += clamp(diffuse_color * vec4(plights[i].CalcPointLightAtten(pos),(Float)0.0) * fmax(0.0f, dot(normal, l_p)) + |
| 2137 | ! | vec4(plights[i].CalcPointLightAtten(pos),0.0f) * spec, (Float)0.0,(Float)1.0); |
| 2138 | } | |
| 2139 | ! | color += amb; |
| 2140 | ! | color += emit; |
| 2141 | ! | bc = uv; |
| 2142 | ! | return false; |
| 2143 | } |
| 1 | /// @ref core | |
| 2 | /// @file glm/detail/func_common.inl | |
| 3 | ||
| 4 | #include "../vector_relational.hpp" | |
| 5 | #include "compute_common.hpp" | |
| 6 | #include "type_vec1.hpp" | |
| 7 | #include "type_vec2.hpp" | |
| 8 | #include "type_vec3.hpp" | |
| 9 | #include "type_vec4.hpp" | |
| 10 | #include "_vectorize.hpp" | |
| 11 | #include <limits> | |
| 12 | ||
| 13 | namespace glm | |
| 14 | { | |
| 15 | // min | |
| 16 | template<typename genType> | |
| 17 | ! | GLM_FUNC_QUALIFIER GLM_CONSTEXPR genType min(genType x, genType y) |
| 18 | { | |
| 19 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559 || std::numeric_limits<genType>::is_integer, "'min' only accept floating-point or integer inputs"); | |
| 20 | ! | return (y < x) ? y : x; |
| 21 | } | |
| 22 | ||
| 23 | // max | |
| 24 | template<typename genType> | |
| 25 | ! | GLM_FUNC_QUALIFIER GLM_CONSTEXPR genType max(genType x, genType y) |
| 26 | { | |
| 27 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559 || std::numeric_limits<genType>::is_integer, "'max' only accept floating-point or integer inputs"); | |
| 28 | ||
| 29 | ! | return (x < y) ? y : x; |
| 30 | } | |
| 31 | ||
| 32 | // abs | |
| 33 | template<> | |
| 34 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR int abs(int x) | |
| 35 | { | |
| 36 | int const y = x >> (sizeof(int) * 8 - 1); | |
| 37 | return (x ^ y) - y; | |
| 38 | } | |
| 39 | ||
| 40 | // round | |
| 41 | # if GLM_HAS_CXX11_STL | |
| 42 | using ::std::round; | |
| 43 | # else | |
| 44 | template<typename genType> | |
| 45 | GLM_FUNC_QUALIFIER genType round(genType x) | |
| 46 | { | |
| 47 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'round' only accept floating-point inputs"); | |
| 48 | ||
| 49 | return x < static_cast<genType>(0) ? static_cast<genType>(int(x - static_cast<genType>(0.5))) : static_cast<genType>(int(x + static_cast<genType>(0.5))); | |
| 50 | } | |
| 51 | # endif | |
| 52 | ||
| 53 | // trunc | |
| 54 | # if GLM_HAS_CXX11_STL | |
| 55 | using ::std::trunc; | |
| 56 | # else | |
| 57 | template<typename genType> | |
| 58 | GLM_FUNC_QUALIFIER genType trunc(genType x) | |
| 59 | { | |
| 60 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'trunc' only accept floating-point inputs"); | |
| 61 | ||
| 62 | return x < static_cast<genType>(0) ? -std::floor(-x) : std::floor(x); | |
| 63 | } | |
| 64 | # endif | |
| 65 | ||
| 66 | }//namespace glm | |
| 67 | ||
| 68 | namespace glm{ | |
| 69 | namespace detail | |
| 70 | { | |
| 71 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 72 | struct compute_abs_vector | |
| 73 | { | |
| 74 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static vec<L, T, Q> call(vec<L, T, Q> const& x) | |
| 75 | { | |
| 76 | return detail::functor1<vec, L, T, T, Q>::call(abs, x); | |
| 77 | } | |
| 78 | }; | |
| 79 | ||
| 80 | template<length_t L, typename T, typename U, qualifier Q, bool Aligned> | |
| 81 | struct compute_mix_vector | |
| 82 | { | |
| 83 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x, vec<L, T, Q> const& y, vec<L, U, Q> const& a) | |
| 84 | { | |
| 85 | GLM_STATIC_ASSERT(std::numeric_limits<U>::is_iec559 || GLM_CONFIG_UNRESTRICTED_GENTYPE, "'mix' only accept floating-point inputs for the interpolator a"); | |
| 86 | ||
| 87 | return vec<L, T, Q>(vec<L, U, Q>(x) * (static_cast<U>(1) - a) + vec<L, U, Q>(y) * a); | |
| 88 | } | |
| 89 | }; | |
| 90 | ||
| 91 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 92 | struct compute_mix_vector<L, T, bool, Q, Aligned> | |
| 93 | { | |
| 94 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x, vec<L, T, Q> const& y, vec<L, bool, Q> const& a) | |
| 95 | { | |
| 96 | vec<L, T, Q> Result; | |
| 97 | for(length_t i = 0; i < x.length(); ++i) | |
| 98 | Result[i] = a[i] ? y[i] : x[i]; | |
| 99 | return Result; | |
| 100 | } | |
| 101 | }; | |
| 102 | ||
| 103 | template<length_t L, typename T, typename U, qualifier Q, bool Aligned> | |
| 104 | struct compute_mix_scalar | |
| 105 | { | |
| 106 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x, vec<L, T, Q> const& y, U const& a) | |
| 107 | { | |
| 108 | GLM_STATIC_ASSERT(std::numeric_limits<U>::is_iec559 || GLM_CONFIG_UNRESTRICTED_GENTYPE, "'mix' only accept floating-point inputs for the interpolator a"); | |
| 109 | ||
| 110 | return vec<L, T, Q>(vec<L, U, Q>(x) * (static_cast<U>(1) - a) + vec<L, U, Q>(y) * a); | |
| 111 | } | |
| 112 | }; | |
| 113 | ||
| 114 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 115 | struct compute_mix_scalar<L, T, bool, Q, Aligned> | |
| 116 | { | |
| 117 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x, vec<L, T, Q> const& y, bool const& a) | |
| 118 | { | |
| 119 | return a ? y : x; | |
| 120 | } | |
| 121 | }; | |
| 122 | ||
| 123 | template<typename T, typename U> | |
| 124 | struct compute_mix | |
| 125 | { | |
| 126 | GLM_FUNC_QUALIFIER static T call(T const& x, T const& y, U const& a) | |
| 127 | { | |
| 128 | GLM_STATIC_ASSERT(std::numeric_limits<U>::is_iec559 || GLM_CONFIG_UNRESTRICTED_GENTYPE, "'mix' only accept floating-point inputs for the interpolator a"); | |
| 129 | ||
| 130 | return static_cast<T>(static_cast<U>(x) * (static_cast<U>(1) - a) + static_cast<U>(y) * a); | |
| 131 | } | |
| 132 | }; | |
| 133 | ||
| 134 | template<typename T> | |
| 135 | struct compute_mix<T, bool> | |
| 136 | { | |
| 137 | GLM_FUNC_QUALIFIER static T call(T const& x, T const& y, bool const& a) | |
| 138 | { | |
| 139 | return a ? y : x; | |
| 140 | } | |
| 141 | }; | |
| 142 | ||
| 143 | template<length_t L, typename T, qualifier Q, bool isFloat, bool Aligned> | |
| 144 | struct compute_sign | |
| 145 | { | |
| 146 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x) | |
| 147 | { | |
| 148 | return vec<L, T, Q>(glm::lessThan(vec<L, T, Q>(0), x)) - vec<L, T, Q>(glm::lessThan(x, vec<L, T, Q>(0))); | |
| 149 | } | |
| 150 | }; | |
| 151 | ||
| 152 | # if GLM_ARCH == GLM_ARCH_X86 | |
| 153 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 154 | struct compute_sign<L, T, Q, false, Aligned> | |
| 155 | { | |
| 156 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x) | |
| 157 | { | |
| 158 | T const Shift(static_cast<T>(sizeof(T) * 8 - 1)); | |
| 159 | vec<L, T, Q> const y(vec<L, typename detail::make_unsigned<T>::type, Q>(-x) >> typename detail::make_unsigned<T>::type(Shift)); | |
| 160 | ||
| 161 | return (x >> Shift) | y; | |
| 162 | } | |
| 163 | }; | |
| 164 | # endif | |
| 165 | ||
| 166 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 167 | struct compute_floor | |
| 168 | { | |
| 169 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x) | |
| 170 | { | |
| 171 | return detail::functor1<vec, L, T, T, Q>::call(std::floor, x); | |
| 172 | } | |
| 173 | }; | |
| 174 | ||
| 175 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 176 | struct compute_ceil | |
| 177 | { | |
| 178 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x) | |
| 179 | { | |
| 180 | return detail::functor1<vec, L, T, T, Q>::call(std::ceil, x); | |
| 181 | } | |
| 182 | }; | |
| 183 | ||
| 184 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 185 | struct compute_fract | |
| 186 | { | |
| 187 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x) | |
| 188 | { | |
| 189 | return x - floor(x); | |
| 190 | } | |
| 191 | }; | |
| 192 | ||
| 193 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 194 | struct compute_trunc | |
| 195 | { | |
| 196 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x) | |
| 197 | { | |
| 198 | return detail::functor1<vec, L, T, T, Q>::call(trunc, x); | |
| 199 | } | |
| 200 | }; | |
| 201 | ||
| 202 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 203 | struct compute_round | |
| 204 | { | |
| 205 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x) | |
| 206 | { | |
| 207 | return detail::functor1<vec, L, T, T, Q>::call(round, x); | |
| 208 | } | |
| 209 | }; | |
| 210 | ||
| 211 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 212 | struct compute_mod | |
| 213 | { | |
| 214 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& a, vec<L, T, Q> const& b) | |
| 215 | { | |
| 216 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'mod' only accept floating-point inputs. Include <glm/gtc/integer.hpp> for integer inputs."); | |
| 217 | return a - b * floor(a / b); | |
| 218 | } | |
| 219 | }; | |
| 220 | ||
| 221 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 222 | struct compute_min_vector | |
| 223 | { | |
| 224 | ! | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x, vec<L, T, Q> const& y) |
| 225 | { | |
| 226 | ! | return detail::functor2<vec, L, T, Q>::call(min, x, y); |
| 227 | } | |
| 228 | }; | |
| 229 | ||
| 230 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 231 | struct compute_max_vector | |
| 232 | { | |
| 233 | ! | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x, vec<L, T, Q> const& y) |
| 234 | { | |
| 235 | ! | return detail::functor2<vec, L, T, Q>::call(max, x, y); |
| 236 | } | |
| 237 | }; | |
| 238 | ||
| 239 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 240 | struct compute_clamp_vector | |
| 241 | { | |
| 242 | ! | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& x, vec<L, T, Q> const& minVal, vec<L, T, Q> const& maxVal) |
| 243 | { | |
| 244 | ! | return min(max(x, minVal), maxVal); |
| 245 | } | |
| 246 | }; | |
| 247 | ||
| 248 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 249 | struct compute_step_vector | |
| 250 | { | |
| 251 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& edge, vec<L, T, Q> const& x) | |
| 252 | { | |
| 253 | return mix(vec<L, T, Q>(1), vec<L, T, Q>(0), glm::lessThan(x, edge)); | |
| 254 | } | |
| 255 | }; | |
| 256 | ||
| 257 | template<length_t L, typename T, qualifier Q, bool Aligned> | |
| 258 | struct compute_smoothstep_vector | |
| 259 | { | |
| 260 | GLM_FUNC_QUALIFIER static vec<L, T, Q> call(vec<L, T, Q> const& edge0, vec<L, T, Q> const& edge1, vec<L, T, Q> const& x) | |
| 261 | { | |
| 262 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559 || GLM_CONFIG_UNRESTRICTED_GENTYPE, "'smoothstep' only accept floating-point inputs"); | |
| 263 | vec<L, T, Q> const tmp(clamp((x - edge0) / (edge1 - edge0), static_cast<T>(0), static_cast<T>(1))); | |
| 264 | return tmp * tmp * (static_cast<T>(3) - static_cast<T>(2) * tmp); | |
| 265 | } | |
| 266 | }; | |
| 267 | }//namespace detail | |
| 268 | ||
| 269 | template<typename genFIType> | |
| 270 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR genFIType abs(genFIType x) | |
| 271 | { | |
| 272 | return detail::compute_abs<genFIType, std::numeric_limits<genFIType>::is_signed>::call(x); | |
| 273 | } | |
| 274 | ||
| 275 | template<length_t L, typename T, qualifier Q> | |
| 276 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<L, T, Q> abs(vec<L, T, Q> const& x) | |
| 277 | { | |
| 278 | return detail::compute_abs_vector<L, T, Q, detail::is_aligned<Q>::value>::call(x); | |
| 279 | } | |
| 280 | ||
| 281 | // sign | |
| 282 | // fast and works for any type | |
| 283 | template<typename genFIType> | |
| 284 | GLM_FUNC_QUALIFIER genFIType sign(genFIType x) | |
| 285 | { | |
| 286 | GLM_STATIC_ASSERT( | |
| 287 | std::numeric_limits<genFIType>::is_iec559 || (std::numeric_limits<genFIType>::is_signed && std::numeric_limits<genFIType>::is_integer), | |
| 288 | "'sign' only accept signed inputs"); | |
| 289 | ||
| 290 | return detail::compute_sign<1, genFIType, defaultp, | |
| 291 | std::numeric_limits<genFIType>::is_iec559, detail::is_aligned<highp>::value>::call(vec<1, genFIType>(x)).x; | |
| 292 | } | |
| 293 | ||
| 294 | template<length_t L, typename T, qualifier Q> | |
| 295 | GLM_FUNC_QUALIFIER vec<L, T, Q> sign(vec<L, T, Q> const& x) | |
| 296 | { | |
| 297 | GLM_STATIC_ASSERT( | |
| 298 | std::numeric_limits<T>::is_iec559 || (std::numeric_limits<T>::is_signed && std::numeric_limits<T>::is_integer), | |
| 299 | "'sign' only accept signed inputs"); | |
| 300 | ||
| 301 | return detail::compute_sign<L, T, Q, std::numeric_limits<T>::is_iec559, detail::is_aligned<Q>::value>::call(x); | |
| 302 | } | |
| 303 | ||
| 304 | // floor | |
| 305 | using ::std::floor; | |
| 306 | template<length_t L, typename T, qualifier Q> | |
| 307 | GLM_FUNC_QUALIFIER vec<L, T, Q> floor(vec<L, T, Q> const& x) | |
| 308 | { | |
| 309 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'floor' only accept floating-point inputs."); | |
| 310 | return detail::compute_floor<L, T, Q, detail::is_aligned<Q>::value>::call(x); | |
| 311 | } | |
| 312 | ||
| 313 | template<length_t L, typename T, qualifier Q> | |
| 314 | GLM_FUNC_QUALIFIER vec<L, T, Q> trunc(vec<L, T, Q> const& x) | |
| 315 | { | |
| 316 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'trunc' only accept floating-point inputs"); | |
| 317 | return detail::compute_trunc<L, T, Q, detail::is_aligned<Q>::value>::call(x); | |
| 318 | } | |
| 319 | ||
| 320 | template<length_t L, typename T, qualifier Q> | |
| 321 | GLM_FUNC_QUALIFIER vec<L, T, Q> round(vec<L, T, Q> const& x) | |
| 322 | { | |
| 323 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'round' only accept floating-point inputs"); | |
| 324 | return detail::compute_round<L, T, Q, detail::is_aligned<Q>::value>::call(x); | |
| 325 | } | |
| 326 | ||
| 327 | /* | |
| 328 | // roundEven | |
| 329 | template<typename genType> | |
| 330 | GLM_FUNC_QUALIFIER genType roundEven(genType const& x) | |
| 331 | { | |
| 332 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'roundEven' only accept floating-point inputs"); | |
| 333 | ||
| 334 | return genType(int(x + genType(int(x) % 2))); | |
| 335 | } | |
| 336 | */ | |
| 337 | ||
| 338 | // roundEven | |
| 339 | template<typename genType> | |
| 340 | GLM_FUNC_QUALIFIER genType roundEven(genType x) | |
| 341 | { | |
| 342 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'roundEven' only accept floating-point inputs"); | |
| 343 | ||
| 344 | int Integer = static_cast<int>(x); | |
| 345 | genType IntegerPart = static_cast<genType>(Integer); | |
| 346 | genType FractionalPart = fract(x); | |
| 347 | ||
| 348 | if(FractionalPart > static_cast<genType>(0.5) || FractionalPart < static_cast<genType>(0.5)) | |
| 349 | { | |
| 350 | return round(x); | |
| 351 | } | |
| 352 | else if((Integer % 2) == 0) | |
| 353 | { | |
| 354 | return IntegerPart; | |
| 355 | } | |
| 356 | else if(x <= static_cast<genType>(0)) // Work around... | |
| 357 | { | |
| 358 | return IntegerPart - static_cast<genType>(1); | |
| 359 | } | |
| 360 | else | |
| 361 | { | |
| 362 | return IntegerPart + static_cast<genType>(1); | |
| 363 | } | |
| 364 | //else // Bug on MinGW 4.5.2 | |
| 365 | //{ | |
| 366 | // return mix(IntegerPart + genType(-1), IntegerPart + genType(1), x <= genType(0)); | |
| 367 | //} | |
| 368 | } | |
| 369 | ||
| 370 | template<length_t L, typename T, qualifier Q> | |
| 371 | GLM_FUNC_QUALIFIER vec<L, T, Q> roundEven(vec<L, T, Q> const& x) | |
| 372 | { | |
| 373 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'roundEven' only accept floating-point inputs"); | |
| 374 | return detail::functor1<vec, L, T, T, Q>::call(roundEven, x); | |
| 375 | } | |
| 376 | ||
| 377 | // ceil | |
| 378 | using ::std::ceil; | |
| 379 | template<length_t L, typename T, qualifier Q> | |
| 380 | GLM_FUNC_QUALIFIER vec<L, T, Q> ceil(vec<L, T, Q> const& x) | |
| 381 | { | |
| 382 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'ceil' only accept floating-point inputs"); | |
| 383 | return detail::compute_ceil<L, T, Q, detail::is_aligned<Q>::value>::call(x); | |
| 384 | } | |
| 385 | ||
| 386 | // fract | |
| 387 | template<typename genType> | |
| 388 | GLM_FUNC_QUALIFIER genType fract(genType x) | |
| 389 | { | |
| 390 | return fract(vec<1, genType>(x)).x; | |
| 391 | } | |
| 392 | ||
| 393 | template<length_t L, typename T, qualifier Q> | |
| 394 | GLM_FUNC_QUALIFIER vec<L, T, Q> fract(vec<L, T, Q> const& x) | |
| 395 | { | |
| 396 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'fract' only accept floating-point inputs"); | |
| 397 | return detail::compute_fract<L, T, Q, detail::is_aligned<Q>::value>::call(x); | |
| 398 | } | |
| 399 | ||
| 400 | // mod | |
| 401 | template<typename genType> | |
| 402 | GLM_FUNC_QUALIFIER genType mod(genType x, genType y) | |
| 403 | { | |
| 404 | # if GLM_COMPILER & GLM_COMPILER_CUDA | |
| 405 | // Another Cuda compiler bug https://github.com/g-truc/glm/issues/530 | |
| 406 | vec<1, genType, defaultp> Result(mod(vec<1, genType, defaultp>(x), y)); | |
| 407 | return Result.x; | |
| 408 | # else | |
| 409 | return mod(vec<1, genType, defaultp>(x), y).x; | |
| 410 | # endif | |
| 411 | } | |
| 412 | ||
| 413 | template<length_t L, typename T, qualifier Q> | |
| 414 | GLM_FUNC_QUALIFIER vec<L, T, Q> mod(vec<L, T, Q> const& x, T y) | |
| 415 | { | |
| 416 | return detail::compute_mod<L, T, Q, detail::is_aligned<Q>::value>::call(x, vec<L, T, Q>(y)); | |
| 417 | } | |
| 418 | ||
| 419 | template<length_t L, typename T, qualifier Q> | |
| 420 | GLM_FUNC_QUALIFIER vec<L, T, Q> mod(vec<L, T, Q> const& x, vec<L, T, Q> const& y) | |
| 421 | { | |
| 422 | return detail::compute_mod<L, T, Q, detail::is_aligned<Q>::value>::call(x, y); | |
| 423 | } | |
| 424 | ||
| 425 | // modf | |
| 426 | template<typename genType> | |
| 427 | GLM_FUNC_QUALIFIER genType modf(genType x, genType & i) | |
| 428 | { | |
| 429 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'modf' only accept floating-point inputs"); | |
| 430 | return std::modf(x, &i); | |
| 431 | } | |
| 432 | ||
| 433 | template<typename T, qualifier Q> | |
| 434 | GLM_FUNC_QUALIFIER vec<1, T, Q> modf(vec<1, T, Q> const& x, vec<1, T, Q> & i) | |
| 435 | { | |
| 436 | return vec<1, T, Q>( | |
| 437 | modf(x.x, i.x)); | |
| 438 | } | |
| 439 | ||
| 440 | template<typename T, qualifier Q> | |
| 441 | GLM_FUNC_QUALIFIER vec<2, T, Q> modf(vec<2, T, Q> const& x, vec<2, T, Q> & i) | |
| 442 | { | |
| 443 | return vec<2, T, Q>( | |
| 444 | modf(x.x, i.x), | |
| 445 | modf(x.y, i.y)); | |
| 446 | } | |
| 447 | ||
| 448 | template<typename T, qualifier Q> | |
| 449 | GLM_FUNC_QUALIFIER vec<3, T, Q> modf(vec<3, T, Q> const& x, vec<3, T, Q> & i) | |
| 450 | { | |
| 451 | return vec<3, T, Q>( | |
| 452 | modf(x.x, i.x), | |
| 453 | modf(x.y, i.y), | |
| 454 | modf(x.z, i.z)); | |
| 455 | } | |
| 456 | ||
| 457 | template<typename T, qualifier Q> | |
| 458 | GLM_FUNC_QUALIFIER vec<4, T, Q> modf(vec<4, T, Q> const& x, vec<4, T, Q> & i) | |
| 459 | { | |
| 460 | return vec<4, T, Q>( | |
| 461 | modf(x.x, i.x), | |
| 462 | modf(x.y, i.y), | |
| 463 | modf(x.z, i.z), | |
| 464 | modf(x.w, i.w)); | |
| 465 | } | |
| 466 | ||
| 467 | //// Only valid if (INT_MIN <= x-y <= INT_MAX) | |
| 468 | //// min(x,y) | |
| 469 | //r = y + ((x - y) & ((x - y) >> (sizeof(int) * | |
| 470 | //CHAR_BIT - 1))); | |
| 471 | //// max(x,y) | |
| 472 | //r = x - ((x - y) & ((x - y) >> (sizeof(int) * | |
| 473 | //CHAR_BIT - 1))); | |
| 474 | ||
| 475 | // min | |
| 476 | template<length_t L, typename T, qualifier Q> | |
| 477 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<L, T, Q> min(vec<L, T, Q> const& a, T b) | |
| 478 | { | |
| 479 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559 || std::numeric_limits<T>::is_integer, "'min' only accept floating-point or integer inputs"); | |
| 480 | return detail::compute_min_vector<L, T, Q, detail::is_aligned<Q>::value>::call(a, vec<L, T, Q>(b)); | |
| 481 | } | |
| 482 | ||
| 483 | template<length_t L, typename T, qualifier Q> | |
| 484 | ! | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<L, T, Q> min(vec<L, T, Q> const& a, vec<L, T, Q> const& b) |
| 485 | { | |
| 486 | ! | return detail::compute_min_vector<L, T, Q, detail::is_aligned<Q>::value>::call(a, b); |
| 487 | } | |
| 488 | ||
| 489 | // max | |
| 490 | template<length_t L, typename T, qualifier Q> | |
| 491 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<L, T, Q> max(vec<L, T, Q> const& a, T b) | |
| 492 | { | |
| 493 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559 || std::numeric_limits<T>::is_integer, "'max' only accept floating-point or integer inputs"); | |
| 494 | return detail::compute_max_vector<L, T, Q, detail::is_aligned<Q>::value>::call(a, vec<L, T, Q>(b)); | |
| 495 | } | |
| 496 | ||
| 497 | template<length_t L, typename T, qualifier Q> | |
| 498 | ! | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<L, T, Q> max(vec<L, T, Q> const& a, vec<L, T, Q> const& b) |
| 499 | { | |
| 500 | ! | return detail::compute_max_vector<L, T, Q, detail::is_aligned<Q>::value>::call(a, b); |
| 501 | } | |
| 502 | ||
| 503 | // clamp | |
| 504 | template<typename genType> | |
| 505 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR genType clamp(genType x, genType minVal, genType maxVal) | |
| 506 | { | |
| 507 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559 || std::numeric_limits<genType>::is_integer, "'clamp' only accept floating-point or integer inputs"); | |
| 508 | return min(max(x, minVal), maxVal); | |
| 509 | } | |
| 510 | ||
| 511 | template<length_t L, typename T, qualifier Q> | |
| 512 | ! | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<L, T, Q> clamp(vec<L, T, Q> const& x, T minVal, T maxVal) |
| 513 | { | |
| 514 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559 || std::numeric_limits<T>::is_integer, "'clamp' only accept floating-point or integer inputs"); | |
| 515 | ! | return detail::compute_clamp_vector<L, T, Q, detail::is_aligned<Q>::value>::call(x, vec<L, T, Q>(minVal), vec<L, T, Q>(maxVal)); |
| 516 | } | |
| 517 | ||
| 518 | template<length_t L, typename T, qualifier Q> | |
| 519 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR vec<L, T, Q> clamp(vec<L, T, Q> const& x, vec<L, T, Q> const& minVal, vec<L, T, Q> const& maxVal) | |
| 520 | { | |
| 521 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559 || std::numeric_limits<T>::is_integer, "'clamp' only accept floating-point or integer inputs"); | |
| 522 | return detail::compute_clamp_vector<L, T, Q, detail::is_aligned<Q>::value>::call(x, minVal, maxVal); | |
| 523 | } | |
| 524 | ||
| 525 | template<typename genTypeT, typename genTypeU> | |
| 526 | GLM_FUNC_QUALIFIER genTypeT mix(genTypeT x, genTypeT y, genTypeU a) | |
| 527 | { | |
| 528 | return detail::compute_mix<genTypeT, genTypeU>::call(x, y, a); | |
| 529 | } | |
| 530 | ||
| 531 | template<length_t L, typename T, typename U, qualifier Q> | |
| 532 | GLM_FUNC_QUALIFIER vec<L, T, Q> mix(vec<L, T, Q> const& x, vec<L, T, Q> const& y, U a) | |
| 533 | { | |
| 534 | return detail::compute_mix_scalar<L, T, U, Q, detail::is_aligned<Q>::value>::call(x, y, a); | |
| 535 | } | |
| 536 | ||
| 537 | template<length_t L, typename T, typename U, qualifier Q> | |
| 538 | GLM_FUNC_QUALIFIER vec<L, T, Q> mix(vec<L, T, Q> const& x, vec<L, T, Q> const& y, vec<L, U, Q> const& a) | |
| 539 | { | |
| 540 | return detail::compute_mix_vector<L, T, U, Q, detail::is_aligned<Q>::value>::call(x, y, a); | |
| 541 | } | |
| 542 | ||
| 543 | // step | |
| 544 | template<typename genType> | |
| 545 | GLM_FUNC_QUALIFIER genType step(genType edge, genType x) | |
| 546 | { | |
| 547 | return mix(static_cast<genType>(1), static_cast<genType>(0), x < edge); | |
| 548 | } | |
| 549 | ||
| 550 | template<length_t L, typename T, qualifier Q> | |
| 551 | GLM_FUNC_QUALIFIER vec<L, T, Q> step(T edge, vec<L, T, Q> const& x) | |
| 552 | { | |
| 553 | return detail::compute_step_vector<L, T, Q, detail::is_aligned<Q>::value>::call(vec<L, T, Q>(edge), x); | |
| 554 | } | |
| 555 | ||
| 556 | template<length_t L, typename T, qualifier Q> | |
| 557 | GLM_FUNC_QUALIFIER vec<L, T, Q> step(vec<L, T, Q> const& edge, vec<L, T, Q> const& x) | |
| 558 | { | |
| 559 | return detail::compute_step_vector<L, T, Q, detail::is_aligned<Q>::value>::call(edge, x); | |
| 560 | } | |
| 561 | ||
| 562 | // smoothstep | |
| 563 | template<typename genType> | |
| 564 | GLM_FUNC_QUALIFIER genType smoothstep(genType edge0, genType edge1, genType x) | |
| 565 | { | |
| 566 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559 || GLM_CONFIG_UNRESTRICTED_GENTYPE, "'smoothstep' only accept floating-point inputs"); | |
| 567 | ||
| 568 | genType const tmp(clamp((x - edge0) / (edge1 - edge0), genType(0), genType(1))); | |
| 569 | return tmp * tmp * (genType(3) - genType(2) * tmp); | |
| 570 | } | |
| 571 | ||
| 572 | template<length_t L, typename T, qualifier Q> | |
| 573 | GLM_FUNC_QUALIFIER vec<L, T, Q> smoothstep(T edge0, T edge1, vec<L, T, Q> const& x) | |
| 574 | { | |
| 575 | return detail::compute_smoothstep_vector<L, T, Q, detail::is_aligned<Q>::value>::call(vec<L, T, Q>(edge0), vec<L, T, Q>(edge1), x); | |
| 576 | } | |
| 577 | ||
| 578 | template<length_t L, typename T, qualifier Q> | |
| 579 | GLM_FUNC_QUALIFIER vec<L, T, Q> smoothstep(vec<L, T, Q> const& edge0, vec<L, T, Q> const& edge1, vec<L, T, Q> const& x) | |
| 580 | { | |
| 581 | return detail::compute_smoothstep_vector<L, T, Q, detail::is_aligned<Q>::value>::call(edge0, edge1, x); | |
| 582 | } | |
| 583 | ||
| 584 | # if GLM_HAS_CXX11_STL | |
| 585 | using std::isnan; | |
| 586 | # else | |
| 587 | template<typename genType> | |
| 588 | GLM_FUNC_QUALIFIER bool isnan(genType x) | |
| 589 | { | |
| 590 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'isnan' only accept floating-point inputs"); | |
| 591 | ||
| 592 | # if GLM_HAS_CXX11_STL | |
| 593 | return std::isnan(x); | |
| 594 | # elif GLM_COMPILER & GLM_COMPILER_VC | |
| 595 | return _isnan(x) != 0; | |
| 596 | # elif GLM_COMPILER & GLM_COMPILER_INTEL | |
| 597 | # if GLM_PLATFORM & GLM_PLATFORM_WINDOWS | |
| 598 | return _isnan(x) != 0; | |
| 599 | # else | |
| 600 | return ::isnan(x) != 0; | |
| 601 | # endif | |
| 602 | # elif (GLM_COMPILER & (GLM_COMPILER_GCC | GLM_COMPILER_CLANG)) && (GLM_PLATFORM & GLM_PLATFORM_ANDROID) && __cplusplus < 201103L | |
| 603 | return _isnan(x) != 0; | |
| 604 | # elif GLM_COMPILER & GLM_COMPILER_CUDA | |
| 605 | return ::isnan(x) != 0; | |
| 606 | # else | |
| 607 | return std::isnan(x); | |
| 608 | # endif | |
| 609 | } | |
| 610 | # endif | |
| 611 | ||
| 612 | template<length_t L, typename T, qualifier Q> | |
| 613 | GLM_FUNC_QUALIFIER vec<L, bool, Q> isnan(vec<L, T, Q> const& v) | |
| 614 | { | |
| 615 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'isnan' only accept floating-point inputs"); | |
| 616 | ||
| 617 | vec<L, bool, Q> Result; | |
| 618 | for (length_t l = 0; l < v.length(); ++l) | |
| 619 | Result[l] = glm::isnan(v[l]); | |
| 620 | return Result; | |
| 621 | } | |
| 622 | ||
| 623 | # if GLM_HAS_CXX11_STL | |
| 624 | using std::isinf; | |
| 625 | # else | |
| 626 | template<typename genType> | |
| 627 | GLM_FUNC_QUALIFIER bool isinf(genType x) | |
| 628 | { | |
| 629 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'isinf' only accept floating-point inputs"); | |
| 630 | ||
| 631 | # if GLM_HAS_CXX11_STL | |
| 632 | return std::isinf(x); | |
| 633 | # elif GLM_COMPILER & (GLM_COMPILER_INTEL | GLM_COMPILER_VC) | |
| 634 | # if(GLM_PLATFORM & GLM_PLATFORM_WINDOWS) | |
| 635 | return _fpclass(x) == _FPCLASS_NINF || _fpclass(x) == _FPCLASS_PINF; | |
| 636 | # else | |
| 637 | return ::isinf(x); | |
| 638 | # endif | |
| 639 | # elif GLM_COMPILER & (GLM_COMPILER_GCC | GLM_COMPILER_CLANG) | |
| 640 | # if(GLM_PLATFORM & GLM_PLATFORM_ANDROID && __cplusplus < 201103L) | |
| 641 | return _isinf(x) != 0; | |
| 642 | # else | |
| 643 | return std::isinf(x); | |
| 644 | # endif | |
| 645 | # elif GLM_COMPILER & GLM_COMPILER_CUDA | |
| 646 | // http://developer.download.nvidia.com/compute/cuda/4_2/rel/toolkit/docs/online/group__CUDA__MATH__DOUBLE_g13431dd2b40b51f9139cbb7f50c18fab.html#g13431dd2b40b51f9139cbb7f50c18fab | |
| 647 | return ::isinf(double(x)) != 0; | |
| 648 | # else | |
| 649 | return std::isinf(x); | |
| 650 | # endif | |
| 651 | } | |
| 652 | # endif | |
| 653 | ||
| 654 | template<length_t L, typename T, qualifier Q> | |
| 655 | GLM_FUNC_QUALIFIER vec<L, bool, Q> isinf(vec<L, T, Q> const& v) | |
| 656 | { | |
| 657 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'isinf' only accept floating-point inputs"); | |
| 658 | ||
| 659 | vec<L, bool, Q> Result; | |
| 660 | for (length_t l = 0; l < v.length(); ++l) | |
| 661 | Result[l] = glm::isinf(v[l]); | |
| 662 | return Result; | |
| 663 | } | |
| 664 | ||
| 665 | GLM_FUNC_QUALIFIER int floatBitsToInt(float const& v) | |
| 666 | { | |
| 667 | union | |
| 668 | { | |
| 669 | float in; | |
| 670 | int out; | |
| 671 | } u; | |
| 672 | ||
| 673 | u.in = v; | |
| 674 | ||
| 675 | return u.out; | |
| 676 | } | |
| 677 | ||
| 678 | template<length_t L, qualifier Q> | |
| 679 | GLM_FUNC_QUALIFIER vec<L, int, Q> floatBitsToInt(vec<L, float, Q> const& v) | |
| 680 | { | |
| 681 | return reinterpret_cast<vec<L, int, Q>&>(const_cast<vec<L, float, Q>&>(v)); | |
| 682 | } | |
| 683 | ||
| 684 | GLM_FUNC_QUALIFIER uint floatBitsToUint(float const& v) | |
| 685 | { | |
| 686 | union | |
| 687 | { | |
| 688 | float in; | |
| 689 | uint out; | |
| 690 | } u; | |
| 691 | ||
| 692 | u.in = v; | |
| 693 | ||
| 694 | return u.out; | |
| 695 | } | |
| 696 | ||
| 697 | template<length_t L, qualifier Q> | |
| 698 | GLM_FUNC_QUALIFIER vec<L, uint, Q> floatBitsToUint(vec<L, float, Q> const& v) | |
| 699 | { | |
| 700 | return reinterpret_cast<vec<L, uint, Q>&>(const_cast<vec<L, float, Q>&>(v)); | |
| 701 | } | |
| 702 | ||
| 703 | GLM_FUNC_QUALIFIER float intBitsToFloat(int const& v) | |
| 704 | { | |
| 705 | union | |
| 706 | { | |
| 707 | int in; | |
| 708 | float out; | |
| 709 | } u; | |
| 710 | ||
| 711 | u.in = v; | |
| 712 | ||
| 713 | return u.out; | |
| 714 | } | |
| 715 | ||
| 716 | template<length_t L, qualifier Q> | |
| 717 | GLM_FUNC_QUALIFIER vec<L, float, Q> intBitsToFloat(vec<L, int, Q> const& v) | |
| 718 | { | |
| 719 | return reinterpret_cast<vec<L, float, Q>&>(const_cast<vec<L, int, Q>&>(v)); | |
| 720 | } | |
| 721 | ||
| 722 | GLM_FUNC_QUALIFIER float uintBitsToFloat(uint const& v) | |
| 723 | { | |
| 724 | union | |
| 725 | { | |
| 726 | uint in; | |
| 727 | float out; | |
| 728 | } u; | |
| 729 | ||
| 730 | u.in = v; | |
| 731 | ||
| 732 | return u.out; | |
| 733 | } | |
| 734 | ||
| 735 | template<length_t L, qualifier Q> | |
| 736 | GLM_FUNC_QUALIFIER vec<L, float, Q> uintBitsToFloat(vec<L, uint, Q> const& v) | |
| 737 | { | |
| 738 | return reinterpret_cast<vec<L, float, Q>&>(const_cast<vec<L, uint, Q>&>(v)); | |
| 739 | } | |
| 740 | ||
| 741 | # if GLM_HAS_CXX11_STL | |
| 742 | using std::fma; | |
| 743 | # else | |
| 744 | template<typename genType> | |
| 745 | GLM_FUNC_QUALIFIER genType fma(genType const& a, genType const& b, genType const& c) | |
| 746 | { | |
| 747 | return a * b + c; | |
| 748 | } | |
| 749 | # endif | |
| 750 | ||
| 751 | template<typename genType> | |
| 752 | GLM_FUNC_QUALIFIER genType frexp(genType x, int& exp) | |
| 753 | { | |
| 754 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'frexp' only accept floating-point inputs"); | |
| 755 | ||
| 756 | return std::frexp(x, &exp); | |
| 757 | } | |
| 758 | ||
| 759 | template<length_t L, typename T, qualifier Q> | |
| 760 | GLM_FUNC_QUALIFIER vec<L, T, Q> frexp(vec<L, T, Q> const& v, vec<L, int, Q>& exp) | |
| 761 | { | |
| 762 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'frexp' only accept floating-point inputs"); | |
| 763 | ||
| 764 | vec<L, T, Q> Result; | |
| 765 | for (length_t l = 0; l < v.length(); ++l) | |
| 766 | Result[l] = std::frexp(v[l], &exp[l]); | |
| 767 | return Result; | |
| 768 | } | |
| 769 | ||
| 770 | template<typename genType> | |
| 771 | GLM_FUNC_QUALIFIER genType ldexp(genType const& x, int const& exp) | |
| 772 | { | |
| 773 | GLM_STATIC_ASSERT(std::numeric_limits<genType>::is_iec559, "'ldexp' only accept floating-point inputs"); | |
| 774 | ||
| 775 | return std::ldexp(x, exp); | |
| 776 | } | |
| 777 | ||
| 778 | template<length_t L, typename T, qualifier Q> | |
| 779 | GLM_FUNC_QUALIFIER vec<L, T, Q> ldexp(vec<L, T, Q> const& v, vec<L, int, Q> const& exp) | |
| 780 | { | |
| 781 | GLM_STATIC_ASSERT(std::numeric_limits<T>::is_iec559, "'ldexp' only accept floating-point inputs"); | |
| 782 | ||
| 783 | vec<L, T, Q> Result; | |
| 784 | for (length_t l = 0; l < v.length(); ++l) | |
| 785 | Result[l] = std::ldexp(v[l], exp[l]); | |
| 786 | return Result; | |
| 787 | } | |
| 788 | }//namespace glm | |
| 789 | ||
| 790 | #if GLM_CONFIG_SIMD == GLM_ENABLE | |
| 791 | # include "func_common_simd.inl" | |
| 792 | #endif |
| 1 | #pragma once | |
| 2 | ||
| 3 | namespace glm{ | |
| 4 | namespace detail | |
| 5 | { | |
| 6 | template<template<length_t L, typename T, qualifier Q> class vec, length_t L, typename R, typename T, qualifier Q> | |
| 7 | struct functor1{}; | |
| 8 | ||
| 9 | template<template<length_t L, typename T, qualifier Q> class vec, typename R, typename T, qualifier Q> | |
| 10 | struct functor1<vec, 1, R, T, Q> | |
| 11 | { | |
| 12 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static vec<1, R, Q> call(R (*Func) (T x), vec<1, T, Q> const& v) | |
| 13 | { | |
| 14 | return vec<1, R, Q>(Func(v.x)); | |
| 15 | } | |
| 16 | }; | |
| 17 | ||
| 18 | template<template<length_t L, typename T, qualifier Q> class vec, typename R, typename T, qualifier Q> | |
| 19 | struct functor1<vec, 2, R, T, Q> | |
| 20 | { | |
| 21 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static vec<2, R, Q> call(R (*Func) (T x), vec<2, T, Q> const& v) | |
| 22 | { | |
| 23 | return vec<2, R, Q>(Func(v.x), Func(v.y)); | |
| 24 | } | |
| 25 | }; | |
| 26 | ||
| 27 | template<template<length_t L, typename T, qualifier Q> class vec, typename R, typename T, qualifier Q> | |
| 28 | struct functor1<vec, 3, R, T, Q> | |
| 29 | { | |
| 30 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static vec<3, R, Q> call(R (*Func) (T x), vec<3, T, Q> const& v) | |
| 31 | { | |
| 32 | return vec<3, R, Q>(Func(v.x), Func(v.y), Func(v.z)); | |
| 33 | } | |
| 34 | }; | |
| 35 | ||
| 36 | template<template<length_t L, typename T, qualifier Q> class vec, typename R, typename T, qualifier Q> | |
| 37 | struct functor1<vec, 4, R, T, Q> | |
| 38 | { | |
| 39 | GLM_FUNC_QUALIFIER GLM_CONSTEXPR static vec<4, R, Q> call(R (*Func) (T x), vec<4, T, Q> const& v) | |
| 40 | { | |
| 41 | return vec<4, R, Q>(Func(v.x), Func(v.y), Func(v.z), Func(v.w)); | |
| 42 | } | |
| 43 | }; | |
| 44 | ||
| 45 | template<template<length_t L, typename T, qualifier Q> class vec, length_t L, typename T, qualifier Q> | |
| 46 | struct functor2{}; | |
| 47 | ||
| 48 | template<template<length_t L, typename T, qualifier Q> class vec, typename T, qualifier Q> | |
| 49 | struct functor2<vec, 1, T, Q> | |
| 50 | { | |
| 51 | GLM_FUNC_QUALIFIER static vec<1, T, Q> call(T (*Func) (T x, T y), vec<1, T, Q> const& a, vec<1, T, Q> const& b) | |
| 52 | { | |
| 53 | return vec<1, T, Q>(Func(a.x, b.x)); | |
| 54 | } | |
| 55 | }; | |
| 56 | ||
| 57 | template<template<length_t L, typename T, qualifier Q> class vec, typename T, qualifier Q> | |
| 58 | struct functor2<vec, 2, T, Q> | |
| 59 | { | |
| 60 | GLM_FUNC_QUALIFIER static vec<2, T, Q> call(T (*Func) (T x, T y), vec<2, T, Q> const& a, vec<2, T, Q> const& b) | |
| 61 | { | |
| 62 | return vec<2, T, Q>(Func(a.x, b.x), Func(a.y, b.y)); | |
| 63 | } | |
| 64 | }; | |
| 65 | ||
| 66 | template<template<length_t L, typename T, qualifier Q> class vec, typename T, qualifier Q> | |
| 67 | struct functor2<vec, 3, T, Q> | |
| 68 | { | |
| 69 | GLM_FUNC_QUALIFIER static vec<3, T, Q> call(T (*Func) (T x, T y), vec<3, T, Q> const& a, vec<3, T, Q> const& b) | |
| 70 | { | |
| 71 | return vec<3, T, Q>(Func(a.x, b.x), Func(a.y, b.y), Func(a.z, b.z)); | |
| 72 | } | |
| 73 | }; | |
| 74 | ||
| 75 | template<template<length_t L, typename T, qualifier Q> class vec, typename T, qualifier Q> | |
| 76 | struct functor2<vec, 4, T, Q> | |
| 77 | { | |
| 78 | ! | GLM_FUNC_QUALIFIER static vec<4, T, Q> call(T (*Func) (T x, T y), vec<4, T, Q> const& a, vec<4, T, Q> const& b) |
| 79 | { | |
| 80 | ! | return vec<4, T, Q>(Func(a.x, b.x), Func(a.y, b.y), Func(a.z, b.z), Func(a.w, b.w)); |
| 81 | } | |
| 82 | }; | |
| 83 | ||
| 84 | template<template<length_t L, typename T, qualifier Q> class vec, length_t L, typename T, qualifier Q> | |
| 85 | struct functor2_vec_sca{}; | |
| 86 | ||
| 87 | template<template<length_t L, typename T, qualifier Q> class vec, typename T, qualifier Q> | |
| 88 | struct functor2_vec_sca<vec, 1, T, Q> | |
| 89 | { | |
| 90 | GLM_FUNC_QUALIFIER static vec<1, T, Q> call(T (*Func) (T x, T y), vec<1, T, Q> const& a, T b) | |
| 91 | { | |
| 92 | return vec<1, T, Q>(Func(a.x, b)); | |
| 93 | } | |
| 94 | }; | |
| 95 | ||
| 96 | template<template<length_t L, typename T, qualifier Q> class vec, typename T, qualifier Q> | |
| 97 | struct functor2_vec_sca<vec, 2, T, Q> | |
| 98 | { | |
| 99 | GLM_FUNC_QUALIFIER static vec<2, T, Q> call(T (*Func) (T x, T y), vec<2, T, Q> const& a, T b) | |
| 100 | { | |
| 101 | return vec<2, T, Q>(Func(a.x, b), Func(a.y, b)); | |
| 102 | } | |
| 103 | }; | |
| 104 | ||
| 105 | template<template<length_t L, typename T, qualifier Q> class vec, typename T, qualifier Q> | |
| 106 | struct functor2_vec_sca<vec, 3, T, Q> | |
| 107 | { | |
| 108 | GLM_FUNC_QUALIFIER static vec<3, T, Q> call(T (*Func) (T x, T y), vec<3, T, Q> const& a, T b) | |
| 109 | { | |
| 110 | return vec<3, T, Q>(Func(a.x, b), Func(a.y, b), Func(a.z, b)); | |
| 111 | } | |
| 112 | }; | |
| 113 | ||
| 114 | template<template<length_t L, typename T, qualifier Q> class vec, typename T, qualifier Q> | |
| 115 | struct functor2_vec_sca<vec, 4, T, Q> | |
| 116 | { | |
| 117 | GLM_FUNC_QUALIFIER static vec<4, T, Q> call(T (*Func) (T x, T y), vec<4, T, Q> const& a, T b) | |
| 118 | { | |
| 119 | return vec<4, T, Q>(Func(a.x, b), Func(a.y, b), Func(a.z, b), Func(a.w, b)); | |
| 120 | } | |
| 121 | }; | |
| 122 | ||
| 123 | template<length_t L, typename T, qualifier Q> | |
| 124 | struct functor2_vec_int {}; | |
| 125 | ||
| 126 | template<typename T, qualifier Q> | |
| 127 | struct functor2_vec_int<1, T, Q> | |
| 128 | { | |
| 129 | GLM_FUNC_QUALIFIER static vec<1, int, Q> call(int (*Func) (T x, int y), vec<1, T, Q> const& a, vec<1, int, Q> const& b) | |
| 130 | { | |
| 131 | return vec<1, int, Q>(Func(a.x, b.x)); | |
| 132 | } | |
| 133 | }; | |
| 134 | ||
| 135 | template<typename T, qualifier Q> | |
| 136 | struct functor2_vec_int<2, T, Q> | |
| 137 | { | |
| 138 | GLM_FUNC_QUALIFIER static vec<2, int, Q> call(int (*Func) (T x, int y), vec<2, T, Q> const& a, vec<2, int, Q> const& b) | |
| 139 | { | |
| 140 | return vec<2, int, Q>(Func(a.x, b.x), Func(a.y, b.y)); | |
| 141 | } | |
| 142 | }; | |
| 143 | ||
| 144 | template<typename T, qualifier Q> | |
| 145 | struct functor2_vec_int<3, T, Q> | |
| 146 | { | |
| 147 | GLM_FUNC_QUALIFIER static vec<3, int, Q> call(int (*Func) (T x, int y), vec<3, T, Q> const& a, vec<3, int, Q> const& b) | |
| 148 | { | |
| 149 | return vec<3, int, Q>(Func(a.x, b.x), Func(a.y, b.y), Func(a.z, b.z)); | |
| 150 | } | |
| 151 | }; | |
| 152 | ||
| 153 | template<typename T, qualifier Q> | |
| 154 | struct functor2_vec_int<4, T, Q> | |
| 155 | { | |
| 156 | GLM_FUNC_QUALIFIER static vec<4, int, Q> call(int (*Func) (T x, int y), vec<4, T, Q> const& a, vec<4, int, Q> const& b) | |
| 157 | { | |
| 158 | return vec<4, int, Q>(Func(a.x, b.x), Func(a.y, b.y), Func(a.z, b.z), Func(a.w, b.w)); | |
| 159 | } | |
| 160 | }; | |
| 161 | }//namespace detail | |
| 162 | }//namespace glm |
| 1 | /// @ref gtc_matrix_inverse | |
| 2 | ||
| 3 | namespace glm | |
| 4 | { | |
| 5 | template<typename T, qualifier Q> | |
| 6 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> affineInverse(mat<3, 3, T, Q> const& m) | |
| 7 | { | |
| 8 | mat<2, 2, T, Q> const Inv(inverse(mat<2, 2, T, Q>(m))); | |
| 9 | ||
| 10 | return mat<3, 3, T, Q>( | |
| 11 | vec<3, T, Q>(Inv[0], static_cast<T>(0)), | |
| 12 | vec<3, T, Q>(Inv[1], static_cast<T>(0)), | |
| 13 | vec<3, T, Q>(-Inv * vec<2, T, Q>(m[2]), static_cast<T>(1))); | |
| 14 | } | |
| 15 | ||
| 16 | template<typename T, qualifier Q> | |
| 17 | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> affineInverse(mat<4, 4, T, Q> const& m) | |
| 18 | { | |
| 19 | mat<3, 3, T, Q> const Inv(inverse(mat<3, 3, T, Q>(m))); | |
| 20 | ||
| 21 | return mat<4, 4, T, Q>( | |
| 22 | vec<4, T, Q>(Inv[0], static_cast<T>(0)), | |
| 23 | vec<4, T, Q>(Inv[1], static_cast<T>(0)), | |
| 24 | vec<4, T, Q>(Inv[2], static_cast<T>(0)), | |
| 25 | vec<4, T, Q>(-Inv * vec<3, T, Q>(m[3]), static_cast<T>(1))); | |
| 26 | } | |
| 27 | ||
| 28 | template<typename T, qualifier Q> | |
| 29 | GLM_FUNC_QUALIFIER mat<2, 2, T, Q> inverseTranspose(mat<2, 2, T, Q> const& m) | |
| 30 | { | |
| 31 | T Determinant = m[0][0] * m[1][1] - m[1][0] * m[0][1]; | |
| 32 | ||
| 33 | mat<2, 2, T, Q> Inverse( | |
| 34 | + m[1][1] / Determinant, | |
| 35 | - m[0][1] / Determinant, | |
| 36 | - m[1][0] / Determinant, | |
| 37 | + m[0][0] / Determinant); | |
| 38 | ||
| 39 | return Inverse; | |
| 40 | } | |
| 41 | ||
| 42 | template<typename T, qualifier Q> | |
| 43 | GLM_FUNC_QUALIFIER mat<3, 3, T, Q> inverseTranspose(mat<3, 3, T, Q> const& m) | |
| 44 | { | |
| 45 | T Determinant = | |
| 46 | + m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) | |
| 47 | - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) | |
| 48 | + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]); | |
| 49 | ||
| 50 | mat<3, 3, T, Q> Inverse; | |
| 51 | Inverse[0][0] = + (m[1][1] * m[2][2] - m[2][1] * m[1][2]); | |
| 52 | Inverse[0][1] = - (m[1][0] * m[2][2] - m[2][0] * m[1][2]); | |
| 53 | Inverse[0][2] = + (m[1][0] * m[2][1] - m[2][0] * m[1][1]); | |
| 54 | Inverse[1][0] = - (m[0][1] * m[2][2] - m[2][1] * m[0][2]); | |
| 55 | Inverse[1][1] = + (m[0][0] * m[2][2] - m[2][0] * m[0][2]); | |
| 56 | Inverse[1][2] = - (m[0][0] * m[2][1] - m[2][0] * m[0][1]); | |
| 57 | Inverse[2][0] = + (m[0][1] * m[1][2] - m[1][1] * m[0][2]); | |
| 58 | Inverse[2][1] = - (m[0][0] * m[1][2] - m[1][0] * m[0][2]); | |
| 59 | Inverse[2][2] = + (m[0][0] * m[1][1] - m[1][0] * m[0][1]); | |
| 60 | Inverse /= Determinant; | |
| 61 | ||
| 62 | return Inverse; | |
| 63 | } | |
| 64 | ||
| 65 | template<typename T, qualifier Q> | |
| 66 | 11x | GLM_FUNC_QUALIFIER mat<4, 4, T, Q> inverseTranspose(mat<4, 4, T, Q> const& m) |
| 67 | { | |
| 68 | 11x | T SubFactor00 = m[2][2] * m[3][3] - m[3][2] * m[2][3]; |
| 69 | 11x | T SubFactor01 = m[2][1] * m[3][3] - m[3][1] * m[2][3]; |
| 70 | 11x | T SubFactor02 = m[2][1] * m[3][2] - m[3][1] * m[2][2]; |
| 71 | 11x | T SubFactor03 = m[2][0] * m[3][3] - m[3][0] * m[2][3]; |
| 72 | 11x | T SubFactor04 = m[2][0] * m[3][2] - m[3][0] * m[2][2]; |
| 73 | 11x | T SubFactor05 = m[2][0] * m[3][1] - m[3][0] * m[2][1]; |
| 74 | 11x | T SubFactor06 = m[1][2] * m[3][3] - m[3][2] * m[1][3]; |
| 75 | 11x | T SubFactor07 = m[1][1] * m[3][3] - m[3][1] * m[1][3]; |
| 76 | 11x | T SubFactor08 = m[1][1] * m[3][2] - m[3][1] * m[1][2]; |
| 77 | 11x | T SubFactor09 = m[1][0] * m[3][3] - m[3][0] * m[1][3]; |
| 78 | 11x | T SubFactor10 = m[1][0] * m[3][2] - m[3][0] * m[1][2]; |
| 79 | 11x | T SubFactor11 = m[1][0] * m[3][1] - m[3][0] * m[1][1]; |
| 80 | 11x | T SubFactor12 = m[1][2] * m[2][3] - m[2][2] * m[1][3]; |
| 81 | 11x | T SubFactor13 = m[1][1] * m[2][3] - m[2][1] * m[1][3]; |
| 82 | 11x | T SubFactor14 = m[1][1] * m[2][2] - m[2][1] * m[1][2]; |
| 83 | 11x | T SubFactor15 = m[1][0] * m[2][3] - m[2][0] * m[1][3]; |
| 84 | 11x | T SubFactor16 = m[1][0] * m[2][2] - m[2][0] * m[1][2]; |
| 85 | 11x | T SubFactor17 = m[1][0] * m[2][1] - m[2][0] * m[1][1]; |
| 86 | ||
| 87 | mat<4, 4, T, Q> Inverse; | |
| 88 | 11x | Inverse[0][0] = + (m[1][1] * SubFactor00 - m[1][2] * SubFactor01 + m[1][3] * SubFactor02); |
| 89 | 11x | Inverse[0][1] = - (m[1][0] * SubFactor00 - m[1][2] * SubFactor03 + m[1][3] * SubFactor04); |
| 90 | 11x | Inverse[0][2] = + (m[1][0] * SubFactor01 - m[1][1] * SubFactor03 + m[1][3] * SubFactor05); |
| 91 | 11x | Inverse[0][3] = - (m[1][0] * SubFactor02 - m[1][1] * SubFactor04 + m[1][2] * SubFactor05); |
| 92 | ||
| 93 | 11x | Inverse[1][0] = - (m[0][1] * SubFactor00 - m[0][2] * SubFactor01 + m[0][3] * SubFactor02); |
| 94 | 11x | Inverse[1][1] = + (m[0][0] * SubFactor00 - m[0][2] * SubFactor03 + m[0][3] * SubFactor04); |
| 95 | 11x | Inverse[1][2] = - (m[0][0] * SubFactor01 - m[0][1] * SubFactor03 + m[0][3] * SubFactor05); |
| 96 | 11x | Inverse[1][3] = + (m[0][0] * SubFactor02 - m[0][1] * SubFactor04 + m[0][2] * SubFactor05); |
| 97 | ||
| 98 | 11x | Inverse[2][0] = + (m[0][1] * SubFactor06 - m[0][2] * SubFactor07 + m[0][3] * SubFactor08); |
| 99 | 11x | Inverse[2][1] = - (m[0][0] * SubFactor06 - m[0][2] * SubFactor09 + m[0][3] * SubFactor10); |
| 100 | 11x | Inverse[2][2] = + (m[0][0] * SubFactor07 - m[0][1] * SubFactor09 + m[0][3] * SubFactor11); |
| 101 | 11x | Inverse[2][3] = - (m[0][0] * SubFactor08 - m[0][1] * SubFactor10 + m[0][2] * SubFactor11); |
| 102 | ||
| 103 | 11x | Inverse[3][0] = - (m[0][1] * SubFactor12 - m[0][2] * SubFactor13 + m[0][3] * SubFactor14); |
| 104 | 11x | Inverse[3][1] = + (m[0][0] * SubFactor12 - m[0][2] * SubFactor15 + m[0][3] * SubFactor16); |
| 105 | 11x | Inverse[3][2] = - (m[0][0] * SubFactor13 - m[0][1] * SubFactor15 + m[0][3] * SubFactor17); |
| 106 | 11x | Inverse[3][3] = + (m[0][0] * SubFactor14 - m[0][1] * SubFactor16 + m[0][2] * SubFactor17); |
| 107 | ||
| 108 | 11x | T Determinant = |
| 109 | 11x | + m[0][0] * Inverse[0][0] |
| 110 | 11x | + m[0][1] * Inverse[0][1] |
| 111 | 11x | + m[0][2] * Inverse[0][2] |
| 112 | 11x | + m[0][3] * Inverse[0][3]; |
| 113 | ||
| 114 | 11x | Inverse /= Determinant; |
| 115 | ||
| 116 | 11x | return Inverse; |
| 117 | } | |
| 118 | }//namespace glm |
| 1 | #include <Rcpp.h> | |
| 2 | using namespace Rcpp; | |
| 3 | ||
| 4 | // [[Rcpp::export]] | |
| 5 | ! | List smooth_normals_mesh_rcpp(List mesh_input, bool override_existing = false) { |
| 6 | ! | List mesh = Rcpp::clone(mesh_input); |
| 7 | ! | List shapes = Rcpp::as<List>(mesh["shapes"]); |
| 8 | ! | List vertices = Rcpp::as<List>(mesh["vertices"]); |
| 9 | ! | List normals = Rcpp::as<List>(mesh["normals"]); |
| 10 | ||
| 11 | ! | int nShapes = shapes.size(); |
| 12 | ||
| 13 | ! | for (int s = 0; s < nShapes; s++) { |
| 14 | ! | NumericMatrix curr_vertices = Rcpp::as<NumericMatrix>(vertices[s]); |
| 15 | ! | List curr_shape = Rcpp::as<List>(shapes[s]); |
| 16 | ! | NumericMatrix curr_normals = Rcpp::as<NumericMatrix>(normals[s]); |
| 17 | ! | IntegerMatrix indices = Rcpp::as<IntegerMatrix>(curr_shape["indices"]); |
| 18 | ||
| 19 | ! | int nVertices = curr_vertices.nrow(); |
| 20 | ! | int nTriangles = indices.nrow(); |
| 21 | ||
| 22 | ! | NumericMatrix new_normals(nVertices, 3); |
| 23 | ! | NumericMatrix face_normals(nTriangles, 3); |
| 24 | ||
| 25 | //Two pass algorithm: First calculate face normals, then sum to get vertex normals | |
| 26 | ! | for (int i = 0; i < nTriangles; i++) { |
| 27 | ! | NumericVector face_normal(3); |
| 28 | ! | NumericVector vec1 = curr_vertices(indices(i, 1), _) - curr_vertices(indices(i, 0), _); |
| 29 | ! | NumericVector vec2 = curr_vertices(indices(i, 2), _) - curr_vertices(indices(i, 0), _); |
| 30 | ||
| 31 | // Compute the cross product of the vectors | |
| 32 | ! | face_normal[0] += vec1[1] * vec2[2] - vec1[2] * vec2[1]; |
| 33 | ! | face_normal[1] += vec1[2] * vec2[0] - vec1[0] * vec2[2]; |
| 34 | ! | face_normal[2] += vec1[0] * vec2[1] - vec1[1] * vec2[0]; |
| 35 | ! | face_normals(i, _) = face_normal; |
| 36 | } | |
| 37 | ||
| 38 | ! | for (int i = 0; i < indices.nrow(); i++) { |
| 39 | ! | NumericVector normal(3); |
| 40 | ! | size_t idx1 = indices(i, 0); |
| 41 | ! | size_t idx2 = indices(i, 1); |
| 42 | ! | size_t idx3 = indices(i, 2); |
| 43 | ! | NumericVector norm = face_normals(i,_); |
| 44 | ||
| 45 | ! | new_normals(idx1, _) = new_normals(idx1, _) + norm; |
| 46 | ! | new_normals(idx2, _) = new_normals(idx2, _) + norm; |
| 47 | ! | new_normals(idx3, _) = new_normals(idx3, _) + norm; |
| 48 | } | |
| 49 | ||
| 50 | ! | for (int i = 0; i < new_normals.nrow(); i++) { |
| 51 | ! | double len = sqrt(sum(pow(new_normals(i, _), 2.0))); |
| 52 | ! | new_normals(i, _) = new_normals(i, _) / len; |
| 53 | } | |
| 54 | ||
| 55 | // Check if all elements of the has_vertex_normals vector are FALSE | |
| 56 | ! | LogicalVector has_vertex_normals = Rcpp::as<LogicalVector>(curr_shape["has_vertex_normals"]); |
| 57 | ! | bool allFalse = true; |
| 58 | ! | for (int i = 0; i < has_vertex_normals.size(); i++) { |
| 59 | ! | if (has_vertex_normals[i]) { |
| 60 | ! | allFalse = false; |
| 61 | ! | break; |
| 62 | } | |
| 63 | } | |
| 64 | ||
| 65 | // Update the normals for the shape if override_existing is TRUE or if all normals are FALSE | |
| 66 | ! | if (override_existing || allFalse) { |
| 67 | ! | normals[s] = new_normals; |
| 68 | ! | has_vertex_normals.fill(true); |
| 69 | ! | curr_shape["norm_indices"] = curr_shape["indices"]; |
| 70 | } | |
| 71 | } | |
| 72 | ||
| 73 | ! | return mesh; |
| 74 | } |
| 1 | #ifndef WIREFRAMEH | |
| 2 | #define WIREFRAMEH | |
| 3 | ||
| 4 | #include "Rcpp.h" | |
| 5 | #include "vec3.hpp" | |
| 6 | ||
| 7 | using namespace Rcpp; | |
| 8 | ||
| 9 | using namespace glm; | |
| 10 | ||
| 11 | ! | void line(int x0, int y0, int x1, int y1, NumericMatrix &r, NumericMatrix &b, NumericMatrix &g, vec3 color) { |
| 12 | ! | bool steep = false; |
| 13 | ! | if (std::abs(x0-x1)<std::abs(y0-y1)) { |
| 14 | ! | std::swap(x0, y0); |
| 15 | ! | std::swap(x1, y1); |
| 16 | ! | steep = true; |
| 17 | } | |
| 18 | ! | if (x0>x1) { |
| 19 | ! | std::swap(x0, x1); |
| 20 | ! | std::swap(y0, y1); |
| 21 | } | |
| 22 | ! | int dx = x1-x0; |
| 23 | ! | int dy = y1-y0; |
| 24 | ! | int derror2 = std::abs(dy)*2; |
| 25 | ! | int error2 = 0; |
| 26 | ! | int y = y0; |
| 27 | ! | for (int x=x0; x<=x1; x++) { |
| 28 | ! | if (steep) { |
| 29 | ! | r(y, x) = color[0]; |
| 30 | ! | g(y, x) = color[1]; |
| 31 | ! | b(y, x) = color[2]; |
| 32 | } else { | |
| 33 | ! | r(x, y) = color[0]; |
| 34 | ! | g(x, y) = color[1]; |
| 35 | ! | b(x, y) = color[2]; |
| 36 | } | |
| 37 | ! | error2 += derror2; |
| 38 | ! | if (error2 > dx) { |
| 39 | ! | y += (y1>y0?1:-1); |
| 40 | ! | error2 -= dx*2; |
| 41 | } | |
| 42 | } | |
| 43 | } | |
| 44 | ||
| 45 | ||
| 46 | ! | void wu_line(float x0, float y0, float x1, float y1, |
| 47 | NumericMatrix &r, NumericMatrix &b, NumericMatrix &g, vec3 color) { | |
| 48 | ! | auto ipart = [](float x) -> int {return int(std::floor(x));}; |
| 49 | ! | auto round = [](float x) -> float {return std::round(x);}; |
| 50 | ! | auto fpart = [](float x) -> float {return x - std::floor(x);}; |
| 51 | ! | auto rfpart = [=](float x) -> float {return 1 - fpart(x);}; |
| 52 | ||
| 53 | ! | const bool steep = std::fabs(y1 - y0) > std::fabs(x1 - x0); |
| 54 | ! | if (steep) { |
| 55 | ! | std::swap(x0,y0); |
| 56 | ! | std::swap(x1,y1); |
| 57 | } | |
| 58 | ! | if (x0 > x1) { |
| 59 | ! | std::swap(x0,x1); |
| 60 | ! | std::swap(y0,y1); |
| 61 | } | |
| 62 | ||
| 63 | ! | const float dx = x1 - x0; |
| 64 | ! | const float dy = y1 - y0; |
| 65 | ! | const float gradient = (dx == 0) ? 1 : dy/dx; |
| 66 | ||
| 67 | int xpx11; | |
| 68 | float intery; | |
| 69 | { | |
| 70 | ! | const float xend = round(x0); |
| 71 | ! | const float yend = y0 + gradient * (xend - x0); |
| 72 | ! | const float xgap = rfpart(x0 + 0.5); |
| 73 | ! | xpx11 = int(xend); |
| 74 | ! | const int ypx11 = ipart(yend); |
| 75 | ! | if (steep) { |
| 76 | ! | r(ypx11, xpx11) = rfpart(yend) * xgap * color[0]; |
| 77 | ! | r(ypx11 + 1, xpx11) = fpart(yend) * xgap * color[0]; |
| 78 | ! | g(ypx11, xpx11) = rfpart(yend) * xgap * color[1]; |
| 79 | ! | g(ypx11 + 1, xpx11) = fpart(yend) * xgap * color[1]; |
| 80 | ! | b(ypx11, xpx11) = rfpart(yend) * xgap * color[2]; |
| 81 | ! | b(ypx11 + 1, xpx11) = fpart(yend) * xgap * color[2]; |
| 82 | } else { | |
| 83 | ! | r(xpx11, ypx11) = rfpart(yend) * xgap * color[0]; |
| 84 | ! | r(xpx11, ypx11 + 1) = fpart(yend) * xgap * color[0]; |
| 85 | ! | g(xpx11, ypx11) = rfpart(yend) * xgap * color[1]; |
| 86 | ! | g(xpx11, ypx11 + 1) = fpart(yend) * xgap * color[1]; |
| 87 | ! | b(xpx11, ypx11) = rfpart(yend) * xgap * color[2]; |
| 88 | ! | b(xpx11, ypx11 + 1) = fpart(yend) * xgap * color[2]; |
| 89 | } | |
| 90 | ! | intery = yend + gradient; |
| 91 | } | |
| 92 | ||
| 93 | int xpx12; | |
| 94 | { | |
| 95 | ! | const float xend = round(x1); |
| 96 | ! | const float yend = y1 + gradient * (xend - x1); |
| 97 | ! | const float xgap = rfpart(x1 + 0.5); |
| 98 | ! | xpx12 = int(xend); |
| 99 | ! | const int ypx12 = ipart(yend); |
| 100 | ! | if (steep) { |
| 101 | ! | if(ypx12 + 1 < r.nrow()) { |
| 102 | ! | r(ypx12, xpx12) = rfpart(yend) * xgap * color[0]; |
| 103 | ! | r(ypx12 + 1, xpx12) = fpart(yend) * xgap * color[0]; |
| 104 | ! | g(ypx12, xpx12) = rfpart(yend) * xgap * color[1]; |
| 105 | ! | g(ypx12 + 1, xpx12) = fpart(yend) * xgap * color[1]; |
| 106 | ! | b(ypx12, xpx12) = rfpart(yend) * xgap * color[2]; |
| 107 | ! | b(ypx12 + 1, xpx12) = fpart(yend) * xgap * color[2]; |
| 108 | } | |
| 109 | } else { | |
| 110 | ! | if(ypx12 + 1 < r.ncol()) { |
| 111 | ! | r(xpx12, ypx12) = rfpart(yend) * xgap * color[0]; |
| 112 | ! | r(xpx12, ypx12 + 1) = fpart(yend) * xgap * color[0]; |
| 113 | ! | g(xpx12, ypx12) = rfpart(yend) * xgap * color[1]; |
| 114 | ! | g(xpx12, ypx12 + 1) = fpart(yend) * xgap * color[1]; |
| 115 | ! | b(xpx12, ypx12) = rfpart(yend) * xgap * color[2]; |
| 116 | ! | b(xpx12, ypx12 + 1) = fpart(yend) * xgap * color[2]; |
| 117 | } | |
| 118 | } | |
| 119 | } | |
| 120 | ||
| 121 | ! | if (steep) { |
| 122 | ! | for (int x = xpx11 + 1; x < xpx12; x++) { |
| 123 | ! | if(ipart(intery) + 1 < r.nrow()) { |
| 124 | ! | r(ipart(intery), x) = rfpart(intery) * color[0]; |
| 125 | ! | r(ipart(intery) + 1, x) = fpart(intery) * color[0]; |
| 126 | ! | g(ipart(intery), x) = rfpart(intery) * color[1]; |
| 127 | ! | g(ipart(intery) + 1, x) = fpart(intery) * color[1]; |
| 128 | ! | b(ipart(intery), x) = rfpart(intery) * color[2]; |
| 129 | ! | b(ipart(intery) + 1, x) = fpart(intery) * color[2]; |
| 130 | } | |
| 131 | ! | intery += gradient; |
| 132 | } | |
| 133 | } else { | |
| 134 | ! | for (int x = xpx11 + 1; x < xpx12; x++) { |
| 135 | ! | if(ipart(intery) + 1 < r.ncol()) { |
| 136 | ! | r(x, ipart(intery) ) = rfpart(intery) * color[0]; |
| 137 | ! | r(x, ipart(intery) + 1) = fpart(intery) * color[0]; |
| 138 | ! | g(x, ipart(intery) ) = rfpart(intery) * color[1]; |
| 139 | ! | g(x, ipart(intery) + 1) = fpart(intery) * color[1]; |
| 140 | ! | b(x, ipart(intery) ) = rfpart(intery) * color[2]; |
| 141 | ! | b(x, ipart(intery) + 1) = fpart(intery) * color[2]; |
| 142 | } | |
| 143 | ! | intery += gradient; |
| 144 | } | |
| 145 | } | |
| 146 | } | |
| 147 | ||
| 148 | ||
| 149 | // [[Rcpp::export]] | |
| 150 | ! | List wireframe(NumericMatrix verts, IntegerMatrix inds, int nx, int ny) { |
| 151 | ! | vec3 color{1,1,1}; |
| 152 | ||
| 153 | //Initialize output matrices | |
| 154 | ! | NumericMatrix r(nx,ny); |
| 155 | ! | NumericMatrix g(nx,ny); |
| 156 | ! | NumericMatrix b(nx,ny); |
| 157 | ||
| 158 | ! | int n = inds.nrow(); |
| 159 | ! | int cols = inds.ncol(); |
| 160 | ! | if(cols < 2) { |
| 161 | ! | throw std::runtime_error("Too few columns in index matrix"); |
| 162 | } | |
| 163 | ! | for(int i = 0; i < n; i++) { |
| 164 | ! | for(int j = 0; j < cols-1; j++) { |
| 165 | ! | float x0 = (verts(inds(i,j ) -1 , 0) + 1)/2 * (nx-1); |
| 166 | ! | float x1 = (verts(inds(i,j+1) -1 , 0) + 1)/2 * (nx-1); |
| 167 | ! | float y0 = (verts(inds(i,j ) -1 , 1) + 1)/2 * (ny-1); |
| 168 | ! | float y1 = (verts(inds(i,j+1) -1 , 1) + 1)/2 * (ny-1); |
| 169 | ||
| 170 | ! | wu_line(x0,y0,x1,y1,r,g,b,color); |
| 171 | } | |
| 172 | } | |
| 173 | ||
| 174 | ! | return(List::create(_["r"] = r, _["g"] = g, _["b"] = b)); |
| 175 | } | |
| 176 | ||
| 177 | #endif |