1use crate::{
2 comp::{self, pet::is_mountable, ship::figuredata::VOXEL_COLLIDER_MANIFEST},
3 link::{Is, Link, LinkHandle, Role},
4 terrain::{Block, TerrainGrid},
5 tether,
6 uid::{IdMaps, Uid},
7 vol::ReadVol,
8};
9use hashbrown::HashMap;
10use serde::{Deserialize, Serialize};
11use specs::{
12 Component, Entities, Entity, FlaggedStorage, Read, ReadExpect, ReadStorage, Write,
13 WriteStorage, storage::GenericWriteStorage,
14};
15use vek::*;
16
17#[derive(Serialize, Deserialize, Debug)]
18pub struct Rider;
19
20impl Role for Rider {
21 type Link = Mounting;
22}
23
24#[derive(Serialize, Deserialize, Debug)]
25pub struct Mount;
26
27impl Role for Mount {
28 type Link = Mounting;
29}
30
31#[derive(Serialize, Deserialize, Debug)]
32pub struct Mounting {
33 pub mount: Uid,
34 pub rider: Uid,
35}
36
37#[derive(Debug)]
38pub enum MountingError {
39 NoSuchEntity,
40 NotMountable,
41}
42
43impl Link for Mounting {
44 type CreateData<'a> = (
45 Read<'a, IdMaps>,
46 Entities<'a>,
47 WriteStorage<'a, Is<Mount>>,
48 WriteStorage<'a, Is<Rider>>,
49 ReadStorage<'a, Is<VolumeRider>>,
50 ReadStorage<'a, Is<tether::Follower>>,
51 ReadStorage<'a, comp::Health>,
52 ReadStorage<'a, comp::CharacterState>,
53 );
54 type DeleteData<'a> = (
55 Read<'a, IdMaps>,
56 WriteStorage<'a, Is<Mount>>,
57 WriteStorage<'a, Is<Rider>>,
58 WriteStorage<'a, comp::Pos>,
59 WriteStorage<'a, comp::ForceUpdate>,
60 ReadExpect<'a, TerrainGrid>,
61 );
62 type Error = MountingError;
63 type PersistData<'a> = (
64 Read<'a, IdMaps>,
65 Entities<'a>,
66 ReadStorage<'a, comp::Health>,
67 ReadStorage<'a, comp::Body>,
68 ReadStorage<'a, comp::Mass>,
69 ReadStorage<'a, Is<Mount>>,
70 ReadStorage<'a, Is<Rider>>,
71 ReadStorage<'a, comp::CharacterState>,
72 );
73
74 fn create(
75 this: &LinkHandle<Self>,
76 (
77 id_maps,
78 entities,
79 is_mounts,
80 is_riders,
81 is_volume_rider,
82 is_followers,
83 healths,
84 character_states,
85 ): &mut Self::CreateData<'_>,
86 ) -> Result<(), Self::Error> {
87 let entity = |uid: Uid| id_maps.uid_entity(uid);
88 if this.mount == this.rider {
89 Err(MountingError::NotMountable)
91 } else if let Some((mount, rider)) = entity(this.mount).zip(entity(this.rider)) {
92 let is_alive_and_well = |entity| {
93 entities.is_alive(entity)
94 && !comp::is_downed_or_dead(healths.get(entity), character_states.get(entity))
95 };
96
97 if !is_mounts.contains(mount)
100 && !is_riders.contains(rider)
101 && !is_followers.contains(rider)
102 && (!is_mounts.contains(rider) || !is_riders.contains(mount))
104 && !is_volume_rider.contains(rider)
105 && is_alive_and_well(rider)
107 && is_alive_and_well(rider)
108 {
109 let _ = is_mounts.insert(mount, this.make_role());
110 let _ = is_riders.insert(rider, this.make_role());
111 Ok(())
112 } else {
113 Err(MountingError::NotMountable)
114 }
115 } else {
116 Err(MountingError::NoSuchEntity)
117 }
118 }
119
120 fn persist(
121 this: &LinkHandle<Self>,
122 (id_maps, entities, healths, bodies, masses, is_mounts, is_riders, character_states): &mut Self::PersistData<'_>,
123 ) -> bool {
124 let entity = |uid: Uid| id_maps.uid_entity(uid);
125
126 if let Some((mount, rider)) = entity(this.mount).zip(entity(this.rider)) {
127 let is_alive_and_well = |entity| {
128 entities.is_alive(entity)
129 && !comp::is_downed_or_dead(healths.get(entity), character_states.get(entity))
130 };
131
132 let is_in_ridable_state = character_states
133 .get(mount)
134 .is_some_and(|cs| !matches!(cs, comp::CharacterState::Roll(_)));
135
136 is_alive_and_well(mount)
138 && is_alive_and_well(rider)
139 && is_mounts.get(mount).is_some()
140 && is_riders.get(rider).is_some()
141 && bodies.get(mount).zip(masses.get(mount)).is_some_and(
142 |(mount_body, mount_mass)| {
143 is_mountable(mount_body, mount_mass, bodies.get(rider), masses.get(rider))
144 },
145 )
146 && is_in_ridable_state
147 } else {
148 false
149 }
150 }
151
152 fn delete(
153 this: &LinkHandle<Self>,
154 (id_maps, is_mounts, is_riders, positions, force_update, terrain): &mut Self::DeleteData<
155 '_,
156 >,
157 ) {
158 let entity = |uid: Uid| id_maps.uid_entity(uid);
159
160 let mount = entity(this.mount);
161 let rider = entity(this.rider);
162
163 mount.map(|mount| is_mounts.remove(mount));
165 rider.map(|rider| is_riders.remove(rider));
166
167 let safe_pos = rider
169 .and_then(|rider| positions.get(rider).copied())
170 .filter(|rider_pos| terrain.is_space(rider_pos.0.map(|e| e.floor() as i32)))
171 .or_else(|| {
172 mount
173 .and_then(|mount| positions.get(mount).copied())
174 .filter(|mount_pos| {
175 terrain.is_space(
176 (mount_pos.0 + Vec3::unit_z() * 0.1).map(|e| e.floor() as i32),
177 )
178 })
179 });
180 rider
181 .and_then(|rider| Some(rider).zip(positions.get_mut(rider)))
182 .map(|(rider, pos)| {
183 let old_pos = pos.0.map(|e| e.floor() as i32);
184 pos.0 = safe_pos
185 .map(|p| p.0.map(|e| e.floor()))
186 .unwrap_or_else(|| terrain.find_ground(old_pos).map(|e| e as f32))
187 + Vec3::new(0.5, 0.5, 0.0);
188 if let Some(force_update) = force_update.get_mut(rider) {
189 force_update.update();
190 }
191 });
192 }
193}
194
195#[derive(Serialize, Deserialize, Debug)]
196pub struct VolumeRider;
197
198impl Role for VolumeRider {
199 type Link = VolumeMounting;
200}
201
202#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug, Hash)]
203pub enum Volume<E> {
204 Terrain,
205 Entity(E),
206}
207
208#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Debug, Hash)]
209pub struct VolumePos<E = Uid> {
210 pub kind: Volume<E>,
211 pub pos: Vec3<i32>,
212}
213
214impl<E> VolumePos<E> {
215 pub fn terrain(block_pos: Vec3<i32>) -> Self {
216 Self {
217 kind: Volume::Terrain,
218 pos: block_pos,
219 }
220 }
221
222 pub fn entity(block_pos: Vec3<i32>, uid: E) -> Self {
223 Self {
224 kind: Volume::Entity(uid),
225 pos: block_pos,
226 }
227 }
228
229 pub fn try_map_entity<U>(self, f: impl FnOnce(E) -> Option<U>) -> Option<VolumePos<U>> {
230 Some(VolumePos {
231 pos: self.pos,
232 kind: match self.kind {
233 Volume::Terrain => Volume::Terrain,
234 Volume::Entity(e) => Volume::Entity(f(e)?),
235 },
236 })
237 }
238
239 pub fn is_entity(&self) -> bool { matches!(self.kind, Volume::Entity(_)) }
240}
241
242impl VolumePos {
243 pub fn get_block_and_transform(
248 &self,
249 terrain: &TerrainGrid,
250 id_maps: &IdMaps,
251 mut read_pos_and_ori: impl FnMut(Entity) -> Option<(comp::Pos, comp::Ori)>,
252 colliders: &ReadStorage<comp::Collider>,
253 ) -> Option<(Mat4<f32>, comp::Ori, Block)> {
254 match self.kind {
255 Volume::Terrain => Some((
256 Mat4::translation_3d(self.pos.as_()),
257 comp::Ori::default(),
258 *terrain.get(self.pos).ok()?,
259 )),
260 Volume::Entity(uid) => id_maps.uid_entity(uid).and_then(|entity| {
261 let collider = colliders.get(entity)?;
262 let (pos, ori) = read_pos_and_ori(entity)?;
263
264 let voxel_colliders_manifest = VOXEL_COLLIDER_MANIFEST.read();
265 let voxel_collider = collider.get_vol(&voxel_colliders_manifest)?;
266
267 let block = *voxel_collider.volume().get(self.pos).ok()?;
268
269 let local_translation = voxel_collider.translation + self.pos.as_();
270
271 let trans = Mat4::from(ori.to_quat()).translated_3d(pos.0)
272 * Mat4::<f32>::translation_3d(local_translation);
273
274 Some((trans, ori, block))
275 }),
276 }
277 }
278
279 pub fn get_block(
281 &self,
282 terrain: &TerrainGrid,
283 id_maps: &IdMaps,
284 colliders: &ReadStorage<comp::Collider>,
285 ) -> Option<Block> {
286 match self.kind {
287 Volume::Terrain => Some(*terrain.get(self.pos).ok()?),
288 Volume::Entity(uid) => id_maps.uid_entity(uid).and_then(|entity| {
289 let collider = colliders.get(entity)?;
290
291 let voxel_colliders_manifest = VOXEL_COLLIDER_MANIFEST.read();
292 let voxel_collider = collider.get_vol(&voxel_colliders_manifest)?;
293
294 let block = *voxel_collider.volume().get(self.pos).ok()?;
295
296 Some(block)
297 }),
298 }
299 }
300}
301
302#[derive(Default, Clone, Serialize, Deserialize, Debug)]
303pub struct VolumeRiders {
304 riders: HashMap<Vec3<i32>, LinkHandle<VolumeMounting>>,
305}
306
307impl VolumeRiders {
308 pub fn clear(&mut self) -> bool {
309 let res = !self.riders.is_empty();
310 self.riders.clear();
311 res
312 }
313
314 pub fn iter_riders(&self) -> impl Iterator<Item = Uid> + '_ {
315 self.riders.values().map(|link| link.rider)
316 }
317}
318
319impl Component for VolumeRiders {
320 type Storage = FlaggedStorage<Self>;
321}
322
323#[derive(Serialize, Deserialize, Debug)]
324pub struct VolumeMounting {
325 pub pos: VolumePos,
326 pub block: Block,
327 pub rider: Uid,
328}
329
330impl VolumeMounting {
331 pub fn is_steering_entity(&self) -> bool {
332 matches!(self.pos.kind, Volume::Entity(..)) && self.block.is_controller()
333 }
334}
335
336impl Link for VolumeMounting {
337 type CreateData<'a> = (
338 Entities<'a>,
339 Write<'a, VolumeRiders>,
340 WriteStorage<'a, VolumeRiders>,
341 WriteStorage<'a, Is<VolumeRider>>,
342 ReadStorage<'a, Is<Rider>>,
343 ReadExpect<'a, TerrainGrid>,
344 Read<'a, IdMaps>,
345 ReadStorage<'a, comp::Collider>,
346 ReadStorage<'a, comp::Health>,
347 ReadStorage<'a, comp::CharacterState>,
348 );
349 type DeleteData<'a> = (
350 Write<'a, VolumeRiders>,
351 WriteStorage<'a, VolumeRiders>,
352 WriteStorage<'a, Is<VolumeRider>>,
353 Read<'a, IdMaps>,
354 );
355 type Error = MountingError;
356 type PersistData<'a> = (
357 Entities<'a>,
358 ReadStorage<'a, comp::Health>,
359 Read<'a, VolumeRiders>,
360 ReadStorage<'a, VolumeRiders>,
361 ReadStorage<'a, Is<VolumeRider>>,
362 ReadExpect<'a, TerrainGrid>,
363 Read<'a, IdMaps>,
364 ReadStorage<'a, comp::Collider>,
365 ReadStorage<'a, comp::CharacterState>,
366 );
367
368 fn create(
369 this: &LinkHandle<Self>,
370 (
371 entities,
372 terrain_riders,
373 volume_riders,
374 is_volume_riders,
375 is_riders,
376 terrain_grid,
377 id_maps,
378 colliders,
379 healths,
380 character_states,
381 ): &mut Self::CreateData<'_>,
382 ) -> Result<(), Self::Error> {
383 let entity = |uid: Uid| id_maps.uid_entity(uid);
384 let is_alive_and_well = |entity| {
385 entities.is_alive(entity)
386 && !comp::is_downed_or_dead(healths.get(entity), character_states.get(entity))
387 };
388
389 let riders = match this.pos.kind {
390 Volume::Terrain => &mut *terrain_riders,
391 Volume::Entity(uid) => entity(uid)
392 .filter(|entity| is_alive_and_well(*entity))
393 .and_then(|entity| volume_riders.get_mut_or_default(entity))
394 .ok_or(MountingError::NoSuchEntity)?,
395 };
396 let rider = entity(this.rider).ok_or(MountingError::NoSuchEntity)?;
397
398 if !riders.riders.contains_key(&this.pos.pos)
399 && !is_volume_riders.contains(rider)
400 && !is_volume_riders.contains(rider)
401 && !is_riders.contains(rider)
402 && is_alive_and_well(rider)
403 {
404 let block = this
405 .pos
406 .get_block(terrain_grid, id_maps, colliders)
407 .ok_or(MountingError::NoSuchEntity)?;
408
409 if block == this.block {
410 let _ = is_volume_riders.insert(rider, this.make_role());
411 riders.riders.insert(this.pos.pos, this.clone());
412 Ok(())
413 } else {
414 Err(MountingError::NotMountable)
415 }
416 } else {
417 Err(MountingError::NotMountable)
418 }
419 }
420
421 fn persist(
422 this: &LinkHandle<Self>,
423 (
424 entities,
425 healths,
426 terrain_riders,
427 volume_riders,
428 is_volume_riders,
429 terrain_grid,
430 id_maps,
431 colliders,
432 character_states,
433 ): &mut Self::PersistData<'_>,
434 ) -> bool {
435 let entity = |uid: Uid| id_maps.uid_entity(uid);
436 let is_alive_and_well = |entity| {
437 entities.is_alive(entity)
438 && !comp::is_downed_or_dead(healths.get(entity), character_states.get(entity))
439 };
440
441 let riders = match this.pos.kind {
442 Volume::Terrain => &*terrain_riders,
443 Volume::Entity(uid) => {
444 let Some(riders) = entity(uid)
445 .filter(|entity| is_alive_and_well(*entity))
446 .and_then(|entity| volume_riders.get(entity))
447 else {
448 return false;
449 };
450 riders
451 },
452 };
453
454 let rider_exists = entity(this.rider)
455 .is_some_and(|rider| is_volume_riders.contains(rider) && is_alive_and_well(rider));
456 let mount_spot_exists = riders.riders.contains_key(&this.pos.pos);
457
458 let block_exists = this
459 .pos
460 .get_block(terrain_grid, id_maps, colliders)
461 .is_some_and(|block| block == this.block);
462
463 rider_exists && mount_spot_exists && block_exists
464 }
465
466 fn delete(
467 this: &LinkHandle<Self>,
468 (terrain_riders, volume_riders, is_rider, id_maps): &mut Self::DeleteData<'_>,
469 ) {
470 let entity = |uid: Uid| id_maps.uid_entity(uid);
471
472 let riders = match this.pos.kind {
473 Volume::Terrain => Some(&mut **terrain_riders),
474 Volume::Entity(uid) => {
475 entity(uid).and_then(|entity| volume_riders.get_mut_or_default(entity))
476 },
477 };
478
479 if let Some(riders) = riders {
480 riders.riders.remove(&this.pos.pos);
481 }
482
483 if let Some(entity) = entity(this.rider) {
484 is_rider.remove(entity);
485 }
486 }
487}