rayshader

repository·master·Indexed 24 days ago

https://github.com/tylermorganwall/rayshader

An R package for creating high-quality 2D and 3D visualizations. It specializes in transforming elevation matrices into shaded maps and converting ggplot2 objects into 3D surfaces using raytracing and advanced shading algorithms. Key features include 2D/3D mapping, integration with rayrender for cinematic high-quality rendering, support for spatial objects (points, paths, polygons) via the sf library, and the ability to export 3D models to STL and OBJ formats.

Tokens
4.5K
Snippets
11
Records
23
Agent score
30%

What's inside rayshader

  1. Overview of rayshader capabilities

    master

    What is rayshader?

    rayshader is an R package used to produce 2D and 3D data visualizations. It primarily works by using elevation data in a base R matrix and applying raytracing, hillshading algorithms, and overlays.

    Key Features

    • 2D/3D Mapping: Generate stunning maps from elevation matrices using various shading techniques.
    • ggplot2 Integration: Translate ggplot2 objects into 3D data visualizations using plot_gg().
    • Interactive & Scripted Views: Rotate models interactively or script camera movements to create animations.
    • High-Quality Rendering: Use the rayrender pathtracer for realistic light transport and cinematic depth-of-field effects.
    • Export Options: Export 3D models to STL (for 3D printing) or OBJ formats.
  2. Install system dependencies for Ubuntu

    master

    If you are using Ubuntu, you must install the following system libraries before installing the R package to ensure all features (like rendering and spatial processing) work correctly:

    libpng-dev libjpeg-dev libfreetype6-dev libglu1-mesa-dev libgl1-mesa-dev pandoc zlib1g-dev libicu-dev libgdal-dev gdal-bin libgeos-dev libproj-dev
  3. Create 2D maps with rayshader

    master

    You can generate 2D shaded maps by converting a raster to a matrix and applying shading functions.

    Key functions:

    • raster_to_matrix(): Converts a raster object to a matrix.
    • sphere_shade(): Applies a texture (e.g., texture = "desert") and can shift sun direction using sunangle.
    • detect_water(): Identifies water areas in the matrix.
    • add_water(): Adds a colored water layer to the map.
    • add_shadow(): Adds shadows using ray_shade() or ambient_shade().
    • plot_map(): Renders the final 2D map.
    library(rayshader)
    
    # Convert raster to matrix
    elmat = raster_to_matrix(localtif)
    
    # Basic 2D map with texture
    elmat |>
        sphere_shade(texture = "desert") |
        plot_map()
    
    # 2D map with water, ray-traced shadows, and ambient occlusion
    elmat |>
        sphere_shade(texture = "desert") |
        add_water(detect_water(elmat), color = "desert") |
        add_shadow(ray_shade(elmat), 0.5) |
        add_shadow(ambient_shade(elmat, maxsearch = 30), 0) |
        plot_map()
  4. Render high-quality images with render_highquality()

    master

    For professional-grade rendering, use render_highquality(), which is powered by rayrender. When using this method, you do not need to pre-compute shadows with _shade() functions.

    Key features:

    • Atmospheric/Sun Modeling: Pass lat, long, and datetime (as POSIXct) to render realistic lighting for a specific time and place.
    • Customization: Control samples, text_size, and line_radius for labels.
    • Ground Material: Use rayrender functions like diffuse() to set ground textures (e.g., checker patterns).
    # High quality render with specific location and time
    elmat_lat_long = c(-42.745792, 147.171103)
    render_highquality(
        samples = 16,
        lat = elmat_lat_long[1],
        long = elmat_lat_long[2],
        iso = 5, 
        clamp_value = 1000,
        datetime = as.POSIXct("2025-06-21 15:00:00", tz = "Australia/Sydney"), 
        sky_args = list(hosek = FALSE),
        width=1000, height=800
    )
  5. Capture 3D snapshots with render_snapshot()

    master

    After using plot_gg() to initialize a 3D view, use render_snapshot() to capture the current view as an image.

    Parameters:

    • clear: Boolean; if TRUE, clears the current scene.
    • plot: Boolean; if FALSE, prevents the function from re-plotting the ggplot object (useful when you just want to capture the existing 3D state).
  6. Create 3D plots from ggplot2 objects with plot_gg()

    master

    The plot_gg() function allows you to project ggplot2 objects into 3D space. Rayshader automatically detects aesthetics like fill or color to determine how to map the figure into 3D.

    Key behaviors:

    • If fill is mapped, it is used for the 3D projection.
    • If color is mapped (and fill is not), it is used for the 3D projection.
    • If both color and fill are provided, fill takes precedence.
    • Elements like lines or contours that are not part of the primary aesthetic mapping are automatically ignored and not projected into 3D.

    Common parameters for plot_gg():

    • width, height: Dimensions of the plot.
    • raytrace: Boolean; enables raytracing effects.
    • preview: Boolean; returns a quick preview snapshot.
    • multicore: Boolean; enables multicore processing.
    • scale: Controls the vertical scale/elevation.
    • zoom: Controls the camera zoom.
    • theta, phi: Camera rotation angles.
    • windowsize: A vector c(width, height) for the rendering window.
    • max_error: Increases the allowable error in triangulation (powered by {terrainmeshr}) to reduce model size and improve performance without significant quality loss.
    # Basic usage to create a 3D density plot
    plot_gg(
        ggdiamonds,
        width = 5,
        height = 5,
        raytrace = FALSE,
        preview = TRUE
    )
  7. Add labels, scale bars, and compasses

    master

    Enhance your 3D maps with annotations and navigational aids:

    • render_label(): Adds text labels at specific x, y, z coordinates. Customize textcolor, linecolor, textsize, and linewidth.
    • render_scalebar(): Adds a scale bar. Use limits for scale values, label_unit (e.g., "km"), and position (e.g., "W").
    • render_compass(): Adds a compass at a specified position (e.g., "E").
    • render_camera(): Sets the camera position (fov, theta, zoom, phi) before rendering snapshots.
    # Adding a label
    render_label(
        montereybay,
        x = 50, y = 270, z = 1000,
        zscale = 50,
        text = "Monterey Canyon",
        textcolor = "white",
        linecolor = "white",
        textsize = 5,
        linewidth = 5
    )
    
    # Adding scale bar and compass
    render_scalebar(limits = c(0, 5, 10), label_unit = "km", position = "W")
    render_compass(position = "E")
  8. Render 3D spatial objects (Points, Paths, Polygons)

    master

    You can overlay spatial data from the sf library onto your 3D maps:

    • render_polygons(): Renders polygons. Use extent to match the map, data_column_top for scaling, and color for styling.
    • render_points(): Renders points using lat, long, and altitude. Use size and color for styling.
    • render_path(): Renders lines/paths. Use linewidth, color, and antialias. Setting use_extruded_paths = TRUE in render_highquality() can create 3D paths.
    # Render Polygons
    render_polygons(
        mont_county_buff,
        extent = attr(montereybay, "extent"),
        data_column_top = "ALAND",
        scale_data = 300 / (2.6E9),
        color = "chartreuse4",
        parallel = TRUE
    )
    
    # Render Points
    render_points(
        extent = attr(montereybay, "extent"),
        lat = unlist(bird_track_lat),
        long = unlist(bird_track_long),
        altitude = z_out,
        zscale = 50,
        size = 3,
        color = "red"
    )
  9. Add clouds and procedural weather

    master

    Rayshader allows adding procedurally-generated cloud layers using cloud_shade() and render_clouds().

    • cloud_shade(): Generates a cloud texture to be added as a shadow layer.
    • render_clouds(): Renders the clouds in the 3D scene.

    Key parameters for render_clouds():

    • start_altitude, end_altitude: Vertical range of clouds.
    • sun_altitude: Sun angle for cloud lighting.
    • attenuation_coef: Cloud density/light attenuation.
    • cloud_cover: Coverage percentage.
    • frequency: Cloud pattern frequency.
    • clear_clouds: Boolean to clear existing clouds.
    # Adding cloud shadows to a 3D map
    elmat |> 
        sphere_shade(texture = "desert") |
        add_water(detect_water(elmat), color = "lightblue") |
        add_shadow(
            cloud_shade(
                elmat,
                zscale = 10,
                start_altitude = 500,
                end_altitude = 1000
            ),
            0
        ) |
        plot_3d(elmat, zscale = 10)
    
    # Rendering the clouds
    render_clouds(
        elmat,
        zscale = 10,
        start_altitude = 800,
        end_altitude = 1000,
        attenuation_coef = 5,
        sun_altitude = 10,
        clear_clouds = T
    )
  10. Create 3D maps with plot_3d()

    master

    Rayshader supports 3D mapping by passing a texture map into plot_3d(). You can control the camera view, scale, and background.

    Key parameters for plot_3d():

    • zscale: Vertical exaggeration.
    • fov: Field of view.
    • theta, phi: Camera rotation angles.
    • zoom: Zoom level.
    • windowsize: Vector c(width, height).
    • background: Background color.
    • water: Boolean to enable water layer.
    • waterdepth, wateralpha, watercolor, waterlinecolor, waterlinealpha: Water customization.
    • baseshape: Map shape, e.g., "circle" or "hex".
    elmat |> 
        sphere_shade(texture = "desert") |
        add_water(detect_water(elmat), color = "desert") |
        add_shadow(ray_shade(elmat, zscale = 3), 0.3) |
        add_shadow(ambient_shade(elmat), 0) |
        plot_3d(
            elmat,
            zscale = 10,
            fov = 0,
            theta = 135,
            zoom = 0.75,
            phi = 45,
            windowsize = c(1000, 800)
        )