rayrender R Package

repository·master·Indexed 20 days ago

https://github.com/tylermorganwall/rayrender

An open-source R package providing a tidy interface for raytracing scenes using a fast C++ pathtracer. It supports scene construction with primitives and meshes, various materials (diffuse, metallic, dielectric, glossy, microfacet, and light-emitting), procedural and image textures, and HDR environment lighting. Features include multicore support via RcppThread, OBJ and PLY file support, Constructive Solid Geometry (CSG) operations, and optional denoising via Intel Open Image Denoise (OIDN).

Tokens
4.9K
Snippets
17
Records
21
Agent score
21%

What's inside rayrender

  1. Overview of rayrender

    master

    rayrender is an open-source R package for raytracing scenes created in R. It provides a tidy R interface to a fast C++ pathtracer.

    Key features include:

    • Scene Construction: Uses a pipeable iterative interface to build scenes from primitives and meshes.
    • Material Support: Supports diffuse, metallic, dielectric (glass), glossy, microfacet, and light-emitting materials.
    • Textures: Supports procedural and user-specified image, roughness, bump, and normal textures, as well as HDR environment lighting.
    • Performance: Multicore support via RcppThread and random number generation via PCG RNG.
    • File Support: Supports OBJ and PLY formats.
    • Denoising: Optional support for Intel Open Image Denoise (OIDN).
  2. Use Constructive Solid Geometry (CSG)

    master

    Rayrender supports CSG operations to create complex shapes by combining primitives.

    • csg_combine(..., operation="intersection"): Keeps only the overlapping part.
    • csg_combine(..., operation="subtract"): Removes one shape from another.
    • csg_combine(..., operation="blend"): Blends two shapes together.
    • csg_group(list(...)): Groups multiple objects.
    • csg_translate(..., x=...): Moves a CSG object.
    • csg_onion(...): Creates layered shell effects.
    # Example of a subtracted CSG object
    add_object(csg_object(csg_combine(
        csg_combine(
          csg_box(),
          csg_sphere(radius=0.707),
          operation="intersection"),
        csg_group(list(csg_cylinder(start=c(-1,0,0), end=c(1,0,0), radius=0.4),
                       csg_cylinder(start=c(0,-1,0), end=c(0,1,0), radius=0.4),
                       csg_cylinder(start=c(0,0,-1), end=c(0,0,1), radius=0.4))),
        operation="subtract"),
        material=glossy(color="red")))
  3. Enable denoising with Intel Open Image Denoise (OIDN)

    master

    rayrender can use Intel Open Image Denoise (OIDN) to denoise rendered images. If OIDN is not found, the package will still function but without denoising support.

    To enable denoising, you must install OIDN binaries (or build from source) and set the OIDN_PATH environment variable in your .Renviron file to the directory containing the OIDN installation (specifically the directory containing include/OpenImageDenoise and lib or lib64).

  4. Benchmark across release commits

    master

    To run a benchmark across every release commit in the current first-parent history that contains a version string (e.g., v0.x.y), use the run_release_render_benchmarks.R wrapper.

    This wrapper automatically handles C++ standard selection: it reads the DESCRIPTION file of each release commit and sets CXX_STD to C++20 if required, otherwise defaulting to CXX17 for older releases to ensure compatibility with modern R toolchains.

    Key flags:

    • --max-releases N: Limit the number of releases to check.
    • --dry-run: Print the planned matrix and build commands without executing.
    • --all-refs: Search branches, tags, and remotes instead of just the current first-parent history.
    Rscript tools/benchmarks/run_release_render_benchmarks.R \
      --repo . \
      --config tools/benchmarks/configs/default.json \
      --benchmarks bvh_many_spheres,bvh_mixed_primitives \
      --iterations 5 \
      --warmup 1 \
      --output tools/benchmarks/results/release_render_benchmark_times.csv
  5. Add a new scene to the benchmark harness

    master

    To add a new scene, create a file at tools/benchmarks/scenes/<name>.R. The file must export a function named run_benchmark(settings).

    Requirements:

    1. The function must accept a settings object.
    2. It should use settings$width, settings$height, and settings$samples for rendering parameters.
    3. It should return either the rendered object directly or a list/data frame containing optional metric fields.

    Supported optional metric fields:

    • render_seconds (Required for timing)
    • bvh_build_seconds (If BVH construction can be separated)
    • scene_build_seconds
    • total_seconds
    • output_hash
    • artifact_path

    If the scene supports timing construction, use settings$time_build.

    run_benchmark = function(settings) {
      scene = rayrender::generate_ground()
      elapsed = system.time({
        image = rayrender::render_scene(
          scene,
          width = settings$width,
          height = settings$height,
          samples = settings$samples,
          preview = FALSE,
          plot_scene = FALSE,
          progress = FALSE,
          denoise = FALSE
        )
      })[["elapsed"]]
      attr(image, "render_seconds") = as.numeric(elapsed)
      image
    }
  6. Install OIDN on Windows (Manual Build)

    master

    Installing OIDN on Windows requires Rtools45 and building from source.

    1. Install Prerequisites

    Open the “Rtools45 MinGW UCRT64” shell and install the necessary build tools via pacman:

    pacman -Sy --needed \
        mingw-w64-ucrt-x86_64-make \
        mingw-w64-ucrt-x86_64-ninja \
        mingw-w64-ucrt-x86_64-cmake \
        mingw-w64-ucrt-x86_64-ispc

    Ensure the toolchain is on your PATH:

    export PATH="/c/rtools45/x86_64-w64-mingw32.static.posix/bin:/mingw64/bin:${PATH}"

    2. Build OIDN from Source

    Run these commands from the Rtools45 ucrt64 shell:

    # Download the OIDN source
    git clone --recursive https://github.com/RenderKit/oidn.git
    cd oidn
    
    # Create a separate build directory
    mkdir build-cpu-static
    cd build-cpu-static
    
    # Choose an install prefix
    OIDN_PREFIX="C:/local/oidn-static"
    
    # Configure OIDN
    cmake \
      -G "Ninja" \
      -DCMAKE_BUILD_TYPE=Release \
      -DCMAKE_C_COMPILER="/path/to/rtools45/x86_64-w64-mingw32.static.posix/bin/gcc.exe" \
      -DCMAKE_CXX_COMPILER="/path/to/rtools45/x86_64-w64-mingw32.static.posix/bin/g++.exe" \
      -DOIDN_STATIC_LIB=ON \
      -DOIDN_DEVICE_CPU=ON \
      -DOIDN_DEVICE_SYCL=OFF \
      -DOIDN_DEVICE_CUDA=OFF \
      -DOIDN_DEVICE_HIP=OFF \
      -DOIDN_DEVICE_METAL=OFF \
      -DOIDN_APPS=OFF \
      -DISPC_EXECUTABLE="$(command -v ispc)" \
      -DTBB_DIR="/path/to/rtools45/x86_64-w64-mingw32.static.posix/lib/cmake/TBB" \
      -DCMAKE_INSTALL_PREFIX="${OIDN_PREFIX}" \
      ..
    
    # Build and install
    ninja
    ninja install

    Note: If CMake cannot find TBB, add -DTBB_ROOT=/path/to/rtools45/x86_64-w64-mingw32.static.posix to the cmake command.

    3. Configure R

    Add the path to your .Renviron file and reinstall rayrender:

    echo 'OIDN_PATH=C:/local/oidn' >> "$HOME/.Renviron"

    Then in R:

    devtools::install_github("tylermorganwall/rayrender", force = TRUE)
  7. Install rayrender from GitHub

    master

    To install the latest development version of rayrender directly from GitHub, use the devtools package in R.

    # To install the latest version from Github:
    # install.packages("devtools")
    devtools::install_github("tylermorganwall/rayrender")
  8. Install OIDN on macOS

    master

    To enable denoising on macOS, download the appropriate binary for your architecture, extract it, and set the OIDN_PATH in your .Renviron file.

    # Download the appropriate binary for your architecture
    curl -LO https://github.com/OpenImageDenoise/oidn/releases/download/v2.3.1/oidn-2.3.1.x86_64.macos.tar.gz
    # or for Apple Silicon
    curl -LO https://github.com/OpenImageDenoise/oidn/releases/download/v2.3.1/oidn-2.3.1.arm64.macos.tar.gz
    
    # Extract the archive
    tar -xvzf oidn-2.3.1.x86_64.macos.tar.gz
    # or for Apple Silicon
    tar -xvzf oidn-2.3.1.arm64.macos.tar.gz
    
    # Set OIDN_PATH in your .Renviron file to the extracted directory
    echo "OIDN_PATH=/path/to/extracted/oidn" >> ~/.Renviron
  9. Install OIDN on Linux

    master

    To enable denoising on Linux, download the binary, extract it, and set the OIDN_PATH in your .Renviron file.

    # Download the binary
    curl -LO https://github.com/OpenImageDenoise/oidn/releases/download/v2.3.1/oidn-2.3.1.x86_64.linux.tar.gz
    
    # Extract the archive
    tar -xvzf oidn-2.3.1.x86_64.linux.tar.gz
    
    # Set OIDN_PATH in your .Renviron file to the extracted directory
    echo "OIDN_PATH=/path/to/extracted/oidn" >> ~/.Renviron
  10. Run the Render Benchmark Harness

    master

    The Render Benchmark Harness is an R-only tool for measuring rayrender render times across different source references, build settings, and R-defined scenes. It orchestrates the process by checking out a source tree, installing rayrender into an isolated temporary R library using R CMD INSTALL -l, and executing an R worker for each iteration.

    To run a smoke benchmark against your current local checkout (including uncommitted changes), use the run_render_benchmarks.R script.

    Rscript tools/benchmarks/run_render_benchmarks.R \
      --repo . \
      --ref current \
      --config tools/benchmarks/configs/default.json \
      --benchmarks bvh_many_spheres \
      --iterations 1 \
      --warmup 0 \
      --output /tmp/rayrender_benchmark_smoke.csv
  11. Configure build settings for benchmarks

    master

    Build configurations are defined in JSON files located in tools/benchmarks/configs. You can extend the default configuration by adding entries to build_configs. Each entry can specify environment variables (env) and makevars keys to control the compilation process.

    Supported makevars keys include:

    • CXX_STD, CXX, CC
    • CFLAGS, CXXFLAGS, PKG_CXXFLAGS
    • CXX11FLAGS, CXX14FLAGS, CXX17FLAGS, CXX20FLAGS
    • PKG_LIBS, MAKEFLAGS

    Example of a custom optimized configuration:

    {
      "name": "o3_native_simd",
      "env": {},
      "makevars": {
        "CXX17FLAGS": "-O3 -march=native -DRAYSIMD",
        "CXX14FLAGS": "-O3 -march=native -DRAYSIMD",
        "CXXFLAGS": "-O3 -march=native -DRAYSIMD"
      }
    }
  12. Apply image textures to materials

    master

    To apply an image as a texture to a surface, use the image_texture argument within a material (e.g., diffuse()). You can pass an array loaded via png::readPNG() to this argument.

    # Assuming image_array is a loaded PNG array
    scene = generate_cornell() |>
      add_object(yz_rect(x=0.01,y=300,z=555/2,zwidth=400,ywidth=400,
                         material = diffuse(image_texture = image_array)))
    render_scene(parallel=TRUE, width=800, height=800)