Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Created December 17, 2023 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewjberger/7ca653fd5d8c71a2491193e688b0b520 to your computer and use it in GitHub Desktop.
Save matthewjberger/7ca653fd5d8c71a2491193e688b0b520 to your computer and use it in GitHub Desktop.
Scenegraph
use petgraph::graph::{DiGraph, NodeIndex};
use petgraph::Direction;
use nalgebra::{Vector3, Isometry3};
use std::collections::HashMap;
#[derive(Debug, Clone)]
enum SceneNode {
Spatial(SpatialNode),
Mesh { base: SpatialNode, vertices: Vec<Vector3<f32>> },
}
#[derive(Debug, Clone)]
struct SpatialNode {
name: String,
transform: Isometry3<f32>,
}
impl SpatialNode {
fn new(name: impl Into<String>, transform: Isometry3<f32>) -> Self {
SpatialNode { name: name.into(), transform }
}
}
fn main() {
let mut graph = DiGraph::new();
let mut node_lookup = HashMap::new();
// Creating spatial and mesh nodes
let root_node = SceneNode::Spatial(SpatialNode::new("Root", Isometry3::identity()));
let root_index = graph.add_node(root_node.clone());
node_lookup.insert("Root", root_index);
let mesh_node = SceneNode::Mesh {
base: SpatialNode::new("Mesh Node", Isometry3::identity()),
vertices: vec![
Vector3::new(0.0, 0.0, 0.0),
Vector3::new(1.0, 0.0, 0.0),
Vector3::new(0.0, 1.0, 0.0),
],
};
let mesh_index = graph.add_node(mesh_node.clone());
node_lookup.insert("Mesh Node", mesh_index);
// Establishing parent-child relationships
if let Some(&root_index) = node_lookup.get("Root") {
graph.add_edge(root_index, mesh_index, ());
}
// Displaying the graph
println!("Scenegraph Structure:");
for node in graph.node_indices() {
match &graph[node] {
SceneNode::Spatial(spatial_node) => println!("Spatial Node: {:?}", spatial_node),
SceneNode::Mesh { base, vertices } => {
println!("Mesh Node: {:?}", base);
println!("Vertices: {:?}", vertices);
}
}
for neighbor in graph.neighbors_directed(node, Direction::Outgoing) {
println!(" Child Node: {:#?}", graph[neighbor]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment