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
use crate::{
    comp::{
        self,
        character_state::OutputEvents,
        inventory::loadout_builder::{self, LoadoutBuilder},
        object::Body::FieryTornado,
        Behavior, BehaviorCapability,
        Body::Object,
        CharacterState, Projectile, StateUpdate,
    },
    event::{CreateNpcEvent, LocalEvent, NpcBuilder},
    npc::NPC_NAMES,
    outcome::Outcome,
    skillset_builder::{self, SkillSetBuilder},
    states::{
        behavior::{CharacterBehavior, JoinData},
        utils::*,
    },
    terrain::Block,
    util::Dir,
    vol::ReadVol,
};
use rand::Rng;
use serde::{Deserialize, Serialize};
use std::{f32::consts::PI, ops::Sub, time::Duration};
use vek::*;

/// Separated out to condense update portions of character state
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StaticData {
    /// How long the state builds up for
    pub buildup_duration: Duration,
    /// How long the state is casting for
    pub cast_duration: Duration,
    /// How long the state recovers for
    pub recover_duration: Duration,
    /// How many creatures the state should summon
    pub summon_amount: u32,
    /// Range of the summons relative to the summoner
    pub summon_distance: (f32, f32),
    /// Information about the summoned creature
    pub summon_info: SummonInfo,
    /// Miscellaneous information about the ability
    pub ability_info: AbilityInfo,
    /// Duration of the summoned entity
    pub duration: Option<Duration>,
}

#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Data {
    /// Struct containing data that does not change over the course of the
    /// character state
    pub static_data: StaticData,
    /// How many creatures have been summoned
    pub summon_count: u32,
    /// Timer for each stage
    pub timer: Duration,
    /// What section the character stage is in
    pub stage_section: StageSection,
}

impl CharacterBehavior for Data {
    fn behavior(&self, data: &JoinData, output_events: &mut OutputEvents) -> StateUpdate {
        let mut update = StateUpdate::from(data);

        match self.stage_section {
            StageSection::Buildup => {
                if self.timer < self.static_data.buildup_duration {
                    // Build up
                    update.character = CharacterState::BasicSummon(Data {
                        timer: tick_attack_or_default(data, self.timer, None),
                        ..*self
                    });
                } else {
                    // Transitions to recover section of stage
                    update.character = CharacterState::BasicSummon(Data {
                        timer: Duration::default(),
                        stage_section: StageSection::Action,
                        ..*self
                    });
                }
            },
            StageSection::Action => {
                if self.timer < self.static_data.cast_duration
                    || self.summon_count < self.static_data.summon_amount
                {
                    if self.timer
                        > self.static_data.cast_duration * self.summon_count
                            / self.static_data.summon_amount
                    {
                        let SummonInfo {
                            body,
                            loadout_config,
                            skillset_config,
                            ..
                        } = self.static_data.summon_info;

                        let loadout = {
                            let loadout_builder =
                                LoadoutBuilder::empty().with_default_maintool(&body);
                            // If preset is none, use default equipment
                            if let Some(preset) = loadout_config {
                                loadout_builder.with_preset(preset).build()
                            } else {
                                loadout_builder.with_default_equipment(&body).build()
                            }
                        };

                        let skill_set = {
                            let skillset_builder = SkillSetBuilder::default();
                            if let Some(preset) = skillset_config {
                                skillset_builder.with_preset(preset).build()
                            } else {
                                skillset_builder.build()
                            }
                        };

                        let stats = comp::Stats::new(
                            self.static_data
                                .summon_info
                                .use_npc_name
                                .then(|| {
                                    let all_names = NPC_NAMES.read();
                                    all_names
                                        .get_species_meta(&self.static_data.summon_info.body)
                                        .map(|meta| meta.generic.clone())
                                })
                                .flatten()
                                .unwrap_or_else(|| "Summon".to_string()),
                            body,
                        );

                        let health = self
                            .static_data
                            .summon_info
                            .has_health
                            .then(|| comp::Health::new(body));

                        // Ray cast to check where summon should happen
                        let summon_frac =
                            self.summon_count as f32 / self.static_data.summon_amount as f32;

                        let length = rand::thread_rng().gen_range(
                            self.static_data.summon_distance.0..=self.static_data.summon_distance.1,
                        );
                        let extra_height =
                            if self.static_data.summon_info.body == Object(FieryTornado) {
                                15.0
                            } else {
                                0.0
                            };
                        let position =
                            Vec3::new(data.pos.0.x, data.pos.0.y, data.pos.0.z + extra_height);
                        // Summon in a clockwise fashion
                        let ray_vector = Vec3::new(
                            (summon_frac * 2.0 * PI).sin() * length,
                            (summon_frac * 2.0 * PI).cos() * length,
                            0.0,
                        );

                        // Check for collision on the xy plane, subtract 1 to get point before block
                        let obstacle_xy = data
                            .terrain
                            .ray(position, position + length * ray_vector)
                            .until(Block::is_solid)
                            .cast()
                            .0
                            .sub(1.0);

                        let collision_vector = Vec3::new(
                            position.x + (summon_frac * 2.0 * PI).sin() * obstacle_xy,
                            position.y + (summon_frac * 2.0 * PI).cos() * obstacle_xy,
                            position.z + data.body.eye_height(data.scale.map_or(1.0, |s| s.0)),
                        );

                        // Check for collision in z up to 50 blocks
                        let obstacle_z = data
                            .terrain
                            .ray(collision_vector, collision_vector - Vec3::unit_z() * 50.0)
                            .until(Block::is_solid)
                            .cast()
                            .0;

                        // If a duration is specified, create a projectile component for the npc
                        let projectile = self.static_data.duration.map(|duration| Projectile {
                            hit_solid: Vec::new(),
                            hit_entity: Vec::new(),
                            time_left: duration,
                            owner: Some(*data.uid),
                            ignore_group: true,
                            is_sticky: false,
                            is_point: false,
                        });

                        let mut rng = rand::thread_rng();
                        // Send server event to create npc
                        output_events.emit_server(CreateNpcEvent {
                            pos: comp::Pos(collision_vector - Vec3::unit_z() * obstacle_z),
                            ori: comp::Ori::from(Dir::random_2d(&mut rng)),
                            npc: NpcBuilder::new(stats, body, comp::Alignment::Owned(*data.uid))
                                .with_skill_set(skill_set)
                                .with_health(health)
                                .with_inventory(comp::Inventory::with_loadout(loadout, body))
                                .with_agent(
                                    comp::Agent::from_body(&body)
                                        .with_behavior(Behavior::from(BehaviorCapability::SPEAK))
                                        .with_no_flee_if(true),
                                )
                                .with_scale(
                                    self.static_data
                                        .summon_info
                                        .scale
                                        .unwrap_or(comp::Scale(1.0)),
                                )
                                .with_projectile(projectile),
                            rider: None,
                        });

                        // Send local event used for frontend shenanigans
                        output_events.emit_local(LocalEvent::CreateOutcome(
                            Outcome::SummonedCreature {
                                pos: data.pos.0,
                                body,
                            },
                        ));

                        update.character = CharacterState::BasicSummon(Data {
                            timer: tick_attack_or_default(data, self.timer, None),
                            summon_count: self.summon_count + 1,
                            ..*self
                        });
                    } else {
                        // Cast
                        update.character = CharacterState::BasicSummon(Data {
                            timer: tick_attack_or_default(data, self.timer, None),
                            ..*self
                        });
                    }
                } else {
                    // Transitions to recover section of stage
                    update.character = CharacterState::BasicSummon(Data {
                        timer: Duration::default(),
                        stage_section: StageSection::Recover,
                        ..*self
                    });
                }
            },
            StageSection::Recover => {
                if self.timer < self.static_data.recover_duration {
                    // Recovery
                    update.character = CharacterState::BasicSummon(Data {
                        timer: tick_attack_or_default(
                            data,
                            self.timer,
                            Some(data.stats.recovery_speed_modifier),
                        ),
                        ..*self
                    });
                } else {
                    // Done
                    end_ability(data, &mut update);
                }
            },
            _ => {
                // If it somehow ends up in an incorrect stage section
                end_ability(data, &mut update);
            },
        }

        update
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SummonInfo {
    body: comp::Body,
    scale: Option<comp::Scale>,
    has_health: bool,
    #[serde(default)]
    use_npc_name: bool,
    // TODO: use assets for specifying skills and loadout?
    loadout_config: Option<loadout_builder::Preset>,
    skillset_config: Option<skillset_builder::Preset>,
}