Skip to content
0.2.0-dev Download ZIP
391 lines ·21.1 KB Raw
1using System.Diagnostics;
2using System.Globalization;
3using System.Text.RegularExpressions;
4using EvilEngine.Client.Audio;
5using EvilEngine.Formats;
6using EvilEngine.Formats.Records;
7using EvilEngine.Host;
8using EvilEngine.Host.Sessions;
9using EvilEngine.Host.Steps;
10using EvilEngine.Shared;
11using EvilEngine.Shared.Sessions;
12using EvilEngine.Shared.World;
13using Godot;
14
15namespace EvilEngine.Client.World;
16
17public partial class MapShot : Node
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);
26 GetTree().Quit(code);
27 }
28
29 private async Task<int> Run(Dictionary<string, string> args)
30 {
31 var output = args.GetValueOrDefault("--screenshot");
32 var shots = args.GetValueOrDefault("--shots");
33 var bench = args.ContainsKey("--bench");
34 var frames = args.GetValueOrDefault("--frames");
35 if (!args.TryGetValue("--map", out var id) ||
36 new[] { output is not null, shots is not null, bench, frames is not null }.Count(given => given) != 1)
37 {
38 GD.PrintErr(
39 "MapShot needs --map=<record id> and one of --bench=1 to time the map's start as Start runs it, entering it and drawing its first frame, --screenshot=<png> with --at=x,y,z, --look=pitch,yaw and --fov, or --shots=<file> of 'name x y z pitch yaw fov' lines with --out=<folder>, or --frames=<file> of the same lines to measure each view uncapped, its draw calls, objects, primitives and rendering's CPU and GPU time, and takes --size=WxH, --exposure=<scale> to hold the tonemap scale, --bloom=0 to leave bloom out, --remastered=liquids to draw every liquid through evil:shaders/liquid, --sky=<sky record or content id> to show another sky, --lighting=baked|realtime to light it as a server would, each of gi, ao, ssil, ssr, fog and bloom after a + turning it on or a - off (like realtime+ssr-fog), and --walk=<keys>:<seconds>,... to spawn the walking player and hold each set of keys (like W+Shift) for its seconds, facing the yaw after an @ if one is given, with kill as a step's keys running the kill command, --bots=<n> to join that many bots, --playerclass=<id> to live as that player class, --view=body|first|third to look through that view mode, and --spawn=<model>[@x,y,z];... to spawn each model as a prop where the player aims or at the point, before the screenshot.");
40 return 2;
41 }
42
43 var boot = await EngineBoot.Start(line => GD.Print(line.ToString()));
44 AudioManager.Instance?.Attach(boot.Host.Conversion, id => boot.Registry.Sound(id));
45 if (boot.Registry.Map(ContentId.Parse(id)) is not { } map)
46 {
47 GD.PrintErr($"No map record {id}.");
48 return 1;
49 }
50
51 var clock = Stopwatch.StartNew();
52
53 void Line(TranscriptTag tag, string text)
54 {
55 GD.Print(new TranscriptLine(clock.Elapsed, tag, text).ToString());
56 }
57
58 var walk = args.GetValueOrDefault("--walk");
59 var size = (args.GetValueOrDefault("--size") ?? "1920x1080").Split('x').Select(int.Parse).ToArray();
60 GetWindow().Size = new Vector2I(size[0], size[1]);
61 var (world, times) = await Task.Run(() => MapStart.Build(boot.Host.Conversion, map, Line,
62 walk is not null || bench || shots is not null,
63 args.GetValueOrDefault("--remastered") == "liquids"));
64 if (world is null)
65 return 1;
66
67 if (bench)
68 return await Bench(world, map.Id.ToString(), times, clock);
69 if (args.GetValueOrDefault("--lighting") is { } lit)
70 world.ShowLighting(Lighting(lit));
71 await world.Enter(this);
72 if (args.GetValueOrDefault("--sky") is { } skyId)
73 {
74 var record = boot.Registry.Sky(ContentId.Parse(skyId));
75 var (look, problem) =
76 await Task.Run(() => world.Look(boot.Host.Conversion, record?.Sky ?? ContentId.Parse(skyId)));
77 if (look is null)
78 {
79 GD.PrintErr($"{skyId} didn't convert: {problem}");
80 return 1;
81 }
82
83 world.ShowSky(look);
84 }
85
86 if (walk is not null && world.Hulls is not null && output is not null)
87 {
88 var bots = int.Parse(args.GetValueOrDefault("--bots") ?? "0", CultureInfo.InvariantCulture);
89 var life = args.GetValueOrDefault("--playerclass") is { } named
90 ? boot.Registry.PlayerClass(ContentId.Parse(named)) ??
91 throw new ArgumentException($"No player class {named}.")
92 : EnginePlayers.Default;
93 var (server, client) = LocalServer.Play(world.SessionStart(map.Id, boot.Registry.Surface) with
94 {
95 Seed = 1, People = boot.Registry.Playermodels().ToArray(), Movements = boot.Registry.Movements,
96 MaxPlayers = 1 + bots, PlayerClass = life,
97 Flashlight = args.GetValueOrDefault("--flashlight") is { } beam
98 ? FlashlightSettings(beam)
99 : ServerFlashlight.Default,
100 StepSounds = StepSounds.From(boot.Registry, boot.Host.Conversion)
101 }, "MapShot");
102 for (var bot = 0; bot < bots; bot++)
103 server.Session.AddBot();
104 var player = new PlayerCamera(client)
105 {
106 View = args.GetValueOrDefault("--view") switch
107 {
108 "first" => ViewMode.First,
109 "third" => ViewMode.Third,
110 _ => ViewMode.Body
111 }
112 };
113 world.AddChild(player);
114 var bodies = new WorldBodies(client, boot.Host.Conversion, boot.Registry.Person)
115 { DrawOwn = () => player.DrawsOwnBody };
116 player.Dressing = bodies.Dressing;
117 world.AddChild(bodies);
118 var props = new WorldProps(client, boot.Host.Conversion);
119 world.AddChild(props);
120 var sounds = new WorldSounds(client, bodies);
121 world.AddChild(sounds);
122 var ambience = new WorldAmbience(world, boot.Registry.Soundscape);
123 world.AddChild(ambience);
124 var flashlights = new WorldFlashlights(client) { OwnAim = () => player.Aim };
125 world.AddChild(flashlights);
126 if (args.GetValueOrDefault("--exposure") is { } fixedExposure)
127 world.ForceExposure(double.Parse(fixedExposure, CultureInfo.InvariantCulture));
128 if (args.GetValueOrDefault("--spawn") is { } spawning)
129 {
130 while (client.State != ClientState.Active || client.Controlled is null)
131 await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
132 foreach (var spawn in spawning.Split(';', StringSplitOptions.RemoveEmptyEntries))
133 {
134 var parts = spawn.Split('@');
135 client.Command(parts.Length > 1
136 ? $"{ServerSession.SpawnCommand} {parts[0]} {parts[1].Replace(',', ' ')}"
137 : $"{ServerSession.SpawnCommand} {parts[0]}");
138 }
139 }
140
141 var steps = walk.Split(',', StringSplitOptions.RemoveEmptyEntries);
142 var hold = args.ContainsKey("--hold");
143 foreach (var step in steps)
144 {
145 var timing = step.Split(':')[1].Split('@');
146 var (keys, seconds) = (step.Split(':')[0], double.Parse(timing[0], CultureInfo.InvariantCulture));
147 if (timing.Length > 1)
148 player.Look(0, double.Parse(timing[1], CultureInfo.InvariantCulture));
149 if (keys == ServerSession.Kill)
150 client.Command(ServerSession.Kill);
151 var held = keys.Split('+', StringSplitOptions.RemoveEmptyEntries)
152 .Where(key => key is not "-" and not ServerSession.Kill).Select(key => Enum.Parse<Key>(key, true))
153 .ToArray();
154 foreach (var key in held)
155 Input.ParseInputEvent(new InputEventKey { PhysicalKeycode = key, Keycode = key, Pressed = true });
156 await ToSignal(GetTree().CreateTimer(seconds), SceneTreeTimer.SignalName.Timeout);
157 if (!hold || !ReferenceEquals(step, steps[^1]))
158 foreach (var key in held)
159 Input.ParseInputEvent(new InputEventKey
160 { PhysicalKeycode = key, Keycode = key, Pressed = false });
161 if (client.Controlled is { } body)
162 GD.Print(
163 $"walk {keys} {seconds} s: {body.Body} at {body.Feet}, moving {body.Velocity}, {(body.OnGround ? "on the ground" : "in the air")}{(body.Crouched ? ", crouched" : "")}, facing {body.Yaw}, {body.Health} health as {body.Look.Person?.ToString() ?? "nobody"}");
164 else if (client.OwnBody is { } dead)
165 GD.Print($"walk {keys} {seconds} s: dead, {dead.Body} lying at {dead.Feet}");
166 GD.Print(
167 $"walk {keys} {seconds} s: {sounds.Heard} sounds heard, {AudioManager.Instance?.Started ?? 0} started, {AudioManager.Instance?.Placed ?? 0} placed now, {flashlights.Lit} flashlights lit");
168 GD.Print(
169 $"walk {keys} {seconds} s: soundscape {ambience.Playing?.ToString() ?? "none"}, {ambience.Loops} loops, {ambience.Randoms} random sets, {ambience.RandomsPlayed} random sounds played, {AudioManager.Instance?.Playing.Count(voice => voice.Record.Branch == SoundBranch.Ambience) ?? 0} playing on Ambience");
170 foreach (var prop in client.Props)
171 GD.Print(
172 $"walk {keys} {seconds} s: prop {prop.Prop} {prop.Model} at {prop.Position} turned {prop.Orientation} moving {prop.Velocity}{(prop.Asleep ? ", asleep" : "")}, {props.Drawn} drawn");
173 foreach (var other in client.Bodies.Where(other => other.Body != client.Own?.Body))
174 GD.Print(
175 $"walk {keys} {seconds} s: {other.Body} of {other.Owner} at {other.Feet} facing {other.Yaw} as {other.Look.Person?.ToString() ?? "nobody"}, {(other.Alive ? "alive" : "dead")}, {bodies.Drawn} drawn");
176 }
177
178 await Shoot(player, output);
179 server.Stop("MapShot is done.");
180 return 0;
181 }
182
183 var camera = new Camera3D
184 {
185 Transform = world.Spawn, Near = 0.05f, Far = 4000,
186 Fov = float.Parse(args.GetValueOrDefault("--fov") ?? "75", CultureInfo.InvariantCulture)
187 };
188 world.AddChild(camera);
189 camera.MakeCurrent();
190 if (args.GetValueOrDefault("--exposure") is { } forced)
191 world.ForceExposure(double.Parse(forced, CultureInfo.InvariantCulture));
192 if (args.GetValueOrDefault("--bloom") == "0")
193 world.DropBloom();
194 if (frames is not null)
195 {
196 await Frames(camera, world, frames);
197 return 0;
198 }
199
200 if (shots is null)
201 {
202 if (Numbers(args.GetValueOrDefault("--at")) is [var x, var y, var z])
203 camera.Position = new Vector3(x, y, z);
204 if (Numbers(args.GetValueOrDefault("--look")) is [var pitch, var yaw])
205 camera.Basis = Basis.FromEuler(new Vector3(Mathf.DegToRad(pitch), Mathf.DegToRad(yaw), 0));
206 await Shoot(camera, output!);
207 return 0;
208 }
209
210 var folder = args.GetValueOrDefault("--out") ?? Path.GetDirectoryName(Path.GetFullPath(shots))!;
211 var heard = new WorldAmbience(world, boot.Registry.Soundscape);
212 world.AddChild(heard);
213 foreach (var shot in File.ReadAllLines(shots)
214 .Select(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries))
215 .Where(parts => parts.Length == 7))
216 {
217 var n = shot[1..].Select(part => float.Parse(part, CultureInfo.InvariantCulture)).ToArray();
218 camera.Position = new Vector3(n[0], n[1], n[2]);
219 camera.Basis = Basis.FromEuler(new Vector3(Mathf.DegToRad(n[3]), Mathf.DegToRad(n[4]), 0));
220 camera.Fov = n[5];
221 await Shoot(camera, Path.Combine(folder, shot[0] + ".png"));
222 if (world.Ambience.Count > 0)
223 GD.Print(
224 $"shot {shot[0]}: soundscape {heard.Playing?.ToString() ?? "none"}, {heard.Loops} loops, {heard.Randoms} random sets, {heard.RandomsPlayed} random sounds played, {AudioManager.Instance?.Playing.Count(voice => voice.Record.Branch == SoundBranch.Ambience) ?? 0} playing on Ambience");
225 }
226
227 return 0;
228 }
229
230 private async Task<int> Bench(MapWorld world, string id, MapStartTimes times, Stopwatch clock)
231 {
232 var entering = clock.Elapsed;
233 await world.Enter(this);
234 if (world.Hulls is not null)
235 world.AddChild(new PlayerCamera(LocalServer
236 .Play(world.SessionStart(ContentId.Parse(id)) with { Seed = 1 }, "MapShot").Client));
237 else
238 world.AddChild(new FreeCamera { Transform = world.Spawn });
239 var entered = clock.Elapsed;
240 await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
241 var drawn = clock.Elapsed;
242 var frames = new List<double>();
243 for (var frame = 0; frame < 60; frame++)
244 {
245 var from = clock.Elapsed;
246 await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
247 frames.Add((clock.Elapsed - from).TotalMilliseconds);
248 }
249
250 var waits = times.WaitCount == 0
251 ? "no waits"
252 : $"{times.WaitCount:N0} waits for {times.Waited.TotalSeconds:0.00} s ({string.Join(", ", times.Waits.Take(3).Select(wait => $"{wait.Where} {wait.Count:N0}x {wait.Took.TotalMilliseconds:0} ms"))})";
253 GD.Print(string.Create(CultureInfo.InvariantCulture,
254 $"bench {id}: load {times.Load.TotalSeconds:0.000} s, collision {times.Collision.TotalSeconds:0.000} s, world {times.World.TotalSeconds:0.000} s with {waits}, enter {(entered - entering).TotalSeconds:0.000} s, first frame {(drawn - entered).TotalSeconds:0.000} s, start to first frame {drawn.TotalSeconds:0.000} s, slowest of the next 60 frames {frames.Max():0.0} ms"));
255 foreach (var wait in times.Waits)
256 GD.Print(string.Create(CultureInfo.InvariantCulture,
257 $"bench wait {wait.Where}: {wait.Count:N0}x, {wait.Took.TotalMilliseconds:0.0} ms, of which Godot's worker pool {wait.PoolCount:N0}x, {wait.PoolTook.TotalMilliseconds:0.0} ms"));
258 return 0;
259 }
260
261 private async Task Frames(Camera3D camera, MapWorld world, string file)
262 {
263 DisplayServer.WindowSetVsyncMode(DisplayServer.VSyncMode.Disabled);
264 Engine.MaxFps = 0;
265 var viewports = new List<Rid> { GetViewport().GetViewportRid() };
266 viewports.AddRange(world.FindChildren("*", nameof(SubViewport), true, false).Cast<SubViewport>()
267 .Select(view => view.GetViewportRid()));
268 foreach (var viewport in viewports)
269 RenderingServer.ViewportSetMeasureRenderTime(viewport, true);
270 foreach (var shot in File.ReadAllLines(file)
271 .Select(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries))
272 .Where(parts => parts.Length == 7))
273 {
274 var n = shot[1..].Select(part => float.Parse(part, CultureInfo.InvariantCulture)).ToArray();
275 camera.Position = new Vector3(n[0], n[1], n[2]);
276 camera.Basis = Basis.FromEuler(new Vector3(Mathf.DegToRad(n[3]), Mathf.DegToRad(n[4]), 0));
277 camera.Fov = n[5];
278 for (var frame = 0; frame < 60; frame++)
279 await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
280 var samples = new List<double[]>();
281 for (var frame = 0; frame < 240; frame++)
282 {
283 await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
284 double Info(Rid viewport, RenderingServer.ViewportRenderInfoType type,
285 RenderingServer.ViewportRenderInfo info)
286 {
287 return RenderingServer.ViewportGetRenderInfo(viewport, type, info);
288 }
289
290 const RenderingServer.ViewportRenderInfo calls = RenderingServer.ViewportRenderInfo.DrawCallsInFrame;
291 const RenderingServer.ViewportRenderInfoType visible = RenderingServer.ViewportRenderInfoType.Visible;
292 const RenderingServer.ViewportRenderInfoType shadow = RenderingServer.ViewportRenderInfoType.Shadow;
293 samples.Add([
294 Info(viewports[0], visible, calls), Info(viewports[0], shadow, calls),
295 viewports.Skip(1).Sum(view => Info(view, visible, calls) + Info(view, shadow, calls)),
296 Info(viewports[0], visible, RenderingServer.ViewportRenderInfo.ObjectsInFrame),
297 viewports.Sum(view => Info(view, visible, RenderingServer.ViewportRenderInfo.PrimitivesInFrame) +
298 Info(view, shadow, RenderingServer.ViewportRenderInfo.PrimitivesInFrame)),
299 RenderingServer.GetFrameSetupTimeCpu() +
300 viewports.Sum(RenderingServer.ViewportGetMeasuredRenderTimeCpu),
301 viewports.Sum(RenderingServer.ViewportGetMeasuredRenderTimeGpu)
302 ]);
303 }
304
305 double Median(int column)
306 {
307 var sorted = samples.Select(sample => sample[column]).Order().ToArray();
308 return sorted[sorted.Length / 2];
309 }
310
311 GD.Print(string.Create(CultureInfo.InvariantCulture,
312 $"frames {shot[0]}: {Median(0) + Median(1) + Median(2):0} draw calls ({Median(0):0} in view, {Median(1):0} for its shadows, {Median(2):0} in {viewports.Count - 1} other views), {Median(3):0} objects in view, {Median(4) / 1000:0} k primitives, rendering {Median(5):0.00} ms of CPU and {Median(6):0.00} ms of GPU"));
313 }
314 }
315
316 private async Task Shoot(Camera3D camera, string output)
317 {
318 var world = camera.GetParent() as MapWorld;
319 world?.SettleExposure();
320 for (var frame = 0; frame < 8 || (world is { ExposureSettled: false } && frame < 240); frame++)
321 await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
322 for (var frame = 0; frame < 4; frame++)
323 await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
324 var image = GetViewport().GetTexture().GetImage();
325 Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(output))!);
326 image.SavePng(output);
327 GD.Print(
328 $"Saved {output} from {camera.Position}, looking {camera.Basis.GetEuler() * (180 / Mathf.Pi)}, exposure {world?.Exposure?.Scale ?? 1:0.000}");
329 }
330
331 private static float[]? Numbers(string? text)
332 {
333 return text?.Split(',').Select(part => float.Parse(part, CultureInfo.InvariantCulture)).ToArray();
334 }
335
336 private static ServerFlashlight FlashlightSettings(string text)
337 {
338 var flashlight = ServerFlashlight.Default;
339 foreach (var pair in text.Split(',', StringSplitOptions.RemoveEmptyEntries))
340 {
341 var (key, value) = (pair.Split('=')[0], pair.Split('=').ElementAtOrDefault(1) ?? "");
342 double Number() => double.Parse(value, CultureInfo.InvariantCulture);
343 flashlight = key switch
344 {
345 "range" => flashlight with { Range = Number() },
346 "angle" => flashlight with { Angle = Number() },
347 "intensity" => flashlight with { Intensity = Number() },
348 "falloff" => flashlight with { Falloff = Number() },
349 "colour" when Color.HtmlIsValid(value) => flashlight with
350 {
351 Colour = ServerSettings.Vector(Color.FromHtml(value))
352 },
353 "cookie" => flashlight with { Cookie = value != "0" },
354 "click" => flashlight with { Click = value != "0" },
355 _ => throw new ArgumentException($"--flashlight has no {pair}.")
356 };
357 }
358
359 return flashlight;
360 }
361
362 private static ServerLighting Lighting(string text)
363 {
364 var parts = Regex.Split(text, "(?=[+-])");
365 var lighting = new ServerLighting
366 {
367 Mode = parts[0] switch
368 {
369 "baked" => LightingMode.Baked,
370 "realtime" => LightingMode.Realtime,
371 _ => throw new ArgumentException($"--lighting takes baked or realtime, not {parts[0]}.")
372 }
373 };
374 foreach (var part in parts.Skip(1))
375 {
376 var on = part[0] == '+';
377 lighting = part[1..] switch
378 {
379 "gi" => lighting with { GlobalIllumination = on },
380 "ao" => lighting with { AmbientOcclusion = on },
381 "ssil" => lighting with { IndirectLight = on },
382 "ssr" => lighting with { Reflections = on },
383 "fog" => lighting with { Fog = on },
384 "bloom" => lighting with { Bloom = on },
385 _ => throw new ArgumentException($"--lighting has no {part[1..]}.")
386 };
387 }
388
389 return lighting;
390 }
391}