veloren_rtsim/rule/
simulate_npcs.rs

1use crate::{
2    RtState, Rule, RuleError,
3    data::{Sentiment, npc::SimulationMode},
4    event::{EventCtx, OnHealthChange, OnHelped, OnMountVolume, OnTick},
5};
6use common::{
7    comp::{self, Body, agent::FlightMode},
8    mounting::{Volume, VolumePos},
9    rtsim::{Actor, NpcAction, NpcActivity},
10    terrain::{CoordinateConversions, TerrainChunkSize},
11    vol::RectVolSize,
12};
13use slotmap::SecondaryMap;
14use vek::{Clamp, Vec2};
15
16pub struct SimulateNpcs;
17
18impl Rule for SimulateNpcs {
19    fn start(rtstate: &mut RtState) -> Result<Self, RuleError> {
20        rtstate.bind(on_helped);
21        rtstate.bind(on_health_changed);
22        rtstate.bind(on_mount_volume);
23        rtstate.bind(on_tick);
24
25        Ok(Self)
26    }
27}
28
29fn on_mount_volume(ctx: EventCtx<SimulateNpcs, OnMountVolume>) {
30    let data = &mut *ctx.state.data_mut();
31
32    // TODO: Add actor to riders.
33    if let VolumePos {
34        kind: Volume::Entity(vehicle),
35        ..
36    } = ctx.event.pos
37        && let Some(link) = data.npcs.mounts.get_steerer_link(vehicle)
38        && let Actor::Npc(driver) = link.rider
39        && let Some(driver) = data.npcs.get_mut(driver)
40    {
41        driver.controller.actions.push(NpcAction::Say(
42            Some(ctx.event.actor),
43            comp::Content::localized("npc-speech-welcome-aboard"),
44        ))
45    }
46}
47
48fn on_health_changed(ctx: EventCtx<SimulateNpcs, OnHealthChange>) {
49    let data = &mut *ctx.state.data_mut();
50
51    if let Some(cause) = ctx.event.cause
52        && let Actor::Npc(npc) = ctx.event.actor
53        && let Some(npc) = data.npcs.get_mut(npc)
54    {
55        if ctx.event.change < 0.0 {
56            npc.sentiments
57                .toward_mut(cause)
58                .change_by(-0.1, Sentiment::ENEMY);
59        } else if ctx.event.change > 0.0 {
60            npc.sentiments
61                .toward_mut(cause)
62                .change_by(0.05, Sentiment::POSITIVE);
63        }
64    }
65}
66
67fn on_helped(ctx: EventCtx<SimulateNpcs, OnHelped>) {
68    let data = &mut *ctx.state.data_mut();
69
70    if let Some(saver) = ctx.event.saver
71        && let Actor::Npc(npc) = ctx.event.actor
72        && let Some(npc) = data.npcs.get_mut(npc)
73    {
74        npc.controller.actions.push(NpcAction::Say(
75            Some(ctx.event.actor),
76            comp::Content::localized("npc-speech-thank_you"),
77        ));
78        npc.sentiments
79            .toward_mut(saver)
80            .change_by(0.3, Sentiment::FRIEND);
81    }
82}
83
84fn on_tick(ctx: EventCtx<SimulateNpcs, OnTick>) {
85    let data = &mut *ctx.state.data_mut();
86
87    // Maintain links
88    let ids = data.npcs.mounts.ids().collect::<Vec<_>>();
89    let mut mount_activity = SecondaryMap::new();
90    for link_id in ids {
91        if let Some(link) = data.npcs.mounts.get(link_id) {
92            if let Some(mount) = data
93                .npcs
94                .npcs
95                .get(link.mount)
96                .filter(|mount| !mount.is_dead())
97            {
98                let wpos = mount.wpos;
99                if let Actor::Npc(rider) = link.rider {
100                    if let Some(rider) = data
101                        .npcs
102                        .npcs
103                        .get_mut(rider)
104                        .filter(|rider| !rider.is_dead())
105                    {
106                        rider.wpos = wpos;
107                        mount_activity.insert(link.mount, rider.controller.activity);
108                    } else {
109                        data.npcs.mounts.dismount(link.rider)
110                    }
111                }
112            } else {
113                data.npcs.mounts.remove_mount(link.mount)
114            }
115        }
116    }
117
118    for (npc_id, npc) in data.npcs.npcs.iter_mut().filter(|(_, npc)| !npc.is_dead()) {
119        if matches!(npc.mode, SimulationMode::Simulated) {
120            // Consume NPC actions
121            for action in std::mem::take(&mut npc.controller.actions) {
122                match action {
123                    NpcAction::Say(_, _) => {}, // Currently, just swallow interactions
124                    NpcAction::Attack(_) => {}, // TODO: Implement simulated combat
125                    NpcAction::Dialogue(_, _) => {},
126                }
127            }
128
129            let activity = if data.npcs.mounts.get_mount_link(npc_id).is_some() {
130                // We are riding, nothing to do.
131                continue;
132            } else if let Some(activity) = mount_activity.get(npc_id) {
133                *activity
134            } else {
135                npc.controller.activity
136            };
137
138            match activity {
139                // Move NPCs if they have a target destination
140                Some(NpcActivity::Goto(target, speed_factor)) => {
141                    let diff = target - npc.wpos;
142                    let dist2 = diff.magnitude_squared();
143
144                    if dist2 > 0.5f32.powi(2) {
145                        let offset = diff
146                            * (npc.body.max_speed_approx() * speed_factor * ctx.event.dt
147                                / dist2.sqrt())
148                            .min(1.0);
149                        let new_wpos = npc.wpos + offset;
150
151                        let is_valid = match npc.body {
152                            // Don't move water bound bodies outside of water.
153                            Body::Ship(comp::ship::Body::SailBoat | comp::ship::Body::Galleon)
154                            | Body::FishMedium(_)
155                            | Body::FishSmall(_) => {
156                                let chunk_pos = new_wpos.xy().as_().wpos_to_cpos();
157                                ctx.world
158                                    .sim()
159                                    .get(chunk_pos)
160                                    .is_none_or(|f| f.river.river_kind.is_some())
161                            },
162                            Body::Ship(comp::ship::Body::DefaultAirship) => false,
163                            _ => true,
164                        };
165
166                        if is_valid {
167                            npc.wpos = new_wpos;
168                        }
169
170                        npc.dir = (target.xy() - npc.wpos.xy())
171                            .try_normalized()
172                            .unwrap_or(npc.dir);
173                    }
174                },
175                // Move Flying NPCs like airships if they have a target destination
176                Some(NpcActivity::GotoFlying(target, speed_factor, height, dir, mode)) => {
177                    let diff = target - npc.wpos;
178                    let dist2 = diff.magnitude_squared();
179
180                    if dist2 > 0.5f32.powi(2) {
181                        match npc.body {
182                            Body::Ship(comp::ship::Body::DefaultAirship) => {
183                                // RTSim NPCs don't interract with terrain, and their position is
184                                // independent of ground level.
185                                // While movement is simulated, airships will happily stay at ground
186                                // level or fly through mountains.
187                                // The code at the end of this block "Make sure NPCs remain in a
188                                // valid location" just forces
189                                // airships to be at least above ground (on the ground actually).
190                                // The reason is that when docking, airships need to descend much
191                                // closer to the terrain
192                                // than when cruising between sites, so airships cannot be forced to
193                                // stay at a fixed height above
194                                // terrain (i.e. flying_height()). Instead, when mode is
195                                // FlightMode::FlyThrough, set the airship altitude directly to
196                                // terrain height + height (if Some)
197                                // or terrain height + default height (npc.body.flying_height()).
198                                // When mode is FlightMode::Braking, the airship is allowed to
199                                // descend below flying height
200                                // because it is near or at the dock. In this mode, if height is
201                                // Some, set the airship altitude to
202                                // the maximum of target.z or terrain height + height. If height is
203                                // None, set the airship altitude to
204                                // target.z. By forcing the airship altitude to be at a specific
205                                // value, when the airship is
206                                // suddenly in a loaded chunk it will not be below or at the ground
207                                // and will not get stuck.
208
209                                // Move in x,y
210                                let diffxy = target.xy() - npc.wpos.xy();
211                                let distxy2 = diffxy.magnitude_squared();
212                                if distxy2 > 0.5f32.powi(2) {
213                                    let offsetxy = diffxy
214                                        * (npc.body.max_speed_approx()
215                                            * speed_factor
216                                            * ctx.event.dt
217                                            / distxy2.sqrt());
218                                    npc.wpos.x += offsetxy.x;
219                                    npc.wpos.y += offsetxy.y;
220                                }
221                                // The diff is not computed for z like x,y. Rather, the altitude is
222                                // set directly so that when the
223                                // simulated ship is suddenly in a loaded chunk it will not be below
224                                // or at the ground level and risk getting stuck.
225                                let base_height =
226                                    if mode == FlightMode::FlyThrough || height.is_some() {
227                                        ctx.world.sim().get_surface_alt_approx(npc.wpos.xy().as_())
228                                    } else {
229                                        0.0
230                                    };
231                                let ship_z = match mode {
232                                    FlightMode::FlyThrough => {
233                                        base_height + height.unwrap_or(npc.body.flying_height())
234                                    },
235                                    FlightMode::Braking(_) => {
236                                        (base_height + height.unwrap_or(0.0)).max(target.z)
237                                    },
238                                };
239                                npc.wpos.z = ship_z;
240                            },
241                            _ => {
242                                let offset = diff
243                                    * (npc.body.max_speed_approx() * speed_factor * ctx.event.dt
244                                        / dist2.sqrt())
245                                    .min(1.0);
246                                let new_wpos = npc.wpos + offset;
247
248                                let is_valid = match npc.body {
249                                    // Don't move water bound bodies outside of water.
250                                    Body::Ship(
251                                        comp::ship::Body::SailBoat | comp::ship::Body::Galleon,
252                                    )
253                                    | Body::FishMedium(_)
254                                    | Body::FishSmall(_) => {
255                                        let chunk_pos = new_wpos.xy().as_().wpos_to_cpos();
256                                        ctx.world
257                                            .sim()
258                                            .get(chunk_pos)
259                                            .is_none_or(|f| f.river.river_kind.is_some())
260                                    },
261                                    _ => true,
262                                };
263
264                                if is_valid {
265                                    npc.wpos = new_wpos;
266                                }
267                            },
268                        }
269
270                        if let Some(dir_override) = dir {
271                            npc.dir = dir_override.xy().try_normalized().unwrap_or(npc.dir);
272                        } else {
273                            npc.dir = (target.xy() - npc.wpos.xy())
274                                .try_normalized()
275                                .unwrap_or(npc.dir);
276                        }
277                    }
278                },
279                Some(
280                    NpcActivity::Gather(_)
281                    | NpcActivity::HuntAnimals
282                    | NpcActivity::Dance(_)
283                    | NpcActivity::Cheer(_)
284                    | NpcActivity::Sit(..)
285                    | NpcActivity::Talk(..),
286                ) => {
287                    // TODO: Maybe they should walk around randomly
288                    // when gathering resources?
289                },
290                None => {},
291            }
292
293            // Make sure NPCs remain in a valid location
294            let clamped_wpos = npc.wpos.xy().clamped(
295                Vec2::zero(),
296                (ctx.world.sim().get_size() * TerrainChunkSize::RECT_SIZE).as_(),
297            );
298            match npc.body {
299                // Don't force air ships to be at flying_height, else they can't land at docks.
300                Body::Ship(comp::ship::Body::DefaultAirship | comp::ship::Body::AirBalloon) => {
301                    npc.wpos = clamped_wpos.with_z(
302                        ctx.world
303                            .sim()
304                            .get_surface_alt_approx(clamped_wpos.as_())
305                            .max(npc.wpos.z),
306                    );
307                },
308                _ => {
309                    npc.wpos = clamped_wpos.with_z(
310                        ctx.world.sim().get_surface_alt_approx(clamped_wpos.as_())
311                            + npc.body.flying_height(),
312                    );
313                },
314            }
315        }
316
317        // Move home if required
318        if let Some(new_home) = npc.controller.new_home.take() {
319            // Remove the NPC from their old home population
320            if let Some(old_home) = npc.home
321                && let Some(old_home) = data.sites.get_mut(old_home)
322            {
323                old_home.population.remove(&npc_id);
324            }
325            // Add the NPC to their new home population
326            if let Some(new_home) = new_home
327                && let Some(new_home) = data.sites.get_mut(new_home)
328            {
329                new_home.population.insert(npc_id);
330            }
331            npc.home = new_home;
332        }
333
334        // Create registered quests
335        for (id, quest) in core::mem::take(&mut npc.controller.quests_to_create) {
336            data.quests.create(id, quest);
337        }
338
339        // Set job status
340        npc.job = npc.controller.job.clone();
341    }
342}