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
//! [`Relation`] is a concept that is similar to [`Component`].
//! The main difference is that they are not components, but rather relations.
//!
//! [`Component`] is data that can be attached to individual entity
//! and [`Relation`] is data that connects two entities together.
//!
//! [`Component`]: ../component/trait.Component.html

use core::{marker::PhantomData, mem::ManuallyDrop};

use alloc::{vec, vec::Vec};

use crate::{
    action::ActionEncoder,
    borrow_dyn_trait,
    component::{Component, ComponentBorrow},
    entity::EntityId,
};

pub use edict_proc::Relation;

pub use self::{
    child_of::ChildOf,
    query::{
        not_related, not_related_by, not_relates, not_relates_to, related, related_by, relates,
        relates_to, FetchFilterNotRelatedBy, FetchFilterNotRelatesTo, FetchFilterRelatedBy,
        FetchRelated, FetchRelatesExclusiveRead, FetchRelatesExclusiveWrite, FetchRelatesRead,
        FetchRelatesToRead, FetchRelatesToWrite, FetchRelatesWrite, FilterFetchRelationTo,
        FilterNotRelated, FilterNotRelatedBy, FilterNotRelates, FilterNotRelatesTo, FilterRelated,
        FilterRelatedBy, FilterRelates, FilterRelatesTo, Related, Relates, RelatesExclusive,
        RelatesReadIter, RelatesTo, RelatesWriteIter,
    },
};

mod child_of;
mod query;

/// Trait that must be implemented for relations.
pub trait Relation: Send + Sync + Copy + 'static {
    /// If `true` then relation can be added only once to an entity.
    const EXCLUSIVE: bool = false;

    /// If `true` then when relation is added to an entity
    /// it is also added to the target.
    const SYMMETRIC: bool = false;

    /// If `true` then entity in relation is "owned" by the target.
    /// This means that when last target is dropped, entity is also dropped, not just relation.
    const OWNED: bool = false;

    /// Returns name of the relation type.
    #[inline]
    fn name() -> &'static str {
        core::any::type_name::<Self>()
    }

    // /// If `true` then when relation is added to an entity,
    // /// the same relation is checked om target and if present,
    // /// target's targets are added as well.
    // /// When target is removed, transitively added targets are removed.
    // const TRANSITIVE: bool = false;

    /// Method that is called when relation is removed from origin entity.
    /// Does nothing by default.
    #[inline]
    fn on_drop(&mut self, entity: EntityId, target: EntityId, encoder: ActionEncoder) {
        drop(entity);
        drop(target);
        drop(encoder);
    }

    /// Method that is called when relation is re-inserted.
    /// Does nothing by default and returns `true`, causing `on_origin_drop` to be called.
    #[inline]
    fn on_replace(
        &mut self,
        value: &Self,
        entity: EntityId,
        target: EntityId,
        new_target: EntityId,
        encoder: ActionEncoder,
    ) -> bool {
        drop(value);
        drop(entity);
        drop(target);
        drop(new_target);
        drop(encoder);

        true
    }

    /// Method that is called when target entity of the relation is dropped.
    /// Does nothing by default.
    #[inline]
    fn on_target_drop(entity: EntityId, target: EntityId, encoder: ActionEncoder) {
        drop(entity);
        drop(target);
        drop(encoder);
    }
}

pub(crate) struct Origin<R> {
    pub target: EntityId,
    pub relation: R,
}

pub(crate) union OriginComponent<R: Relation> {
    exclusive: ManuallyDrop<Origin<R>>,
    non_exclusive: ManuallyDrop<Vec<Origin<R>>>,
}

impl<R> Drop for OriginComponent<R>
where
    R: Relation,
{
    fn drop(&mut self) {
        match R::EXCLUSIVE {
            false => unsafe { ManuallyDrop::drop(&mut self.non_exclusive) },
            true => unsafe { ManuallyDrop::drop(&mut self.exclusive) },
        }
    }
}

impl<R> OriginComponent<R>
where
    R: Relation,
{
    pub fn new(target: EntityId, relation: R) -> Self {
        match R::EXCLUSIVE {
            false => OriginComponent {
                non_exclusive: ManuallyDrop::new(vec![Origin { target, relation }]),
            },
            true => OriginComponent {
                exclusive: ManuallyDrop::new(Origin { target, relation }),
            },
        }
    }

    pub fn add(&mut self, entity: EntityId, target: EntityId, relation: R, encoder: ActionEncoder) {
        match R::EXCLUSIVE {
            false => {
                let origins = unsafe { &mut *self.non_exclusive };
                for idx in 0..origins.len() {
                    if origins[idx].target == target {
                        Self::set_one(
                            &mut origins[idx],
                            Origin { target, relation },
                            entity,
                            encoder,
                        );
                        return;
                    }
                }
                origins.push(Origin { target, relation });
            }
            true => {
                let old_origin = unsafe { &mut *self.exclusive };
                Self::set_one(old_origin, Origin { target, relation }, entity, encoder);
            }
        }
    }

    pub fn remove_relation(
        &mut self,
        entity: EntityId,
        target: EntityId,
        mut encoder: ActionEncoder,
    ) {
        match R::EXCLUSIVE {
            false => {
                let origins = unsafe { &mut *self.non_exclusive };
                for idx in 0..origins.len() {
                    if origins[idx].target == target {
                        origins.swap_remove(idx);
                        if origins.is_empty() {
                            encoder.drop::<Self>(entity);
                        }
                        return;
                    }
                }
            }
            true => {
                let origin = unsafe { &mut *self.exclusive };
                if origin.target == target {
                    encoder.drop::<Self>(entity);
                }
            }
        }
    }

    pub fn origins(&self) -> &[Origin<R>] {
        match R::EXCLUSIVE {
            false => unsafe { &*self.non_exclusive },
            true => core::slice::from_ref(unsafe { &*self.exclusive }),
        }
    }

    pub fn origins_mut(&mut self) -> &mut [Origin<R>] {
        match R::EXCLUSIVE {
            false => unsafe { &mut *self.non_exclusive },
            true => core::slice::from_mut(unsafe { &mut *self.exclusive }),
        }
    }

    /// Called when target relation component is removed from target entity for non-exclusive relations.
    fn on_non_exclusive_target_drop(
        &mut self,
        entity: EntityId,
        target: EntityId,
        mut encoder: ActionEncoder,
    ) {
        debug_assert!(!R::EXCLUSIVE);

        let origins = unsafe { &mut *self.non_exclusive };

        for idx in 0..origins.len() {
            if origins[idx].target == target {
                if R::SYMMETRIC {
                    R::on_target_drop(target, entity, encoder.reborrow())
                };
                origins[idx]
                    .relation
                    .on_drop(entity, target, encoder.reborrow());
                origins.swap_remove(idx);
                break;
            }
        }

        if origins.is_empty() {
            if R::OWNED {
                encoder.despawn(entity);
            } else {
                encoder.drop::<Self>(entity);
            }
        }
    }

    fn drop_one(origin: &mut Origin<R>, entity: EntityId, mut encoder: ActionEncoder) {
        origin
            .relation
            .on_drop(entity, origin.target, encoder.reborrow());
        if R::SYMMETRIC {
            // This is also a target.
            R::on_target_drop(origin.target, entity, encoder.reborrow());
        }
        Self::clear_one(origin, entity, encoder);
    }

    fn set_one(
        origin: &mut Origin<R>,
        new_origin: Origin<R>,
        entity: EntityId,
        mut encoder: ActionEncoder,
    ) {
        let on_replace = origin.relation.on_replace(
            &new_origin.relation,
            entity,
            origin.target,
            new_origin.target,
            encoder.reborrow(),
        );
        if on_replace {
            origin
                .relation
                .on_drop(entity, origin.target, encoder.reborrow());
        }
        if new_origin.target != origin.target {
            Self::clear_one(origin, entity, encoder);
        }
        *origin = new_origin;
    }

    fn clear_one(origin: &mut Origin<R>, entity: EntityId, mut encoder: ActionEncoder) {
        if R::SYMMETRIC {
            if origin.target != entity {
                R::on_target_drop(origin.target, entity, encoder.reborrow());
                if R::EXCLUSIVE {
                    if R::OWNED {
                        encoder.despawn(origin.target);
                    } else {
                        encoder.drop::<Self>(origin.target);
                    }
                } else {
                    let target = origin.target;
                    encoder.closure_with_encoder(move |world, encoder| {
                        if let Ok(mut target_component) = world.query_one::<&mut Self>(target) {
                            if let Some(target_component) = target_component.get() {
                                target_component
                                    .on_non_exclusive_target_drop(target, entity, encoder);
                            }
                        }
                    });
                }
            }
        } else {
            let target = origin.target;
            encoder.closure_with_encoder(move |world, encoder| {
                if let Ok(mut target_component) = world.query_one::<&mut TargetComponent<R>>(target)
                {
                    if let Some(target_component) = target_component.get() {
                        target_component.on_origin_drop(entity, target, encoder);
                    }
                }
            });
        }
    }
}

impl<R> Component for OriginComponent<R>
where
    R: Relation,
{
    #[inline]
    fn on_drop(&mut self, entity: EntityId, mut encoder: ActionEncoder) {
        for origin in self.origins_mut() {
            Self::drop_one(origin, entity, encoder.reborrow());
        }
    }

    #[inline]
    fn on_replace(&mut self, _value: &Self, _entity: EntityId, _encoder: ActionEncoder) -> bool {
        unimplemented!("This method is not intended to be called");
    }

    #[inline]
    fn borrows() -> Vec<ComponentBorrow> {
        let mut output = Vec::new();
        if R::SYMMETRIC {
            borrow_dyn_trait!(Self as RelationOrigin => output);
            borrow_dyn_trait!(Self as RelationTarget => output);
        } else {
            borrow_dyn_trait!(Self as RelationOrigin => output);
        }
        output
    }
}

/// Component that is added to target entity of the non-symmetric relation.
pub(crate) struct TargetComponent<R> {
    origins: Vec<EntityId>,
    relation: PhantomData<fn() -> R>,
}

impl<R> TargetComponent<R>
where
    R: Relation,
{
    pub(crate) fn new(entity: EntityId) -> Self {
        debug_assert!(!R::SYMMETRIC);

        TargetComponent {
            origins: vec![entity],
            relation: PhantomData,
        }
    }

    pub(crate) fn add(&mut self, entity: EntityId) {
        debug_assert!(!self.origins.contains(&entity));
        self.origins.push(entity);
    }

    /// Called when relation is removed from origin entity.
    /// Or origin entity is dropped.
    fn on_origin_drop(&mut self, entity: EntityId, target: EntityId, mut encoder: ActionEncoder) {
        for idx in 0..self.origins.len() {
            if self.origins[idx] == entity {
                R::on_target_drop(entity, target, encoder.reborrow());
                self.origins.swap_remove(idx);
                break;
            }
        }

        if self.origins.is_empty() {
            encoder.drop::<Self>(target);
        }
    }
}

impl<R> Component for TargetComponent<R>
where
    R: Relation,
{
    #[inline]
    fn on_drop(&mut self, target: EntityId, mut encoder: ActionEncoder) {
        for &entity in &self.origins {
            R::on_target_drop(entity, target, encoder.reborrow());
            if R::EXCLUSIVE {
                if R::OWNED {
                    encoder.despawn(entity);
                } else {
                    encoder.drop::<OriginComponent<R>>(entity);
                }
            } else {
                encoder.closure_with_encoder(move |world, encoder| unsafe {
                    if let Ok(origin) = world.query_one_unchecked::<&mut OriginComponent<R>>(entity)
                    {
                        origin.on_non_exclusive_target_drop(entity, target, encoder);
                    }
                });
            }
        }
    }

    #[inline]
    fn on_replace(&mut self, _value: &Self, _entity: EntityId, _encoder: ActionEncoder) -> bool {
        unimplemented!("This method is not intended to be called");
    }

    #[inline]
    fn borrows() -> Vec<ComponentBorrow> {
        let mut output = Vec::new();
        borrow_dyn_trait!(Self as RelationTarget => output);
        output
    }
}

#[doc(hidden)]
pub trait RelationOrigin {
    fn targets(&self) -> Vec<EntityId>;
}

impl<R> RelationOrigin for OriginComponent<R>
where
    R: Relation,
{
    fn targets(&self) -> Vec<EntityId> {
        self.origins().iter().map(|o| o.target).collect()
    }
}

#[doc(hidden)]
pub trait RelationTarget {
    fn origins(&self) -> Vec<EntityId>;
}

impl<R> RelationTarget for OriginComponent<R>
where
    R: Relation,
{
    fn origins(&self) -> Vec<EntityId> {
        debug_assert!(R::SYMMETRIC);

        self.origins().iter().map(|o| o.target).collect()
    }
}

impl<R> RelationTarget for TargetComponent<R>
where
    R: Relation,
{
    fn origins(&self) -> Vec<EntityId> {
        debug_assert!(!R::SYMMETRIC);

        self.origins.clone()
    }
}