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
use std::{fmt::Debug, iter::Iterator, sync::Arc};

use super::{
    entity::Entity,
    query::filter::LayoutFilter,
    storage::{
        archetype::{Archetype, ArchetypeIndex},
        component::ComponentTypeId,
    },
};

/// Events emitted by a world to subscribers. See `World.subscribe(Sender, EntityFilter)`.
#[derive(Debug, Clone)]
pub enum Event {
    /// A new archetype has been created.
    ArchetypeCreated(ArchetypeIndex),
    /// An entity has been inserted into an archetype.
    EntityInserted(Entity, ArchetypeIndex),
    /// An entity has been removed from an archetype.
    EntityRemoved(Entity, ArchetypeIndex),
}

/// Describes a type which can send entity events.
pub trait EventSender: Send + Sync {
    /// Sends the given event to all listeners.
    /// Returns `true` if the sender is still alive.
    fn send(&self, event: Event) -> bool;
}

#[cfg(feature = "crossbeam-events")]
impl EventSender for crossbeam_channel::Sender<Event> {
    fn send(&self, event: Event) -> bool {
        !matches!(
            self.try_send(event),
            Err(crossbeam_channel::TrySendError::Disconnected(_))
        )
    }
}

#[derive(Clone)]
pub(crate) struct Subscriber {
    filter: Arc<dyn LayoutFilter + Send + Sync>,
    sender: Arc<dyn EventSender>,
}

impl Subscriber {
    pub(crate) fn new<F, S>(filter: F, sender: S) -> Self
    where
        F: LayoutFilter + Send + Sync + 'static,
        S: EventSender + 'static,
    {
        Self {
            filter: Arc::new(filter),
            sender: Arc::new(sender),
        }
    }

    pub(crate) fn is_interested(&self, archetype: &Archetype) -> bool {
        self.filter
            .matches_layout(archetype.layout().component_types())
            .is_pass()
    }

    pub(crate) fn send(&self, message: Event) -> bool {
        self.sender.send(message)
    }
}

#[derive(Clone, Default)]
pub(crate) struct Subscribers {
    subscribers: Vec<Subscriber>,
}

impl Subscribers {
    pub fn push(&mut self, subscriber: Subscriber) {
        self.subscribers.push(subscriber);
    }

    pub fn send(&mut self, message: Event) {
        for i in (0..self.subscribers.len()).rev() {
            if !self.subscribers[i].send(message.clone()) {
                self.subscribers.swap_remove(i);
            }
        }
    }

    pub fn matches_layout(&self, components: &[ComponentTypeId]) -> Self {
        Self {
            subscribers: self
                .subscribers
                .iter()
                .filter(|sub| sub.filter.matches_layout(components).is_pass())
                .cloned()
                .collect(),
        }
    }
}

impl Debug for Subscribers {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Subscribers")
            .field("len", &self.subscribers.len())
            .finish()
    }
}