Skip to content
0.2.0-dev Download ZIP
284 lines ·12.0 KB Raw
1using EvilEngine.Formats;
2using EvilEngine.Formats.Collision;
3using EvilEngine.Formats.Maps;
4using EvilEngine.Host.Collision;
5using EvilEngine.Host.Movement;
6using EvilEngine.Shared;
7using EvilEngine.Shared.World;
8using Godot;
9
10namespace EvilEngine.Client.World;
11
12public partial class SurfaceCheck : Node
13{
14 private const double Tick = 0.015;
15 private const int Ticks = 200;
16 private const int Grid = 64;
17 private const int Layers = 64;
18
19 public override async void _Ready()
20 {
21 var args = OS.GetCmdlineUserArgs()
22 .Select(arg => arg.Split('=', 2))
23 .Where(pair => pair.Length == 2)
24 .ToDictionary(pair => pair[0], pair => pair[1]);
25 var code = await Run(args.GetValueOrDefault("--map") ?? "gmod:gm_construct",
26 (args.GetValueOrDefault("--surfaces") ?? "grass,sand").Split(',', StringSplitOptions.RemoveEmptyEntries));
27 GetTree().Quit(code);
28 }
29
30 private static async Task<int> Run(string id, string[] wanted)
31 {
32 var boot = await EngineBoot.Start(_ => { });
33 if (boot.Registry.Map(ContentId.Parse(id)) is not { } map)
34 {
35 GD.PrintErr($"No map record {id}.");
36 return 2;
37 }
38
39 var (world, _) = await Task.Run(() => MapStart.Build(boot.Host.Conversion, map, (_, _) => { }));
40 if (world is null)
41 {
42 GD.PrintErr($"{id} didn't build.");
43 return 2;
44 }
45
46 var clock = System.Diagnostics.Stopwatch.StartNew();
47 var start = world.SessionStart(map.Id, boot.Registry.Surface);
48 GD.Print($"surface check: {id}'s session world with its surfaces built in {clock.Elapsed.TotalSeconds:0.###} s");
49 using var physics = start.Physics as JoltWorld ??
50 throw new InvalidOperationException("The map has no Jolt world.");
51 using var ray = new PhysicsRayQueryParameters3D { CollisionMask = WorldCollision.WorldLayer };
52 using var hit = new PhysicsIntersectRayResult3D();
53 var failed = 0;
54 foreach (var name in wanted)
55 if (!Check(physics, name, ray, hit))
56 failed++;
57 if (!Agree(physics, start.World, ray, hit))
58 failed++;
59 world.QueueFree();
60 GD.Print(failed == 0
61 ? $"surface check: {string.Join(", ", wanted)} named by a ray and a contact on {id}, and every ray agrees with the hull traces"
62 : $"surface check: {failed} of {wanted.Length + 1} checks failed on {id}");
63 return failed == 0 ? 0 : 1;
64 }
65
66 private static bool Check(JoltWorld physics, string name, PhysicsRayQueryParameters3D ray,
67 PhysicsIntersectRayResult3D hit)
68 {
69 var tried = 0;
70 foreach (var (body, triangle, centre) in Candidates(physics, name))
71 {
72 if (tried++ == 64)
73 break;
74 var space = PhysicsServer3D.SpaceGetDirectState(physics.Space);
75 ray.From = Vec(centre) + Vector3.Up * 2;
76 ray.To = Vec(centre) + Vector3.Down * 0.5f;
77 if (!space.IntersectRayInto(ray, hit) || hit.ColliderRid != body)
78 continue;
79 var cast = physics.Surface(hit.ColliderRid, hit.ColliderShape, hit.ColliderFaceIndex);
80 var castName = Named(physics, cast);
81 if (!Is(castName, name))
82 {
83 GD.PrintErr($"{name}: the ray onto triangle {triangle} reported {castName}, face {hit.ColliderFaceIndex}.");
84 return false;
85 }
86
87 var contact = Contact(physics, centre);
88 if (contact is not var (rid, shape, face, normal))
89 {
90 GD.PrintErr($"{name}: the box dropped on triangle {triangle} touched nothing.");
91 return false;
92 }
93
94 var touched = physics.Surface(rid, shape, face, normal);
95 var touchedName = Named(physics, touched);
96 if (!Is(touchedName, name))
97 {
98 GD.PrintErr($"{name}: the box on triangle {triangle} touched {touchedName}, shape {shape} face {face}.");
99 return false;
100 }
101
102 using var data = (Godot.Collections.Dictionary)PhysicsServer3D.ShapeGetData(PhysicsServer3D.BodyGetShape(rid, shape));
103 var held = data.TryGetValue("friction", out var frictions) ? frictions.AsFloat32Array()[face] : float.NaN;
104 var friction = physics.Record(touched)?.Friction;
105 GD.Print($"{name}: triangle {triangle} at {Format(centre)}, ray face {hit.ColliderFaceIndex} {castName}, " +
106 $"contact shape {shape} face {face} {touchedName}, friction {friction:0.###} held by Jolt as {held:0.###}");
107 if (friction is { } wanted && Math.Abs(held - wanted) > 1e-6)
108 {
109 GD.PrintErr($"{name}: Jolt holds friction {held} for triangle {face}, not the surface's {wanted}.");
110 return false;
111 }
112
113 return true;
114 }
115
116 GD.PrintErr($"{name}: no open, upward triangle of the map's meshes is {name}.");
117 return false;
118 }
119
120 private static bool Agree(JoltWorld physics, IHullWorld hulls, PhysicsRayQueryParameters3D ray,
121 PhysicsIntersectRayResult3D hit)
122 {
123 var points = physics.MapBodies.SelectMany(physics.MapSurfaces.Shapes)
124 .SelectMany(collider => collider.Shape is MapColliderShape.Hull hull ? hull.Points : []).ToArray();
125 var min = new MapVector(points.Min(p => p.X), points.Min(p => p.Y), points.Min(p => p.Z));
126 var max = new MapVector(points.Max(p => p.X), points.Max(p => p.Y), points.Max(p => p.Z));
127 var space = PhysicsServer3D.SpaceGetDirectState(physics.Space);
128 var point = new HullBox(MapVector.Zero, MapVector.Zero);
129 int agreed = 0, apart = 0, differed = 0, meshes = 0, edges = 0;
130 var named = new HashSet<CollisionSurface>();
131 for (var i = 0; i < Grid; i++)
132 for (var j = 0; j < Grid; j++)
133 {
134 var x = min.X + (max.X - min.X) * (i + 0.5) / Grid;
135 var z = min.Z + (max.Z - min.Z) * (j + 0.5) / Grid;
136 var top = max.Y + 1;
137 var stride = 0.25;
138 for (var layer = 0; layer < Layers; layer++)
139 {
140 var from = new MapVector(x, top, z);
141 var to = new MapVector(x, min.Y - 1, z);
142 var traced = hulls.Trace(point, from, to);
143 if (traced.StartSolid)
144 {
145 top -= stride;
146 stride *= 2;
147 continue;
148 }
149
150 stride = 0.25;
151
152 ray.From = Vec(from);
153 ray.To = Vec(to);
154 var hitAny = space.IntersectRayInto(ray, hit);
155 if (!hitAny || traced.Fraction >= 1)
156 {
157 if (hitAny || traced.Fraction < 1)
158 apart++;
159 break;
160 }
161
162 var at = hit.Position;
163 top = Math.Min(at.Y, traced.End.Y) - 0.01;
164 if (Math.Abs(at.Y - traced.End.Y) > 0.01)
165 {
166 apart++;
167 continue;
168 }
169
170 var n = hit.Normal;
171 var jolt = physics.Surface(hit.ColliderRid, hit.ColliderShape, hit.ColliderFaceIndex,
172 new MapVector(n.X, n.Y, n.Z));
173 if (jolt == traced.Surface)
174 {
175 agreed++;
176 named.Add(jolt);
177 if (hit.ColliderFaceIndex >= 0)
178 meshes++;
179 continue;
180 }
181
182 var t = traced.Normal;
183 if (n.X * t.X + n.Y * t.Y + n.Z * t.Z < 0.999 &&
184 physics.Surface(hit.ColliderRid, hit.ColliderShape, hit.ColliderFaceIndex, t) == traced.Surface)
185 {
186 edges++;
187 continue;
188 }
189
190 if (differed++ < 8)
191 GD.PrintErr($"rays: at {x:0.###} {at.Y:0.###} {z:0.###} Jolt named {Named(physics, jolt)}, " +
192 $"the hull trace {Named(physics, traced.Surface)}");
193 }
194 }
195
196 GD.Print($"rays: {agreed} hits over {Grid * Grid} columns name the hull trace's surface ({meshes} on triangles, " +
197 $"{named.Count(surface => surface != CollisionSurface.None)} surfaces), {edges} on an edge Jolt and the trace " +
198 $"each gave a face of, {differed} differ, " +
199 $"{apart} hit elsewhere or only one world");
200 return differed == 0 && named.Count > 1;
201 }
202
203 private static IEnumerable<(Rid Body, int Triangle, MapVector Centre)> Candidates(JoltWorld physics, string name)
204 {
205 foreach (var body in physics.MapBodies)
206 {
207 if (physics.MapSurfaces.Collider(body, 0)?.Shape is not MapColliderShape.Triangles triangles)
208 continue;
209 var mesh = triangles.Mesh;
210 var parts = mesh.Surfaces.Select(surface => Is(Named(physics, surface), name)).ToArray();
211 if (!parts.Contains(true))
212 continue;
213 for (var step = 0; step < mesh.Count; step += Math.Max(1, mesh.Count / 97))
214 {
215 var triangle = (mesh.Count / 2 + step) % mesh.Count;
216 if (!parts[mesh.Parts[triangle]])
217 continue;
218 var a = triangles.Transform.Apply(mesh.Positions[mesh.Indices[triangle * 3]]);
219 var b = triangles.Transform.Apply(mesh.Positions[mesh.Indices[triangle * 3 + 1]]);
220 var c = triangles.Transform.Apply(mesh.Positions[mesh.Indices[triangle * 3 + 2]]);
221 var normal = (Vec(b) - Vec(a)).Cross(Vec(c) - Vec(a)).Normalized();
222 if (Math.Abs(normal.Y) < 0.9)
223 continue;
224 yield return (body, triangle,
225 new MapVector((a.X + b.X + c.X) / 3, (a.Y + b.Y + c.Y) / 3, (a.Z + b.Z + c.Z) / 3));
226 }
227 }
228 }
229
230 private static (Rid Body, int Shape, int Face, MapVector Normal)? Contact(JoltWorld physics, MapVector centre)
231 {
232 var shape = PhysicsServer3D.BoxShapeCreate();
233 PhysicsServer3D.ShapeSetData(shape, new Vector3(0.1f, 0.1f, 0.1f));
234 var box = PhysicsServer3D.BodyCreate();
235 try
236 {
237 PhysicsServer3D.BodySetMode(box, PhysicsServer3D.BodyMode.Rigid);
238 PhysicsServer3D.BodyAddShape(box, shape);
239 PhysicsServer3D.BodySetCollisionLayer(box, WorldCollision.PropLayer);
240 PhysicsServer3D.BodySetCollisionMask(box, WorldCollision.WorldLayer);
241 PhysicsServer3D.BodySetMaxContactsReported(box, 8);
242 PhysicsServer3D.BodySetState(box, PhysicsServer3D.BodyState.Transform,
243 new Transform3D(Basis.Identity, Vec(centre) + Vector3.Up * 0.3f));
244 PhysicsServer3D.BodySetSpace(box, physics.Space);
245 for (var tick = 0; tick < Ticks; tick++)
246 {
247 physics.Step(Tick);
248 var state = PhysicsServer3D.BodyGetDirectState(box);
249 if (state.GetContactCount() == 0)
250 continue;
251 var n = state.GetContactLocalNormal(0);
252 return (state.GetContactCollider(0), state.GetContactColliderShape(0),
253 (int)state.Call("get_contact_collider_face", 0), new MapVector(n.X, n.Y, n.Z));
254 }
255
256 return null;
257 }
258 finally
259 {
260 PhysicsServer3D.FreeRid(box);
261 PhysicsServer3D.FreeRid(shape);
262 }
263 }
264
265 private static string Named(JoltWorld physics, CollisionSurface surface)
266 {
267 return physics.Record(surface)?.Id.ToString() ?? surface.Surface?.ToString() ?? surface.Material?.ToString() ?? "none";
268 }
269
270 private static bool Is(string found, string name)
271 {
272 return found.EndsWith("/" + name, StringComparison.Ordinal);
273 }
274
275 private static string Format(MapVector point)
276 {
277 return $"{point.X:0.##} {point.Y:0.##} {point.Z:0.##}";
278 }
279
280 private static Vector3 Vec(MapVector v)
281 {
282 return new Vector3(v.X, v.Y, v.Z);
283 }
284}