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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
use crate::{
    character::CharacterId,
    combat::{AttackSource, DeathEffects},
    comp::{
        self,
        agent::Sound,
        dialogue::Subject,
        invite::{InviteKind, InviteResponse},
        DisconnectReason, LootOwner, Ori, Pos, UnresolvedChatMsg, Vel,
    },
    generation::{EntityInfo, SpecialEntity},
    lottery::LootSpec,
    mounting::VolumePos,
    outcome::Outcome,
    resources::Secs,
    rtsim::RtSimEntity,
    terrain::SpriteKind,
    trade::{TradeAction, TradeId},
    uid::Uid,
    util::Dir,
    Explosion,
};
use serde::{Deserialize, Serialize};
use specs::{Entity as EcsEntity, World};
use std::{collections::VecDeque, ops::DerefMut, sync::Mutex};
use uuid::Uuid;
use vek::*;

pub type SiteId = u64;
/// Plugin identifier (sha256)
pub type PluginHash = [u8; 32];

pub enum LocalEvent {
    /// Applies upward force to entity's `Vel`
    Jump(EcsEntity, f32),
    /// Applies the `impulse` to `entity`'s `Vel`
    ApplyImpulse {
        entity: EcsEntity,
        impulse: Vec3<f32>,
    },
    /// Applies `vel` velocity to `entity`
    Boost { entity: EcsEntity, vel: Vec3<f32> },
    /// Creates an outcome
    CreateOutcome(Outcome),
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct UpdateCharacterMetadata {
    pub skill_set_persistence_load_error: Option<comp::skillset::SkillsPersistenceError>,
}

pub struct NpcBuilder {
    pub stats: comp::Stats,
    pub skill_set: comp::SkillSet,
    pub health: Option<comp::Health>,
    pub poise: comp::Poise,
    pub inventory: comp::inventory::Inventory,
    pub body: comp::Body,
    pub agent: Option<comp::Agent>,
    pub alignment: comp::Alignment,
    pub scale: comp::Scale,
    pub anchor: Option<comp::Anchor>,
    pub loot: LootSpec<String>,
    pub pets: Vec<(NpcBuilder, Vec3<f32>)>,
    pub rtsim_entity: Option<RtSimEntity>,
    pub projectile: Option<comp::Projectile>,
    pub heads: Option<comp::body::parts::Heads>,
    pub death_effects: Option<DeathEffects>,
}

impl NpcBuilder {
    pub fn new(stats: comp::Stats, body: comp::Body, alignment: comp::Alignment) -> Self {
        Self {
            stats,
            skill_set: comp::SkillSet::default(),
            health: None,
            poise: comp::Poise::new(body),
            inventory: comp::Inventory::with_empty(),
            body,
            agent: None,
            alignment,
            scale: comp::Scale(1.0),
            anchor: None,
            loot: LootSpec::Nothing,
            rtsim_entity: None,
            projectile: None,
            pets: Vec::new(),
            heads: None,
            death_effects: None,
        }
    }

    pub fn with_heads(mut self, heads: impl Into<Option<comp::body::parts::Heads>>) -> Self {
        self.heads = heads.into();
        self
    }

    pub fn with_health(mut self, health: impl Into<Option<comp::Health>>) -> Self {
        self.health = health.into();
        self
    }

    pub fn with_poise(mut self, poise: comp::Poise) -> Self {
        self.poise = poise;
        self
    }

    pub fn with_agent(mut self, agent: impl Into<Option<comp::Agent>>) -> Self {
        self.agent = agent.into();
        self
    }

    pub fn with_anchor(mut self, anchor: comp::Anchor) -> Self {
        self.anchor = Some(anchor);
        self
    }

    pub fn with_rtsim(mut self, rtsim: RtSimEntity) -> Self {
        self.rtsim_entity = Some(rtsim);
        self
    }

    pub fn with_projectile(mut self, projectile: impl Into<Option<comp::Projectile>>) -> Self {
        self.projectile = projectile.into();
        self
    }

    pub fn with_scale(mut self, scale: comp::Scale) -> Self {
        self.scale = scale;
        self
    }

    pub fn with_inventory(mut self, inventory: comp::Inventory) -> Self {
        self.inventory = inventory;
        self
    }

    pub fn with_skill_set(mut self, skill_set: comp::SkillSet) -> Self {
        self.skill_set = skill_set;
        self
    }

    pub fn with_loot(mut self, loot: LootSpec<String>) -> Self {
        self.loot = loot;
        self
    }

    pub fn with_pets(mut self, pets: Vec<(NpcBuilder, Vec3<f32>)>) -> Self {
        self.pets = pets;
        self
    }

    pub fn with_death_effects(mut self, death_effects: Option<DeathEffects>) -> Self {
        self.death_effects = death_effects;
        self
    }
}

pub struct ClientConnectedEvent {
    pub entity: EcsEntity,
}
pub struct ClientDisconnectEvent(pub EcsEntity, pub DisconnectReason);
pub struct ClientDisconnectWithoutPersistenceEvent(pub EcsEntity);

pub struct ChatEvent(pub UnresolvedChatMsg);
pub struct CommandEvent(pub EcsEntity, pub String, pub Vec<String>);

// Entity Creation
pub struct CreateSpecialEntityEvent {
    pub pos: Vec3<f32>,
    pub entity: SpecialEntity,
}

pub struct CreateNpcEvent {
    pub pos: Pos,
    pub ori: Ori,
    pub npc: NpcBuilder,
    pub rider: Option<NpcBuilder>,
}

pub struct CreateShipEvent {
    pub pos: Pos,
    pub ori: Ori,
    pub ship: comp::ship::Body,
    pub rtsim_entity: Option<RtSimEntity>,
    pub driver: Option<NpcBuilder>,
}

pub struct CreateItemDropEvent {
    pub pos: Pos,
    pub vel: Vel,
    pub ori: Ori,
    pub item: comp::PickupItem,
    pub loot_owner: Option<LootOwner>,
}
pub struct CreateObjectEvent {
    pub pos: Pos,
    pub vel: Vel,
    pub body: comp::object::Body,
    pub object: Option<comp::Object>,
    pub item: Option<comp::PickupItem>,
    pub light_emitter: Option<comp::LightEmitter>,
    pub stats: Option<comp::Stats>,
}

pub struct ExplosionEvent {
    pub pos: Vec3<f32>,
    pub explosion: Explosion,
    pub owner: Option<Uid>,
}

pub struct BonkEvent {
    pub pos: Vec3<f32>,
    pub owner: Option<Uid>,
    pub target: Option<Uid>,
}

pub struct HealthChangeEvent {
    pub entity: EcsEntity,
    pub change: comp::HealthChange,
}

pub struct PoiseChangeEvent {
    pub entity: EcsEntity,
    pub change: comp::PoiseChange,
}

pub struct DeleteEvent(pub EcsEntity);

pub struct DestroyEvent {
    pub entity: EcsEntity,
    pub cause: comp::HealthChange,
}

pub struct InventoryManipEvent(pub EcsEntity, pub comp::InventoryManip);

pub struct GroupManipEvent(pub EcsEntity, pub comp::GroupManip);

pub struct RespawnEvent(pub EcsEntity);

pub struct ShootEvent {
    pub entity: EcsEntity,
    pub pos: Pos,
    pub dir: Dir,
    pub body: comp::Body,
    pub light: Option<comp::LightEmitter>,
    pub projectile: comp::Projectile,
    pub speed: f32,
    pub object: Option<comp::Object>,
}

pub struct ShockwaveEvent {
    pub properties: comp::shockwave::Properties,
    pub pos: Pos,
    pub ori: Ori,
}

pub struct KnockbackEvent {
    pub entity: EcsEntity,
    pub impulse: Vec3<f32>,
}

pub struct LandOnGroundEvent {
    pub entity: EcsEntity,
    pub vel: Vec3<f32>,
    pub surface_normal: Vec3<f32>,
}

pub struct SetLanternEvent(pub EcsEntity, pub bool);

pub struct NpcInteractEvent(pub EcsEntity, pub EcsEntity, pub Subject);

pub struct InviteResponseEvent(pub EcsEntity, pub InviteResponse);

pub struct InitiateInviteEvent(pub EcsEntity, pub Uid, pub InviteKind);

pub struct ProcessTradeActionEvent(pub EcsEntity, pub TradeId, pub TradeAction);

pub struct MountEvent(pub EcsEntity, pub EcsEntity);

pub struct MountVolumeEvent(pub EcsEntity, pub VolumePos);

pub struct UnmountEvent(pub EcsEntity);

pub struct SetPetStayEvent(pub EcsEntity, pub EcsEntity, pub bool);

pub struct PossessEvent(pub Uid, pub Uid);

pub struct TransformEvent {
    pub target_entity: Uid,
    pub entity_info: EntityInfo,
    /// If set to false, players wont be transformed unless with a Possessor
    /// presence kind
    pub allow_players: bool,
    /// Whether the entity should be deleted if transforming fails (only applies
    /// to non-players)
    pub delete_on_failure: bool,
}

pub struct InitializeCharacterEvent {
    pub entity: EcsEntity,
    pub character_id: CharacterId,
    pub requested_view_distances: crate::ViewDistances,
}

pub struct InitializeSpectatorEvent(pub EcsEntity, pub crate::ViewDistances);

pub struct UpdateCharacterDataEvent {
    pub entity: EcsEntity,
    pub components: (
        comp::Body,
        Option<comp::Hardcore>,
        comp::Stats,
        comp::SkillSet,
        comp::Inventory,
        Option<comp::Waypoint>,
        Vec<(comp::Pet, comp::Body, comp::Stats)>,
        comp::ActiveAbilities,
        Option<comp::MapMarker>,
    ),
    pub metadata: UpdateCharacterMetadata,
}

pub struct ExitIngameEvent {
    pub entity: EcsEntity,
}

#[derive(Debug)]
pub struct AuraEvent {
    pub entity: EcsEntity,
    pub aura_change: comp::AuraChange,
}

pub struct BuffEvent {
    pub entity: EcsEntity,
    pub buff_change: comp::BuffChange,
}

pub struct EnergyChangeEvent {
    pub entity: EcsEntity,
    pub change: f32,
    pub reset_rate: bool,
}

pub struct ComboChangeEvent {
    pub entity: EcsEntity,
    pub change: i32,
}

pub struct ParryHookEvent {
    pub defender: EcsEntity,
    pub attacker: Option<EcsEntity>,
    pub source: AttackSource,
    pub poise_multiplier: f32,
}

pub struct RequestSiteInfoEvent {
    pub entity: EcsEntity,
    pub id: SiteId,
}

// Attempt to mine a block, turning it into an item
pub struct MineBlockEvent {
    pub entity: EcsEntity,
    pub pos: Vec3<i32>,
    pub tool: Option<comp::tool::ToolKind>,
}

pub struct TeleportToEvent {
    pub entity: EcsEntity,
    pub target: Uid,
    pub max_range: Option<f32>,
}

pub struct CreateSafezoneEvent {
    pub range: Option<f32>,
    pub pos: Pos,
}

pub struct SoundEvent {
    pub sound: Sound,
}

pub struct CreateSpriteEvent {
    pub pos: Vec3<i32>,
    pub sprite: SpriteKind,
    pub del_timeout: Option<(f32, f32)>,
}

pub struct TamePetEvent {
    pub pet_entity: EcsEntity,
    pub owner_entity: EcsEntity,
}

pub struct EntityAttackedHookEvent {
    pub entity: EcsEntity,
    pub attacker: Option<EcsEntity>,
}

pub struct ChangeAbilityEvent {
    pub entity: EcsEntity,
    pub slot: usize,
    pub auxiliary_key: comp::ability::AuxiliaryKey,
    pub new_ability: comp::ability::AuxiliaryAbility,
}

pub struct UpdateMapMarkerEvent {
    pub entity: EcsEntity,
    pub update: comp::MapMarkerChange,
}

pub struct MakeAdminEvent {
    pub entity: EcsEntity,
    pub admin: comp::Admin,
    pub uuid: Uuid,
}

pub struct DeleteCharacterEvent {
    pub entity: EcsEntity,
    pub requesting_player_uuid: String,
    pub character_id: CharacterId,
}

pub struct ChangeStanceEvent {
    pub entity: EcsEntity,
    pub stance: comp::Stance,
}

pub struct ChangeBodyEvent {
    pub entity: EcsEntity,
    pub new_body: comp::Body,
}

pub struct RemoveLightEmitterEvent {
    pub entity: EcsEntity,
}

pub struct TeleportToPositionEvent {
    pub entity: EcsEntity,
    pub position: Vec3<f32>,
}

pub struct StartTeleportingEvent {
    pub entity: EcsEntity,
    pub portal: EcsEntity,
}
pub struct ToggleSpriteLightEvent {
    pub entity: EcsEntity,
    pub pos: Vec3<i32>,
    pub enable: bool,
}
pub struct RequestPluginsEvent {
    pub entity: EcsEntity,
    pub plugins: Vec<PluginHash>,
}

pub struct CreateAuraEntityEvent {
    pub auras: comp::Auras,
    pub pos: Pos,
    pub creator_uid: Uid,
    pub duration: Option<Secs>,
}

pub struct RegrowHeadEvent {
    pub entity: EcsEntity,
}

pub struct EventBus<E> {
    queue: Mutex<VecDeque<E>>,
}

impl<E> Default for EventBus<E> {
    fn default() -> Self {
        Self {
            queue: Mutex::new(VecDeque::new()),
        }
    }
}

impl<E> EventBus<E> {
    pub fn emitter(&self) -> Emitter<E> {
        Emitter {
            bus: self,
            events: VecDeque::new(),
        }
    }

    pub fn emit_now(&self, event: E) { self.queue.lock().unwrap().push_back(event); }

    pub fn recv_all(&self) -> impl ExactSizeIterator<Item = E> {
        std::mem::take(self.queue.lock().unwrap().deref_mut()).into_iter()
    }

    pub fn recv_all_mut(&mut self) -> impl ExactSizeIterator<Item = E> {
        std::mem::take(self.queue.get_mut().unwrap()).into_iter()
    }
}

pub struct Emitter<'a, E> {
    bus: &'a EventBus<E>,
    pub events: VecDeque<E>,
}

impl<'a, E> Emitter<'a, E> {
    pub fn emit(&mut self, event: E) { self.events.push_back(event); }

    pub fn emit_many(&mut self, events: impl IntoIterator<Item = E>) { self.events.extend(events); }

    pub fn append(&mut self, other: &mut VecDeque<E>) { self.events.append(other) }

    // TODO: allow just emitting the whole vec of events at once? without copying
    pub fn append_vec(&mut self, vec: Vec<E>) { self.events.extend(vec) }
}

impl<'a, E> Drop for Emitter<'a, E> {
    fn drop(&mut self) {
        if !self.events.is_empty() {
            self.bus.queue.lock().unwrap().append(&mut self.events);
        }
    }
}

pub trait EmitExt<E> {
    fn emit(&mut self, event: E);
    fn emit_many(&mut self, events: impl IntoIterator<Item = E>);
}

pub fn register_event_busses(ecs: &mut World) {
    ecs.insert(EventBus::<ClientConnectedEvent>::default());
    ecs.insert(EventBus::<ClientDisconnectEvent>::default());
    ecs.insert(EventBus::<ClientDisconnectWithoutPersistenceEvent>::default());
    ecs.insert(EventBus::<ChatEvent>::default());
    ecs.insert(EventBus::<CommandEvent>::default());
    ecs.insert(EventBus::<CreateSpecialEntityEvent>::default());
    ecs.insert(EventBus::<CreateNpcEvent>::default());
    ecs.insert(EventBus::<CreateShipEvent>::default());
    ecs.insert(EventBus::<CreateItemDropEvent>::default());
    ecs.insert(EventBus::<CreateObjectEvent>::default());
    ecs.insert(EventBus::<ExplosionEvent>::default());
    ecs.insert(EventBus::<BonkEvent>::default());
    ecs.insert(EventBus::<HealthChangeEvent>::default());
    ecs.insert(EventBus::<PoiseChangeEvent>::default());
    ecs.insert(EventBus::<DeleteEvent>::default());
    ecs.insert(EventBus::<DestroyEvent>::default());
    ecs.insert(EventBus::<InventoryManipEvent>::default());
    ecs.insert(EventBus::<GroupManipEvent>::default());
    ecs.insert(EventBus::<RespawnEvent>::default());
    ecs.insert(EventBus::<ShootEvent>::default());
    ecs.insert(EventBus::<ShockwaveEvent>::default());
    ecs.insert(EventBus::<KnockbackEvent>::default());
    ecs.insert(EventBus::<LandOnGroundEvent>::default());
    ecs.insert(EventBus::<SetLanternEvent>::default());
    ecs.insert(EventBus::<NpcInteractEvent>::default());
    ecs.insert(EventBus::<InviteResponseEvent>::default());
    ecs.insert(EventBus::<InitiateInviteEvent>::default());
    ecs.insert(EventBus::<ProcessTradeActionEvent>::default());
    ecs.insert(EventBus::<MountEvent>::default());
    ecs.insert(EventBus::<MountVolumeEvent>::default());
    ecs.insert(EventBus::<UnmountEvent>::default());
    ecs.insert(EventBus::<SetPetStayEvent>::default());
    ecs.insert(EventBus::<PossessEvent>::default());
    ecs.insert(EventBus::<InitializeCharacterEvent>::default());
    ecs.insert(EventBus::<InitializeSpectatorEvent>::default());
    ecs.insert(EventBus::<UpdateCharacterDataEvent>::default());
    ecs.insert(EventBus::<ExitIngameEvent>::default());
    ecs.insert(EventBus::<AuraEvent>::default());
    ecs.insert(EventBus::<BuffEvent>::default());
    ecs.insert(EventBus::<EnergyChangeEvent>::default());
    ecs.insert(EventBus::<ComboChangeEvent>::default());
    ecs.insert(EventBus::<ParryHookEvent>::default());
    ecs.insert(EventBus::<RequestSiteInfoEvent>::default());
    ecs.insert(EventBus::<MineBlockEvent>::default());
    ecs.insert(EventBus::<TeleportToEvent>::default());
    ecs.insert(EventBus::<CreateSafezoneEvent>::default());
    ecs.insert(EventBus::<SoundEvent>::default());
    ecs.insert(EventBus::<CreateSpriteEvent>::default());
    ecs.insert(EventBus::<TamePetEvent>::default());
    ecs.insert(EventBus::<EntityAttackedHookEvent>::default());
    ecs.insert(EventBus::<ChangeAbilityEvent>::default());
    ecs.insert(EventBus::<UpdateMapMarkerEvent>::default());
    ecs.insert(EventBus::<MakeAdminEvent>::default());
    ecs.insert(EventBus::<DeleteCharacterEvent>::default());
    ecs.insert(EventBus::<ChangeStanceEvent>::default());
    ecs.insert(EventBus::<ChangeBodyEvent>::default());
    ecs.insert(EventBus::<RemoveLightEmitterEvent>::default());
    ecs.insert(EventBus::<TeleportToPositionEvent>::default());
    ecs.insert(EventBus::<StartTeleportingEvent>::default());
    ecs.insert(EventBus::<ToggleSpriteLightEvent>::default());
    ecs.insert(EventBus::<TransformEvent>::default());
    ecs.insert(EventBus::<RequestPluginsEvent>::default());
    ecs.insert(EventBus::<CreateAuraEntityEvent>::default());
    ecs.insert(EventBus::<RegrowHeadEvent>::default());
}

/// Define ecs read data for event busses. And a way to convert them all to
/// emitters.
///
/// # Example:
/// ```
/// mod some_mod_is_necessary_for_the_test {
///     use veloren_common::event_emitters;
///     pub struct Foo;
///     pub struct Bar;
///     pub struct Baz;
///     event_emitters!(
///       pub struct ReadEvents[EventEmitters] {
///           foo: Foo, bar: Bar, baz: Baz,
///       }
///     );
/// }
/// ```
#[macro_export]
macro_rules! event_emitters {
    ($($vis:vis struct $read_data:ident[$emitters:ident] { $($ev_ident:ident: $ty:ty),+ $(,)? })+) => {
        mod event_emitters {
            use super::*;
            use specs::shred;
            $(
            #[derive(specs::SystemData)]
            pub struct $read_data<'a> {
                $($ev_ident: Option<specs::Read<'a, $crate::event::EventBus<$ty>>>),+
            }

            impl<'a> $read_data<'a> {
                #[allow(unused)]
                pub fn get_emitters(&self) -> $emitters {
                    $emitters {
                        $($ev_ident: self.$ev_ident.as_ref().map(|e| e.emitter())),+
                    }
                }
            }

            pub struct $emitters<'a> {
                $($ev_ident: Option<$crate::event::Emitter<'a, $ty>>),+
            }

            impl<'a> $emitters<'a> {
                #[allow(unused)]
                pub fn append(&mut self, mut other: Self) {
                    $(
                        self.$ev_ident.as_mut().zip(other.$ev_ident).map(|(a, mut b)| a.append(&mut b.events));
                    )+
                }
            }

            $(
                impl<'a> $crate::event::EmitExt<$ty> for $emitters<'a> {
                    fn emit(&mut self, event: $ty) { self.$ev_ident.as_mut().map(|e| e.emit(event)); }
                    fn emit_many(&mut self, events: impl IntoIterator<Item = $ty>) { self.$ev_ident.as_mut().map(|e| e.emit_many(events)); }
                }
            )+
            )+
        }
        $(
            $vis use event_emitters::{$read_data, $emitters};
        )+
    }
}