1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
use std::marker::PhantomData;

use hecs::{Component, DynamicBundle, Entity, EntityBuilder, World};
use hecs_schedule::{CommandBuffer, GenericWorld};
use once_cell::sync::OnceCell;

use crate::{HierarchyMut, TreeBuilderClone};

/// Ergonomically construct trees without knowledge of world.
///
/// This struct builds the world using [EntityBuilder](hecs::EntityBuilder)
///
/// # Example
/// ```rust
/// use hecs_hierarchy::*;
/// use hecs::*;
///
/// struct Tree;
/// let mut world = World::default();
/// let mut builder = TreeBuilder::<Tree>::from(("root",));
/// builder.attach(("child 1",));
/// builder.attach({
///     let mut builder = TreeBuilder::new();
///     builder.add("child 2");
///     builder
/// });

/// let root = builder.spawn(&mut world);

/// assert_eq!(*world.get::<&'static str>(root).unwrap(), "root");

/// for (a, b) in world
///     .descendants_depth_first::<Tree>(root)
///     .zip(["child 1", "child 2"])
/// {
///     assert_eq!(*world.get::<&str>(a).unwrap(), b)
/// }
///
/// ```
pub struct TreeBuilder<T> {
    children: Vec<TreeBuilder<T>>,
    builder: EntityBuilder,
    marker: PhantomData<T>,
    reserved: OnceCell<Entity>,
}

impl<T: Component> TreeBuilder<T> {
    /// Construct a new empty tree
    pub fn new() -> Self {
        Self {
            children: Vec::new(),
            builder: EntityBuilder::new(),
            marker: PhantomData,
            reserved: OnceCell::new(),
        }
    }

    /// Reserve the entity which this node will spawn
    pub fn reserve(&self, world: &impl GenericWorld) -> Entity {
        *self.reserved.get_or_init(|| world.reserve())
    }

    /// Spawn the whole tree into the world
    pub fn spawn(&mut self, world: &mut World) -> Entity {
        let parent = self.reserve(world);
        let builder = self.builder.build();
        world.insert(parent, builder).unwrap();

        for mut child in self.children.drain(..) {
            let child = child.spawn(world);
            world.attach::<T>(child, parent).unwrap();
        }

        parent
    }

    /// Spawn the whole tree into a commandbuffer.
    /// The world is required for reserving entities.
    pub fn spawn_deferred(&mut self, world: &impl GenericWorld, cmd: &mut CommandBuffer) -> Entity {
        let parent = self.reserve(world);
        let builder = self.builder.build();
        cmd.insert(parent, builder);

        for mut child in self.children.drain(..) {
            let child = child.spawn_deferred(world, cmd);
            cmd.write(move |w: &mut World| {
                w.attach::<T>(child, parent).unwrap();
            });
        }
        parent
    }

    /// Add a component to the root
    pub fn add(&mut self, component: impl Component) -> &mut Self {
        self.builder.add(component);
        self
    }

    /// Add a bundle to the root
    pub fn add_bundle(&mut self, bundle: impl DynamicBundle) -> &mut Self {
        self.builder.add_bundle(bundle);
        self
    }

    /// Atttach a new subtree
    pub fn attach_tree(&mut self, child: Self) -> &mut Self {
        self.children.push(child);
        self
    }

    /// Attach a new leaf as a bundle
    pub fn attach(&mut self, child: impl Into<Self>) -> &mut Self {
        self.children.push(child.into());
        self
    }

    /// Consuming variant of [Self::attach].
    ///
    /// This is useful for nesting to alleviate the need to save an intermediate
    /// builder
    pub fn attach_move(mut self, child: impl Into<Self>) -> Self {
        self.children.push(child.into());
        self
    }

    /// Consuming variant of [Self::attach_tree].
    /// This is useful for nesting to alleviate the need to save an intermediate
    /// builder
    pub fn attach_tree_move(mut self, child: impl Into<Self>) -> Self {
        self.children.push(child.into());
        self
    }

    /// Get a reference to the deferred tree builder's children.
    pub fn children(&self) -> &[Self] {
        self.children.as_ref()
    }

    /// Get a reference to the deferred tree builder's root.
    pub fn root(&self) -> &EntityBuilder {
        &self.builder
    }

    /// Get a mutable reference to the deferred tree builder's root.
    pub fn root_mut(&mut self) -> &mut EntityBuilder {
        &mut self.builder
    }
}

impl<B: DynamicBundle, T: Component> From<B> for TreeBuilder<T> {
    fn from(bundle: B) -> Self {
        let mut builder = EntityBuilder::new();
        builder.add_bundle(bundle);

        Self {
            children: Vec::new(),
            builder,
            marker: PhantomData,
            reserved: OnceCell::new(),
        }
    }
}

impl<T: Component> From<TreeBuilderClone<T>> for TreeBuilder<T> {
    fn from(tree: TreeBuilderClone<T>) -> Self {
        let mut builder = EntityBuilder::new();
        builder.add_bundle(&tree.builder.build());

        let children = tree
            .children
            .into_iter()
            .map(|child| child.into())
            .collect();

        Self {
            children,
            builder,
            marker: PhantomData,
            reserved: tree.reserved,
        }
    }
}