Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Yggdrasil: Yet Another 3D Scene Graph!

Yggdrasil is an ecosystem designed to power the perception infrastructure for autonomous systems. Whether deployed in a lab or across complex real-world environments, Yggdrasil provides the structural “backbone” needed to manage spatial data at scale.

The project consists of five core components:

  1. Scene Graph Library: A pure Rust implementation providing the core API and data structure for high-performance spatial management.
  2. Engine: The system runtime responsible for conflict resolution, lazy evaluation, and state updates.
  3. Service: A distributed database implementation optimized for deployment across edge networks.
  4. Adapters: SDKs that facilitate integration between Yggdrasil and external environments, such as ROS2.
  5. Python Bindings: High-level wrappers providing seamless access to the Rust core for Python-based research, scripting, and rapid prototyping.

Introduction

Welcom to The Yggdrasil Book. Yggdrasil is a ecosystem for creating, maintaining, and serving perception fo the environment through 3D Scene Graphs for autonomous systems.

Who Yggdrasil is For

Yggdrasil is a general purpose by design, meaning, anyone can use it to map their specific needs and environment into an Yggdrasil tree. Yggdrasil’s simple design and reach integrations makes it easy to use it for prototyping and research papers while its high performance output makes it a perfect fit for practical usecases.

Why Choose Yggdrasil

Yggdrasil has a rich set of features and integrations that makes it easy to adapt to any downstream or upstream use case within the robotic ecosystem:

  1. Built-in Support for complex positional Queries: Yggdrasil has built-in support for a suite of positional queries, such as the nearest neighbor family of queries, field of view queries, and so many other queries that are commonly used in most downstream tasks such as path planning and navigation.

  2. Advance Support for semantic Retrieval: Yggdrasil also has first-class support for semantic retrieval on nodes and edges.

  3. Automatic State Propagation: Yggdrasil ensures that the scene graph remains in a consistent and valid state at all times. Any modification to a specific node automatically triggers necessary updates and notifications across dependent branches of the tree. This automated propagation eliminates manual state management and ensures that all downstream consumers receive accurate, synchronized data.

  4. Generic Building Blocks: Unlike other scene graphs, Yggdrasil’s generic building blocks makes it easy to map any scenario into an Yggdrasil tree and removes the need for implementing a new 3D scene graph logic from scratch.

  5. Community-Driven & Rapidly Evolving: Yggdrasil is actively maintained and built to grow alongside the robotics ecosystem. Because development is ongoing, the roadmap is highly responsive to user needs. If a specific integration or feature is missing for your use case, we encourage you to request it—new capabilities are frequently rolled out, ensuring the framework stays ahead of industry demands.

Installation

Yggdrasil is published as yggdrasil-3d on both crates.io and PyPI. In both languages it imports as yggdrasil, which is how every example in this book refers to it. (The yggdrasil names on both registries belong to unrelated projects.)

Rust

From crates.io

cargo add yggdrasil-3d
#![allow(unused)]
fn main() {
use yggdrasil::SceneGraph;
}

It needs Rust 1.89 or newer. The API reference is on docs.rs.

From Source

To follow unreleased changes on master, depend on the repository instead:

cargo add yggdrasil-3d --git https://github.com/brdsdsu/Yggdrasil

To build the whole workspace, including the visualizer and the book’s demo:

git clone https://github.com/brdsdsu/Yggdrasil.git && cd Yggdrasil
cargo build --release --workspace
cargo run -p yggdrasil-3d --example demo    # the walkthrough in the next chapter

On Linux the visualizer needs Bevy’s system libraries. On Debian or Ubuntu:

sudo apt-get install pkg-config libx11-dev libasound2-dev libudev-dev libwayland-dev libxkbcommon-dev

Python

From PyPI

pip install yggdrasil-3d
import yggdrasil as ygg

Prebuilt wheels cover CPython 3.8 and newer on Linux (glibc and musl) and macOS, each on x86_64 and arm64, and on Windows x86_64. Anywhere else, pip compiles the source distribution, which needs a Rust toolchain.

From Source

Build and install the bindings from a checkout. pip fetches maturin, the build backend, on its own:

git clone https://github.com/brdsdsu/Yggdrasil.git && cd Yggdrasil
pip install ./python-binding

When working on the bindings themselves, rebuild them in place with uv:

cd python-binding
uv sync                              # creates .venv with maturin
uv run maturin develop --release     # rebuilds the extension into .venv

Program a Demo with Yggdrasil

In this chapter we will write a small program to create and query an yggdrasil scene graph. by the end of this chapter, you should have a basic understanding of how the scene graph library works and how you can use it to create a protype. We will also go through most of the queries that yggdrasil has support for and explain them one by one.

Bootstrap a Scene Graph

Lets start getting familiar with Yggdrasil Scene Graph and its API by creating a new scene graph and running some queries on it.

The following function would create a new demo scene graph which we can use to run some queries on:

#![allow(unused)]
fn main() {
use yggdrasil::Feature;

fn create_demo_graph() -> yggdrasil::Result<yggdrasil::SceneGraph> {
    let mut ygg = yggdrasil::SceneGraph::default();

    let point_cloud_layer_id = ygg.new_layer().id;
    let static_objects_layer_id = ygg.new_layer().id;
    let dynamic_objects_layer_id = ygg.new_layer().id;
    let root_layer_id = ygg.new_layer().id;

    // Define the hierarchy of layers
    // We try to create the following DAG structure:
    //
    // root_layer
    // ├────────── dynamic_objects_layer
    // │                            │
    // │                            │
    // │                            │
    // └─ static_objects_layer      │
    //          │                   │
    //          └──── point_cloud_layer
    //
    ygg.layer_mut(root_layer_id)?
        .add_child(dynamic_objects_layer_id)?;
    ygg.layer_mut(root_layer_id)?
        .add_child(static_objects_layer_id)?;
    ygg.layer_mut(dynamic_objects_layer_id)?
        .add_child(point_cloud_layer_id)?;
    ygg.layer_mut(static_objects_layer_id)?
        .add_child(point_cloud_layer_id)?;

    // Create a root node with a name feature
    // This node will serve as the parent for all other nodes in the scene graph.
    let root_node = ygg.new_node(vec![Feature::new("name", "root")]);
    let root_node_id = ygg.layer_mut(root_layer_id)?.push_node(root_node);

    // Create 100 point cloud nodes with random coordinates. The first 70 nodes will have
    // coordinates between 0 and 10, and the next 30 will have coordinates between 10 and 20.
    // Each node will have a feature "point_cloud_id" with a unique integer value.
    // The nodes will be added to the point cloud layer.
    let mut point_cloud = (0..70)
        .map(|_| {
            let x = rand::random::<f32>() * 10.0;
            let y = rand::random::<f32>() * 10.0;
            let z = rand::random::<f32>() * 10.0;
            (x, y, z)
        })
        .collect::<Vec<_>>();
    point_cloud.extend((0..30).map(|_| {
        let x = rand::random::<f32>() * 10.0 + 10.0;
        let y = rand::random::<f32>() * 10.0 + 10.0;
        let z = rand::random::<f32>() * 10.0 + 10.0;
        (x, y, z)
    }));

    let mut point_cluod_node_ids = Vec::new();
    for (i, (x, y, z)) in point_cloud.iter().enumerate() {
        let point = ygg.new_coordinates(*x, *y, *z, vec![Feature::new("point_cloud_id", i)]);
        let point_cloud_node_id = ygg.layer_mut(point_cloud_layer_id)?.push_node(point);
        point_cluod_node_ids.push(point_cloud_node_id);
    }

    // Create 7 semantic nodes, representing different object in the scene
    // Each node will have a "type" feature with a value like "car", "tree", etc.
    // The nodes will be added to the static layer and will be connected to the root.
    let mut static_object_node_ids = Vec::new();
    let static_object_types = [
        "car", "tree", "building", "bicycle", "bench", "sign", "lamp",
    ];
    for i in 0..static_object_types.len() {
        let object_node = ygg.new_node(vec![Feature::new("type", static_object_types[i])]);
        let object_node_id = ygg
            .layer_mut(static_objects_layer_id)?
            .push_node(object_node);
        static_object_node_ids.push(object_node_id);

        // Nest all the point cloud nodes under this object's semantic node.
        for point_cloud_node_id in &point_cluod_node_ids[i * 10..(i + 1) * 10] {
            ygg.nest(*point_cloud_node_id).under(object_node_id)?;
        }

        // Nest this object's semantic node under the root node.
        ygg.nest(object_node_id).under(root_node_id)?;
    }

    // Create 3 dynamic nodes representing moving objects in the scene.
    // Each node will have a "type" feature with a value like "Humand", "Dog", and "Cat".
    // The nodes will be added to the dynamic layer and will be connected to the root.
    let mut dynamic_node_ids = Vec::new();
    let dynamic_object_types = ["Human", "Dog", "Cat"];
    for i in 0..dynamic_object_types.len() {
        let dynamic_node = ygg.new_node(vec![Feature::new("type", dynamic_object_types[i])]);
        let dynamic_node_id = ygg
            .layer_mut(dynamic_objects_layer_id)?
            .push_node(dynamic_node);
        dynamic_node_ids.push(dynamic_node_id);

        // Nest all the point cloud nodes under this object's semantic node.
        let offset = static_object_types.len() * 10;
        for point_cloud_node_id in &point_cluod_node_ids[offset + i * 10..offset + (i + 1) * 10] {
            ygg.nest(*point_cloud_node_id).under(dynamic_node_id)?;
        }

        // Nest this dynamic node under the root node.
        ygg.nest(dynamic_node_id).under(root_node_id)?;
    }

    // Create semantic relationships between dynamic nodes.
    // For example, we can say that:
    // 1. the "Human" node is "holding" the "Dog" node.
    // 2. the "Dog" node is "looking" the "Cat" node.
    ygg.layer_mut(dynamic_objects_layer_id)?.add_edge(
        dynamic_node_ids[0],
        dynamic_node_ids[1],
        "holding",
    )?;
    ygg.layer_mut(dynamic_objects_layer_id)?.add_edge(
        dynamic_node_ids[1],
        dynamic_node_ids[2],
        "looking",
    )?;
    Ok(ygg)
}
}

Let’s go through each line one by one to better understand how Yggdrasil concepts combine to create this scene graph.

New Scene Graph

#![allow(unused)]
fn main() {
    let mut ygg = yggdrasil::SceneGraph::default();
}

This line creates an empty scene graph for us to manipulate

Allocating layers

#![allow(unused)]
fn main() {
    let point_cloud_layer_id = ygg.new_layer().id;
    let static_objects_layer_id = ygg.new_layer().id;
    let dynamic_objects_layer_id = ygg.new_layer().id;
    let root_layer_id = ygg.new_layer().id;
}

In this snippet, we are allocating four different layers for the scene graph. Layers are an important segmentation logic of the scene graph which help with performance and better modeling logic of the environment. In yggdrasil, you can think of each layer as an isolated graph of nodes and edges. Layer isolation is enforced at the scene graph layers, meaning crossing different layers is not allowed for certain operations. For example, an edge cannot be added between two nodes that belong to different layers.

In this example, we allocate four layers:

  1. point cloud layer: stores the actual position of the points in our scene.
  2. static object layer: stores semantic data for each static object in the scene.
  3. dynamic object layer: stores semantic data for each moving object in the scene.
  4. root layer: holds the root node, which contains the entire scene underneath itself.

Setting Up The Hierarchy

#![allow(unused)]
fn main() {
    // Define the hierarchy of layers
    // We try to create the following DAG structure:
    //
    // root_layer
    // ├────────── dynamic_objects_layer
    // │                            │
    // │                            │
    // │                            │
    // └─ static_objects_layer      │
    //          │                   │
    //          └──── point_cloud_layer
    //
    ygg.layer_mut(root_layer_id)?
        .add_child(dynamic_objects_layer_id)?;
    ygg.layer_mut(root_layer_id)?
        .add_child(static_objects_layer_id)?;
    ygg.layer_mut(dynamic_objects_layer_id)?
        .add_child(point_cloud_layer_id)?;
    ygg.layer_mut(static_objects_layer_id)?
        .add_child(point_cloud_layer_id)?;
}

In yggdrasil, layers have hierarchy and form a DAG in the scene graph. Hierarchy is used to enforce constraints on nodes and edges in the scene graph. For example, the parent-child relationship between two nodes is allowed if and only if their layers have the same (parent-child) relationship.

Using the SceneGraph::layer and SceneGraph::layer_mut functions, we can retrieve a layer using its id. We use Layer::add_child function to declare one Layer object the child of another. Note that layers form a DAG, meaning one layer can have multiple direct parent layers. For example, in our demo point_cloud_layer is a child of both static_objects_layer and dynamic_objects_layer.

Layer ids follow a topological ordering, meaning, a layer with id i can be a child of layer j if and only if i < j

Root Layer

#![allow(unused)]
fn main() {
    // Create a root node with a name feature
    // This node will serve as the parent for all other nodes in the scene graph.
    let root_node = ygg.new_node(vec![Feature::new("name", "root")]);
    let root_node_id = ygg.layer_mut(root_layer_id)?.push_node(root_node);

}

We create a new root node and push it to the root layer. The SceneGraph::new_node function takes a list of SceneGraph::Features which is essentially a key-value pair and creates a new node that is ready to be inserted into the scene graph. Note that the return type of SceneGraph::new_node is AnonNode, which reflects the fact that the node is not yet part of the scene graph. Because it has not been inserted into any layer, it does not have an associated NodeId.

A NodeId is assigned only when the node is pushed into a layer, since part of the identifier is derived from the layer in which the node resides. For this reason, Layer::push_node returns the NodeId of the newly inserted node.

Point Cloud Layer

#![allow(unused)]
fn main() {
    // Create 100 point cloud nodes with random coordinates between 0 and 10.
    // Each node will have a feature "point_cloud_id" with a unique integer value.
    // The nodes will be added to the point cloud layer.
    let point_cloud = (0..100)
        .map(|_| {
            let x = rand::random::<f32>() * 10.0;
            let y = rand::random::<f32>() * 10.0;
            let z = rand::random::<f32>() * 10.0;
            (x, y, z)
        })
        .collect::<Vec<_>>();

    let mut point_cluod_node_ids = Vec::new();
    for (i, (x, y, z)) in point_cloud.iter().enumerate() {
        let point = ygg.new_coordinates(*x, *y, *z, vec![Feature::new("point_cloud_id", i)]);
        let point_cloud_node_id = ygg.layer_mut(point_cloud_layer_id)?.push_node(point);
        point_cluod_node_ids.push(point_cloud_node_id);
    }

}

We create 100 new nodes, each representing a random spatial point in the scene. The SceneGraph::new_coordinates function creates a new node and assigns it 3d coordinates. This Node is the same as the node that is created via SceneGraph::new_node with its position initialized. We can use AnonNode::Coordinates and Node::Cordinates to directly access the position of a node and change it later.

Static Object Layer

#![allow(unused)]
fn main() {
    // Create 7 semantic nodes, representing different object in the scene
    // Each node will have a "type" feature with a value like "car", "tree", etc.
    // The nodes will be added to the static layer and will be connected to the root.
    let mut static_object_node_ids = Vec::new();
    let static_object_types = [
        "car", "tree", "building", "bicycle", "bench", "sign", "lamp",
    ];
    for i in 0..static_object_types.len() {
        let object_node = ygg.new_node(vec![Feature::new("type", static_object_types[i])]);
        let object_node_id = ygg
            .layer_mut(static_objects_layer_id)?
            .push_node(object_node);
        static_object_node_ids.push(object_node_id);

        // Nest all the point cloud nodes under this object's semantic node.
        for point_cloud_node_id in &point_cluod_node_ids[i * 10..(i + 1) * 10] {
            ygg.nest(*point_cloud_node_id).under(object_node_id)?;
        }

        // Nest this object's semantic node under the root node.
        ygg.nest(object_node_id).under(root_node_id)?;
    }
}

The above snippet creates 7 new nodes in the static object layer, each representing a new static object. Since these nodes represent actual objects in the scene, we nest all their points under their semantic node:

#![allow(unused)]
fn main() {
    // Nest all the point cloud nodes under this object's semantic node.
    for point_cloud_node_id in &point_cluod_node_ids[i * 10..(i + 1) * 10] {
        ygg.nest(*point_cloud_node_id).under(object_node_id)?;
    }
}

Using the ygg.nest(nestee_id).under(nester_id) pattern, we can nest the nestee node under the nester node. Note that nester can nest nestee if and only if nestee’s layer is a child of nester’s layer.

Each node in the scene graph can have at most one nester or parent. If under is called on a node that already has a parent, the old parent-child relationship is overwritten.

In this code snippet, we also make sure to mark the object node as a child of the root node

#![allow(unused)]
fn main() {
    // Nest this object's semantic node under the root node.
    ygg.nest(object_node_id).under(root_node_id)?;
}

Dynamic Object Layer

#![allow(unused)]
fn main() {
    // Create 3 dynamic nodes representing moving objects in the scene.
    // Each node will have a "type" feature with a value like "Humand", "Dog", and "Cat".
    // The nodes will be added to the dynamic layer and will be connected to the root.
    let mut dynamic_node_ids = Vec::new();
    let dynamic_object_types = ["Human", "Dog", "Cat"];
    for i in 0..dynamic_object_types.len() {
        let dynamic_node = ygg.new_node(vec![Feature::new("type", dynamic_object_types[i])]);
        let dynamic_node_id = ygg
            .layer_mut(dynamic_objects_layer_id)?
            .push_node(dynamic_node);
        dynamic_node_ids.push(dynamic_node_id);

        // Nest all the point cloud nodes under this object's semantic node.
        let offset = static_object_types.len() * 10;
        for point_cloud_node_id in &point_cluod_node_ids[offset + i * 10..offset + (i + 1) * 10] {
            ygg.nest(*point_cloud_node_id).under(dynamic_node_id)?;
        }

        // Nest this dynamic node under the root node.
        ygg.nest(dynamic_node_id).under(root_node_id)?;
    }
}

Similarly to the static layer, we create 3 dynamic objects to represent living entities, e.g., humans, in the scene.

#![allow(unused)]
fn main() {
    // Create semantic relationships between dynamic nodes.
    // For example, we can say that:
    // 1. the "Human" node is "holding" the "Dog" node.
    // 2. the "Dog" node is "looking" the "Cat" node.
    ygg.layer_mut(dynamic_objects_layer_id)?.add_edge(
        dynamic_node_ids[0],
        dynamic_node_ids[1],
        "holding",
    )?;
    ygg.layer_mut(dynamic_objects_layer_id)?.add_edge(
        dynamic_node_ids[1],
        dynamic_node_ids[2],
        "looking",
    )?;

}

yggdrasil supports semantic edges between two nodes of the same layer. Here, we create two semantic edges representing interactions between the “Human”, the “Dog”, and the “Cat”. These edges can have any arbitrary label. The labels can be used to filter nodes and edges.

Using the Layer::add_edge one can add an edge between two nodes by passing their ids. Note that this function will fail if the nodes are not from this layer.

Run Queries On The Scene Graph

A scene graph is only as useful as its queries! We will explore some of the queries that yggdrasil supports and get a glimpse of what each query does.

Let’s start by using the function we created in the Bootstrapping section to generate our demo scene graph:

use yggdrasil::Feature;

fn main() -> yggdrasil::Result<()> {
    // Create a demo scene graph with the following structure:
    //
    // root_layer (root node with name "root")
    // ├────────── dynamic_objects_layer    (3 dynamic nodes with type "Human", "Dog", 
    // │                            │       "Cat", and edges:
    // │                            │                    "Human" -holding-> "Dog",
    // │                            │                     "Dog" -looking-> "Cat"  )
    // │                            │
    // └─ static_objects_layer      │       (7 static nodes with type "car", "tree", 
    //          │                   │        "building", "bicycle", "bench", "sign",
    //          │                   │           "lamp")
    //          │                   │
    //          └──── point_cloud_layer (100 point cloud nodes)
    //
    let ygg = create_demo_graph()?;

    .
    .
    .

    Ok(())
}

Basic Label Retrieval

Retrieve nodes matching a specific feature (both key and value)

Running this query on the scene graph would return a vector of vector of nodes, each vector of nodes representing the nodes matched in a specific layer. Layers with no matches would be represented as empty vectors. In this case, we expect to find one node in the static object layer, therefore the result would be a vector containing one vector with one node, and the rest of the vectors would be empty.

#![allow(unused)]
fn main() {
    // Retrieve all nodes with the feature "type" equal to "lamp".
    let lamp_nodes = ygg.nodes_matching(&[&Feature::new("type", "lamp")]);

    assert_eq!(lamp_nodes.iter().flatten().collect::<Vec<_>>().len(), 1);
    assert_eq!(lamp_nodes[1].len(), 1);
    assert_eq!(
        lamp_nodes.iter().flatten().collect::<Vec<_>>()[0].features,
        vec![Feature::new("type", "lamp")]
    );

}

The same query can be run on the layer level, which returns a vector of nodes, where the nodes are all matches in that specific layer.

#![allow(unused)]
fn main() {
    let lamp_nodes = ygg
        .layer(1)?
        .nodes_matching(&[&Feature::new("type", "lamp")]);

    assert_eq!(lamp_nodes.len(), 1);
    assert_eq!(lamp_nodes[0].features, vec![Feature::new("type", "lamp")]);
}

Retrieve nodes having a feature with a specific key

Retrieve all nodes that have a feature with a specific key. Same as the previous query, this query can also be run on both scene graph and layer level, and it would return all nodes that have a feature with that specific key, regardless of the value. In this case, we expect to find 10 in total nodes that have a feature with the key “type”, 7 in the static object layer and 3 in the dynamic object layer.

#![allow(unused)]
fn main() {
    // Scene Graph level query
    let nodes_with_type = ygg.nodes_having(&["type"]);

    assert_eq!(
        nodes_with_type.iter().flatten().collect::<Vec<_>>().len(),
        10
    );
    assert_eq!(nodes_with_type[0].len(), 0);
    assert_eq!(nodes_with_type[1].len(), 7);
    assert_eq!(nodes_with_type[2].len(), 3);
    assert_eq!(nodes_with_type[3].len(), 0);

    
    // Layer level query
    let static_nodes_with_type = ygg.layer(1)?.nodes_having(&["type"]);
    assert_eq!(static_nodes_with_type.len(), 7);

    let dynamic_nodes_with_type = ygg.layer(2)?.nodes_having(&["type"]);
    assert_eq!(dynamic_nodes_with_type.len(), 3);
}

Retrieve edges matching a specific description

Retrieve all edges matching the given pattern in the description. This query would return all matching edges in the scene graph, along with the source and destination nodes of those edges. In this case, we expect to only find a single edge matching the “holding” pattern in the dynamic object layer, connecting the “Human” node to the “Dog” node.

Note that this query too can be run on both levels and the outputs have the same format.

#![allow(unused)]
fn main() {

    let holding_edges = ygg.edges_matching("holding");
    assert_eq!(holding_edges.iter().flatten().collect::<Vec<_>>().len(), 1);
    assert_eq!(holding_edges[0].len(), 0);
    assert_eq!(holding_edges[1].len(), 0);
    assert_eq!(holding_edges[2].len(), 1);
    assert_eq!(holding_edges[3].len(), 0);

    // Retrieve Human and Dog nodes.
    let human_node_id = ygg
        .layer(2)?
        .nodes_matching(&[&Feature::new("type", "Human")])[0]
        .id;
    let dog_node_id = ygg
        .layer(2)?
        .nodes_matching(&[&Feature::new("type", "Dog")])[0]
        .id;
    assert_eq!(holding_edges[2][0].src, human_node_id);
    assert_eq!(holding_edges[2][0].dst, dog_node_id);
    assert_eq!(holding_edges[2][0].desc, "holding");
}

Retrieve edges from/to a node

Retrieve all edges from, or to a certain node. For example, we can retrieve all edges that are from/to the “Human” node.

Note that this query can also be run on both levels. The only difference is that, unlike the previous queries, when run on the scene graph level this query would return all edges in a single vector, since edges are not associated with layers, and therefore there is no need to separate the results by layer.

#![allow(unused)]
fn main() {
    // edges from human
    let nodes_from_human = ygg.edges_from(human_node_id);

    assert_eq!(nodes_from_human.len(), 1);
    assert_eq!(nodes_from_human[0].src, human_node_id);
    assert_eq!(nodes_from_human[0].dst, dog_node_id);
    assert_eq!(nodes_from_human[0].desc, "holding");

    // edges to human
    let nodes_to_dog = ygg.edges_to(dog_node_id);

    assert_eq!(nodes_to_dog.len(), 1);
    assert_eq!(nodes_to_dog[0].src, human_node_id);
    assert_eq!(nodes_to_dog[0].dst, dog_node_id);
    assert_eq!(nodes_to_dog[0].desc, "holding");
}

Nearest Neighbors Queries

A Nearest Neighbor query finds the closest point (or m closest points) from a set of coordinates to the given query point. yggdrasil supports a variety of nearest neighbor queries on the scene graph. There are three different ways to run a nearest neighbor query on the scene graph:

  1. layer level: the node with closest coordinate within that layer is returned.
  2. scene graph level: the closest node is chosen among all the nodes in all the layers.
  3. node level: the closest node within the subtree of the given node is returned. The subtree of a node r is defined as a scene graph in which all the nodes are decendants of r. You can think of the subtree of r as a sub-scene-graph from the original scene graph where the root node is r.

Now we can run different nearest neighbor queries in yggdrasil

Nearest Node

First lets start by retrieving the 5 nearest nodes to coordinates (5, 5, 5) in the entire scene graph.

#![allow(unused)]
fn main() {
    use yggdrasil::PosQueryCount;

    let neighbors = ygg.nearest_nodes(&[5.0, 5.0, 5.0].into(), PosQueryCount::Count(5));
    assert_eq!(neighbors.len(), 5);
}

Recall that in our graph creation phase, we randomly assigned static objects points from the (0, 0, 0) to (10, 10, 10) region, and dynamic objects points from the (10, 10, 10) to (20, 20, 20) region. We expect to find that all the returned points are from the static objects. We assert that by checking the layer id of their respective parent in the scene graph.

#![allow(unused)]
fn main() {
    // Check that all the neighbors are from the static object layer.
    assert!(
        neighbors
            .iter()
            .filter_map(|(n, _)| n.pid)
            .all(|pid| ygg.layer_of(pid) == 1)
    );
}

Next, we repeat the same query on the layer level. Knowing that only the point cloud layer has coordinates assigned to its nodes, we can run the exact same query on the point cloud layer and expect the exact same outputs.

#![allow(unused)]
fn main() {
    let neighbors_in_pc_layer = ygg
        .layer(0)?
        .nearest_nodes(&[5.0, 5.0, 5.0].into(), PosQueryCount::Count(5));

    assert_eq!(neighbors_in_pc_layer.len(), 5);

    // Check that all the neighbors are from the static object layer.
    assert!(
        neighbors_in_pc_layer
            .iter()
            .filter_map(|(n, _)| n.pid)
            .all(|pid| ygg.layer_of(pid) == 1)
    );

    // Check that the results of this query are the same as the previous one.
    assert!(
        neighbors_in_pc_layer
            .iter()
            .map(|(n, _)| n.id)
            .eq(neighbors.iter().map(|(n, _)| n.id))
    );
}

Lastly, we run the same query on a specific node. In this example, we choose the Human node and try to find the 5 closest nodes in its subtree to the query point (5, 5, 5). Note that since Human is a dynamic object, the result should be different from the previous queries.

#![allow(unused)]
fn main() {
    // Retrieve Human node's id
    let human_node_id = ygg
        .layer(2)?
        .nodes_matching(&[&Feature::new("type", "Human")])[0]
        .id;

    let neighbors_in_human_subtree = ygg.nearest_in_subtree(
        &[5.0, 5.0, 5.0].into(),
        human_node_id,
        PosQueryCount::Count(5),
    )?;
    assert_eq!(neighbors_in_human_subtree.len(), 5);

    // Check that all the neighbors are from the Human subtree. Since all the nodes with
    // coordinates are from layer 0 and their immediate parents are in layer 1 or 2, we can simply
    // check for parent id instead of traversing the whole subtree.
    assert!(
        neighbors_in_human_subtree
            .iter()
            .filter_map(|(n, _)| n.pid)
            .all(|pid| pid == human_node_id)
    );

    // Check that the results of this query are different from the previous ones.
    assert!(
        !neighbors_in_human_subtree
            .iter()
            .map(|(n, _)| n.id)
            .eq(neighbors.iter().map(|(n, _)| n.id))
    );
}

The Nearest_in_subtree function will search in all layers in the subtree and returns the first m closest nodes regardless of their layer in the subtree.

In all the above queries, if the number of existing nodes is less than the requested count (m), the returning vector would not be of size m

#![allow(unused)]
fn main() {
    // Asking for 20 neighbors when the Human subtree only has 10 nodes with coordinates should
    // return all the 10 nodes without any error.
    let neighbors_in_human_subtree = ygg.nearest_in_subtree(
        &[5.0, 5.0, 5.0].into(),
        human_node_id,
        PosQueryCount::Count(20),
    )?;
    assert_eq!(neighbors_in_human_subtree.len(), 10);
}

Nodes within

Another type of positional query supported by yggdrasil is the nodes_within query which returns nodes that are within a certain radius of a given point. Much like the nearest_node query, this query can run on all tree levels.

#![allow(unused)]
fn main() {
    // Retrieving all nodes within a radius of 5 from the (5, 5, 5) coordinates. The results should
    // contain less than or equal to 70 nodes, since this is the number of point cloud nodes that
    // are located in the (0, 0, 0) to (10, 10, 10) region.
    let nodes_within = ygg.nodes_within(&[5.0, 5.0, 5.0].into(), 5.0, PosQueryCount::All);
    assert!(nodes_within.len() <= 70);

    // Expanding the radious to 26 should return all the point cloud nodes, since now both the
    // static and dynamic nodes are within the radius.
    let nodes_within = ygg.nodes_within(&[5.0, 5.0, 5.0].into(), 26.0, PosQueryCount::All);
    assert_eq!(nodes_within.len(), 100);

    // Retrieving exactly 1 node within a radius of 5 from the (5, 5, 5) coordinates should return
    // the first node retured by the first nodes_within query.
    let nodes_within = ygg.nodes_within(&[5.0, 5.0, 5.0].into(), 5.0, PosQueryCount::Count(1));
    assert_eq!(nodes_within.len(), 1);
    assert_eq!(nodes_within[0].id, neighbors[0].0.id);

}

Field of View Queries

The Field of View query is used when we want to limit the scene graph to a sub set of the scene that is observable by the agent. This has many applications for path planning and navigation as it allows the agent to have a prior perception of what is to be expected as it moves in the scene.

yggdrasil uses frustum-check to filter out all the objects that are within the field of view of the given camera.

Visible Subgraph

In order to query the scene graph for objects within the field of view, we first have to create an observer. Observers in yggdrasil can be thought of as a cone frustum. Cone frustums have three main parameters:

  1. Location
  2. Direction
  3. Far and near reach

The direction is a plain vector in whatever frame your own coordinates use, so nothing here assumes a particular “up” axis. Only its axis matters, since a cone is symmetric about the direction it points along; a direction of zero length or one carrying a NaN is rejected, which is why the constructor returns a Result.

For more detailed documentation on how to setup an observer, you can read the API doc for the yggdrasil::Observer struct.

In the following snippet, we create a cone frustum observer that is located at (0, 0, 0) and can view all the positive space. We limit this observers view by near and far of (0.001,6.0) to make sure it can only observe the static objects for now.

#![allow(unused)]
fn main() {
use yggdrasil::{Coordinate, Observer};
}
#![allow(unused)]
fn main() {

    // Create a cone observer which can view all the positive space, i.e. the space where none of the
    // x, y, z coordinates are negative. The observer is located at the origin and is looking
    // towards the (1, 1, 1) direction, with a field of view of 90 degrees and a far reach of 6
    // units.
    let pos = Coordinate::ZERO;
    let direction = Coordinate::ONE;
    // Widen the cone just past the angle from the (1, 1, 1) diagonal to each axis, so
    // the whole positive octant falls inside it.
    let half_angle = (1.0 / 3.0_f32.sqrt()).acos() + 0.001;

    let near = 0.001;
    let far = 6_f32;

    let observer = Observer::new_looking_along(pos, direction, half_angle, near, far)?;
}

In order to successfully run the visible_subgraph query, we also need to provide a reference node. The reference node acts as a constraining factor, limiting the resulting subgraph to the nodes that are within the subtree of the reference node. In this example, since we have no constraint, we use the root node as the reference.

#![allow(unused)]
fn main() {
    // Retrieve the root node of the scene graph.
    let root_node_id = ygg
        .layer(3)?
        .nodes_matching(&[&Feature::new("name", "root")])[0]
        .id;
}

Now running the query would return a new scene graph, which is a visible subgraph of the original scene graph. Since we limited the far reach of the observer to 6, we should be able to observe some of the static objects and none of the dynamic ones. Since this query returns a subgraph, the entire ancestry of each visible point cloud node should also apear in the subgraph.

#![allow(unused)]
fn main() {
    // Observable subgraph of this observer would contain some of the static objects and none of
    // the dynamic ones, since they are all located in the (10, 10, 10) to (20, 20, 20) region,
    // which is outside the observer's view frustum's far range.
    // We use the root node as the reference node for this query to check the visibility of all
    // nodes in the scene graph.
    let subgraph = ygg.visible_subgraph(&observer, root_node_id)?;

    // We expect to see some of the point cloud nodes in the subgraph
    assert!(subgraph.layer(0)?.all_nodes().len() > 0);

    // For each observed point cloud node, we expect its parent static object to also apear in the
    // subgraph.
    let uniq_static_objects = subgraph
        .layer(0)?
        .all_nodes()
        .filter_map(|n| n.pid)
        .collect::<std::collections::HashSet<_>>()
        .len();
    assert_eq!(subgraph.layer(1)?.all_nodes().len(), uniq_static_objects);

    // We expect to see none of the dynamic objects in the subgraph.
    assert_eq!(subgraph.layer(2)?.all_nodes().len(), 0);
}

Running the same query with the “Human” node as the reference should return an empty subgraph since none of the Human’s point cloud is visible by the observer.

#![allow(unused)]
fn main() {
    // Running the same field of view query with a dynamic object node as the reference node should
    // return an empty subgraph, since none of the dynamic objects are within the field of view of
    // the observer.
    let human_node_id = ygg
        .layer(2)?
        .nodes_matching(&[&Feature::new("type", "Human")])[0]
        .id;
    let subgraph = ygg.visible_subgraph(&observer, human_node_id)?;
    assert_eq!(subgraph.layer(0)?.all_nodes().len(),0);
    assert_eq!(subgraph.layer(1)?.all_nodes().len(),0);
    assert_eq!(subgraph.layer(2)?.all_nodes().len(),0);
}

Expanding the far reach of the observer to 35 (≈sqrt(3*20^2)) should allow the observer to view dynamic objects as well as the static ones.

#![allow(unused)]
fn main() {
    // Expanding the `far` reach of the observer to 35 should include all the dynamic objects as
    // well as the static ones, meaning that the subgraph should be the same as the original scene
    // graph.
    let observer = Observer::looking_along(pos, direction, half_angle, near, 35.0)?;
    let subgraph = ygg.visible_subgraph(&observer, root_node_id)?;
    assert_eq!(subgraph.layer(0)?.all_nodes().len(),ygg.layer(0)?.all_nodes().len());
    assert_eq!(subgraph.layer(1)?.all_nodes().len(),ygg.layer(1)?.all_nodes().len());
    assert_eq!(subgraph.layer(2)?.all_nodes().len(),ygg.layer(2)?.all_nodes().len());
}

Graph Queries

yggdrasil has support for common graph queries.

Node by id

Starting with the basics, besides label matching, a node in yggdrasil can be retrieved via its id.

#![allow(unused)]
fn main() {
    // Here we first retrieve the root node by matching for its features, and then use its id to
    // retrieve the same node using its id.
    let root_node_id = ygg
        .layer(3)?
        .nodes_matching(&[&Feature::new("name", "root")])[0]
        .id;
}

For immutable access:

#![allow(unused)]
fn main() {
    let root_node = ygg.node(root_node_id)?;
    assert_eq!(root_node.features, vec![Feature::new("name", "root")]);
}

And for mutable access:

#![allow(unused)]
fn main() {
   let mut root_node = ygg.node_mut(root_node_id)?;
   root_node.features.push(Feature::new("is_root", "true"));
}

Layer by id

As shown many times throughout this demo, a layer can be retrieved by its id

#![allow(unused)]
fn main() {
    let root_layer = ygg.layer(3)?;
    assert_eq!(root_layer.id, ygg.layer_of(root_node_id));
}

All Nodes

Using the retrieved layer, one can iterate over all nodes in the layer

#![allow(unused)]
fn main() {
    let layer = ygg.layer(0)?
    for node in layer.all_nodes(){
        println!("Node: {:?}",node.id)
    }
}

Sub Graph

yggdrasil allows you to get a sub graph of the scene, given a reference root node. This is especially useful when dealing with agents with limited computational resources that might not have a need for the entire scene and just a sub set of the scene would be enough for them.

#![allow(unused)]
fn main() {
    // Subgraph retrieval: retrieve the subtree under the "car" node. This query would return a new
    // scene graph containing only the nodes in the subtree under the "car" node, along with the
    // edges between those nodes.
    let car_node_id = ygg
        .layer(1)?
        .nodes_matching(&[&Feature::new("type", "car")])[0]
        .id;

    let car_subgraph = ygg.subgraph(car_node_id)?;

    // We expect the subgraph to contain the "car" node and its 10 point cloud nodes, and no other
    // nodes.
    assert_eq!(car_subgraph.layer(0)?.all_nodes().len(), 10);
    assert_eq!(car_subgraph.layer(1)?.all_nodes().len(), 1);
    assert_eq!(car_subgraph.layer(2)?.all_nodes().len(), 0);
    assert_eq!(car_subgraph.layer(3)?.all_nodes().len(), 0);
}

Merge

Updates in yggdrasil can be in the form of sub graph merge requests, that is, merging a newer version of a sub graph of the original scene graph into the scene graph. This is useful in scenarios where a global scene graph is maintained centrally, and agents can send their local updates to it.

yggdrasil will do the following during the merge:

  1. Nodes with the same ID will be merged, meaning the node in the original scene graph gets updated.
  2. New nodes in the subgraph will be added to the original scene graph.
  • Node deletion is not supported in this operation.
  1. Edges from the original scene graph from src to dst where both src and dst are present in the subgraph but the edge itself is not, are removed from the scene graph.
  2. New edges in the subgraph will be added to the original scene graph.
#![allow(unused)]
fn main() {
    ygg.merge(car_subgraph)?;
}

Bounding Box

A common practice in scene graph usage is to keep track of bounding boxes for different objects in the scene. A Bounding Box is an axis-aligned Box that represents the bounds of the coordinates of an object. It can be used for efficient spatial estimation and optimization.

yggdrasil supports this functionality through bounds. bounds is an optional feature that we can activate for any arbitrary node. By default, all nodes that are created via call to SceneGraph::new_coordinates or SceneGraph::new_indexed_node (which we will talk about in the next chapter, a note on performance) have theirs bounds enabled.

#![allow(unused)]
fn main() {
// Scene Graph Construction
let mut ygg = yggdrasil::SceneGraph::default();
let btm_lid = ygg.new_layer().id;
let mid_lid = ygg.new_layer().id;
let top_lid = ygg.new_layer().id;
ygg.layer_mut(top_lid)?.add_child(mid_lid)?;
ygg.layer_mut(mid_lid)?.add_child(btm_lid)?;

let btm_node = ygg.new_coordinates(1_f32, 2_f32, 3_f32, Vec::new());
let mid_node = ygg.new_node(Vec::new());
let top_node = ygg.new_coordinates(4_f32, 5_f32, 6_f32, Vec::new());

println!("{:?}", btm_node.bounds); // Some(BoundingBox { x: (1.0, 1.0), y: (2.0, 2.0), z: (3.0, 3.0) })
println!("{:?}", mid_node.bounds); // None
println!("{:?}", top_node.bounds); // Some(BoundingBox { x: (4.0, 4.0), y: (5.0, 5.0), z: (6.0, 6.0) })

let btm_nid = ygg.layer_mut(btm_lid)?.push_node(btm_node);
let mid_nid = ygg.layer_mut(mid_lid)?.push_node(mid_node);
let top_nid = ygg.layer_mut(top_lid)?.push_node(top_node);
}
Some(Bounded(BoundingBox { x: (1.0, 1.0), y: (2.0, 2.0), z: (3.0, 3.0) }))
None 
Some(Bounded(BoundingBox { x: (4.0, 4.0), y: (5.0, 5.0), z: (6.0, 6.0) }))

A node’s bounds represents the bounds of all the coordinates in its subtree. yggdrasil keep tracks of bounds of every node in the scene graph and will update it upon deletion or addition of a new coordinates in the subtree.

#![allow(unused)]
fn main() {
// Nesting would update the bounds of the parent node.
ygg.nest(btm_nid).under(mid_nid)?;
// mid_node's bounds should still be None since bounds is disabled. 
println!("{:?}", ygg.node(mid_nid)?.bounds); // None 
// top_node's bounds should not change
println!("{:?}", ygg.node(top_nid)?.bounds); // Some(BoundingBox { x: (4.0, 4.0), y: (5.0, 5.0), z: (6.0, 6.0) })

// Nesting mid_node under top_node would further update the bounds of top_node to encompass both top and mid node.
ygg.nest(mid_nid).under(top_nid)?;
println!("{:?}", ygg.node(top_nid)?.bounds); // Some(BoundingBox { x: (1.0, 4.0), y: (2.0, 5.0), z: (3.0, 6.0) })
}
None
Some(Bounded(BoundingBox { x: (4.0, 4.0), y: (5.0, 5.0), z: (6.0, 6.0) }))
Some(Bounded(BoundingBox { x: (1.0, 4.0), y: (2.0, 5.0), z: (3.0, 6.0) }))

Same as addition, node removal would also affect the bounds

#![allow(unused)]
fn main() {
// Detaching btm_node from mid_node would update top_nodes's bounds again.
ygg.detach(mid_nid).from(top_nid)?;
println!("{:?}", ygg.node(top_nid)?.bounds); // Some(BoundingBox { x: (4.0, 4.0), y: (5.0, 5.0), z: (6.0, 6.0) })
}
Some(Bounded(BoundingBox { x: (4.0, 4.0), y: (5.0, 5.0), z: (6.0, 6.0) }))

A Note On Performance

Although yggdrasil has support for a variety of functionalities, they don’t come for free! These functionalities incur performance penalties either at query time, i.e., when the query is being executed, or at graph construction time, i.e., when the graph is created or updated. Understanding this performance tradeoff and the performance tuning options that yggdrasil provides can help you customize the scene graph for your specific use case and guarantee certain performance and latency limitations.

Indexing

yggdrasil provides support for indexing the coordinates in the scene graph. This indexing can be enabled on both the layer level and the node level. By having indexing enabled, yggdrasil will keep track of every coordinate add/update/removal on a layer, in case of layer indexing, or on a node’s subtree in case of node indexing. This would result in faster positional queries such as nearest neighbor or field of view.

In yggdrasil, by calling SceneGraph::new_indexed_layer instead of SceneGraph::new_layer you can create a layer with indexing enabled

#![allow(unused)]
fn main() {
let mut ygg = yggdrasil::SceneGraph::default();

let no_index_layer = ygg.new_layer();
let indexed_layer  = ygg.new_indexed_layer();
}

Following the same pattern, SceneGraph::new_indexed_node will create a new node with indexing enabled.

#![allow(unused)]
fn main() {
let mut ygg = yggdrasil::SceneGraph::default();

let no_index_node = ygg.new_node(Vec::new());
let indexed_node  = ygg.new_inedexed_node(Vec::new());
}

Although indexing results in better performance at query execution time, it would incur some performance penalties on graph creation/update time since now every change in layers with indexing enabled and every change in the subtree of nodes with indexing enabled would result in an update propagation on these indexes.

One way to mitigate this problem for layer indexing, is to have two seperate layers for static and moving objects. If you know there is a subset of objects in the scene that don’t move or rarely change position and you want fast positional query runtime on those, its better to keep them in a seperate layer. This way, there would be no updates on the layer’s index and the performance penalty would only ocur on the dynamic objects layer’s index.

Bounding Box

Bounding boxes can be thought of as some sort of spacial estimation and just like indexing, they come at the cost of scene graph creation/update performance loss. When a node with coordinates is added to/removed from the scene graph, all the ancestors of that node are affected, and if any of those have bounds enabled, their bounding box will go through an update process.

Unlike indexing, bounding box performance penalty has different characteristics that make it less likely to be a performance bottleneck.

Typically, addition/deletion of a single coordinate will not cause a big update propagation throughout the ancestry path of a node: most of the time, the newly added/deleted coordinate is already fully encompassed by the bounding box of the parent node and thus, no further update is required. So it’s safe to say that performance penalty of coordinate change is negligible when it comes to bounding boxes.