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