using Godot; using ViaFerrea.Client.Hud; using ViaFerrea.Client.Map; using ViaFerrea.Client.Net; using ViaFerrea.Client.Screens; using ViaFerrea.Core.Commands; using ViaFerrea.Core.Common; using ViaFerrea.Core.Rail; using ViaFerrea.Protocol.Client; using ViaFerrea.Protocol.Messages; namespace ViaFerrea.Client.App; /// /// Pilota automatico per il collaudo del client (-- --autopilot cartella): nella partita /// locale costruisce stazioni, deposito e una linea con ponte usando l'anteprima, compra un treno, /// lo mette in linea e salva schermate della mappa, del ponte, del treno e del profilo. /// public partial class AutoPilot : Node { private readonly GameScreen _game; private readonly string _out; public AutoPilot(GameScreen game, string outDir) { _game = game; _out = outDir; } private GameSession Session => _game.Session; private ClientWorld World => _game.Session.World; public override async void _Ready() { int code = 0; try { await Run(); GD.Print("autopilot: ok"); } catch (Exception e) { GD.PrintErr($"autopilot: FALLITO {e.Message}\n{e.StackTrace}"); code = 1; } GetTree().Quit(code); } private async Task Frame() => await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); private async Task Until(Func condition, string what, double timeoutS = 120) { ulong start = Time.GetTicksMsec(); while (!condition()) { if (Time.GetTicksMsec() - start > timeoutS * 1000) throw new TimeoutException(what); await Frame(); } } private Task Do(GameCommand command) { var tcs = new TaskCompletionSource(); Session.Command(command, r => tcs.TrySetResult(r)); return tcs.Task; } private async Task Ok(GameCommand command) { var r = await Do(command); if (!r.Ok) throw new InvalidOperationException($"{command.Type}: {r.Message}"); GD.Print($"autopilot: {r.Message}"); return r.Created.Length > 0 ? r.Created[0] : -1; } private async Task Shot(string name, int settleFrames = 30) { for (int i = 0; i < settleFrames; i++) await Frame(); await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw); var image = GetViewport().GetTexture().GetImage(); string path = Path.Combine(_out, name + ".jpg"); image.SaveJpg(path, 0.88f); GD.Print($"autopilot: schermata {path}"); } private async Task Run() { Directory.CreateDirectory(_out); var summary = World.Summary!; Session.Send(new Subscribe { X0 = 0, Y0 = 0, X1 = summary.WidthCells - 1, Y1 = summary.HeightCells - 1 }); int chunks = ((summary.WidthCells + summary.ChunkCells - 1) / summary.ChunkCells) * ((summary.HeightCells + summary.ChunkCells - 1) / summary.ChunkCells); await Until(() => World.Chunks.Count == chunks && World.Towns.Count > 0, "terreno"); await Shot("01_avvio", 90); await Ok(new TakeLoanCommand(Money.FromLire(200_000))); var site = BridgeSiteFinder.Find(World) ?? throw new InvalidOperationException("nessun sito con ponte"); int a = await Ok(new BuildStationCommand(site.A, 2)); int b = await Ok(new BuildStationCommand(site.B, 2)); int depot = await Ok(new BuildDepotCommand(site.Depot, "small")); await Until(() => World.Stations.ContainsKey(b) && World.Depots.ContainsKey(depot), "stazioni"); var main = new BuildTrackCommand([site.A, site.B]); var plan = World.PreviewTrack(main); await Ok(main with { ExpectedCostCents = plan.TotalCost.Cents }); await Until(() => World.Edges.Count > 0, "binario"); var spur = new BuildTrackCommand([site.Depot, site.A]); await Ok(spur with { ExpectedCostCents = World.PreviewTrack(spur).TotalCost.Cents }); // vista d'insieme del cantiere var center = MapScale.V((site.A + site.B) / 2); _game.Map.CenterOn(center); _game.Map.SetZoom(0.22f); await Shot("02_cantiere"); Session.SetSpeed(8); await Until(() => World.Edges.Count >= 2 && World.Edges.Values.All(e => e.State == (byte)EdgeState.Active), "cantieri", 240); var loco = await Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1)); var wagons = await Do(new BuyVehicleCommand("wagon_hopper", new DepotId(depot), 3)); int train = await Ok(new ComposeTrainCommand(new DepotId(depot), loco.Created.Concat(wagons.Created).Select(i => new VehicleId(i)).ToList(), "Treno 1")); var loco2 = await Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1)); var coaches = await Do(new BuyVehicleCommand("coach_worker", new DepotId(depot), 2)); int train2 = await Ok(new ComposeTrainCommand(new DepotId(depot), loco2.Created.Concat(coaches.Created).Select(i => new VehicleId(i)).ToList(), "Treno 2")); int line = await Ok(new CreateLineCommand("Linea 1, collaudo", "#e0a526", [new LineStop(new StationId(a)), new LineStop(new StationId(b))])); await Ok(new AssignTrainCommand(new TrainId(train), new LineId(line))); Session.SetSpeed(1); await Until(() => World.Motions.TryGetValue(train, out var m) && m.Speed > 3, "treno in moto", 120); await Ok(new AssignTrainCommand(new TrainId(train2), new LineId(line))); _game.Map.CenterOn(center); _game.Map.SetZoom(0.22f); await Shot("03_linea"); // ponte da vicino (immagine 02) _game.Map.CenterOn(MapScale.V(site.River)); _game.Map.SetZoom(0.9f); await Shot("04_ponte"); // treno da vicino (immagine 03): la camera lo segue per qualche fotogramma for (int i = 0; i < 40; i++) { if (World.TrainHead(train) is { } head) _game.Map.CenterOn(MapScale.V(head)); _game.Map.SetZoom(1.4f); await Frame(); } _game.SelectTrain(train); await Shot("05_treno", 5); // scheda del treno con la mappa d'insieme _game.Map.SetZoom(0.3f); await Shot("06_scheda_treno", 20); // strumento binari con il profilo di un tracciato in collina _game.UseTool(Tool.Track); var dir = (site.B - site.A).Normalized(); var normal = new Vec2(-dir.Y, dir.X); var p0 = MapScale.V(site.B); var p1 = MapScale.V(site.B + normal * 2500); var p2 = MapScale.V(site.B + normal * 4000 + dir * 1500); _game.SetTrackPoints([p0, p1], p2); _game.Map.CenterOn(MapScale.V(site.B + normal * 2000 + dir * 500)); _game.Map.SetZoom(0.2f); await Shot("07_profilo", 40); _game.UseTool(Tool.None); _game.Map.SetZoom(0.06f); await Shot("08_panoramica", 60); } }