galeon-engine 0.1.0

Core ECS game engine: entities, components, systems, and scheduling.
Documentation
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
// SPDX-License-Identifier: AGPL-3.0-only OR Commercial

use std::any::TypeId;

use crate::system_param::{Access, SystemParam};
use crate::world::UnsafeWorldCell;

// =============================================================================
// Events<T> — double-buffered typed event queue
// =============================================================================

/// Double-buffered typed event queue.
///
/// Events are written to `current` during the tick they are sent. At the start
/// of the next `Schedule::run()`, `World::update_events()` swaps the buffers:
/// `current` becomes `previous` and the old `previous` is cleared. Systems
/// that use `EventReader<T>` iterate over `previous`, so they always read
/// events from the *previous* tick.
///
/// ```text
/// Tick N:   EventWriter sends → current
/// tick N+1: update_events() → current becomes previous, cleared current
///           EventReader reads previous (events from tick N)
/// Tick N+2: update_events() → previous is cleared
/// ```
///
/// Register an event type with [`World::add_event::<T>()`] before using
/// `EventWriter<T>` or `EventReader<T>` in systems.
pub struct Events<T: 'static> {
    /// Events written during the previous tick — readable by `EventReader`.
    previous: Vec<T>,
    /// Events being written this tick — by `EventWriter`.
    current: Vec<T>,
}

impl<T: 'static> Events<T> {
    /// Create an empty double buffer.
    pub fn new() -> Self {
        Self {
            previous: Vec::new(),
            current: Vec::new(),
        }
    }

    /// Send an event. It will be readable by `EventReader` on the next tick.
    pub fn send(&mut self, event: T) {
        self.current.push(event);
    }

    /// Iterate over events sent during the previous tick.
    pub fn read(&self) -> impl Iterator<Item = &T> {
        self.previous.iter()
    }

    /// Advance the double buffer.
    ///
    /// The previous buffer is cleared. The current buffer becomes the new
    /// previous buffer. Called automatically by `World::update_events()` at
    /// the start of each `Schedule::run()`.
    pub fn update(&mut self) {
        // Move current → previous (swap), then clear current.
        // Using swap + clear avoids a heap allocation: we reuse the old
        // previous buffer (now cleared) as the new current buffer.
        std::mem::swap(&mut self.previous, &mut self.current);
        self.current.clear();
    }

    /// Number of readable events (in the previous buffer).
    pub fn len(&self) -> usize {
        self.previous.len()
    }

    /// Returns `true` if there are no readable events.
    pub fn is_empty(&self) -> bool {
        self.previous.is_empty()
    }
}

impl<T: 'static> Default for Events<T> {
    fn default() -> Self {
        Self::new()
    }
}

// =============================================================================
// EventWriter<'w, T> — exclusive write access as a SystemParam
// =============================================================================

/// Exclusive write access to the `Events<T>` resource.
///
/// Use this in a system to send events that other systems can read on the
/// next schedule tick via [`EventReader<T>`].
///
/// ```rust,ignore
/// fn fire_cannon(mut writer: EventWriter<'_, CannonFired>) {
///     writer.send(CannonFired { power: 9000 });
/// }
/// ```
pub struct EventWriter<'w, T: 'static> {
    events: &'w mut Events<T>,
}

impl<'w, T: 'static> EventWriter<'w, T> {
    /// Send an event. Readable by `EventReader<T>` systems on the next tick.
    pub fn send(&mut self, event: T) {
        self.events.send(event);
    }
}

// SAFETY: access() reports ResWrite(Events<T>). fetch() only touches the
// Events<T> resource field via get_resource_mut — no other field is accessed.
unsafe impl<T: 'static> SystemParam for EventWriter<'_, T> {
    type Item<'w> = EventWriter<'w, T>;

    fn access() -> Vec<Access> {
        vec![Access::ResWrite(TypeId::of::<Events<T>>())]
    }

    unsafe fn fetch<'w>(world: UnsafeWorldCell) -> Self::Item<'w> {
        EventWriter {
            events: unsafe { world.get_resource_mut::<Events<T>>() },
        }
    }
}

// =============================================================================
// EventReader<'w, T> — shared read access as a SystemParam
// =============================================================================

/// Shared read access to the `Events<T>` resource.
///
/// Iterates over events sent by `EventWriter<T>` on the *previous* tick.
///
/// ```rust,ignore
/// fn on_cannon_fired(reader: EventReader<'_, CannonFired>) {
///     for ev in reader.read() {
///         println!("cannon fired with power {}", ev.power);
///     }
/// }
/// ```
pub struct EventReader<'w, T: 'static> {
    events: &'w Events<T>,
}

impl<'w, T: 'static> EventReader<'w, T> {
    /// Iterate over events from the previous tick.
    pub fn read(&self) -> impl Iterator<Item = &T> {
        self.events.read()
    }

    /// Number of readable events.
    pub fn len(&self) -> usize {
        self.events.len()
    }

    /// Returns `true` if there are no readable events.
    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }
}

// SAFETY: access() reports ResRead(Events<T>). fetch() only reads the
// Events<T> resource via get_resource — no mutation occurs.
unsafe impl<T: 'static> SystemParam for EventReader<'_, T> {
    type Item<'w> = EventReader<'w, T>;

    fn access() -> Vec<Access> {
        vec![Access::ResRead(TypeId::of::<Events<T>>())]
    }

    unsafe fn fetch<'w>(world: UnsafeWorldCell) -> Self::Item<'w> {
        EventReader {
            events: unsafe { world.get_resource::<Events<T>>() },
        }
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::system_param::{SystemParam, has_conflicts};
    use crate::world::World;

    #[derive(Debug, PartialEq)]
    struct DamageEvent {
        amount: u32,
    }

    #[derive(Debug, PartialEq)]
    struct SpawnEvent {
        x: f32,
    }

    // -------------------------------------------------------------------------
    // Events<T> unit tests
    // -------------------------------------------------------------------------

    #[test]
    fn events_send_and_read() {
        let mut events: Events<DamageEvent> = Events::new();

        // No events readable yet.
        assert!(events.is_empty());
        assert_eq!(events.len(), 0);

        // Send an event.
        events.send(DamageEvent { amount: 42 });

        // Not yet readable — still in current.
        assert!(events.is_empty());

        // Advance the buffer.
        events.update();

        // Now readable in previous.
        assert!(!events.is_empty());
        assert_eq!(events.len(), 1);
        let collected: Vec<_> = events.read().collect();
        assert_eq!(collected, vec![&DamageEvent { amount: 42 }]);
    }

    #[test]
    fn events_double_buffer_semantics() {
        let mut events: Events<DamageEvent> = Events::new();

        // Tick N: send event.
        events.send(DamageEvent { amount: 10 });
        events.update(); // current → previous

        // Tick N+1 start: event is in previous → readable.
        assert_eq!(events.len(), 1);

        // Tick N+1: no new events, advance again.
        events.update(); // previous is cleared, empty current stays current

        // Tick N+2 start: previous is now cleared.
        assert!(events.is_empty());
    }

    #[test]
    fn events_multiple_sends_same_tick() {
        let mut events: Events<DamageEvent> = Events::new();

        events.send(DamageEvent { amount: 1 });
        events.send(DamageEvent { amount: 2 });
        events.send(DamageEvent { amount: 3 });
        events.update();

        assert_eq!(events.len(), 3);
        let amounts: Vec<u32> = events.read().map(|e| e.amount).collect();
        assert_eq!(amounts, vec![1, 2, 3]);
    }

    // -------------------------------------------------------------------------
    // Access declaration tests
    // -------------------------------------------------------------------------

    #[test]
    fn event_writer_access_is_res_write() {
        let access = <EventWriter<'_, DamageEvent> as SystemParam>::access();
        assert_eq!(access.len(), 1);
        assert_eq!(
            access[0],
            Access::ResWrite(TypeId::of::<Events<DamageEvent>>())
        );
    }

    #[test]
    fn event_reader_access_is_res_read() {
        let access = <EventReader<'_, DamageEvent> as SystemParam>::access();
        assert_eq!(access.len(), 1);
        assert_eq!(
            access[0],
            Access::ResRead(TypeId::of::<Events<DamageEvent>>())
        );
    }

    // -------------------------------------------------------------------------
    // Conflict detection tests
    // -------------------------------------------------------------------------

    #[test]
    fn event_writer_reader_different_types_no_conflict() {
        // EventWriter<DamageEvent> and EventReader<SpawnEvent> — different
        // Events<T> TypeIds — must not conflict.
        let writer_access = <EventWriter<'_, DamageEvent> as SystemParam>::access();
        let reader_access = <EventReader<'_, SpawnEvent> as SystemParam>::access();
        assert!(!has_conflicts(&writer_access, &reader_access));
    }

    #[test]
    fn event_writer_reader_same_type_conflicts() {
        // EventWriter<DamageEvent> and EventReader<DamageEvent> both touch
        // Events<DamageEvent> — ResWrite + ResRead on the same TypeId → conflict.
        let writer_access = <EventWriter<'_, DamageEvent> as SystemParam>::access();
        let reader_access = <EventReader<'_, DamageEvent> as SystemParam>::access();
        assert!(has_conflicts(&writer_access, &reader_access));
    }

    #[test]
    fn event_reader_reader_same_type_no_conflict() {
        // Two EventReaders on the same type — ResRead + ResRead → no conflict.
        let a = <EventReader<'_, DamageEvent> as SystemParam>::access();
        let b = <EventReader<'_, DamageEvent> as SystemParam>::access();
        assert!(!has_conflicts(&a, &b));
    }

    // -------------------------------------------------------------------------
    // SystemParam fetch tests
    // -------------------------------------------------------------------------

    #[test]
    fn event_writer_fetch_and_send() {
        let mut world = World::new();
        world.add_event::<DamageEvent>();

        let cell = unsafe { UnsafeWorldCell::new(&mut world as *mut World) };
        unsafe {
            let mut writer = <EventWriter<'_, DamageEvent> as SystemParam>::fetch(cell);
            writer.send(DamageEvent { amount: 99 });
        }

        // Advance to make current → previous.
        world.update_events();

        assert_eq!(world.resource::<Events<DamageEvent>>().len(), 1);
    }

    #[test]
    fn event_reader_fetch_and_read() {
        let mut world = World::new();
        world.add_event::<DamageEvent>();

        // Send an event directly through the resource.
        world
            .resource_mut::<Events<DamageEvent>>()
            .send(DamageEvent { amount: 7 });
        world.update_events();

        let cell = unsafe { UnsafeWorldCell::new(&mut world as *mut World) };
        unsafe {
            let reader = <EventReader<'_, DamageEvent> as SystemParam>::fetch(cell);
            assert_eq!(reader.len(), 1);
            let ev = reader.read().next().unwrap();
            assert_eq!(ev.amount, 7);
        }
    }

    #[test]
    fn add_event_duplicate_no_updater_duplication() {
        let mut world = World::new();
        world.add_event::<DamageEvent>();
        world.add_event::<DamageEvent>(); // no-op

        world
            .resource_mut::<Events<DamageEvent>>()
            .send(DamageEvent { amount: 5 });
        world.update_events();

        // If the updater were duplicated, the second would clear previous.
        assert_eq!(world.resource::<Events<DamageEvent>>().len(), 1);
    }

    #[test]
    fn add_event_duplicate_does_not_drop_queued_events() {
        let mut world = World::new();
        world.add_event::<DamageEvent>();

        // Queue an event, then call add_event again — must not reset the buffer.
        world
            .resource_mut::<Events<DamageEvent>>()
            .send(DamageEvent { amount: 99 });
        world.add_event::<DamageEvent>(); // no-op

        world.update_events();
        assert_eq!(world.resource::<Events<DamageEvent>>().len(), 1);
        assert_eq!(
            world
                .resource::<Events<DamageEvent>>()
                .read()
                .next()
                .unwrap()
                .amount,
            99
        );
    }

    #[test]
    fn add_event_after_take_resource_restores_without_duplicate_updater() {
        let mut world = World::new();
        world.add_event::<DamageEvent>();

        // Remove the resource via the public API.
        let _old: Events<DamageEvent> = world.take_resource();

        // Re-register — must restore the resource and not duplicate the updater.
        world.add_event::<DamageEvent>();

        world
            .resource_mut::<Events<DamageEvent>>()
            .send(DamageEvent { amount: 77 });
        world.update_events();

        // One updater → event survives in previous. Two would clear it.
        assert_eq!(world.resource::<Events<DamageEvent>>().len(), 1);
        assert_eq!(
            world
                .resource::<Events<DamageEvent>>()
                .read()
                .next()
                .unwrap()
                .amount,
            77
        );
    }
}