use std::error::Error; use hecs::{Entity, World}; use hecs_hierarchy::*; fn main() -> Result<(), Box> { // Marker type which allows several hierarchies. struct Tree; let mut world = hecs::World::default(); // Create a root entity, there can be several. let root = world.spawn(("Root",)); // Create a loose entity let child = world.spawn(("Child 1",)); // Attaches the child to a parent, in this case `root` world.attach::(child, root).unwrap(); // Iterate children for child in world.children::(root) { let name = world.get::<&&str>(child).unwrap(); println!("Child: {:?} {}", child, *name); } // Add a grandchild world.attach_new::(child, ("Grandchild",)).unwrap(); // Iterate recursively for child in world.descendants_depth_first::(root) { let name = world.get::<&&str>(child).unwrap(); println!("Child: {:?} {}", child, *name) } // Detach `child` and `grandchild` world.detach::(child).unwrap(); let child2 = world.attach_new::(root, ("Child 2",)).unwrap(); // Reattach as a child of `child2` world.attach::(child, child2).unwrap(); world.attach_new::(root, ("Child 3",)).unwrap(); // Hierarchy now looks like this: // Root // |-------- Child 3 // |-------- Child 2 // |-------- Child 1 // |-------- Grandchild print_tree::(&world, root); world.despawn_all::(child2); print_tree::(&world, root); world .iter() .for_each(|entity| println!("Entity: {:?}", entity.entity())); Ok(()) } fn print_tree(world: &World, root: Entity) { fn internal(world: &World, parent: Entity, depth: usize) { for child in world.children::(parent) { let name = world.get::<&&str>(child).unwrap(); println!( "{}|-------- {}", std::iter::repeat(" ") .take((depth - 1) * 10) .collect::(), *name, ); internal::(world, child, depth + 1) } } let name = world.get::<&&str>(root).unwrap(); println!("{}", *name); internal::(world, root, 1) }