Rayshader 1.0:退出矩阵
Rayshader 1.0: Exit the Matrix

原始链接: https://www.tylermw.com/posts/rayverse/rayshader-1-0-exit-the-matrix.html

Rayshader 1.0 是用于 3D 制图和数据可视化的 R 包的一次重大更新。最初是一个结合光线追踪与地图制作的实验,rayshader 现在被记者和研究人员用来让地理空间数据变得美观且可触。1.0 版本专注于移除空间簿记:rayshader 缓存高度图、范围、CRS、zscale 和对象元数据,因此空间栅格、多边形、线和点可直接传递给渲染函数。它还支持空间输入和输出、灵活的水面渲染、流、地形感知道路、人类尺度模型,以及与 ggplot2 的更紧密集成,用于添加真正的 3D 几何。新的渲染选项包括薄雾和辐射着色、地球曲率、基于日期时间的光照、改进的文本,以及通过 rayrender 的 GPU 加速。总体而言,rayshader 1.0 降低了学习曲线,让用户专注于样式、构图和叙事,而不是 CRS 和范围管理。

```Hacker News 帖子宣布 tylermw 发布 Rayshader 1.0,附带祝贺与讨论。用户将其与类似地理空间 3D 流水线(WorldKit)比较,并报告 iPhone 上的加载/性能问题,包括着色器编译和崩溃;作者修复了 iPad/iPhone 参考文献视频问题。关于 LLM 是否能用 ThreeJS/Raylib 一次性生成类似 3D 可视化产生争论。支持者认为 Rayshader 提供合理默认值、数据栈处理和艺术控制,而批评者指出数据准备和库打包问题。作者回应称 LLM 有助于数据摄取,但对美观输出可靠性较低,Rayshader 等工具减少创作自由度;重建完整空间栈很复杂。总体而言,该版本作为令人印象深刻的 R 包受到称赞,并有实用反馈与关于 AI 角色的讨论。```
相关文章

原文

Be sure to read to the end for what I can guarantee is the most exciting and cinematric R package bibliography you’ve ever seen. Everything you see in the below blog post was rendered in R with the rayverse.

Eight years ago, rayshader started as a small experiment in making beautiful maps in R. The first version was based on a simple question: what if we combined raytracing and cartography? I had always been interested in learning both about mapping and pathtracing, and what better way than to combine the two ideas into a single R package? The big “aha!” moment came when I applied that method with interactive 3D terrain for the first time and took it for a spin.

Figure 1: Left: The original spinning 3D rayshader map made in 2018. Right: We’ve come a long way.

The surface was no longer just a shaded map: it felt tangible and real, a 3D rectangle twirling like a Little Debbie cosmic brownie on a microwave turntable. The combination of cartographic hillshading and 3D raytraced terrain looked spectacular in a way that, at the time, mostly lived in bespoke Blender scenes or other advanced 3D modeling tools. And unlike Blender, you didn’t need to learn a whole new ecosystem to visualize your data in 3D: it lived in the same place your data did (R!), which allowed for a gentler learning curve.

But as time went on and the package and userbase expanded, I had a nagging feeling: rayshader was still too hard.

Not always, of course: plenty of people were using it, quite effectively. Simple use cases were fine: pass in a matrix, add a few layers, call plot_3d(), and suddenly you had a cool-looking 3D landscape. If that’s all you needed: great! But if the story you were trying to tell was about data within the landscape–well, that’s where the friction began to burn.

Beauty is table stakes

I built rayshader for people who wanted to make data beautiful without leaving R. Beauty has a real purpose in the world: it draws people’s eyes. It doesn’t matter how accurate or well-constructed your map is if the reader swipes on by: in the market for human attention, beauty and form are table stakes.

Journalists understood that quickly, and were some of rayshader’s earliest adopters.

The Wall Street Journal’s The Future of Arctic Shipping used detailed shipping, bathymetric, and ice coverage data to explain the complexities of the Northern Sea Route. The piece was recognized by the Information is Beautiful Awards, which described it as a deeply researched story built from shipping, bathymetric, and ice coverage data. It appeared only a few months after I released rayshader: talk about an introduction! Bloomberg’s 2024 Gaza rebuilding story, Gaza Reduced to 42 Million Tonnes of Rubble. What Will It Take to Rebuild?, used R, rayshader, and rayrender as part of the visual system for communicating the scale of destruction and debris in Gaza. And in June 2022, a rayshader 3D flood visualization appeared on the front page of The Sydney Morning Herald, inset into coverage of the Lismore flooding.

The front page of The Sydney Morning Herald with the headline Victims left in the dark and an inset 3D flood visualization.

A June 30, 2022 front page of The Sydney Morning Herald showing a rayshader flood visualization inset into Lismore flooding coverage.

That last one stuck with me (and not only because a rayshader map was featured “above the fold” in a major newspaper!). Rayshader had started as a way to make beautiful data visualizations in R, but here it was being used in deadline journalism to help explain a disaster to a general audience. The package had left the domain of “fun engaging social media posts” and entered the visual language of public-interest reporting.

But getting a reader to stop scrolling is only half the problem. Working with journalists taught me how much friction stood between having the data and making the final product. A newsroom deadline is a very good detector of bad API design. If adding buildings takes half a day of coordinate fiddling, that feature might as well not exist. If a 3D path requires a hand-rolled coordinate transform pipeline, nobody is doing that 30 minutes before a deadline. If a pathtraced render looks great but takes too long to converge, it is not going to make it to print. Especially if the editor needs a slight tweak: “Oh, sure–just give me 8 hours to re-render the animation.” Ha. Nope.

The problem wasn’t so much with rayshader itself: it was how much spatial bookkeeping and manual fiddling you had to do to get data into rayshader before you could do all the fun stuff. And at the root of all that bookkeeping was the humble matrix, rayshader’s original choice for representing terrain.

The problem with matrices

CRS · EPSG:4326 · WGS84 · GDAL · PROJ · EPSG:3857 · UTM · DEM · NAD83

Rayshader used matrices to represent terrain because it simplified a lot of the work that went into turning a bunch of elevation values in a 3D object. But most real data does not arrive nicely packaged as a plain rectangular numeric array. It arrives as georeferenced rasters, polygons, lines, and points. It arrives cloaked in an unknown coordinate reference system. It arrives in meters, feet, yards, degrees, or German legal metres. Choosing the matrix as the base input made it easy for me, the developer, by putting the spatial problem (mostly) on the user.

Is there an… illegal german metre?

Convert the raster to a matrix. Save the extent. Transform the vector data. Save the CRS. Crop the linework. Pass the heightmap again. Pass the extent again. Wait, is the extent format lat/long/lat/long or lat/lat/long/long? I never remember–whatever, try both. The first choice is (somehow!) always wrong. Pass zscale again. Resize the overlay. Pass the CRS again. Check whether the map is oriented correctly. No? Surprise! Errant minus sign. Yuck.

This was not just annoying for beginners. It annoyed me, and I wrote the damn thing: now that’s a usability red flag! The new version of rayshader includes a series of changes that gets rid of all of this overhead and allows you to focus on presentation instead of the data processing.

rayshader has gained object permanence

The big change in rayshader 1.0 is this: rayshader no longer has short-term amnesia. Rayshader now keeps track of all the spatial details from your underlying map so you don’t have to worry about it any more.

This changes the user experience from:

Transform and pass in your data into an aligned matrix coordinate system, and rayshader will render it in beautiful 3D.

To:

Transform and Pass in your data into an aligned matrix coordinate system, and rayshader will render it in beautiful 3D.

The black diamond learning curve is now a gentle bunny slope. Terrain can stay a spatial raster. Road can stay a spatial line and will automatically be converted to the correct coordinate system when plotting. Buildings can be passed in as spatial polygons and will automatically be cropped to the underlying map’s extent.

A rayshader scene now extracts and caches the important metadata from the input data: heightmap, extent, CRS, zscale, vertical exaggeration, and rendered-object metadata. That cache lets downstream render_*() calls do the thing users always wanted them to do: simply drop data into the scene.

Most of the functions can now add to the scene simply by passing the data, plus an optional argument that specifies altitude or height, either directly or through a column in an sf object. The rest of the arguments then focus on how you want to style the data.

For example, let’s load in some road and elevation data and see what the new API looks like. The code below defines the helpers and loads the data into R. There’s no rayshader in it, so you have absolutely no obligation to read it :).

Data loading code (boring, you can skip)

Internally, rayshader still converts the raster to something it can render. Externally, the scene remembers enough to let the render_*() functions just work.

There is now also a cleaner division between physical scale and visual exaggeration. zscale now describes the relationship between horizontal and vertical units, while vertical_exaggeration describes the stylistic exaggeration. For spatial rasters, rayshader can derive zscale from the raster itself, placing the data at its physical scale. You can then adjust vertical_exaggeration to emphasize the terrain without changing the underlying unit conversion.

And this spatial data directionality can now be reversed. spatialize_image() turns a rayshader image, matrix, RGB array, or RGBA array back into a georeferenced terra::SpatRaster. It can inherit the cached extent and CRS from the active scene, convert rayshader’s linear color values to sRGB, and optionally append the source heightmap as an additional raster layer. So rayshader’s output can now feed back into other GIS software, rather than just assume rayshader is the final destination itself.

visualize Moses crossing the Red Sea.

Figure 6: The optimized method (right) fits its shoreline to the terrain; the raster method (left) uses that exact fitted elevation. Raster edge expansion is disabled (water_edge_extension = 0) to keep the grid-cell boundary visible–otherwise, the expansion would hide the edges in the ground.

Another (much cooler, IMO) option is water_render_method = "optimized". It fits a closed shoreline to the actual 3D terrain mesh, adjusting the water elevation to match the supplied area. Using the elevations beneath your water footprint to seed candidate levels, the optimizer searches for a contour that comes as close as possible to the supplied water area without spilling out of the terrain. The animation below shows how candidate levels change the flooded area.

Figure 7: Fitting the lake to its basin: candidate levels change the flooded area. The dark outline follows the actual triangle-clipped water polygon at each candidate level.

If no closed water body is possible—for example, the supplied water would flood the entire map—rayshader falls back to raster water.

A different problem arises when a DEM has no bathymetry: the lake bed and its surface occupy the same plane. shift_terrain() is a new function that can lower the terrain beneath a lake polygon before you add water, making room for the lake instead of letting the surfaces overlap. It can also raise terrain SimCity 2000-style (no tornados or alien invasions… yet).

Additionally, in render_highquality(), water can now use a rough dielectric material to spread reflections into the broad highlights you expect from a rippled lake. A perfectly smooth dielectric surface behaves like glass: reflected light stays coherent, so lakes and rivers can turn into polished sheets. Real water has small wind-driven ripples, each reflecting light in a slightly different direction. The microfacet material models this give a more realistic appearance to bodies of water, especially when viewed at a low angle.

Smooth water reflecting a compact solar disk.

Rough water spreading the same sunset into an elongated highlight.

Figure 8: Glassy water on the left; microfacet water on the right.

Rayshader: now streaming!

Streams need to follow the terrain as they wind downhill. render_streams() takes spatial line data, samples the elevation along each path, and builds ribbons of water that hug the surface. Widths can vary by feature, and connected streams can be merged to reduce visible seams in high-quality renders. Put those streams together with lakes and you have a hydrologic scene driven by data.

Figure 11, each dash is 10 feet long and each gap is 30 feet. Those familiar markings do double duty: they improve the picture and act as little scale bars scattered through the scene. Beautiful! Pack it up, put a bow on it, and move on to the next feature, right?

The spacing is configurable for local standards.

No! Our roads are still smooshed together on one layer. At an interchange, that borders on uninterpretable.

OpenStreetMap doesn’t provide a full 3D road model. But it does carry one tiny (but extremely useful!) nugget of vertical information needed to draw roads correctly in 2D: drawing order. Draw layer 0, then layer 1, then layer 2, and the right road appears on top. That tells us which road crosses over which; it doesn’t tell us their heights or how the ramps return to ground level. Is this enough information to fully reconstruct our 3D roads?

Figure 12: Drawing order determines which road appears to cross above the other, implying a 3D arrangement.

The tempting shortcut is to turn each layer into a fixed height: find the crossings, lift each road by a standard overpass height, and ease it back toward the ground with some sort of ad hoc relaxation rule. What could go wrong?

(a) Abrupt humps and steep ramps.
(b) Road decks that fail to meet cleanly.
Figure 13: Two ways a simple layer-based height offset can go wrong: implausible grades and awkward connections between road segments.

Everything. Everything can go wrong.

Simple hacks? Don’t work here. Turns out the world is filled with little annoying complications like a bridge crossing a sunken highway (the highway is already below ground, so the bridge needs no change in elevation), or short segments in interchanges that are technically not stacked but fall between stacked layers, or places where the road is technically stacked over a traversable water body (which also counts as a layer!), or a thousand other pesky little details.

What are we to do then? How can we implement realistic highways? It’s not like there’s a manual with explicit guidance and standards for how roads should be built in 3D—wait, what is that? There is an explicit manual?

Figure 14: AASHTO’s A Policy on Design Standards—Interstate System

The American Association of State Highway and Transportation Officials (AASHTO) has a design manual for Interstate highways. Two of the things it covers are exactly what our map is missing. How much room does a truck need under a bridge? How steep can the road get on its way up there? Now that rayshader knows the scale of the scene, I can give the solver a clearance in feet and a maximum grade in percent. Here are the default settings I gave the road solver (these are customizable):

  1. Keeping crossing road surfaces at least 14 feet apart
  2. Limiting the road grade to 7%
  3. Ensuring roads default to hugging the ground when not part of an intersection and do not rise unnecessarily

We can turn these requirements into constraints on the road heights. While the rules aren’t guaranteed to generate roads that match the real-world roads exactly, it’s going to be pretty close: excursions from the bare minimum allowable ruleset will usually only increase cost, and we’re talking government contracts here. Around each interchange, we discretize the roads into short segments and solve for their elevations together: maintain the crossing order and clearance, limit the grades, and keep the roads close to the terrain wherever possible.

For example, a road can weave over and under several others. Lifting one crossing changes the grades leading into the next, so solving each crossing independently won’t work–we have to solve all the linked constraints at once. We build a graph of the road connections with {igraph}, locate crossings with {sf}, and follow the constraints along connected road segments. Each connected optimization region gets a sparse quadratic problem, assembled with {Matrix} and solved with {osqp}. It turns out, R has everything you need to build and optimize road profiles.

Figure 15: Roads at a Bernese Oberland interchange with teal profile control points and orange rings at seven crossing constraints.

It’s pretty cool how closely a set of road-design rules and OSM’s layer ordering can recreate a complex interchange. The layer tags tell us which road goes over which, and the rules guide how the ramps connect them. Here’s Houston, now modeled in a sane way:

Figure 16: Elevated decks separate the crossings, with Houston buildings providing context. Now, the merges still need work, but that’ll have to wait for the next update :)

Beautiful. And since I went to Houston for this year’s Posit::conf, I was able to drive over specific intersections I rendered here and confirm that yes: the roads were accurately meshed. Minus the traffic.

The novelty seeking half of my brain immediately followed this thought with: “You should put in cars now!” to which the logical, killjoy side of my brain responded “NO! STOP IT! YOU’VE IMPLEMENTED TOO MANY FEATURES ALREADY! You will never release this update if you keep indulging yourself! Stop it!”

Maybe in 1.1.0…

A human battery? No–a human measuring stick.

Lane markings made the scale of a scene easier to read. Naturally, that led me to the ultimate human-scale feature: humans! But I couldn’t just throw the first set of free human models I found on the internet into the package. I did a fairly extensive search for a suitable pre-made model with both male and female variants, but to no avail. I had some requirements:

  1. Low-poly enough to fit in the package when compressed (an R package is limited to 5 MB).
  2. Proportioned like actual people, which rules out a surprising number of free models.
  3. Not, uh, overly detailed. You can imagine what I’m referring to.

I couldn’t find a model that met these requirements with a suitable redistribution license. So I decided this was a great opportunity to learning something new: mesh sculpting in VR! I pulled out my Quest 3 and downloaded Shapelabs, which after a bit of practice and futzing around got me exactly what I wanted. Low-poly, but still human enough that you can read the pose at a glance.

Figure 17: The male and female raypeople models, in the “walking” pose.

From Shapelabs, the models went into Blender as GLB files for rigging and posing, then out as compact OBJ meshes for the package:

Render both pose galleries

Figure 19: it shows a map of US states with height mapped to population. States share an boundary in the source polygons, but when rasterized to row of pixels, you can see the colors bleed down the step between states. This is an unavoidable problem when you try to force vector data into a raster format. So we avoid it by drawing the actual 3D data. On the right, each state’s own polygon makes a crisp vertical wall.

Better buildings, paths, labels, and objects

The render_*() functions have been rewritten around the same principle: spatial data already encodes where it is, so there is no reason to throw that information out.

render_points() can accept spatial point objects. render_path() can accept spatial line objects. render_label() can accept points, multipoints, polygons, and multipolygons, converting polygon inputs to centroids when needed. render_polygons() and render_beveled_polygons() use cached heightmap and extent metadata. render_buildings() uses spatial footprints, roof materials, roof angles, height columns, and CRS-aware extent filtering. render_obj() can place OBJ models using spatial point data. You can see most of these in action in Figure 22.

New hillshading options

There’s some new basic hillshading options as well. haze_shade() adds an RGBA haze overlay based on an exponential atmospheric model. It is useful for low-elevation haze, valley haze, and scenes where you want the atmosphere to participate in the map rather than sit behind it. It is a good way to subtly separate mountain tops from valleys.

Figure 25 shows three Starlink satellites cross Alaska along paths calculated from real orbital data. Their simulated beams track populated places below, switching targets as they move within reach. Both views show the same moment, but on the right, the surface and orbital altitudes are adjusted to match the global curvature. This helps give the viewer important context clues for the spatial scales we’re dealing with here that the flat projection does not provide.

Even higher quality render_highquality()

Want to realistically light a scene at a very specific time and date? Just give rayshader a date and time–it already knows the place. For a scene with cached spatial coordinates, render_highquality(datetime = ...) can infer the location and generate the corresponding sky and sunlight. You don’t need to look up the latitude, longitude, or sun angle again. Depending on the sky model, that can include stars, planets, and the moon’s phase and brightness.

As an example, around the equinoxes, the low sun lines up with the National Mall’s east–west axis—a favorite alignment for photographers. On March 25, 2026, at 6:56:11 p.m. EDT, the modeled shadow of the Washington Monument runs parallel to the Mall’s main paths. A few days past the equinox, the sun is still high enough at that alignment to keep the shadow within this view.

Figure 27 are drawn in screen space: their positions stay attached to the map, while the text keeps its size and faces the camera throughout the orbit, without casting shadows over the volcanoes. The horsepower axis in Figure 20 uses the same approach. The lines and text are composited in real time when you’re looking at the high quality preview render in rayrender, so you can set up the shot exactly how you want to. Oh, and you can set deferred_render = TRUE now as well, which removes the sample timer so you can have all the time in the world to set up your render. This is especially important now, since rayrender is now fully GPU-accellerated on ARM macs, leading to 30-50x speedups in rendering performance, so your render can often end before you got a chance to click on the screen. This blog post, however, is about rayshader, so I won’t steal its thunder talking about the awesome improvements in rayrender :)

1.0 and beyond!

A complete terrain scene with water and roads.

It’s been a long, properly textured road–why 1.0 after eight years? I now feel that rayshader has firmly found its niche and purpose, and this overhaul feels like a graduation moment for the package. I’m no longer figuring out what a 3D GIS workflow in R should feel like–it’s now about making that workflow work for you. And thinking about all the people who used rayshader to produce everything from beautiful generative art and frameable cartographic works to scientific articles and award winning journalism made me decide to give rayshader the graduation it deserves, and make sure it knows: You’re number 1.0!

The grand finale and most exciting part of any publication: the bibliography.

Rayshader wouldn’t be possible without the work of all the packages and people that supported it and provided great user feedback during its development. In a normal blog post, this is where normally you’d have a list of citations and people to thank. But how often does R’s most cinematic package get a 1.0 release? I decided the people, packages, and data behind rayshader deserved the full cinematic treatment that rayshader has provided the R ecosystem. And that the cinematic treatment should be created entirely in R, using rayrender, of course. Please stick around and hit play for the credits below—and be sure to turn the sound on.

联系我们 contact @ memedata.com