Send from Rust
In this section we'll log and visualize our first non-trivial dataset, putting many of Rerun's core concepts and features to use.
In a few lines of code, we'll go from a blank sheet to something you don't see every day: an animated, interactive, DNA-shaped abacus:
This guide aims to go wide instead of deep. There are links to other doc pages where you can learn more about specific topics.
At any time, you can checkout the complete code listing for this tutorial here to better keep track of the overall picture.
To run the example from the repository, run cargo run -p dna
.
Prerequisites prerequisites
We assume you have a working Rust environment and have started a new project with the rerun
dependency. If not, check out the setup page.
For this example in particular, we're going to need all of these:
[dependencies]
rerun = "0.9"
itertools = "0.11"
rand = "0.8"
While we're at it, let's get imports out of the way:
use std::f32::consts::TAU;
use itertools::Itertools as _;
use rerun::{
demo_util::{bounce_lerp, color_spiral},
external::glam,
};
Starting the Viewer starting-the-viewer
Just run rerun
to start the Rerun Viewer. It will wait for your application to log some data to it. This Viewer is in fact a server that's ready to accept data over TCP (it's listening on 0.0.0.0:9876
by default).
Checkout rerun --help
for more options.
Initializing the SDK initializing-the-sdk
To get going we want to create a RecordingStream
:
We can do all of this with the rerun::RecordingStreamBuilder::new
function which allows us to name the dataset we're working on by setting its ApplicationId
.
We then connect it to the already running Viewer via connect
, returning the RecordingStream
upon success.
fn main() -> Result<(), Box<dyn std::error::Error>> {
let rec = rerun::RecordingStreamBuilder::new("rerun_example_dna_abacus")
.connect(rerun::default_server_addr(), rerun::default_flush_timeout())?;
Ok(())
}
Among other things, a stable ApplicationId
will make it so the Rerun Viewer retains its UI state across runs for this specific dataset, which will make our lives much easier as we iterate.
Check out the reference to learn more about how Rerun deals with applications and recordings.
Logging our first points logging-our-first-points
The core structure of our DNA looking shape can easily be described using two point clouds shaped like spirals.
Add the following to your main
function:
const NUM_POINTS: usize = 100;
let (points1, colors1) = color_spiral(NUM_POINTS, 2.0, 0.02, 0.0, 0.1);
let (points2, colors2) = color_spiral(NUM_POINTS, 2.0, 0.02, TAU * 0.5, 0.1);
rec.log(
"dna/structure/left",
&rerun::Points3D::new(points1.iter().copied())
.with_colors(colors1)
.with_radii([0.08]),
)?;
rec.log(
"dna/structure/right",
&rerun::Points3D::new(points2.iter().copied())
.with_colors(colors2)
.with_radii([0.08]),
)?;
Run your program with cargo run
and you should now see this scene in the viewer:
This is a good time to make yourself familiar with the viewer: try interacting with the scene and exploring the different menus. Checkout the Viewer Walkthrough and viewer reference for a complete tour of the viewer's capabilities.
Under the hood under-the-hood
This tiny snippet of code actually holds much more than meets the eye…
Archetypes archetypes
The easiest way to log geometric primitives is the use the RecordingStream::log
method with one of the built-in archetype class, such as Points3D
. Archetypes take care of building batches
of components that are recognized and correctly displayed by the Rerun viewer.
Components components
Under the hood, the Rerun Rust SDK logs individual components like positions, colors, and radii. Archetypes are just one high-level, convenient way of building such collections of components. For advanced use cases, it's possible to add custom components to archetypes, or even log entirely custom sets of components, bypassing archetypes altogether. For more information on how the Rerun data model works, refer to our section on Entities and Components.
Notably, the RecordingStream::log
method
will handle any data type that implements the AsComponents
trait, making it easy to add your own data.
For more information on how to supply your own components see Use custom data.
Entities & hierarchies entities--hierarchies
Note the two strings we're passing in: "dna/structure/left"
and "dna/structure/right"
.
These are entity paths, which uniquely identify each entity in our scene. Every entity is made up of a path and one or more components. Entity paths typically form a hierarchy which plays an important role in how data is visualized and transformed (as we shall soon see).
Batches batches
One final observation: notice how we're logging a whole batch of points and colors all at once here. Batches of data are first-class citizens in Rerun and come with all sorts of performance benefits and dedicated features. You're looking at one of these dedicated features right now in fact: notice how we're only logging a single radius for all these points, yet somehow it applies to all of them. We call this clamping.
A lot is happening in these two simple function calls. Good news is: once you've digested all of the above, logging any other entity will simply be more of the same. In fact, let's go ahead and log everything else in the scene now.
Adding the missing pieces adding-the-missing-pieces
We can represent the scaffolding using a batch of 3D line segments:
let points_interleaved: Vec<[glam::Vec3; 2]> = points1
.into_iter()
.interleave(points2)
.chunks(2)
.into_iter()
.map(|chunk| chunk.into_iter().collect_vec().try_into().unwrap())
.collect_vec();
rec.log(
"dna/structure/scaffolding",
&rerun::LineStrips3D::new(points_interleaved.iter().cloned())
.with_colors([rerun::Color::from([128, 128, 128, 255])]),
)?;
Which only leaves the beads:
use rand::Rng as _;
let mut rng = rand::thread_rng();
let offsets = (0..NUM_POINTS).map(|_| rng.gen::<f32>()).collect_vec();
let (beads, colors): (Vec<_>, Vec<_>) = points_interleaved
.iter()
.enumerate()
.map(|(n, &[p1, p2])| {
let c = bounce_lerp(80.0, 230.0, times[n] * 2.0) as u8;
(
rerun::Position3D::from(bounce_lerp(p1, p2, times[n])),
rerun::Color::from_rgb(c, c, c),
)
})
.unzip();
rec.log(
"dna/structure/scaffolding/beads",
&rerun::Points3D::new(beads)
.with_colors(colors)
.with_radii([0.06]),
)?;
Once again, although we are getting fancier and fancier with our iterator mappings, there is nothing new here: it's all about populating archetypes and feeding them to the Rerun API.
Animating the beads animating-the-beads
Introducing time introducing-time
Up until this point, we've completely set aside one of the core concepts of Rerun: Time and Timelines.
Even so, if you look at your Timeline View right now, you'll notice that Rerun has kept track of time on your behalf anyway by memorizing when each log call occurred.
Unfortunately, the logging time isn't particularly helpful to us in this case: we can't have our beads animate depending on the logging time, else they would move at different speeds depending on the performance of the logging process! For that, we need to introduce our own custom timeline that uses a deterministic clock which we control.
Rerun has rich support for time: whether you want concurrent or disjoint timelines, out-of-order insertions or even data that lives outside the timeline(s). You will find a lot of flexibility in there.
Let's add our custom timeline:
for i in 0..400 {
let time = i as f32 * 0.01;
rec.set_time_seconds("stable_time", time as f64);
let times = offsets.iter().map(|offset| time + offset).collect_vec();
let (beads, colors): (Vec<_>, Vec<_>) = points_interleaved
.iter()
.enumerate()
.map(|(n, &[p1, p2])| {
let c = bounce_lerp(80.0, 230.0, times[n] * 2.0) as u8;
(
rerun::Position3D::from(bounce_lerp(p1, p2, times[n])),
rerun::Color::from_rgb(c, c, c),
)
})
.unzip();
rec.log(
"dna/structure/scaffolding/beads",
&rerun::Points3D::new(beads)
.with_colors(colors)
.with_radii([0.06]),
)?;
}
First we use RecordingStream::set_time_seconds
to declare our own custom Timeline
and set the current timestamp.
You can add as many timelines and timestamps as you want when logging data.
⚠️ If you run this code as is, the result will be.. surprising: the beads are animating as expected, but everything we've logged until that point is gone! ⚠️
Enter…
Latest-at semantics latestat-semantics
That's because the Rerun Viewer has switched to displaying your custom timeline by default, but the original data was only logged to the default timeline (called log_time
).
To fix this, add this at the beginning of the main function:
rec.set_time_seconds("stable_time", 0f64);
This fix actually introduces yet another very important concept in Rerun: "latest-at" semantics.
Notice how entities "dna/structure/left"
& "dna/structure/right"
have only ever been logged at time zero, and yet they are still visible when querying times far beyond that point.
Rerun always reasons in terms of "latest" data: for a given entity, it retrieves all of its most recent components at a given time.
Transforming space transforming-space
There's only one thing left: our original scene had the abacus rotate along its principal axis.
As was the case with time, (hierarchical) space transformations are first class-citizens in Rerun. Now it's just a matter of combining the two: we need to log the transform of the scaffolding at each timestamp.
Either expand the previous loop to include logging transforms or simply add a second loop like this:
for i in 0..400 {
// …everything else…
rec.log(
"dna/structure",
&rerun::archetypes::Transform3D::from_rotation(rerun::RotationAxisAngle::new(
glam::Vec3::Z,
rerun::Angle::Radians(time / 4.0 * TAU),
)),
)?;
}
Voila!
Other ways of logging & visualizing data other-ways-of-logging--visualizing-data
Saving & loading to/from RRD files saving--loading-tofrom-rrd-files
Sometimes, sending the data over the network is not an option. Maybe you'd like to share the data, attach it to a bug report, etc.
Rerun has you covered:
- Use
RecordingStream::save
to stream all logging data to disk. - Visualize it via
rerun path/to/recording.rrd
You can also save a recording (or a portion of it) as you're visualizing it, directly from the viewer.
⚠️ RRD files are not yet stable across different versions! ⚠️
Spawning the Viewer from your process spawning-the-viewer-from-your-process
If the Rerun Viewer is installed and available in your PATH
, you can use RecordingStream::spawn
to automatically start a Viewer in a new process and connect to it over TCP.
If an external Viewer was already running, spawn
will connect to that one instead of spawning a new one.
fn main() -> Result<(), Box<dyn std::error::Error>> {
let rec = rerun::RecordingStreamBuilder::new("rerun_example_dna_abacus")
.spawn()?;
// … log data to `rec` …
Ok(())
}
Alternatively, you can use rerun::native_viewer::show
to start a Viewer on the main thread (for platform-compatibility reasons) and feed it data from memory.
This requires the native_viewer
feature to be enabled in Cargo.toml
:
rerun = { version = "0.9", features = ["native_viewer"] }
Doing so means you're building the Rerun Viewer itself as part of your project, meaning compilation will take a bit longer the first time.
Unlike spawn
however, this expects a complete recording instead of being fed in real-time:
let (rec, storage) = rerun::RecordingStreamBuilder::new("rerun_example_dna_abacus").memory()?;
// … log data to `rec` …
rerun::native_viewer::show(storage.take())?;
The Viewer will block the main thread until it is closed.
Closing closing
This closes our whirlwind tour of Rerun. We've barely scratched the surface of what's possible, but this should have hopefully given you plenty pointers to start experimenting.
As a next step, browse through our example gallery for some more realistic example use-cases, or browse the Types section for more simple examples of how to use the main data types.