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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
#![doc = include_str!("../README.md")]

use std::fmt;

use bevy_core::Name;
use bevy_ecs::{
    prelude::*,
    query::{QueryData, QueryEntityError, QueryFilter, QueryItem},
    system::SystemParam,
};
use moonshine_kind::prelude::*;
use moonshine_util::hierarchy::HierarchyQuery;

pub mod prelude {
    pub use super::{Object, Objects};
}

pub use moonshine_kind::{Any, CastInto, Kind};

/// A [`SystemParam`] similar to [`Query`] which provides [`Object<T>`] access for its items.
#[derive(SystemParam)]
pub struct Objects<'w, 's, T = Any, F = ()>
where
    T: Kind,
    F: 'static + QueryFilter,
{
    pub instance: Query<'w, 's, Instance<T>, F>,
    pub hierarchy: HierarchyQuery<'w, 's>,
    pub name: Query<'w, 's, &'static Name>,
}

impl<'w, 's, T, F> Objects<'w, 's, T, F>
where
    T: Kind,
    F: 'static + QueryFilter,
{
    /// Iterates over all [`Object`]s of [`Kind`] `T` which match the [`QueryFilter`] `F`.
    pub fn iter(&self) -> impl Iterator<Item = Object<'w, 's, '_, T>> {
        self.instance.iter().map(|instance| Object {
            instance,
            hierarchy: &self.hierarchy,
            name: &self.name,
        })
    }

    /// Gets the [`Object`] of [`Kind`] `T` from an [`Entity`], if it matches.
    pub fn get(&self, entity: Entity) -> Result<Object<'w, 's, '_, T>, QueryEntityError> {
        self.instance.get(entity).map(|instance| Object {
            instance,
            hierarchy: &self.hierarchy,
            name: &self.name,
        })
    }

    /// Gets the [`Object`] of [`Kind`] `T` from an [`Instance`].
    ///
    /// # Safety
    /// Assumes `instance` is a valid [`Instance`] of [`Kind`] `T`.
    pub fn instance(&self, instance: Instance<T>) -> Object<'w, 's, '_, T> {
        self.get(instance.entity()).expect("instance must be valid")
    }
}

/// Represents an [`Entity`] of [`Kind`] `T` with hierarchy and name information.
pub struct Object<'w, 's, 'a, T: Kind = Any> {
    instance: Instance<T>,
    hierarchy: &'a HierarchyQuery<'w, 's>,
    name: &'a Query<'w, 's, &'static Name>,
}

impl<'w, 's, 'a, T: Kind> Object<'w, 's, 'a, T> {
    /// Creates a new [`Object<T>`] from an [`Object<Any>`].
    ///
    /// This is semantically equivalent to an unsafe downcast.
    ///
    /// # Safety
    /// Assumes `base` is of [`Kind`] `T`.
    pub unsafe fn from_base_unchecked(base: Object<'w, 's, 'a>) -> Self {
        Self {
            instance: base.instance.cast_into_unchecked(),
            hierarchy: base.hierarchy,
            name: base.name,
        }
    }

    /// Returns this object as an [`Instance<T>`].
    pub fn instance(&self) -> Instance<T> {
        self.instance
    }

    /// Returns this object as an [`Entity`].
    pub fn entity(&self) -> Entity {
        self.instance.entity()
    }

    /// Returns the [`Name`] of this object.
    pub fn name(&self) -> Option<&str> {
        self.name.get(self.entity()).ok().map(|name| name.as_str())
    }

    /// Returns the [`Name`] of this object if it has one, or a given default string otherwise.
    pub fn name_or_default(&self, default: &'a str) -> &'a str {
        self.name
            .get(self.entity())
            .map(|name| name.as_str())
            .unwrap_or(default)
    }

    /// Returns true if this object has no parent.
    pub fn is_root(&self) -> bool {
        self.hierarchy.is_root(self.entity())
    }

    #[deprecated(note = "use `has_children` instead")]
    pub fn is_parent(&self) -> bool {
        self.has_children()
    }

    /// Returns true if this object has a parent.
    pub fn is_child(&self) -> bool {
        self.parent().is_some()
    }

    /// Returns true if this object is a child of the given `parent` [`Entity`].
    pub fn is_child_of(&self, parent: Entity) -> bool {
        self.hierarchy.is_child_of(self.entity(), parent)
    }

    /// Returns true if this object has some children.
    pub fn has_children(&self) -> bool {
        self.hierarchy.has_children(self.entity())
    }

    /// Returns true if this object is a descendant of the given `ancestor` [`Entity`].
    pub fn is_descendant_of(&self, ancestor: Entity) -> bool {
        self.hierarchy.is_descendant_of(self.entity(), ancestor)
    }

    /// Attempts to find an object by its path, relative to this one.
    ///
    /// # Usage
    ///
    /// An **Object Path** is a string of object names separated by slashes which represents
    /// the path to an object within a hierarchy.
    ///
    /// In additional to object names, the path may contain the following special characters:
    ///   - `.` represents this object.
    ///   - `..` represents the parent object.
    ///   - `*` represents any child object.
    ///
    /// Note that this method of object search is relatively slow, and should be reserved for
    /// when performance is not the top priority, such as during initialization or prototyping.
    ///
    /// Instead, prefer to use [`Component`] to tag your entities and [`Query`] them instead, if possible.
    ///
    /// # Safety
    /// This method is somewhat experimental with plans for future expansion.
    /// Please [report](https://github.com/Zeenobit/moonshine_object/issues) any bugs you encounter or features you'd like.
    pub fn find_by_path(&self, path: impl AsRef<str>) -> Option<Object<'w, 's, 'a>> {
        let tail: Vec<&str> = path.as_ref().split('/').collect();
        find_by_path(self.cast_into(), &tail)
    }

    /// Returns the root of this object's hierarchy.
    pub fn root(&self) -> Object<'w, 's, 'a> {
        self.rebind_any(self.hierarchy.root(self.entity()))
    }

    /// Returns the parent of this object.
    pub fn parent(&self) -> Option<Object<'w, 's, 'a>> {
        self.hierarchy
            .parent(self.entity())
            .map(|entity| self.rebind_any(entity))
    }

    /// Iterates over all children of this object.
    pub fn children(&self) -> impl Iterator<Item = Object<'w, 's, 'a>> + '_ {
        self.hierarchy
            .children(self.entity())
            .map(|entity| self.rebind_any(entity))
    }

    /// Iterates over this object in addition to all its ancestors.
    pub fn self_and_ancestors(&self) -> impl Iterator<Item = Object<'w, 's, 'a>> + '_ {
        std::iter::once(self.cast_into()).chain(self.ancestors())
    }

    /// Iterates over all ancestors of this object.
    pub fn ancestors(&self) -> impl Iterator<Item = Object<'w, 's, 'a>> + '_ {
        self.hierarchy
            .ancestors(self.entity())
            .map(|entity| self.rebind_any(entity))
    }

    /// Queries all ancestors of this object with a given [`Query`].
    pub fn query_ancestors<Q: QueryData>(
        &'a self,
        query: &'a Query<'w, 's, Q>,
    ) -> impl Iterator<Item = QueryItem<'_, Q::ReadOnly>> + 'a {
        self.ancestors().filter_map(move |object| {
            let entity = object.entity();
            query.get(entity).ok()
        })
    }

    /// Iterates over this object in addition to all its descendants.
    pub fn self_and_descendants(&self) -> impl Iterator<Item = Object<'w, 's, 'a>> + '_ {
        std::iter::once(self.cast_into()).chain(self.descendants())
    }

    /// Iterates over all descendants of this object.
    pub fn descendants(&self) -> impl Iterator<Item = Object<'w, 's, 'a>> + '_ {
        self.hierarchy
            .descendants(self.entity())
            .map(|entity| self.rebind_any(entity))
    }

    /// Queries all descendants of this object with a given [`Query`].
    pub fn query_descendants<Q: QueryData>(
        &'a self,
        query: &'a Query<'w, 's, Q>,
    ) -> impl Iterator<Item = QueryItem<'_, Q::ReadOnly>> + 'a {
        self.descendants().filter_map(move |object| {
            let entity = object.entity();
            query.get(entity).ok()
        })
    }

    /// Uses this object to create a new [`Object`] which references the given `instance` of the same [`Kind`].
    ///
    /// This function is useful when you already have an [`Object<T>`] and another [`Instance<T>`].
    /// It gives you type-safe object access to the other instance.
    pub fn rebind(&self, instance: Instance<T>) -> Object<'w, 's, 'a, T> {
        Object {
            instance,
            hierarchy: self.hierarchy,
            name: self.name,
        }
    }

    /// Uses this object to create a new [`Object`] which references the given [`Entity`].
    ///
    /// This function is useful when you already have an [`Object<T>`] and another [`Entity`].
    /// It gives you generic object access to the other entity.
    pub fn rebind_any(&self, entity: Entity) -> Object<'w, 's, 'a> {
        Object {
            instance: Instance::from(entity),
            hierarchy: self.hierarchy,
            name: self.name,
        }
    }

    /// Uses this object to create a new [`Object`] which references the given `instance` of a different [`Kind`].
    ///
    /// This function is useful when you already have an [`Object<T>`] and another [`Instance<U>`].
    /// It gives you type-safe object access to the other instance.
    ///
    /// Note that this function assumes the given instance is a valid instance of the given kind.
    pub fn rebind_as<U: Kind>(&self, instance: Instance<U>) -> Object<'w, 's, 'a, U> {
        Object {
            instance,
            hierarchy: self.hierarchy,
            name: self.name,
        }
    }

    /// Safety casts this object into another [`Kind`].
    ///
    /// See [`CastInto`] for more information.
    pub fn cast_into<U: Kind>(self) -> Object<'w, 's, 'a, U>
    where
        T: CastInto<U>,
    {
        Object {
            instance: self.instance.cast_into(),
            hierarchy: self.hierarchy,
            name: self.name,
        }
    }

    /// Returns this object as an [`Object<Any>`].
    pub fn as_any(&self) -> Object<'_, '_, '_> {
        self.cast_into()
    }

    /// Casts this object into another [`Kind`] without any safety checks.
    ///
    /// This is semantically equivalent to a raw C-style cast.
    ///
    /// # Safety
    /// Assumes any instance of kind `T` is also a valid instance of kind `U`.
    pub unsafe fn cast_into_unchecked<U: Kind>(self) -> Object<'w, 's, 'a, U> {
        Object {
            instance: self.instance.cast_into_unchecked(),
            hierarchy: self.hierarchy,
            name: self.name,
        }
    }
}

impl<'w, 's, 'a, T: Component> Object<'w, 's, 'a, T> {
    pub fn from_base(world: &World, object: Object<'w, 's, 'a>) -> Option<Object<'w, 's, 'a, T>> {
        let entity = world.entity(object.entity());
        let instance = Instance::<T>::from_entity(entity)?;
        // SAFE: Entity was just checked to a valid instance of T.
        Some(object.rebind_as(instance))
    }
}

impl<T: Kind> Clone for Object<'_, '_, '_, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: Kind> Copy for Object<'_, '_, '_, T> {}

impl<T: Kind> From<Object<'_, '_, '_, T>> for Entity {
    fn from(object: Object<'_, '_, '_, T>) -> Self {
        object.entity()
    }
}

impl<T: Kind> From<Object<'_, '_, '_, T>> for Instance<T> {
    fn from(object: Object<'_, '_, '_, T>) -> Self {
        object.instance()
    }
}

impl<T: Kind> PartialEq for Object<'_, '_, '_, T> {
    fn eq(&self, other: &Self) -> bool {
        self.instance == other.instance
    }
}

impl<T: Kind> Eq for Object<'_, '_, '_, T> {}

impl<T: Kind> fmt::Debug for Object<'_, '_, '_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut out = f.debug_tuple(&T::debug_name());
        out.field(&self.entity());
        if let Some(name) = self.name() {
            out.field(&name);
        }
        out.finish()
    }
}

fn find_by_path<'w, 's, 'a>(curr: Object<'w, 's, 'a>, tail: &[&str]) -> Option<Object<'w, 's, 'a>> {
    if tail.is_empty() {
        return Some(curr);
    }

    let head = tail[0];
    let tail = &tail[1..];

    if head == "." || head.is_empty() {
        find_by_path(curr, tail)
    } else if head == ".." {
        if let Some(parent) = curr
            .hierarchy
            .parent(curr.entity())
            .map(|parent| curr.rebind_any(parent))
        {
            find_by_path(parent, tail)
        } else {
            None
        }
    } else if head == "*" {
        for child in curr.hierarchy.children(curr.entity()) {
            let child = curr.rebind_any(child);
            if let Some(result) = find_by_path(child, tail) {
                return Some(result);
            }
        }
        return None;
    } else if let Some(child) = curr
        .hierarchy
        .children(curr.entity())
        .map(|child| curr.rebind_any(child))
        .find(|part| part.name().is_some_and(|name| name == head))
    {
        find_by_path(child, tail)
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use bevy::{ecs::system::RunSystemOnce, prelude::*};

    #[test]
    fn find_by_path() {
        let mut w = World::new();

        //     A
        //    /
        //   B
        //  / \
        // C   D

        let (a, b, c, d) = w.run_system_once(|mut commands: Commands| {
            let a = commands.spawn(Name::new("A")).id();
            let b = commands.spawn(Name::new("B")).id();
            let c = commands.spawn(Name::new("C")).id();
            let d = commands.spawn(Name::new("D")).id();

            commands.entity(a).push_children(&[b]);
            commands.entity(b).push_children(&[c, d]);

            (a, b, c, d)
        });

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(a).unwrap().find_by_path("").unwrap().entity();
            assert_eq!(a, x);
        });

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(a).unwrap().find_by_path(".").unwrap().entity();
            assert_eq!(a, x);
        });

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(a).unwrap().find_by_path("B").unwrap().entity();
            assert_eq!(b, x);
        });

        w.run_system_once(move |objects: Objects| {
            let x = objects
                .get(a)
                .unwrap()
                .find_by_path("B/C")
                .unwrap()
                .entity();
            assert_eq!(c, x);
        });

        w.run_system_once(move |objects: Objects| {
            let x = objects
                .get(a)
                .unwrap()
                .find_by_path("B/D")
                .unwrap()
                .entity();
            assert_eq!(d, x);
        });

        w.run_system_once(move |objects: Objects| {
            let x = objects
                .get(a)
                .unwrap()
                .find_by_path("B/*")
                .unwrap()
                .entity();
            assert_eq!(c, x);
        });

        w.run_system_once(move |objects: Objects| {
            let x = objects
                .get(a)
                .unwrap()
                .find_by_path("*/D")
                .unwrap()
                .entity();
            assert_eq!(d, x);
        });

        w.run_system_once(move |objects: Objects| {
            let x = objects
                .get(a)
                .unwrap()
                .find_by_path("*/*")
                .unwrap()
                .entity();
            assert_eq!(c, x);
        });

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(b).unwrap().find_by_path("..").unwrap().entity();
            assert_eq!(a, x);
        });

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(c).unwrap().find_by_path("..").unwrap().entity();
            assert_eq!(b, x);
        });

        w.run_system_once(move |objects: Objects| {
            let x = objects
                .get(c)
                .unwrap()
                .find_by_path("../D")
                .unwrap()
                .entity();
            assert_eq!(d, x);
        });

        w.run_system_once(move |objects: Objects| {
            let x = objects
                .get(c)
                .unwrap()
                .find_by_path("../C")
                .unwrap()
                .entity();
            assert_eq!(c, x);
        });
    }
}