library(osmdata)
library(sf)
library(dplyr)
library(ggplot2)
library(rgdal)
library(raster)
library(rayshader)
library(tidyverse)
library(broom)


# https://www.tylermw.com/adding-open-street-map-data-to-rayshader-maps-in-r/

#remotes::install_github("tylermorganwall/rayshader",force=TRUE)
#rayrender

rutrast<-"C:/Users/Claudia.Guerrero/Dropbox/Investigacion y escritos/shinydashboardcgs/"
rst_mosaic <-raster(paste0(rutrast,'coadgo.tif'))
#rst_mosaic <-zonaproyectada

rutacam<-"D:/Documents/Claudia/Midropbox/Investigacion y escritos/mapasnacionales/"
limitesbox<-read.csv(paste0(rutacam,"limites.txt"),header=TRUE, sep=",",encoding="latin")
names(limitesbox)<-c("long","lat")
p = Polygon(limitesbox)
ps = Polygons(list(p),1)

sps = SpatialPolygons(list(ps))
sp::proj4string(sps) <- CRS("+proj=longlat +datum=WGS84 +no_defs")

rutamc<-"D:/Documents/Claudia/Midropbox/Investigacion y escritos/mapasnacionales/mexico-latest-free.shp"
#rutacam<-"D:/Documents/Claudia/Midropbox/Investigacion y escritos/mapasnacionales/mexico-latest-free.shp/"
mexosmlayer <- readOGR(rutamc,"gis_osm_waterways_free_1", use_iconv = TRUE, encoding = "latin1")
## OGR data source with driver: ESRI Shapefile 
## Source: "D:\Documents\Claudia\Midropbox\Investigacion y escritos\mapasnacionales\mexico-latest-free.shp", layer: "gis_osm_waterways_free_1"
## with 82019 features
## It has 5 fields
mexosmroads <- readOGR(rutamc,"gis_osm_roads_free_1", use_iconv = TRUE, encoding = "latin1")
## OGR data source with driver: ESRI Shapefile 
## Source: "D:\Documents\Claudia\Midropbox\Investigacion y escritos\mapasnacionales\mexico-latest-free.shp", layer: "gis_osm_roads_free_1"
## with 4294586 features
## It has 10 fields
## Integer64 fields read as strings:  layer
sp::proj4string(mexosmlayer) <- CRS("+proj=longlat +datum=WGS84 +no_defs")
recorte <- crop(mexosmlayer, extent(sps))
recorteosmlayer <- recorte
#recorteosmlayer$id<-rownames(recorteosmlayer@data)
#recorteosmlayer_df <- tidy(recorteosmlayer,region="id")
#recorteosmlayer_df <- left_join(recorteosmlayer_df,recorteosmlayer@data,by = "id")

sp::proj4string(mexosmroads) <- CRS("+proj=longlat +datum=WGS84 +no_defs")


memory.limit(size=10000000)
## [1] 1e+07
recorteosmroads <- crop(mexosmroads, extent(sps))
#recorteosmroads <- recorteroads
#recorteosmroads$id<-rownames(recorteosmroads@data)
#memory.limit(size=10000000)
#recorteosmroads_df <-as.data.frame(recorteosmroads)
#recorteosmroads_df <- tidy(recorteosmroads,region="id")
#recorteosmroads_df <- left_join(recorteosmroads_df,recorteosmroads@data,by = "id")


#ef <-extent(-105.2032470, -103.2531738, 25.0532571, 25.8048368)
ef <-extent(sps)
rstmos<-crop(rst_mosaic,ef)
#https://www.tylermw.com/adding-open-street-map-data-to-rayshader-maps-in-r/

bryce_mat = raster_to_matrix(rstmos)
bryce_small = resize_matrix(bryce_mat,0.25)
bryce_small %>% 
  height_shade() %>% 
  plot_map()

bryce_small %>% 
  height_shade() %>% 
  add_overlay(sphere_shade(bryce_small, texture = "desert", zscale=4, colorintensity = 5), alphalayer=0.5) %>%
  plot_map()

bryce_small %>% 
  height_shade() %>% 
  add_overlay(sphere_shade(bryce_small, texture = "desert", zscale=4, colorintensity = 5), alphalayer=0.5) %>%
  add_shadow(lamb_shade(bryce_small,zscale = 6),0) %>%
  plot_map()

#remotes::install_github("tylermorganwall/rayrender",force=TRUE)
bryce_small %>% 
  height_shade() %>% 
  add_overlay(sphere_shade(bryce_small, texture = "desert", zscale=4, colorintensity = 5), alphalayer=0.5) %>%
  add_shadow(lamb_shade(bryce_small,zscale=6), 0) %>%
  add_shadow(texture_shade(bryce_small,detail=8/10,contrast=9,brightness = 11), 0.1) %>%
  plot_map()

bryce_small %>% 
  height_shade() %>% 
  add_overlay(sphere_shade(bryce_small, texture = "desert", 
                           zscale=4, colorintensity = 5), alphalayer=0.5) %>%
  add_shadow(lamb_shade(bryce_small,zscale=6), 0) %>%
  add_shadow(ambient_shade(bryce_small), 0) %>%
  add_shadow(texture_shade(bryce_small,detail=8/10,contrast=9,brightness = 11), 0.1) %>%
  plot_map()

#render_snapshot()
#rgl::rgl.close()

watercolor = "#2a89b3"
maxcolor = "#e6dbc8"
mincolor = "#b6bba5"
contour_color = "#7d4911"

bryce_small %>% 
  height_shade(texture = grDevices::colorRampPalette(c(mincolor,maxcolor))(256)) %>%
  add_shadow(lamb_shade(bryce_small),0.2) %>% 
  plot_map(title_text="Comarca Lagunera", title_color = "white",
           title_bar_alpha = 1, title_bar_color = "black")

base_map = bryce_small %>% 
  height_shade(texture = grDevices::colorRampPalette(c(mincolor,maxcolor))(256)) %>%
  add_overlay(sphere_shade(bryce_small, texture = "desert", 
                           zscale=4, colorintensity = 5), alphalayer=0.5) %>%
  add_shadow(lamb_shade(bryce_small,zscale=6), 0) %>%
  add_shadow(ambient_shade(bryce_small), 0) %>%
  add_shadow(texture_shade(bryce_small,detail=8/10,contrast=9,brightness = 11), 0.1)%>%
  plot_map(title_text="Comarca Lagunera", title_color = "white",
           title_bar_alpha = 1, title_bar_color = "black")

base_map = bryce_small %>% 
height_shade(texture = "white") %>%
  add_shadow(lamb_shade(bryce_small),0.6) %>% 
  add_shadow(ambient_shade(bryce_small), 0) %>%
  add_shadow(texture_shade(bryce_small,detail=8/10,contrast=9,brightness = 11), 0.1)%>%
  plot_map(title_text="Comarca Lagunera", title_color = "white",
           title_bar_alpha = 1, title_bar_color = "black")

base_map = bryce_small %>% 
  sphere_shade(texture = create_texture("#f5dfca","#63372c","#dfa283","#195f67","#c2d1cf",
                                        cornercolors = c("#ffc500", "#387642", "#d27441","#296176")),
               sunangle = 0, colorintensity = 5) %>%
  add_shadow(lamb_shade(bryce_small),0.2) %>%
  add_water(detect_water(bryce_small)) %>%
  plot_map()

base_map = bryce_small %>% 
  height_shade() %>%
  add_shadow(texture_shade(bryce_small,detail=8/10,contrast=9,brightness = 11), 0) 


bryce_lines = st_as_sf(recorteosmlayer, crs=crs(bryce_small))
bryce_lines2 = st_as_sf(recorteosmroads, crs=crs(bryce_small))
#bryce_lines3 = st_as_sf(torcoa2, crs=crs(bryce_small))
subbryce_lines<-subset(bryce_lines, fclass == "river")

base_map %>% 
  add_overlay(generate_line_overlay(subbryce_lines,extent = ef,linewidth = 10, color="#263C38",heightmap = bryce_small)) %>% 
  add_overlay(generate_line_overlay(bryce_lines2,extent = ef,linewidth = 1, color="black",heightmap = bryce_small)) %>% 
 # add_overlay(generate_line_overlay(bryce_lines3,extent = ef,linewidth = 1, color="red",heightmap = bryce_small)) %>%
  plot_map() 

#  save_png("3filename_map")

base_map = bryce_small %>% 
  sphere_shade(texture = create_texture("#f5dfca","#63372c","#dfa283","#195f67","#c2d1cf",
                                        cornercolors = c("#ffc500", "#387642", "#d27441","#296176")),
               sunangle = 0, colorintensity = 5) %>%
  add_shadow(lamb_shade(bryce_small),0.2) 
  
base_map %>% 
  add_overlay(generate_line_overlay(subbryce_lines,extent = ef,linewidth = 10, color="#263C38",heightmap = bryce_small)) %>% 
  add_overlay(generate_line_overlay(bryce_lines2,extent = ef,linewidth = 1, color="red",heightmap = bryce_small)) %>% 
  #add_overlay(generate_line_overlay(bryce_lines3,extent = ef,linewidth = 1, color="black",heightmap = bryce_small)) %>%
  save_png("4filename_map") 


#Sys.sleep(0.2)
#render_snapshot()
#rgl::rgl.open()