Skip to main content

veloren_voxygen/session/
target.rs

1use specs::{Join, LendJoin, WorldExt};
2use vek::*;
3
4use client::{self, Client};
5use common::{
6    comp::{self, CapsulePrism, tool::ToolKind},
7    consts::{MAX_INTERACT_RANGE, MAX_PICKUP_RANGE},
8    link::Is,
9    mounting::{Mount, Rider},
10    uid::Uid,
11    util::{
12        find_dist::{Cylinder, FindDist},
13        lines::closest_points_3d,
14    },
15    vol::ReadVol,
16};
17use common_base::span;
18
19#[derive(Clone, Copy, Debug)]
20pub struct Target<T> {
21    pub kind: T,
22    pub position: Vec3<f32>,
23}
24
25#[derive(Clone, Copy, Debug)]
26pub struct Build(pub Vec3<f32>);
27
28#[derive(Clone, Copy, Debug)]
29pub struct Collectable;
30
31#[derive(Clone, Copy, Debug)]
32pub struct Entity(pub specs::Entity);
33
34#[derive(Clone, Copy, Debug)]
35pub struct Mine;
36
37#[derive(Clone, Copy, Debug)]
38// line of sight (if not bocked by entity). Not build/mine mode dependent.
39pub struct Terrain;
40
41impl<T> Target<T> {
42    pub fn position_int(self) -> Vec3<i32> { self.position.map(|p| p.floor() as i32) }
43}
44
45/// Max distance an entity can be "targeted"
46pub const MAX_TARGET_RANGE: f32 = 300.0;
47
48/// Calculate what the cursor is pointing at within the 3d scene
49pub(super) fn targets_under_cursor(
50    client: &Client,
51    cam_pos: Vec3<f32>,
52    cam_dir: Vec3<f32>,
53    can_build: bool,
54    active_mine_tool: Option<ToolKind>,
55    viewpoint_entity: specs::Entity,
56) -> (
57    Option<Target<Build>>,
58    Option<Target<Collectable>>,
59    Option<Target<Entity>>,
60    Option<Target<Mine>>,
61    Option<Target<Terrain>>,
62) {
63    span!(_guard, "targets_under_cursor");
64    // Choose a spot above the player's head for item distance checks
65    let player_entity = client.entity();
66    let ecs = client.state().ecs();
67    let positions = ecs.read_storage::<comp::Pos>();
68    let player_pos = match positions.get(player_entity) {
69        Some(pos) => pos.0,
70        None => cam_pos, // Should never happen, but a safe fallback
71    };
72    let scales = ecs.read_storage();
73    let colliders = ecs.read_storage();
74    let char_states = ecs.read_storage::<comp::CharacterState>();
75    let player_char_state = char_states.get(player_entity);
76    let player_scale = scales.get(player_entity).copied();
77    // Get the player's cylinder
78    let player_cylinder = Cylinder::from_components(
79        player_pos,
80        player_scale,
81        colliders.get(player_entity),
82        player_char_state,
83    );
84    let eye_height = ecs
85        .read_storage::<comp::Body>()
86        .get(player_entity)
87        .map(|b| b.eye_height(player_scale.map_or(1.0, |s| s.0)))
88        .unwrap_or(0.0);
89    let eye_pos = player_pos + Vec3::unit_z() * eye_height;
90    let terrain = client.state().terrain();
91
92    // The maximum distance we might need to go, plus a safe threshold
93    const MAX_RAY_DIST: f32 = MAX_TARGET_RANGE
94        .max(MAX_PICKUP_RANGE)
95        .max(MAX_INTERACT_RANGE)
96        + 1.0;
97    let ray = terrain
98        .ray(cam_pos, cam_pos + cam_dir * MAX_RAY_DIST)
99        .max_iter(500);
100
101    let break_tgt_pos = |dist: f32| (cam_pos + cam_dir * (dist + 0.01)).map(|e| e.floor() + 0.5);
102    let place_tgt_pos = |dist: f32| (cam_pos + cam_dir * (dist - 0.01)).map(|e| e.floor() + 0.5);
103
104    let collect_cast = Some(ray.until(|b| b.is_solid() || b.is_directly_collectible()).cast())
105        .filter(|(_, b)| matches!(b, Ok(Some(b)) if b.is_directly_collectible()))
106        // Collection is limited by the player's actual position
107        .filter(|(d, _)| player_pos.distance(break_tgt_pos(*d)) < MAX_INTERACT_RANGE);
108    let mine_cast = Some(ray.until(|b| b.is_solid() || b.mine_tool().is_some()).cast())
109        // Mining is limited by the target block being mineable with the active mining tool...
110        .filter(|(_, b)| matches!(b, Ok(Some(b)) if b.mine_tool().zip(active_mine_tool).map_or(false, |(a, b)| a == b)))
111        // ...and by the distance to the player's eye position
112        .filter(|(d, _)| eye_pos.distance(break_tgt_pos(*d)) < MAX_PICKUP_RANGE);
113    let build_cast = Some(ray.until(|b| b.is_solid()).cast())
114        // Building is limited by the maximum target distance
115        .filter(|(d, _)| *d < MAX_TARGET_RANGE);
116    // Visual obstacles are limited by filled blocks
117    let obstacle_cast =
118        Some(ray.until(|b| b.is_filled()).cast()).filter(|(d, _)| *d < MAX_TARGET_RANGE);
119
120    // The maximum distance at which entities can be targetted is based on the
121    // distance to the nearest terrain obstacle being looked at
122    let max_target_dist = obstacle_cast.map_or(MAX_TARGET_RANGE, |(d, _)| d);
123
124    let uids = ecs.read_storage::<Uid>();
125
126    // Need to raycast by distance to cam
127    // But also filter out by distance to the player (but this only needs to be done
128    // on final result)
129    let mut nearby = (
130        &ecs.entities(),
131        &positions,
132        scales.maybe(),
133        &ecs.read_storage::<comp::Body>(),
134        ecs.read_storage::<comp::PickupItem>().maybe(),
135        !&ecs.read_storage::<Is<Mount>>(),
136        ecs.read_storage::<Is<Rider>>().maybe(),
137    )
138        .join()
139        .filter(|(e, _, _, _, _, _, _)| *e != viewpoint_entity)
140        .filter_map(|(e, p, s, b, i, _, is_rider)| {
141            const RADIUS_SCALE: f32 = 3.0;
142            // TODO: use collider radius instead of body radius?
143            let radius = s.map_or(1.0, |s| s.0) * (b.dimensions() * Vec3::new(1.0, 1.0, 0.5)).reduce_partial_max() * RADIUS_SCALE;
144            // Move position up from the feet
145            let pos = Vec3::new(p.0.x, p.0.y, p.0.z + radius);
146            // Distance squared from camera to the entity
147            let dist_sqr = pos.distance_squared(cam_pos);
148            // We only care about interacting with entities that contain items,
149            // or are not inanimate (to trade with), and are not riding the player.
150            let not_riding_player = is_rider.is_none_or(|is_rider| Some(&is_rider.mount) != uids.get(viewpoint_entity));
151            if (i.is_some() || !matches!(b, comp::Body::Object(_))) && not_riding_player {
152                Some((e, pos, radius, dist_sqr))
153            } else {
154                None
155            }
156        })
157        // Roughly filter out entities farther than ray distance
158        .filter(|(_, _, r, d_sqr)| *d_sqr <= max_target_dist.powi(2) + 2.0 * max_target_dist * r + r.powi(2))
159        // Ignore entities intersecting the camera
160        .filter(|(_, _, r, d_sqr)| *d_sqr > r.powi(2))
161        // Substract sphere radius from distance to the camera
162        .map(|(e, p, r, d_sqr)| (e, p, r, d_sqr.sqrt() - r))
163        .collect::<Vec<_>>();
164    // Sort by distance
165    nearby.sort_unstable_by(|a, b| a.3.partial_cmp(&b.3).unwrap());
166
167    let seg_ray = LineSegment3 {
168        start: cam_pos,
169        end: cam_pos + cam_dir * max_target_dist,
170    };
171    // TODO: fuzzy borders
172    let entity_target = nearby
173        .iter()
174        .map(|(e, p, r, _)| (e, *p, r))
175        // Find first one that intersects the ray segment, allow for entities nearby to the camera ray when wielding a weapon (as some abilities target an entity)
176        .find(|(_, p, r)| {
177            if player_char_state.is_some_and(|cs| cs.is_wield()) {
178                seg_ray.projected_point(*p).distance_squared(*p) < (*r + cam_pos.distance(*p) / 10.0).powi(2)
179            } else {
180                seg_ray.projected_point(*p).distance_squared(*p) < r.powi(2)
181            }
182        })
183        .and_then(|(e, p, _)| {
184            // Get the entity's cylinder
185            let target_cylinder = Cylinder::from_components(
186                p,
187                scales.get(*e).copied(),
188                colliders.get(*e),
189                char_states.get(*e),
190            );
191
192            if player_cylinder.min_distance(target_cylinder) < MAX_TARGET_RANGE {
193                Some(Target {
194                    kind: Entity(*e),
195                    position: p,
196                })
197            } else { None }
198        });
199
200    let terrain_target = obstacle_cast.map(|(d, _)| Target {
201        kind: Terrain,
202        position: break_tgt_pos(d),
203    });
204
205    let build_target = if let (true, Some((d, _))) = (can_build, build_cast) {
206        Some(Target {
207            kind: Build(place_tgt_pos(d)),
208            position: break_tgt_pos(d),
209        })
210    } else {
211        None
212    };
213
214    let collect_target = collect_cast.map(|(d, _)| Target {
215        kind: Collectable,
216        position: break_tgt_pos(d),
217    });
218
219    let mine_target = mine_cast.map(|(d, _)| Target {
220        kind: Mine,
221        position: break_tgt_pos(d),
222    });
223
224    // Return multiple possible targets
225    // GameInput events determine which target to use.
226    (
227        build_target,
228        collect_target,
229        entity_target,
230        mine_target,
231        terrain_target,
232    )
233}
234
235pub(super) fn ray_entities(
236    client: &Client,
237    start: Vec3<f32>,
238    end: Vec3<f32>,
239    cast_dist: f32,
240) -> (f32, Option<Entity>) {
241    let player_entity = client.entity();
242    let ecs = client.state().ecs();
243    let positions = ecs.read_storage::<comp::Pos>();
244    let colliders = ecs.read_storage::<comp::Collider>();
245
246    let mut nearby = (
247        &ecs.entities(),
248        &positions,
249        &colliders,
250    )
251        .join()
252        .filter(|(e, _, _)| *e != player_entity)
253        .map(|(e, p, c)| {
254            let height = c.get_height();
255            let radius = c.bounding_radius().max(height / 2.0);
256            // Move position up from the feet
257            let pos = Vec3::new(p.0.x, p.0.y, p.0.z + c.get_z_limits(1.0).0 + height/2.0);
258            // Distance squared from start to the entity
259            let dist_sqr = pos.distance_squared(start);
260            (e, pos, radius, dist_sqr, c)
261        })
262        // Roughly filter out entities farther than ray distance
263        .filter(|(_, _, _, d_sqr, _)| *d_sqr <= cast_dist.powi(2))
264        .collect::<Vec<_>>();
265    // Sort by distance
266    nearby.sort_unstable_by(|a, b| a.3.partial_cmp(&b.3).unwrap());
267
268    let seg_ray = LineSegment3 { start, end };
269
270    let entity = nearby.iter().find_map(|(e, p, r, _, c)| {
271        let nearest = seg_ray.projected_point(*p);
272
273        match c {
274            comp::Collider::CapsulePrism(CapsulePrism {
275                p0,
276                p1,
277                radius,
278                z_min,
279                z_max,
280            }) => {
281                // Check if the nearest point is within the capsule's inclusive radius (radius
282                // from center to furthest possible edge corner) If not, then
283                // the ray doesn't intersect the capsule at all and we can skip it
284                if nearest.distance_squared(*p) > (r * 3.0_f32.sqrt()).powi(2) {
285                    return None;
286                }
287
288                let entity_rotation = ecs
289                    .read_storage::<comp::Ori>()
290                    .get(*e)
291                    .copied()
292                    .unwrap_or_default();
293                let entity_position = ecs.read_storage::<comp::Pos>().get(*e).copied().unwrap();
294                let world_p0 = entity_position.0
295                    + (entity_rotation.to_quat()
296                        * Vec3::new(p0.x, p0.y, z_min + c.get_height() / 2.0));
297                let world_p1 = entity_position.0
298                    + (entity_rotation.to_quat()
299                        * Vec3::new(p1.x, p1.y, z_min + c.get_height() / 2.0));
300
301                // Get the closest points between the ray and the capsule's line segment
302                // If the capsule's line segment is a point, then the closest point is the point
303                // itself
304                let (p_a, p_b) = if p0 != p1 {
305                    let seg_capsule = LineSegment3 {
306                        start: world_p0,
307                        end: world_p1,
308                    };
309                    closest_points_3d(seg_ray, seg_capsule)
310                } else {
311                    let nearest = seg_ray.projected_point(world_p0);
312                    (nearest, world_p0)
313                };
314
315                // Check if the distance between the closest points are within the capsule
316                // prism's radius on the xy plane and if the closest points are
317                // within the capsule prism's z range
318                let distance = p_a.xy().distance_squared(p_b.xy());
319                if distance < radius.powi(2)
320                    && p_a.z >= entity_position.0.z + z_min
321                    && p_a.z <= entity_position.0.z + z_max
322                {
323                    return Some((p_a.distance(start), Entity(*e)));
324                }
325
326                // If all else fails, then the ray doesn't intersect the capsule
327                None
328            },
329            // TODO: handle other collider types, for now just use the bounding sphere
330            _ => {
331                if nearest.distance_squared(*p) < r.powi(2) {
332                    return Some((nearest.distance(start), Entity(*e)));
333                }
334                None
335            },
336        }
337    });
338    entity
339        .map(|(dist, e)| (dist, Some(e)))
340        .unwrap_or((cast_dist, None))
341}