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
use core::{
    alloc::Layout,
    any::TypeId,
    fmt::{self, Debug, Display, Formatter},
    marker::PhantomData,
    ptr,
    sync::atomic::AtomicU32,
};

#[cfg(feature = "serde")]
use serde::{
    de::{Error, Visitor},
    ser::SerializeTupleStruct,
    Deserialize, Serialize,
};

use crate::{
    buffer::ComponentBuffer,
    entity::EntityKind,
    fetch::MaybeMut,
    filter::{ChangeFilter, RemovedFilter, With, WithRelation, Without, WithoutRelation},
    vtable::{ComponentVTable, UntypedVTable},
    ChangeKind, Entity, Metadata, Mutable, RelationExt,
};

/// Trait alias for a 'static + Send + Sync type which can be used as a
/// component.
pub trait ComponentValue: Send + Sync + 'static {}
impl<T> ComponentValue for T where T: Send + Sync + 'static {}

/// A unique component identifier
/// Is not stable between executions, and should as such not be used for
/// execution.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ComponentKey {
    pub(crate) id: Entity,
    /// The object entity if the component is a pair
    pub(crate) object: Option<Entity>,
}

#[cfg(feature = "serde")]
impl Serialize for ComponentKey {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let mut seq = serializer.serialize_tuple_struct("ComponentId", 2)?;
        seq.serialize_field(&self.id)?;
        seq.serialize_field(&self.object)?;

        seq.end()
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for ComponentKey {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct ComponentIdVisitor;
        impl<'de> Visitor<'de> for ComponentIdVisitor {
            type Value = ComponentKey;

            fn expecting(
                &self,
                formatter: &mut smallvec::alloc::fmt::Formatter,
            ) -> smallvec::alloc::fmt::Result {
                write!(
                    formatter,
                    "A tuple of a component id and optional relation object"
                )
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::SeqAccess<'de>,
            {
                let id = seq
                    .next_element()?
                    .ok_or_else(|| Error::invalid_length(0, &self))?;
                let object = seq
                    .next_element()?
                    .ok_or_else(|| Error::invalid_length(1, &self))?;

                Ok(ComponentKey::new(id, object))
            }
        }

        deserializer.deserialize_tuple_struct("ComponentId", 2, ComponentIdVisitor)
    }
}

impl ComponentKey {
    /// Returns true if the component is a relation
    #[inline]
    pub fn is_relation(&self) -> bool {
        self.object.is_some()
    }

    pub(crate) fn new(id: Entity, object: Option<Entity>) -> Self {
        Self { id, object }
    }

    #[inline]
    /// Returns the object of the relation
    pub fn object(&self) -> Option<Entity> {
        self.object
    }

    #[inline]
    /// Returns the component id
    pub fn id(&self) -> Entity {
        self.id
    }
}

impl Display for ComponentKey {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        Debug::fmt(self, f)
    }
}

impl Debug for ComponentKey {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self.object {
            Some(s) => write!(f, "{}({s})", self.id),
            None => Debug::fmt(&self.id, f),
        }
    }
}

/// Type alias for a function which instantiates a component
pub type ComponentFn<T> = fn() -> Component<T>;

/// Type alias for a function which instantiates a relation with the specified
/// object
pub type RelationFn<T> = fn(object: Entity) -> Component<T>;

crate::component! {
    pub(crate) dummy,
}

/// Defines a strongly typed component
pub struct Component<T> {
    key: ComponentKey,
    marker: PhantomData<T>,

    pub(crate) vtable: &'static UntypedVTable,
}

impl<T> Eq for Component<T> {}

impl<T> PartialEq for Component<T> {
    fn eq(&self, other: &Self) -> bool {
        self.key == other.key
    }
}

impl<T> Copy for Component<T> {}

impl<T> Clone for Component<T> {
    fn clone(&self) -> Self {
        Self {
            key: self.key,
            vtable: self.vtable,
            marker: PhantomData,
        }
    }
}

impl<T> fmt::Debug for Component<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("Component").field("key", &self.key).finish()
    }
}

impl<T> Display for Component<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}({})", self.vtable.name, self.key)
    }
}

impl<T: ComponentValue> Component<T> {
    pub(crate) fn new(key: ComponentKey, vtable: &'static ComponentVTable<T>) -> Self {
        Self {
            key,
            marker: PhantomData,
            vtable: vtable.erase(),
        }
    }
    /// Creates a new component from the given untyped vtable
    ///
    /// # Panics
    /// If the types do not match
    pub(crate) fn from_raw_parts(key: ComponentKey, vtable: &'static UntypedVTable) -> Self {
        if !vtable.is::<T>() {
            panic!("Mismatched type");
        }

        Self {
            key,
            marker: PhantomData,
            vtable,
        }
    }

    #[doc(hidden)]
    pub fn static_init(
        id: &AtomicU32,
        kind: EntityKind,
        vtable: &'static ComponentVTable<T>,
    ) -> Self {
        let id = Entity::static_init(id, kind);

        Self {
            key: ComponentKey::new(id, None),
            vtable,
            marker: PhantomData,
        }
    }

    /// Get the component's id.
    #[inline(always)]
    pub fn key(&self) -> ComponentKey {
        self.key
    }

    /// Get the component's base id.
    /// This is the id without any relation object
    #[inline(always)]
    pub fn id(&self) -> Entity {
        self.key.id
    }

    /// Returns the type erased component info
    pub fn info(self) -> ComponentInfo {
        ComponentInfo::of(self)
    }

    /// Transform this into a mutable fetch
    pub fn as_mut(self) -> Mutable<T> {
        Mutable(self)
    }

    /// Transform this into a (maybe) mutable fetch
    pub fn maybe_mut(self) -> MaybeMut<T> {
        MaybeMut(self)
    }

    /// Construct a fine grained change detection filter.
    pub fn modified(self) -> ChangeFilter<T> {
        ChangeFilter::new(self, ChangeKind::Modified)
    }

    /// Construct a fine grained insert detection filter.
    pub fn inserted(self) -> ChangeFilter<T> {
        ChangeFilter::new(self, ChangeKind::Inserted)
    }

    /// Construct a fine grained component remove detection filter.
    ///
    /// **Note**: This filter will yield entities **which are still alive** for which `component` was
    /// removed, and the rest of the fetch matches.
    ///
    /// Since a query only iterates the living world, this filter does not work for despawned entities.
    ///
    /// In other words, queries only return valid entities.
    ///
    /// To capture *all* removed components, including despawned entities, prefer
    /// [`World::subscribe`](crate::World::subscribe).
    pub fn removed(self) -> RemovedFilter<T> {
        RemovedFilter::new(self)
    }

    /// Construct a new filter yielding entities without this component.
    pub fn without(self) -> Without {
        Without {
            component: self.key(),
            name: self.name(),
        }
    }

    /// Construct a new filter yielding entities with this component.
    pub fn with(self) -> With {
        With {
            component: self.key(),
            name: self.name(),
        }
    }

    /// Get the component's name.
    #[must_use]
    #[inline(always)]
    pub fn name(&self) -> &'static str {
        self.vtable.name
    }

    /// Returns all metadata components
    pub fn get_meta(&self) -> ComponentBuffer {
        self.vtable.meta.get(self.info())
    }
}

impl<T: ComponentValue> Metadata<T> for Component<T> {
    fn attach(info: ComponentInfo, buffer: &mut ComponentBuffer) {
        buffer.set(crate::components::component_info(), info);
    }
}

impl<T: ComponentValue> From<Component<T>> for Entity {
    fn from(v: Component<T>) -> Self {
        v.key().id
    }
}

impl<T: ComponentValue> RelationExt<T> for Component<T> {
    fn id(&self) -> Entity {
        self.key().id
    }

    fn of(&self, object: Entity) -> Component<T> {
        Self {
            key: ComponentKey::new(self.key().id, Some(object)),
            ..*self
        }
    }

    #[inline]
    fn with_relation(self) -> WithRelation {
        WithRelation {
            relation: self.id(),
            name: self.name(),
        }
    }

    #[inline]
    fn without_relation(self) -> WithoutRelation {
        WithoutRelation {
            relation: self.id(),
            name: self.name(),
        }
    }

    fn vtable(&self) -> &'static UntypedVTable {
        self.vtable
    }
}

/// Represents a type erased component along with its memory layout and drop fn.
#[derive(Clone, Copy)]
pub struct ComponentInfo {
    pub(crate) key: ComponentKey,
    pub(crate) vtable: &'static UntypedVTable,
}

impl Eq for ComponentInfo {}
impl PartialEq for ComponentInfo {
    fn eq(&self, other: &Self) -> bool {
        self.key == other.key && ptr::eq(self.vtable, other.vtable)
    }
}

impl core::fmt::Debug for ComponentInfo {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("ComponentInfo")
            .field("key", &self.key)
            .field("name", &self.vtable.name)
            .finish()
    }
}

impl<T: ComponentValue> From<Component<T>> for ComponentInfo {
    fn from(v: Component<T>) -> Self {
        ComponentInfo::of(v)
    }
}

impl PartialOrd for ComponentInfo {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        self.key.partial_cmp(&other.key)
    }
}

impl Ord for ComponentInfo {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.key.cmp(&other.key)
    }
}

impl ComponentInfo {
    /// Convert back to a typed form
    ///
    /// # Panics
    /// If the types do not match
    #[inline]
    pub fn downcast<T: ComponentValue>(self) -> Component<T> {
        Component::from_raw_parts(self.key, self.vtable)
    }

    /// Returns the component info of a types component
    pub fn of<T: ComponentValue>(component: Component<T>) -> Self {
        Self {
            key: component.key(),
            vtable: component.vtable,
        }
    }

    #[inline]
    pub(crate) fn is<T: ComponentValue>(&self) -> bool {
        (self.vtable.type_id)() == TypeId::of::<T>()
    }

    #[inline]
    pub(crate) fn size(&self) -> usize {
        self.vtable.layout.size()
    }

    /// Returns the component name
    #[inline]
    pub fn name(&self) -> &'static str {
        self.vtable.name
    }

    /// Returns the component id
    #[inline(always)]
    pub fn key(&self) -> ComponentKey {
        self.key
    }

    #[inline]
    pub(crate) fn align(&self) -> usize {
        self.vtable.layout.align()
    }

    #[inline]
    pub(crate) unsafe fn drop(&self, ptr: *mut u8) {
        (self.vtable.drop)(ptr)
    }

    #[inline]
    pub(crate) fn layout(&self) -> Layout {
        self.vtable.layout
    }

    #[inline]
    /// Returns the type id of the component
    pub fn type_id(&self) -> TypeId {
        (self.vtable.type_id)()
    }

    #[inline]
    /// Returns the type name of the component
    pub fn type_name(&self) -> &'static str {
        (self.vtable.type_name)()
    }

    #[inline]
    pub(crate) fn is_relation(&self) -> bool {
        self.key.object.is_some()
    }

    pub(crate) fn get_meta(&self) -> ComponentBuffer {
        self.vtable.meta.get(*self)
    }

    pub(crate) fn meta_ref(&self) -> &ComponentBuffer {
        self.vtable.meta.get_ref(*self)
    }
}

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

    component! {
        foo: i32,
        bar: f32,
    }

    #[test]
    fn component_ids() {
        let _c_foo = foo();
        // eprintln!("Foo: {c_foo:?}");
        // eprintln!("Bar: {:?}", bar().id());
        assert_ne!(foo().key(), bar().key());
        assert_eq!(foo(), foo());
    }
}