Skip to content
0.2.0-dev Download ZIP
79 lines ·2.5 KB Raw
1using EvilEngine.Formats.Maps;
2using EvilEngine.Host.Movement;
3
4namespace EvilEngine.Host.Physics;
5
6[Flags]
7public enum QueryLayers
8{
9 None = 0,
10 World = 1,
11 PlayerClip = 2,
12 NpcClip = 4,
13 VehicleClip = 8,
14 PhysicsClip = 16,
15 Props = 32,
16 Sight = World | Props,
17 PlayerHull = World | PlayerClip | Props,
18 All = World | PlayerClip | NpcClip | VehicleClip | PhysicsClip | Props
19}
20
21public readonly record struct QueryHit(double Fraction, MapVector End, MapVector Normal, bool StartSolid)
22{
23 public bool Hit => StartSolid || Fraction < 1;
24}
25
26public interface IWorldQueries
27{
28 QueryHit Line(MapVector start, MapVector end, QueryLayers layers);
29
30 QueryHit Box(HullBox box, MapVector start, MapVector end, QueryLayers layers);
31
32 bool Overlaps(HullBox box, MapVector at, QueryLayers layers);
33}
34
35public static class WorldQueries
36{
37 public static QueryLayers Layer(IReadOnlyList<string> contents)
38 {
39 if (SolidContents.Blocks(contents))
40 return QueryLayers.World;
41 if (contents.Contains(SolidContents.PlayerClip))
42 return QueryLayers.PlayerClip;
43 if (contents.Contains(SolidContents.NpcClip))
44 return QueryLayers.NpcClip;
45 if (contents.Contains(SolidContents.VehicleClip))
46 return QueryLayers.VehicleClip;
47 return contents.Contains(SolidContents.PhysicsClip) ? QueryLayers.PhysicsClip : QueryLayers.None;
48 }
49
50 public static MapVector? Free(this IWorldQueries queries, HullBox hull, MapVector near, QueryLayers layers,
51 double reach = 4, double step = 0.25)
52 {
53 if (!queries.Overlaps(hull, near, layers))
54 return near;
55 for (var ring = 1; ring * step <= reach; ring++)
56 {
57 var best = (MapVector?)null;
58 var bestDistance = double.MaxValue;
59 for (var dy = -ring; dy <= ring; dy++)
60 for (var dx = -ring; dx <= ring; dx++)
61 for (var dz = -ring; dz <= ring; dz++)
62 {
63 if (Math.Max(Math.Abs(dx), Math.Max(Math.Abs(dy), Math.Abs(dz))) != ring)
64 continue;
65 var distance = dx * dx + dy * dy + dz * dz;
66 if (distance >= bestDistance)
67 continue;
68 var at = new MapVector(near.X + dx * step, near.Y + dy * step, near.Z + dz * step);
69 if (!queries.Overlaps(hull, at, layers))
70 (best, bestDistance) = (at, distance);
71 }
72
73 if (best is not null)
74 return best;
75 }
76
77 return null;
78 }
79}