pi_world/
event.rs

1//! 事件,及组件移除
2//!
3use std::any::{Any, TypeId};
4use std::borrow::Cow;
5use std::marker::PhantomData;
6use std::mem::{size_of, transmute};
7use std::ops::Deref;
8use std::sync::atomic::Ordering;
9
10use pi_append_vec::{SafeVec, SafeVecIter};
11use pi_share::{Share, ShareUsize};
12
13use crate::archetype::{ComponentInfo, COMPONENT_TICK};
14
15use crate::column::{Column, ColumnInfo};
16use crate::system::{SystemMeta, TypeInfo};
17use crate::system_params::SystemParam;
18use crate::world::*;
19
20pub type ComponentEventVec = EventVec<Entity>;
21
22#[derive(Debug, Default)]
23pub struct EventVec<E> {
24    name: Cow<'static, str>,
25    listeners: Vec<ShareUsize>, // 每个监听器的已读取的长度
26    vec: SafeVec<E>,            // 记录的事件
27}
28unsafe impl<E> Send for EventVec<E> {}
29unsafe impl<E> Sync for EventVec<E> {}
30
31impl<E> EventVec<E> {
32    pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
33        Self {
34            name: name.into(),
35            listeners: Vec::new(),
36            vec: SafeVec::default(),
37        }
38    }
39    pub fn capacity(&self) -> usize {
40        self.listeners.capacity() * 8 + self.vec.capacity() * size_of::<E>()
41    }
42    pub fn name(&self) -> &str {
43        &self.name
44    }
45    /// 插入一个监听者,返回监听者的位置
46    pub(crate) fn insert_listener(&mut self) -> usize {
47        // let listeners = unsafe { &mut *self.listeners.get() };
48        let listener_index = self.listeners.len();
49        self.listeners.push(ShareUsize::new(0));
50        listener_index
51    }
52    // #[inline(always)]
53    pub(crate) fn record(&self, e: E) {
54        self.vec.insert(e);
55    }
56    /// 获得指定监听者的读取长度
57    pub(crate) fn len(&self, listener_index: usize) -> usize {
58        let read_len = unsafe { self.listeners.get_unchecked(listener_index) };
59        self.vec.len() - read_len.load(std::sync::atomic::Ordering::Relaxed)
60    }
61
62    /// 标记为已读
63    pub(crate) fn mark_read(&self, listener_index: usize) {
64        let len = self.vec.len();
65        if len > 0 {
66            let read_len = unsafe { self.listeners.get_unchecked(listener_index) };
67            read_len.store(len, std::sync::atomic::Ordering::Relaxed);
68        }
69    }
70    /// 获得指定监听者的读取长度
71    pub(crate) fn get_iter(&self, listener_index: usize) -> SafeVecIter<'_, E> {
72        let end = self.vec.len();
73        // 从上次读取到的位置开始读取
74        let read_len = unsafe { self.listeners.get_unchecked(listener_index) };
75        let start = read_len.swap(end, Ordering::Relaxed);
76        self.vec.slice(start..end)
77    }
78    /// 判断是否能够清空事件列表, 如果所有的监听器都读取了全部的事件列表,才可以清空事件列表, 返回Ok(len)表示可以清空,事件列表长度为len,返回Err((len, index))表示不能清空,len表示事件列表的长度,index表示监听器的最小读取长度,即index之前的监听器已经读取完毕,index及之后的监听器还未读取完毕
79    pub(crate) fn can_clear(&mut self) -> Result<usize, (usize, usize)> {
80        let len = self.vec.len();
81        if len == 0 {
82            return Ok(0);
83        }
84        let mut min = 0;
85        for read_len in self.listeners.iter_mut() {
86            min = min.max(*read_len.get_mut());
87        }
88        if min < len {
89            return Err((len, min));
90        }
91        // 只有所有的监听器都读取了全部的事件列表,才可以清空事件列表
92        Ok(len)
93    }
94    /// 清理方法
95    pub(crate) fn clear(&mut self) {
96        self.vec.clear(0);
97        for read_len in self.listeners.iter_mut() {
98            *read_len.get_mut() = 0;
99        }
100    }
101    /// 清理部分已读的事件列表
102    pub(crate) fn clear_part(&mut self, index: usize) {
103        self.vec.remain_settle(index..usize::MAX, 0);
104        if index == 0 {
105            return;
106        }
107        for read_len in self.listeners.iter_mut() {
108            *read_len.get_mut() -= index;
109        }
110    }
111    // 整理方法, 返回是否已经将事件列表清空,只有所有的监听器都读取了全部的事件列表,才可以清空事件列表
112    pub(crate) fn settle(&mut self) -> bool {
113        match self.can_clear() {
114            Ok(len) => {
115                if len > 0 {
116                    self.clear();
117                }
118                true
119            }
120            Err((len, index)) => {
121                if len.saturating_add(len) > self.vec.vec_capacity() {
122                    // 如果事件列表的数据大于事件列表内的快速槽位的一半,则清理部分事件列表
123                    self.clear_part(index);
124                }
125                false
126            },
127        }
128    }
129}
130
131impl<E: 'static> Settle for EventVec<E> {
132    fn settle(&mut self) {
133        self.settle();
134    }
135}
136impl<E: 'static> Downcast for EventVec<E> {
137    fn into_any(self: Share<Self>) -> Share<dyn Any + Send + Sync> {
138        self
139    }
140
141    fn into_box_any(self: Box<Self>) -> Box<dyn Any> {
142        self
143    }
144
145    fn as_any(&self) -> &dyn Any {
146        self
147    }
148
149    fn as_any_mut(&mut self) -> &mut dyn Any {
150        self
151    }
152}
153
154pub type EventReader<'w, E> = Event<'w, E>;
155
156pub struct Event<'w, E: 'static> (&'w (Share<EventVec<E>>, usize));
157unsafe impl<E> Send for Event<'_, E> {}
158unsafe impl<E> Sync for Event<'_, E> {}
159
160impl<'w, E: 'static> Event<'w, E> {
161    #[inline]
162    pub(crate) fn new(state: &'w (Share<EventVec<E>>, usize)) -> Self {
163        Event (state)
164    }
165    #[inline(always)]
166    pub fn len(&self) -> usize {
167        self.0.0.len(self.0.1)
168    }
169    pub fn iter(&self) -> SafeVecIter<'_, E> {
170        self.0.0.get_iter(self.0.1)
171    }
172
173    pub fn mark_read(&self) {
174        self.0.0.mark_read(self.0.1);
175    }
176}
177
178impl<E: 'static> SystemParam for Event<'_, E> {
179    type State = (Share<EventVec<E>>, usize);
180    type Item<'w> = Event<'w, E>;
181
182    fn init_state(world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {
183        let mut vec = init_state(world);
184        let index = unsafe { Share::get_mut_unchecked(&mut vec).insert_listener() };
185        (vec, index)
186    }
187
188    #[inline]
189    fn get_param<'world>(
190        // world: &'world World,
191        state: &'world mut Self::State,
192    ) -> Self::Item<'world> {
193        Event::new(state)
194    }
195    #[inline]
196    fn get_self<'world>(
197        // world: &'world World,
198        state: &'world mut Self::State,
199    ) -> Self {
200        unsafe { transmute(Self::get_param(state)) }
201    }
202}
203
204pub type EventWriter<'w, E> = EventSender<'w, E>;
205
206pub struct EventSender<'w, E: 'static>(&'w Share<EventVec<E>>);
207unsafe impl<E> Send for EventSender<'_, E> {}
208unsafe impl<E> Sync for EventSender<'_, E> {}
209
210impl<'w, E: 'static> EventSender<'w, E> {
211    pub fn send(&self, e: E) {
212        self.0.record(e)
213    }
214}
215
216impl<E: 'static> SystemParam for EventSender<'_, E> {
217    type State = Share<EventVec<E>>;
218    type Item<'w> = EventSender<'w, E>;
219
220    fn init_state(world: &mut World, _system_meta: &mut SystemMeta) -> Self::State {
221        init_state(world)
222    }
223
224    #[inline]
225    fn get_param<'world>(
226        state: &'world mut Self::State,
227    ) -> Self::Item<'world> {
228        EventSender(state)
229    }
230    #[inline]
231    fn get_self<'world>(
232        state: &'world mut Self::State,
233    ) -> Self {
234        unsafe { transmute(Self::get_param(state)) }
235    }
236}
237
238// pub type ComponentChanged<'w, T> = &'w mut ComponentChanged<'w, T>;
239pub struct ComponentChanged<'w, T: 'static>(ComponentEvent<'w, T>);
240unsafe impl<T> Send for ComponentChanged<'_, T> {}
241unsafe impl<T> Sync for ComponentChanged<'_, T> {}
242impl<'w, T> Deref for ComponentChanged<'w, T> {
243    type Target = ComponentEvent<'w, T>;
244
245    fn deref(&self) -> &Self::Target {
246        &self.0
247    }
248}
249
250impl<T: 'static> SystemParam for ComponentChanged<'_, T> {
251    type State = (Share<ComponentEventVec>, usize);
252    type Item<'w> = ComponentChanged<'w, T>;
253
254    fn init_state(world: &mut World, _meta: &mut SystemMeta) -> Self::State {
255        let info = ComponentInfo::of::<T>(COMPONENT_TICK);
256        init_changed_state(world, TypeId::of::<ComponentChanged<'static, T>>(), info)
257    }
258
259    #[inline]
260    fn get_param<'world>(
261        state: &'world mut Self::State,
262    ) -> Self::Item<'world> {
263        ComponentChanged(ComponentEvent::new(&state.0, state.1))
264    }
265    #[inline]
266    fn get_self<'world>(
267        state: &'world mut Self::State,
268    ) -> Self {
269        unsafe { transmute(Self::get_param( state)) }
270    }
271}
272
273// pub type ComponentAdded<'w, T> = &'w mut ComponentAdded<'w, T>;
274pub struct ComponentAdded<'w, T: 'static>(ComponentEvent<'w, T>);
275unsafe impl<T> Send for ComponentAdded<'_, T> {}
276unsafe impl<T> Sync for ComponentAdded<'_, T> {}
277impl<'w, T> Deref for ComponentAdded<'w, T> {
278    type Target = ComponentEvent<'w, T>;
279
280    fn deref(&self) -> &Self::Target {
281        &self.0
282    }
283}
284
285impl<T: 'static> SystemParam for ComponentAdded<'_, T> {
286    type State = (Share<ComponentEventVec>, usize);
287    type Item<'w> = ComponentAdded<'w, T>;
288
289    fn init_state(world: &mut World, _meta: &mut SystemMeta) -> Self::State {
290        let info = ComponentInfo::of::<T>(0);
291        init_added_state(world, TypeId::of::<ComponentAdded<'static, T>>(), info)
292    }
293
294    #[inline]
295    fn get_param<'world>(
296        // world: &'world World,
297        state: &'world mut Self::State,
298    ) -> Self::Item<'world> {
299        ComponentAdded(ComponentEvent::new(&state.0, state.1))
300    }
301    #[inline]
302    fn get_self<'world>(
303        // world: &'world World,
304        state: &'world mut Self::State,
305    ) -> Self {
306        unsafe { transmute(Self::get_param( state)) }
307    }
308}
309
310// pub type ComponentRemoved<'w, T> = &'w mut ComponentRemoved<'w, T>;
311pub struct ComponentRemoved<'w, T: 'static>(ComponentEvent<'w, T>);
312unsafe impl<T> Send for ComponentRemoved<'_, T> {}
313unsafe impl<T> Sync for ComponentRemoved<'_, T> {}
314impl<'w, T> Deref for ComponentRemoved<'w, T> {
315    type Target = ComponentEvent<'w, T>;
316
317    fn deref(&self) -> &Self::Target {
318        &self.0
319    }
320}
321impl<T: 'static> SystemParam for ComponentRemoved<'_, T> {
322    type State = (Share<ComponentEventVec>, usize);
323    type Item<'w> = ComponentRemoved<'w, T>;
324
325    fn init_state(world: &mut World, _meta: &mut SystemMeta) -> Self::State {
326        let info = ComponentInfo::of::<T>(0);
327        init_removed_state(world, TypeId::of::<ComponentRemoved<'static, T>>(), info)
328    }
329
330    #[inline]
331    fn get_param<'world>(
332        // world: &'world World,
333        state: &'world mut Self::State,
334    ) -> Self::Item<'world> {
335        ComponentRemoved(ComponentEvent::new(&state.0, state.1))
336    }
337    #[inline]
338    fn get_self<'world>(
339        // world: &'world World,
340        state: &'world mut Self::State,
341    ) -> Self {
342        unsafe { transmute(Self::get_param(state)) }
343    }
344}
345
346pub struct ComponentEvent<'w, T: 'static> {
347    pub(crate) record: &'w Share<ComponentEventVec>,
348    pub(crate) listener_index: usize,
349    _p: PhantomData<T>,
350}
351impl<'w, T: 'static> ComponentEvent<'w, T> {
352    #[inline]
353    pub(crate) fn new(record: &'w Share<ComponentEventVec>, listener_index: usize) -> Self {
354        Self {
355            record,
356            listener_index,
357            _p: PhantomData,
358        }
359    }
360    #[inline(always)]
361    pub fn capacity(&self) -> usize {
362        self.record.capacity()
363    }
364    #[inline(always)]
365    pub fn len(&self) -> usize {
366        self.record.len(self.listener_index)
367    }
368    pub fn iter(&self) -> SafeVecIter<'_, Entity> {
369        self.record.get_iter(self.listener_index)
370    }
371    /// 标记为已读
372    pub fn mark_read(&self) {
373        self.record.mark_read(self.listener_index);
374    }
375}
376
377#[inline]
378fn init_state<E: 'static>(world: &mut World) -> Share<EventVec<E>> {
379    let info = TypeInfo::of::<Event<E>>();
380    // let r = world.get_event_record(&info.type_id);
381    // if let Some(er) = r {
382    //     Share::downcast::<EventVec<E>>(er.into_any()).unwrap()
383    // } else {
384    //     let r = Share::new(EventVec::<E>::new(info.type_name.clone()));
385    //     world.init_event_record(info.type_id, r.clone());
386    //     r
387    // }
388    match _init_state(world, &info) {
389        Ok(r) => Share::downcast::<EventVec<E>>(r).unwrap(),
390        Err(r) => {
391            let r = Share::new(EventVec::<E>::new(r));
392            world.init_event_record(info.type_id, r.clone());
393            r
394        },
395    }
396}
397
398fn _init_state(world: &mut World, info: &TypeInfo) -> Result<Share<dyn Any + Send + Sync>, Cow<'static, str>> {
399    let r = world.get_event_record(&info.type_id);
400    if let Some(er) = r {
401        Ok(er.into_any())
402    } else {
403        Err(info.type_name.clone())
404    }
405}
406
407fn init_changed_state(world: &mut World, typeid: TypeId, info: ComponentInfo) -> (Share<ComponentEventVec>, usize) {
408    let (r, c) = init_component_state(world, info, |info| match &info.changed {
409        Some(r) => r.clone(),
410        None => {
411            let r = Share::new(ComponentEventVec::new(info.info.type_name().clone()));
412            info.changed = Some(r.clone());
413            r
414        }
415    });
416    world.init_event_record(typeid, r.0.clone());
417    // 首次创建监听器,将所有相关原型的实体都放入到事件列表中
418    if r.1 == 0 {
419        c.update(&world.archetype_arr, |_, row, ar| {
420            r.0.record(ar.get_unchecked(row));
421        })
422    }
423    r
424}
425fn init_added_state(world: &mut World, typeid: TypeId, info: ComponentInfo) -> (Share<ComponentEventVec>, usize) {
426    let r = init_component_state(world, info, |info| match &info.added {
427        Some(r) => r.clone(),
428        None => {
429            let r = Share::new(ComponentEventVec::new(info.info.type_name().clone()));
430            info.added = Some(r.clone());
431            r
432        }
433    })
434    .0;
435    world.init_event_record(typeid, r.0.clone());
436    r
437}
438
439fn init_removed_state(world: &mut World, typeid: TypeId, info: ComponentInfo) -> (Share<ComponentEventVec>, usize) {
440    let r = init_component_state(world, info, |info| match &info.removed {
441        Some(r) => r.clone(),
442        None => {
443            let r = Share::new(ComponentEventVec::new(info.info.type_name().clone()));
444            info.removed = Some(r.clone());
445            r
446        }
447    })
448    .0;
449    world.init_event_record(typeid, r.0.clone());
450    r
451}
452
453fn init_component_state<F>(
454    world: &mut World,
455    info: ComponentInfo,
456    get_fn: F,
457) -> ((Share<ComponentEventVec>, usize), Share<Column>)
458where
459    F: FnOnce(&mut ColumnInfo) -> Share<ComponentEventVec>,
460{
461    let mut column = world.add_component_info(info).1;
462    let c = unsafe { Share::get_mut_unchecked(&mut column) };
463    let mut vec = get_fn(&mut c.info);
464    let index = unsafe { Share::get_mut_unchecked(&mut vec) }.insert_listener();
465    ((vec, index), column)
466}