
# Crater Lake: Terrain Shading
# https://www.tylermw.com/posts/data_visualization/adding-open-street-map-data-to-rayshader-maps-in-r.html

library(rayshader)
library(raster)
library(sf)
library(osmdata)
library(dplyr)
library(ggplot2)
library(magick)

# --------------------------------------------------
# 1. Load and prepare elevation data
# --------------------------------------------------

crater <- raster(
  "~/desktop/working/dwv26/Crater_Lake.tif"
)

crater_mat <- raster_to_matrix(crater)
crater_small <- resize_matrix(crater_mat, 0.25)


# --------------------------------------------------
# 2. Generate shading layers
# --------------------------------------------------

# Basic elevation shading
base_map <- height_shade(crater_small)

# Desert texture with an explicit alpha channel
desert_overlay <- sphere_shade(
  crater_small,
  texture = "desert",
  zscale = 4,
  colorintensity = 5
) %>%
  rayimage::ray_read_image(convert_to_array = TRUE)

# Lambertian shading
lamb_shadow <- lamb_shade(
  crater_small,
  zscale = 6
)

# Fine terrain texture
texture_shadow <- texture_shade(
  crater_small,
  detail = 0.8,
  contrast = 9,
  brightness = 11
)

# Ambient occlusion shading
ambient_shadow <- ambient_shade(crater_small)


# --------------------------------------------------
# 3. Map 1: Basic elevation shading
# --------------------------------------------------

base_map %>%
  plot_map()


# --------------------------------------------------
# 4. Map 2: Add desert texture
# --------------------------------------------------

base_map %>%
  add_overlay(
    desert_overlay,
    alphalayer = 0.5
  ) %>%
  plot_map()


# --------------------------------------------------
# 5. Map 3: Add Lambertian shading
# --------------------------------------------------

base_map %>%
  add_overlay(
    desert_overlay,
    alphalayer = 0.5
  ) %>%
  add_shadow(lamb_shadow, max_darken = 0) %>%
  plot_map()


# --------------------------------------------------
# 6. Map 4: Add fine terrain texture
# --------------------------------------------------

base_map %>%
  add_overlay(
    desert_overlay,
    alphalayer = 0.5
  ) %>%
  add_shadow(lamb_shadow, max_darken = 0) %>%
  add_shadow(texture_shadow, max_darken = 0.1) %>%
  plot_map()


# --------------------------------------------------
# 7. Map 5: Add ambient occlusion
# --------------------------------------------------

base_map %>%
  add_overlay(
    desert_overlay,
    alphalayer = 0.5
  ) %>%
  add_shadow(lamb_shadow, max_darken = 0) %>%
  add_shadow(ambient_shadow, max_darken = 0) %>%
  add_shadow(texture_shadow, max_darken = 0.1) %>%
  plot_map()



# --------------------------------------------------
# 8. Map 6: Add blue water
# --------------------------------------------------

# Identify water surfaces
water_map <- detect_water(
  crater_small,
  min_area = 100
)

base_map %>%
  add_overlay(
    desert_overlay,
    alphalayer = 0.5
  ) %>%
  add_shadow(lamb_shadow, max_darken = 0) %>%
  add_shadow(ambient_shadow, max_darken = 0) %>%
  add_shadow(texture_shadow, max_darken = 0.1) %>%
  add_water(water_map, color = "#2471A3") %>%
  plot_map()


# Better water!


# --------------------------------------------------
# 8. Map 6: Add water from OpenStreetMap
# --------------------------------------------------

# Get the geographic extent of our elevation raster
crater_bbox <- st_bbox(
  c(
    xmin = xmin(crater),
    ymin = ymin(crater),
    xmax = xmax(crater),
    ymax = ymax(crater)
  ),
  crs = st_crs(projection(crater))
)

# Convert bounding box to latitude/longitude for OSM
osm_bbox <- crater_bbox %>%
  st_as_sfc() %>%
  st_transform(4326) %>%
  st_bbox()

# Download water features from OpenStreetMap
osm_water <- opq(bbox = osm_bbox) %>%
  add_osm_feature(key = "natural", value = "water") %>%
  osmdata_sf()

# Combine ordinary polygons and multipolygons
water_polygons <- bind_rows(
  select(osm_water$osm_polygons, geometry),
  select(osm_water$osm_multipolygons, geometry)
)

# Match the coordinate system of the elevation raster
water_polygons <- water_polygons %>%
  st_transform(st_crs(projection(crater)))

# Convert OSM water polygons to a blue image overlay
water_overlay <- generate_polygon_overlay(
  water_polygons,
  extent = extent(crater),
  heightmap = crater_small,
  palette = "#2471A3",
  linewidth = NA
)

# Draw the map with the water overlay
base_map %>%
  add_overlay(desert_overlay, alphalayer = 0.5) %>%
  add_shadow(lamb_shadow, max_darken = 0) %>%
  add_shadow(ambient_shadow, max_darken = 0) %>%
  add_shadow(texture_shadow, max_darken = 0.1) %>%
  add_overlay(water_overlay) %>%
  plot_map()




# --------------------------------------------------
# 8. Map 6: OSM lakes and streams
# --------------------------------------------------

map_crs <- st_crs(projection(crater))

# 1. Separate water multipolygons from ordinary polygons

water_multi <- osm_water$osm_multipolygons %>%
  filter(natural == "water") %>%
  st_transform(map_crs)

water_simple <- osm_water$osm_polygons %>%
  filter(natural == "water") %>%
  st_transform(map_crs)

# 2. Keep multipolygons (which preserve island holes)
# and ordinary polygons that do not overlap them

if (nrow(water_multi) == 0) {
  stop("No water multipolygons found in OSM data.")
}

water_simple <- water_simple[
  lengths(st_intersects(water_simple, water_multi)) == 0,
]

water_polygons <- rbind(
  st_sf(geometry = st_geometry(water_multi)),
  st_sf(geometry = st_geometry(water_simple))
)

# 3. Create blue lake overlay

water_overlay <- generate_polygon_overlay(
  water_polygons,
  extent = extent(crater),
  heightmap = crater_small,
  palette = "#2471A3",
  linewidth = NA
)

# 4. Download streams and other waterways

osm_streams <- opq(bbox = osm_bbox) %>%
  add_osm_feature(
    key = "waterway",
    value = c("stream", "river", "ditch", "drain")
  ) %>%
  osmdata_sf()

streams <- osm_streams$osm_lines %>%
  filter(waterway %in% c("stream", "river", "ditch", "drain")) %>%
  st_transform(map_crs)

# 5. Generate stream overlay

stream_overlay <- NULL

if (nrow(streams) > 0) {
  stream_overlay <- generate_line_overlay(
    streams,
    extent = extent(crater),
    heightmap = crater_small,
    color = "#2471A3",
    linewidth = 2
  )
}

# 6. Draw final map

final_map <- base_map %>%
  add_overlay(desert_overlay, alphalayer = 0.5) %>%
  add_shadow(lamb_shadow, max_darken = 0) %>%
  add_shadow(ambient_shadow, max_darken = 0) %>%
  add_shadow(texture_shadow, max_darken = 0.1) %>%
  add_overlay(water_overlay)

if (!is.null(stream_overlay)) {
  final_map <- final_map %>%
    add_overlay(stream_overlay)
}

final_map %>%
  plot_map()




# --------------------------------------------------
# 9. Map 7: Add Rim Drive with a black outline
# --------------------------------------------------

# Download roads from OpenStreetMap
osm_roads <- opq(bbox = osm_bbox) %>%
  add_osm_feature(key = "highway") %>%
  osmdata_sf()

# Select East and West Rim Drive
rim_road <- osm_roads$osm_lines %>%
  filter(
    !is.na(name),
    grepl("Rim Drive|Rim Dr", name, ignore.case = TRUE)
  ) %>%
  st_transform(map_crs)

# Check that OSM returned the road
if (nrow(rim_road) == 0) {
  stop("Rim Drive not found. Check OSM road names.")
}

# Black outline (wider line)
road_outline <- generate_line_overlay(
  rim_road,
  extent = extent(crater),
  heightmap = crater_small,
  color = "black",
  linewidth = 5
)

# White road (narrower line)
road_white <- generate_line_overlay(
  rim_road,
  extent = extent(crater),
  heightmap = crater_small,
  color = "white",
  linewidth = 2.5
)

# Add road layers to Map 6
final_map %>%
  add_overlay(road_outline) %>%
  add_overlay(road_white) %>%
  plot_map()



# --------------------------------------------------
# 10. Map 8: Roads, hiking trails, and Mount Scott
# --------------------------------------------------

# 1. Separate roads and hiking trails

all_routes <- osm_roads$osm_lines %>%
  st_transform(map_crs)

# Hiking paths and pedestrian trails
trails <- all_routes %>%
  filter(highway %in% c(
    "path", "footway", "steps", "bridleway", "pedestrian"
  ))

# Other roads, excluding Rim Drive
other_roads <- all_routes %>%
  filter(highway %in% c(
    "primary", "secondary", "tertiary",
    "unclassified", "residential",
    "service", "track", "road"
  )) %>%
  filter(!grepl(
    "Rim Drive|Rim Dr",
    coalesce(name, ""),
    ignore.case = TRUE
  ))


# 2. Draw other roads with thinner white/black styling

other_road_outline <- generate_line_overlay(
  other_roads,
  extent = extent(crater),
  heightmap = crater_small,
  color = "black",
  linewidth = 3
)

other_road_white <- generate_line_overlay(
  other_roads,
  extent = extent(crater),
  heightmap = crater_small,
  color = "white",
  linewidth = 1.5
)


# 3. Draw trails as thin dashed black lines

trail_overlay <- generate_line_overlay(
  trails,
  extent = extent(crater),
  heightmap = crater_small,
  color = "black",
  linewidth = 1.5,
  lty = 2
)


# 4. Locate Mount Scott (USGS summit coordinates)

mt_scott <- st_as_sf(
  data.frame(
    lon = -122.0160296,
    lat = 42.9229346
  ),
  coords = c("lon", "lat"),
  crs = 4326
) %>%
  st_transform(map_crs)

scott_xy <- st_coordinates(mt_scott)

# Verify the summit falls within the raster
if (
  scott_xy[1, 1] < xmin(crater) ||
  scott_xy[1, 1] > xmax(crater) ||
  scott_xy[1, 2] < ymin(crater) ||
  scott_xy[1, 2] > ymax(crater)
) {
  warning("Mount Scott is outside the elevation raster extent.")
}


# 5. Create a white triangle with red outline
# Using a transparent PNG allows separate fill
# and border colors for the point symbol.

marker_file <- tempfile(fileext = ".png")

png(
  marker_file,
  width = nrow(crater_small),
  height = ncol(crater_small),
  bg = "transparent"
)

par(mar = c(0, 0, 0, 0))

plot(
  NA,
  xlim = c(xmin(crater), xmax(crater)),
  ylim = c(ymin(crater), ymax(crater)),
  xaxs = "i", yaxs = "i",
  axes = FALSE,
  xlab = "", ylab = "",
  type = "n"
)

points(
  scott_xy[1, 1],
  scott_xy[1, 2],
  pch = 24,
  bg = "white",
  col = "#CC2222",
  lwd = 2,
  cex = 2
)

dev.off()

scott_overlay <- png::readPNG(marker_file)


# 6. Draw the completed map

final_map %>%
  add_overlay(trail_overlay) %>%
  add_overlay(other_road_outline) %>%
  add_overlay(other_road_white) %>%
  add_overlay(road_outline) %>%
  add_overlay(road_white) %>%
  add_overlay(scott_overlay) %>%
  plot_map()




###################


# --------------------------------------------------
# 11. Map 9: Park boundary, darker water, and title
# --------------------------------------------------

# 1. Darken the lake

dark_water_overlay <- generate_polygon_overlay(
  water_polygons,
  extent = extent(crater),
  heightmap = crater_small,
  palette = "#1E5F8A",
  linewidth = NA
)


# 2. Download Crater Lake National Park boundary
# OSM relation ID: 1274747

park_osm <- opq_osm_id(
  id = "1274747",
  type = "relation",
  timeout = 90
) %>%
  opq_string() %>%
  osmdata_sf()


# 3. Extract the park boundary

if (!is.null(park_osm$osm_multipolygons) &&
    nrow(park_osm$osm_multipolygons) > 0) {

  park_boundary <- st_sf(
    geometry = st_boundary(
      st_geometry(park_osm$osm_multipolygons)
    )
  )

} else if (!is.null(park_osm$osm_multilines) &&
           nrow(park_osm$osm_multilines) > 0) {

  park_boundary <- park_osm$osm_multilines

} else {
  stop("Could not extract the OSM park boundary.")
}

park_boundary <- park_boundary %>%
  st_transform(map_crs)


# 4. Generate a thick brown boundary line

boundary_overlay <- generate_line_overlay(
  park_boundary,
  extent = extent(crater),
  heightmap = crater_small,
  color = "#75472B",
  linewidth = 5
)


# 5. Rebuild the map with all existing features

map9 <- final_map %>%
  add_overlay(dark_water_overlay) %>%
  add_overlay(trail_overlay) %>%
  add_overlay(other_road_outline) %>%
  add_overlay(other_road_white) %>%
  add_overlay(road_outline) %>%
  add_overlay(road_white) %>%
  add_overlay(boundary_overlay) %>%
  add_overlay(scott_overlay)


# 6. Add white title in the upper left

map9 %>%
  plot_map(
    title_text = "Crater Lake National Park",
    title_color = "white",
    title_size = 60,
    title_font = "sans",
    title_style = "bold",
    title_offset = c(22, 22)
  )


#################
#################


# --------------------------------------------------
# 12. Map 10: Slightly tilted 3D perspective
# --------------------------------------------------

map9 %>%
  plot_3d(
    crater_small,
    zscale = 6,
    theta = 20,
    phi = 70,
    zoom = 0.75,
    fov = 0,
    windowsize = c(1200, 900),
    background = "#202020",
    solid = FALSE
  )

# Bank the view: a lower camera angle lets the shaded relief stand out
render_camera(theta = 20, phi = 35, zoom = 0.6)

render_snapshot(
  title_text = "Crater Lake National Park",
  title_color = "white",
  title_size = 30,
  title_offset = c(25, 25)
)
