1use 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>, vec: SafeVec<E>, }
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 pub(crate) fn insert_listener(&mut self) -> usize {
47 let listener_index = self.listeners.len();
49 self.listeners.push(ShareUsize::new(0));
50 listener_index
51 }
52 pub(crate) fn record(&self, e: E) {
54 self.vec.insert(e);
55 }
56 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 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 pub(crate) fn get_iter(&self, listener_index: usize) -> SafeVecIter<'_, E> {
72 let end = self.vec.len();
73 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 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 Ok(len)
93 }
94 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 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 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 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 state: &'world mut Self::State,
192 ) -> Self::Item<'world> {
193 Event::new(state)
194 }
195 #[inline]
196 fn get_self<'world>(
197 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
238pub 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
273pub 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 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 state: &'world mut Self::State,
305 ) -> Self {
306 unsafe { transmute(Self::get_param( state)) }
307 }
308}
309
310pub 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 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 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 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 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 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}