using System; using System.Diagnostics; using System.IO; using System.Linq; using GladiatorIdle.Arena; using GladiatorIdle.Gfx; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace GladiatorIdle { /// /// Das Spiel: Startmenü → (Intro) → Erstellung des eigenen Gladiators → Arena ↔ Kampf. /// Einstellungen und Pause liegen als Ebenen darüber. Eigener Spielstand (arena.json), /// gespeichert nach jedem Kampf, alle 30 s und beim Beenden. Testläufe speichern nie. /// internal sealed class ArenaGame : Game { readonly GraphicsDeviceManager _gdm; SpriteBatch _sb = null!; BasicEffect _fx = null!; RenderTarget2D? _rt; GameState? _game; MenuScene? _menu; IntroScene? _intro; CreatorScene? _creator; HubScene? _hub; DuelScene? _scene; ModelTestScene? _model; // --model3d: 3D-Test FreedomScene? _freedom; // Freiheit: Clip, Bilanz, Götter OfflineReport? _welcome; // was offline passiert ist (beim Weiterspielen gezeigt) LeaderboardScene? _board; // Bestenliste (aus dem Menü) bool _nextLife; // nächste Erstellung behält das Profil (Legenden, Götter) Legend? _legend; // laufendes Duell gegen eine Legende static readonly bool DevFreedomRun = Array.IndexOf(Environment.GetCommandLineArgs(), "--freedom") >= 0; static readonly bool DevChampionRun = Array.IndexOf(Environment.GetCommandLineArgs(), "--champion") >= 0; static readonly bool DevAdventureRun = Array.IndexOf(Environment.GetCommandLineArgs(), "--adventure") >= 0; static readonly bool DevBoardRun = Array.IndexOf(Environment.GetCommandLineArgs(), "--leaderboard") >= 0; static readonly bool DevTutorialRun = Array.IndexOf(Environment.GetCommandLineArgs(), "--tutorial") >= 0; static readonly bool Model3DTest = Array.IndexOf(Environment.GetCommandLineArgs(), "--model3d") >= 0; SettingsOverlay _settings = null!; bool _paused; readonly Ui _pauseUi = new(); bool _introThenCreate; // erster Start: nach dem Intro gleich die Erstellung Offer? _offer; (double Gold, double Fame, double Xp, int Level, int Items) _before; double _saveIn = 30; Enemy _enemy = null!; readonly Input _input = new(), _noInput = new(); int _seed = 1; // Testlauf double _devTime; int _rec = -1; string? _capture; readonly System.Collections.Generic.HashSet _shots = new(); readonly Stopwatch _drawWatch = new(); double _drawMs, _frameSum; int _frames; double _hubDraw, _duelDraw; int _hubFrames, _duelFrames; public ArenaGame() { _gdm = new GraphicsDeviceManager(this) { SynchronizeWithVerticalRetrace = true, GraphicsProfile = GraphicsProfile.HiDef, PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8 }; // Stencil: Schatten im Duell SetMode(AppSettings.Fullscreen); IsFixedTimeStep = false; ApplyFrameLimit(apply: false); IsMouseVisible = true; Window.Title = L.t("app.title"); Window.AllowUserResizing = true; } void SetMode(bool fullscreen) { if (fullscreen) { _gdm.HardwareModeSwitch = false; _gdm.IsFullScreen = true; var mode = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode; _gdm.PreferredBackBufferWidth = mode.Width; _gdm.PreferredBackBufferHeight = mode.Height; } else { _gdm.IsFullScreen = false; var size = DevShot.WindowSize ?? new System.Drawing.Size(1600, 900); _gdm.PreferredBackBufferWidth = size.Width; _gdm.PreferredBackBufferHeight = size.Height; } } /// Bildrate nach Einstellung: VSync, feste 120 Bilder/s oder unbegrenzt (Testläufe: immer VSync). void ApplyFrameLimit(bool apply = true) { int mode = DevShot.Active ? 0 : AppSettings.FrameLimit; _gdm.SynchronizeWithVerticalRetrace = mode == 0; IsFixedTimeStep = mode == 1; if (mode == 1) TargetElapsedTime = TimeSpan.FromSeconds(1 / 120.0); if (apply) _gdm.ApplyChanges(); } readonly Gfx.PostFx _post = new(); object? _shown; // zuletzt gezeigter Bildschirm (für das Überblenden) double _fadeIn = 1; // 0 → 1 nach einem Wechsel /// Spielstand sofort sichern (Absturz-Behandlung); Testläufe speichern ohnehin nie. public void SaveNow() => _game?.Save(); void ToggleFullscreen() { AppSettings.Fullscreen = !AppSettings.Fullscreen; AppSettings.Save(); SetMode(AppSettings.Fullscreen); _gdm.ApplyChanges(); } protected override void Initialize() { base.Initialize(); Window.ClientSizeChanged += (_, _) => { if (_gdm.IsFullScreen || Window.ClientBounds.Width < 64) return; _gdm.PreferredBackBufferWidth = Window.ClientBounds.Width; _gdm.PreferredBackBufferHeight = Window.ClientBounds.Height; _gdm.ApplyChanges(); }; } protected override void LoadContent() { _sb = new SpriteBatch(GraphicsDevice); _fx = new BasicEffect(GraphicsDevice) { TextureEnabled = true, VertexColorEnabled = true, LightingEnabled = false, World = Matrix.Identity }; Assets.Init(GraphicsDevice); Gfx.Model3D.PreloadAll(); // alle Figuren im Hintergrund vorbereiten _settings = new SettingsOverlay(ToggleFullscreen) { ApplyGraphics = () => ApplyFrameLimit(), Tutorial = () => _game == null ? null : _game.TutorialDone, ReplayTutorial = () => { if (_game != null) { _game.TutorialDone = false; _game.Save(); } } }; Window.TextInput += (_, e) => { if (!_settings.Open) _creator?.OnText(e.Character, e.Key); }; // eigener Spielstand fürs neue Spiel; vorhandenen laden und Abwesenheit nachrechnen GameState.SaveFile = "arena.json"; if (Model3DTest) { _model = new ModelTestScene(GraphicsDevice); return; } if (!DevShot.Active && GameState.Load(out var savedUtc) is GameState loaded) { _game = loaded; var away = _game.ApplyOffline((DateTime.UtcNow - savedUtc).TotalSeconds); if (away.Seconds >= 120) _welcome = away; // im Hub als erstes Fenster ToMenu(); } else if (!DevShot.Active) { _introThenCreate = true; _intro = new IntroScene(); } // erster Start: Intro else ToMenu(); } void ToMenu() { _hub = null; _scene = null; _creator = null; _intro = null; _freedom = null; _board = null; _paused = false; _nextLife = false; _menu = new MenuScene(_game != null, _game?.Freedoms ?? 0); SoundManager.StopAmbience(); } protected override void OnExiting(object sender, ExitingEventArgs args) { if (_game != null && _creator == null) { _game.Save(); Net.Leaderboard.Submit(_game); } // Testläufe speichern und senden nie base.OnExiting(sender, args); } /// Erstellung fertig: neues Leben mit dem eigenen Gladiator, dann in die Arena. void StartGame(CreatorScene c) { if (_nextLife && _game != null) { // nach der Freiheit: neues Leben im selben Profil (Legenden, Götter, Freiheiten bleiben) _nextLife = false; _game.Create(c.Name.Trim(), c.Class, c.Look, c.Bonus, c.StartSkill); } else { _game = new GameState(seed: DevShot.Active ? 7 : Environment.TickCount); _game.Create(c.Name.Trim(), c.Class, c.Look, c.Bonus, c.StartSkill); } // --sim H: weiter vorn einsteigen (Testläufe, Ausprobieren späterer Arenen) if (Array.IndexOf(Environment.GetCommandLineArgs(), "--sim") >= 0) Playtest.Advance(_game, DevShot.SimHours); // --duelarena N: gleich in Arena N (Kulisse prüfen) var cmd = Environment.GetCommandLineArgs(); int da = Array.IndexOf(cmd, "--duelarena"); if (da >= 0 && da + 1 < cmd.Length && int.TryParse(cmd[da + 1], out int arenaN)) _game.DevArena(arenaN); _game.Save(); _creator = null; var sw = Stopwatch.StartNew(); _hub = new HubScene(_game); DevShot.Log($"timing: hub created in {sw.ElapsedMilliseconds} ms"); } /// Letzter Champion besiegt: Freiheit annehmen (Legende, Gunst), dann der Freiheits-Bildschirm. void StartFreedom() { int favor = _game!.TakeFreedom(); if (favor <= 0 && _game.Legends.Count == 0) return; _game.Save(); Net.Leaderboard.Submit(_game); _hub = null; _scene = null; _paused = false; _freedom = new FreedomScene(_game, _game.Legends[^1], favor); _devTime = 0; } /// Duell gegen eine Legende aus der Ehrenhalle. void StartLegendDuel(Legend l) { _legend = l; _offer = null; _enemy = GameState.LegendEnemy(l); _before = _hub!.Snapshot(); _scene = new DuelScene(_game, _enemy, _seed++); if (DevShot.Active) _scene.Bot = new DuelBot(0.8, new Random(3)); DevShot.Log($"legend duel vs #{l.Number} {l.Name} ratio={_game.DuelRatio(_enemy):0.00}"); } /// Gegner gewählt: Duell beginnt. void StartDuel(Offer o) { _offer = o; _enemy = o.Enemy; _before = _hub!.Snapshot(); var sw = Stopwatch.StartNew(); _scene = new DuelScene(_game, _enemy, _seed++); DevShot.Log($"timing: duel created in {sw.ElapsedMilliseconds} ms"); // erster Kampf eines neuen Profils: Einführung (in Testläufen nur mit --tutorial) if (!_game.TutorialDone && o.Kind != OfferKind.Champion && (!DevShot.Active || DevTutorialRun)) _scene.StartTutorial(); if (DevShot.Active) _scene.Bot = new DuelBot(0.8, new Random(3)); DevShot.Log($"duel vs {_enemy.NameKey} ({o.Kind}) arena={_game.Arena} rank={_game.Rank} ratio={_game.DuelRatio(_enemy):0.00}"); } /// Duell vorbei: Ergebnis übernehmen, zurück in den Hub mit Meldung, speichern. void EndDuel() { bool won = _scene!.Won; if (_scene.TutorialRan) _game!.TutorialDone = true; if (_legend is Legend l) { bool first = _game!.ResolveLegendDuel(l, won); _hub!.ShowResult(new[] { L.t(won ? "duel.win" : "duel.lose"), first ? string.Format(L.t("hall.reward"), l.Name, GameState.LEGEND_FAVOR) : l.Name }, won ? Gfx.Draw.Gold : Gfx.Draw.Red); if (first) SoundManager.PlayAchievement(); _legend = null; } else { _game!.ResolveFight(_offer!, won); var lines = new System.Collections.Generic.List(_hub!.ResultLines(_before, won)); // Gnadenstoß: Folgen der Wahl bzw. Urteil des Publikums if (won && _scene.MercyChosen is bool mercy) { double bonus = _game.ApplyMissio(mercy, _scene.CrowdMercy, _game.FameRun - _before.Fame); lines.Add(mercy == _scene.CrowdMercy ? string.Format(L.t("missio.toast.match"), NumberFormat.Format(bonus)) : mercy ? string.Format(L.t("missio.toast.mercy"), NumberFormat.Format(bonus)) : L.t("missio.toast.against")); } else if (!won && _scene.Spared is bool spared) { _game.ApplyVerdict(spared); lines.Add(L.t(spared ? "missio.spared" : "missio.doomed")); } _hub.ShowResult(lines.ToArray(), won ? Gfx.Draw.Gold : Gfx.Draw.Red); if (won && _offer!.Enemy.IsChampion) Net.Leaderboard.Submit(_game); } SoundManager.StartAmbient("music_ludus"); _scene = null; _game.Save(); } // Speichern bald nach einem Klick außerhalb des Kampfs (Kauf, Anlegen, Lernen, Opfern, Expedition, // Entscheidung …): gebündelt, höchstens alle 2 s. Testläufe speichern nie (GameState.Save). double _saveSoon = -1, _clock, _lastSave = -9; void SaveSoon(float dt) { _clock += dt; if (_game == null || _creator != null) return; if (_scene == null && _input.LeftClick) _saveSoon = 0.6; if (_saveSoon < 0 || (_saveSoon -= dt) > 0) return; if (_clock - _lastSave < 2) { _saveSoon = 0.3; return; } _game.Save(); _lastSave = _clock; _saveSoon = -1; } /// Fenster verliert den Fokus (Alt+Tab, minimiert): sofort speichern. protected override void OnDeactivated(object sender, EventArgs args) { if (_game != null && _creator == null) { _game.Save(); _lastSave = _clock; } base.OnDeactivated(sender, args); } readonly Stopwatch _updWatch = new(); double _updMs; Matrix UiMatrix(out float s, out Vector2 off) { s = Math.Min(GraphicsDevice.Viewport.Width / Camera.W, GraphicsDevice.Viewport.Height / Camera.H); off = new Vector2((GraphicsDevice.Viewport.Width - Camera.W * s) / 2, (GraphicsDevice.Viewport.Height - Camera.H * s) / 2); return Matrix.CreateScale(s) * Matrix.CreateTranslation(off.X, off.Y, 0); } protected override void Update(GameTime gameTime) { _updWatch.Restart(); float dt = (float)Math.Min(0.05, gameTime.ElapsedGameTime.TotalSeconds); ClipCache.Pump(GraphicsDevice, 4); // Video-Sprites nachladen (höchstens 4 ms pro Bild) _input.PrevKeys = _input.Keys; _input.PrevMouse = _input.Mouse; _input.Keys = Keyboard.GetState(); _input.Mouse = IsActive ? Mouse.GetState() : default; _input.PrevPad = _input.Pad; _input.Pad = IsActive ? GamePad.GetState(PlayerIndex.One) : default; _input.DetectDevice(); var ui = UiMatrix(out _, out _); Window.Title = L.t("app.title"); // Einstellungen liegen über allem und nehmen die Eingaben var input = _input; if (_settings.Open) { _settings.Update(_input, ui); input = _noInput; } SaveSoon(dt); if (DevShot.Active) DevMenu(dt); if (_model != null) { _model.Update(dt, input); if (input.Pressed(Keys.Escape)) Exit(); if (DevShot.Active) DevModel(dt); } else if (_board != null) { _board.Update(dt, input, ui); if (DevShot.Active) DevBoard(dt); if (_board != null && _board.Done) ToMenu(); } else if (_freedom != null) { _freedom.Update(dt, input, ui); if (DevShot.Active) DevFreedom(dt); if (_freedom != null && _freedom.Done) { // der nächste Gladiator: Erstellung im selben Profil _freedom = null; _nextLife = true; _creator = new CreatorScene(DevShot.Active ? DevShot.Name : L.t("gladiator.defaultname")); _devTime = 0; } } else if (_intro != null) { _intro.Update(dt, input, ui); if (_intro.Done) { _intro = null; if (_introThenCreate) { _introThenCreate = false; _creator = new CreatorScene(L.t("gladiator.defaultname")); } else ToMenu(); } } else if (_menu != null) { _menu.Update(dt, input, ui, _settings.Open); switch (_menu.Picked) { case MenuScene.Choice.Continue when _game != null: _menu = null; _hub = new HubScene(_game) { Welcome = _welcome }; _welcome = null; break; case MenuScene.Choice.New: _menu = null; _creator = new CreatorScene(DevShot.Active ? DevShot.Name : L.t("gladiator.defaultname")); break; case MenuScene.Choice.Intro: _menu = null; _intro = new IntroScene(); break; case MenuScene.Choice.Leaderboard: _menu = null; _board = new LeaderboardScene(_game); if (DevShot.Active) _board.DevSample(_game); break; case MenuScene.Choice.Settings: _menu.Picked = MenuScene.Choice.None; _settings.Open = true; break; case MenuScene.Choice.Quit: Exit(); break; } if (_menu != null && input.Pressed(Keys.Escape)) Exit(); } else if (_creator != null) { _creator.Update(dt, input, ui); if (input.Pressed(Keys.Escape)) ToMenu(); if (DevShot.Active) DevCreator(dt); if (_creator != null && _creator.Done) StartGame(_creator); } else if (_scene == null && _hub != null) { // Arena zwischen den Kämpfen; Esc: Schublade zu, sonst Pause-Menü if ((_saveIn -= dt) <= 0) { _saveIn = 30; _game!.Save(); } bool drawer = _hub.DrawerOpen; _hub.Update(dt, _paused ? _noInput : input, ui); if (!drawer && !_settings.Open && input.Pressed(Keys.Escape)) _paused = !_paused; if (_paused) _pauseUi.Begin(input, ui); if (DevShot.Active) DevHub(dt); if (_hub?.Chosen is Offer o) { _hub.Chosen = null; StartDuel(o); } else if (_hub?.ChosenLegend is Legend lg) { _hub.ChosenLegend = null; StartLegendDuel(lg); } else if (_hub != null && _game!.FreedomEarned && !_settings.Open) StartFreedom(); } else if (_scene != null) { if ((_saveIn -= dt) <= 0) { _saveIn = 30; _game!.Save(); } if (!IsActive && !DevShot.Active && !_scene.Over) _scene.Paused = true; // Fenster verlassen: Pause if ((input.Pressed(Keys.Escape) || input.PadPressed(Buttons.Start)) && !_scene.Over) _scene.Paused = !_scene.Paused; if (_scene.Paused && input.Pressed(Keys.X)) _scene.GiveUp(); _game!.Tick(dt); // Training läuft auch im Kampf weiter _scene.Update(dt, input, ui); if (DevShot.Active) DevSteps(dt); if (_scene != null && _scene.Finished && (input.Pressed(Keys.Enter) || input.LeftClick || DevShot.Active && _shots.Contains("m_end") && _capture == null)) EndDuel(); } base.Update(gameTime); _updMs += _updWatch.Elapsed.TotalMilliseconds; } /// Pause-Menü in der Arena: Weiter / Einstellungen / Hauptmenü / Beenden. void DrawPause(SpriteBatch sb, Matrix ui) { sb.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearClamp, null, null, null, ui); Gfx.Draw.Rect(sb, new RectangleF(0, 0, Camera.W, Camera.H), Color.Black * 0.6f); Gfx.Draw.Text(sb, Assets.Serif, 100, L.t("duel.pause").ToUpperInvariant(), new Vector2(Camera.W / 2, 300), Gfx.Draw.Gold, Align.Center); float w = 460, h = 70, x = (Camera.W - w) / 2, y = 420; if (_pauseUi.Button(sb, new RectangleF(x, y, w, h), L.t("duel.resume"), selected: true, size: 28)) _paused = false; if (_pauseUi.Button(sb, new RectangleF(x, y + 90, w, h), L.t("main.settings"), size: 26)) _settings.Open = true; if (_pauseUi.Button(sb, new RectangleF(x, y + 180, w, h), L.t("pause.menu"), size: 26)) { _game!.Save(); ToMenu(); } if (_pauseUi.Button(sb, new RectangleF(x, y + 270, w, h), L.t("main.quit"), size: 26)) Exit(); sb.End(); } // ── Testläufe ─────────────────────────────────────────────── /// Testlauf: Menü und Einstellungen aufnehmen (mit --full auch das Intro), dann Neuer Gladiator. void DevMenu(float dt) { if (_menu == null && _intro == null) return; _devTime += dt; void Shot(string name) { if (_shots.Add(name)) _capture = name; } if (_intro != null) { var times = _intro.CaptureTimes(); int k = _shots.Count(s => s.StartsWith("i_")); if (k < times.Length && _capture == null) { _intro.Time = times[k]; Shot($"i_{k}"); } else if (k >= times.Length && _capture == null) { _intro = null; _devTime = 0; ToMenu(); } return; } if (_devTime > 1.0) Shot("c_menu"); if (_devTime > 1.4 && !_shots.Contains("c_settings_open")) { _shots.Add("c_settings_open"); _settings.Open = true; } if (_devTime > 1.9) Shot("c_settings"); if (_devTime > 2.3 && _capture == null && _settings.Open) _settings.Open = false; if (_devTime > 2.5 && _capture == null && DevShot.Full && !_shots.Contains("i_intro")) { _shots.Add("i_intro"); _menu = null; _intro = new IntroScene(); return; } if (DevBoardRun && _devTime > 1.2 && _capture == null && _menu != null) { _menu.Picked = MenuScene.Choice.Leaderboard; _devTime = 0; return; } if (_devTime > 2.6 && _capture == null && _menu != null) { _menu.Picked = MenuScene.Choice.New; _devTime = 0; } } /// --model3d im Testlauf: Ansichten (vorn, schräg, Seite) und je ein Bild pro Bewegung. int _mStep; double _mWait; bool _mArmed; void DevModel(float dt) { var m = _model!; if (m.Model == null) { DevShot.Log("model3d: no model"); Exit(); return; } if (_capture != null) return; var clips = m.Model.Clips; // --clip=: 8 Bilder über eine Bewegung verteilt (Seitenansicht), mit Treffermoment im Protokoll var only = Array.Find(Environment.GetCommandLineArgs(), a => a.StartsWith("--clip="))?.Substring(7); int ci = only == null ? -1 : clips.FindIndex(c => c.Name == only); if (ci >= 0) { float impact = m.Model.ImpactTime(clips[ci]); if (_mStep >= 9) { DevShot.Log($"model3d clip {only}: length {clips[ci].Length:0.00} impact {impact:0.00}"); Exit(); return; } if (!_mArmed) { m.Paused = true; m.SetView(2); m.Color = -1; m.Play(ci); m.Time = _mStep == 8 ? impact : clips[ci].Length * _mStep / 7f; _mArmed = true; _mWait = 0.35; return; } if ((_mWait -= dt) > 0) return; _capture = $"clip_{_mStep}"; _mStep++; _mArmed = false; return; } if (_mStep >= 3 + clips.Count) { DevShot.Log($"model3d: {clips.Count} clips, {m.Model.BoneCount} bones, {m.Model.Vertices.Length} vertices, {m.Model.Indices.Length / 3} triangles, draw {_drawMs / Math.Max(1, _frames):0.00} ms/frame"); Exit(); return; } if (!_mArmed) { m.Paused = true; if (_mStep < 3) { m.SetView(_mStep); m.Color = _mStep == 2 ? 1 : -1; m.Play(clips.FindIndex(c => c.Name == "idle")); m.Time = 1f; } else { int i = _mStep - 3; m.SetView(1); m.Color = -1; m.Play(i); m.Time = clips[i].Length * 0.45f; } _mArmed = true; _mWait = 0.35; return; } if ((_mWait -= dt) > 0) return; _capture = _mStep < 3 ? $"m3_view{_mStep}" : $"m3_{_mStep - 2:00}_{clips[_mStep - 3].Name}"; _mStep++; _mArmed = false; } /// Testlauf: Erstellung aufnehmen (Grundeinstellung, dann eine eigene Zusammenstellung). void DevCreator(float dt) { _devTime += dt; void Shot(string name) { if (_shots.Add(name)) _capture = name; } if (_devTime > 1.0) Shot("c_creator"); if (_devTime > 1.6 && !_shots.Contains("c_pick")) { _shots.Add("c_pick"); _creator!.DevPick(DevShot.Class, int.TryParse(Environment.GetEnvironmentVariable("GI_PRESET"), out int pr) ? pr : 1, 1, 2); } if (_devTime > 2.6) Shot("c_custom"); if (_devTime > 3.2 && _capture == null) { _creator!.Finish(); _devTime = 0; } } /// Testlauf: Arena aufnehmen, Schubladen öffnen, Gegner wählen; nach dem Kampf Ergebnis, Pause, dann Ende. void DevHub(float dt) { _devTime += dt; void Shot(string name) { if (_shots.Add(name)) _capture = name; } if (DevFreedomRun && _game!.Legends.Count == 0 && _devTime > 0.5) { _game.DevFreedom(); return; } if (DevFreedomRun && _game!.Legends.Count > 0 && !_shots.Contains("m_end")) { if (_devTime > 0.8 && !_shots.Contains("h_hall_open")) { _shots.Add("h_hall_open"); _hub!.DevOpen("hall"); } if (_devTime > 1.5) Shot("h_hall"); if (_devTime > 1.8 && _capture == null && _shots.Contains("h_hall")) { _hub!.DevOpen("none"); _hub.ChosenLegend = _game.Legends[0]; _devTime = 0; } return; } if (Array.IndexOf(Environment.GetCommandLineArgs(), "--welcome") >= 0) { if (_devTime > 0.5 && !_shots.Contains("w_set")) { _shots.Add("w_set"); _hub!.Welcome = new OfflineReport(3 * 3600 + 1240, 1840, 96, 0, 0, 7); } if (_devTime > 1.2) Shot("w_welcome"); if (_devTime > 1.6 && _capture == null && _shots.Contains("w_welcome")) Exit(); return; } if (DevAdventureRun) { // Expeditionen: Feldzugkarte, Aufbruch, Karte unterwegs, Reise in 3D zu vier Tageszeiten, // Rückkehr-Bericht; dann ein Ereignis mit Entscheidung if (_devTime > 0.8 && !_shots.Contains("x_open")) { _shots.Add("x_open"); _hub!.DevOpen("expedition"); } if (_devTime > 1.6) Shot("x_map"); if (_devTime > 1.9 && !_shots.Contains("x_go")) { _shots.Add("x_go"); _game!.StartExpedition("gallia", 1); _game.Tick(700); } if (_devTime > 2.6) Shot("x_map_away"); if (_devTime > 2.9 && !_shots.Contains("x_jopen")) { _shots.Add("x_jopen"); _hub!.DevOpen("journey"); _hub.DevDayPhase = 0.1f; } if (_devTime > 4.2) Shot("x_journey_morning"); if (_devTime > 4.4 && !_shots.Contains("x_noon")) { _shots.Add("x_noon"); _hub!.DevDayPhase = 0.3f; } if (_devTime > 5.0) Shot("x_journey_noon"); if (_devTime > 5.2 && !_shots.Contains("x_dusk")) { _shots.Add("x_dusk"); _hub!.DevDayPhase = 0.52f; } if (_devTime > 5.8) Shot("x_journey_dusk"); if (_devTime > 6.0 && !_shots.Contains("x_night")) { _shots.Add("x_night"); _hub!.DevDayPhase = 0.78f; } if (_devTime > 6.8) Shot("x_journey_night"); if (_devTime > 7.0 && !_shots.Contains("x_close")) { _shots.Add("x_close"); _hub!.DevOpen("none"); _hub.DevDayPhase = null; } if (_devTime > 7.6) Shot("x_away"); if (_devTime > 7.9 && !_shots.Contains("x_back")) { _shots.Add("x_back"); _game!.DevExpeditionOutcome = true; _game.Tick(Adventures.Durations[1] + 1); } // Heimkehr (Erfolg): Lauf, Titel und Tagebuch, Karten, fertig if (_devTime > 8.8) Shot("x_home_walk"); if (_devTime > 11.4) Shot("x_home_title"); if (_devTime > 14.2) Shot("x_home_cards"); if (_devTime > 19.0) Shot("x_home_done"); if (_devTime > 19.3 && !_shots.Contains("x_fail_go")) { _shots.Add("x_fail_go"); _game!.DismissExpeditionResult(); _game.DevExpeditionOutcome = false; _game.StartExpedition("gallia", 0); _game.Tick(Adventures.Durations[0] + 1); } if (_devTime > 25.0) Shot("x_home_fail"); if (_devTime > 25.3 && !_shots.Contains("x_event")) { _shots.Add("x_event"); _game!.DismissExpeditionResult(); _game.DevExpeditionOutcome = null; _game.DevEvent("nightduel"); } if (_devTime > 26.0) Shot("x_eventcard"); if (_devTime > 26.3 && !_shots.Contains("x_choose")) { _shots.Add("x_choose"); _game!.Choose(0); } if (_devTime > 26.7 && _capture == null && _shots.Contains("x_choose")) { DevShot.Log($"adventure: buffs={_game!.Buffs.Count} gold={_game.Gold:0}"); Exit(); } return; } if (DevChampionRun && !_shots.Contains("m_end")) { if (_devTime > 0.5 && _capture == null) { _hub!.Chosen = new Offer(_game!.ChampionEnemy, 1, OfferKind.Champion); _devTime = 0; } return; } if (!_shots.Contains("m_end")) { if (_devTime > 1.0) Shot("h_hub"); if (_devTime > 1.5 && !_shots.Contains("h_pick")) { _shots.Add("h_pick"); _hub!.DevOpen("gladiator"); } if (_devTime > 2.2) Shot("h_gladiator"); if (_devTime > 2.6 && !_shots.Contains("h_ludus_open")) { _shots.Add("h_ludus_open"); _hub!.DevOpen("ludus"); } if (_devTime > 3.3) Shot("h_ludus"); if (_devTime > 3.5 && !_shots.Contains("h_forum_open")) { _shots.Add("h_forum_open"); _hub!.DevOpen("gladiator"); } if (_devTime > 4.2) Shot("h_forum"); if (_devTime > 4.4 && !_shots.Contains("h_skills_open")) { _shots.Add("h_skills_open"); _hub!.DevOpen("skills"); } if (_devTime > 5.1) Shot("h_skills"); if (_devTime > 5.3 && !_shots.Contains("h_hall_tab")) { _shots.Add("h_hall_tab"); _hub!.DevOpen("hall"); } if (_devTime > 6.0) Shot("h_hall2"); if (_devTime > 6.2 && !_shots.Contains("h_exp_tab")) { _shots.Add("h_exp_tab"); _hub!.DevOpen("expedition"); } if (_devTime > 6.9) Shot("h_exp"); if (_devTime > 7.3 && _capture == null) { _hub!.DevOpen("none"); var offers = _game!.Offers(); _hub.Chosen = offers[Math.Min(1, offers.Count - 1)]; _devTime = 0; } } else { if (_devTime > 0.6) Shot("h_result"); if (_devTime > 0.8 && !_shots.Contains("h_inv_open")) { _shots.Add("h_inv_open"); _hub!.DevOpen("gladiator"); } if (_devTime > 1.4) Shot("h_inventory"); if (_devTime > 1.6 && !_shots.Contains("h_pause_open")) { _shots.Add("h_pause_open"); _hub!.DevOpen("none"); _paused = true; } if (_devTime > 2.0) Shot("h_pause"); if (_shots.Contains("h_pause") && _capture == null && _devTime > 2.2) { DevShot.Log($"after duel: arena={_game!.Arena} rank={_game.Rank} gold={_game.Gold:0} fame={_game.FameRun:0} wins={_game.Wins} " + $"draw hub {_hubDraw / Math.Max(1, _hubFrames):0.00} ms, duel {_duelDraw / Math.Max(1, _duelFrames):0.00} ms at {GraphicsDevice.PresentationParameters.BackBufferWidth}x{GraphicsDevice.PresentationParameters.BackBufferHeight}"); Exit(); } } } /// Testlauf --leaderboard: beide Wertungen aufnehmen (Beispieldaten), dann Ende. void DevBoard(float dt) { _devTime += dt; void Shot(string name) { if (_shots.Add(name)) _capture = name; } if (_devTime > 1.0) Shot("l_power"); if (_devTime > 1.4 && _capture == null && _shots.Contains("l_power") && !_shots.Contains("l_tab")) { _shots.Add("l_tab"); typeof(LeaderboardScene).GetField("_tab", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.SetValue(_board, 1); } if (_devTime > 2.0) Shot("l_fastest"); if (_devTime > 2.4 && _capture == null && _shots.Contains("l_fastest")) Exit(); } /// Testlauf --freedom: Clip, Bilanz und Götter aufnehmen, dann weiter zum nächsten Leben. void DevFreedom(float dt) { _devTime += dt; void Shot(string name) { if (_shots.Add(name)) _capture = name; } if (_devTime > 2.5) Shot("f_clip"); if (_devTime > 2.7 && !_shots.Contains("f_sum_open")) { _shots.Add("f_sum_open"); _freedom!.DevShow(1, 0.2f); } if (_devTime > 4.2) Shot("f_summary"); if (_devTime > 4.4 && !_shots.Contains("f_gods_open")) { _shots.Add("f_gods_open"); _freedom!.DevShow(2, 0.5f); } if (_devTime > 5.0) Shot("f_gods"); if (_devTime > 5.3 && _capture == null && _shots.Contains("f_gods")) _freedom!.DevDone(); } /// Testlauf: Bot kämpft; Aufnahmen an markanten Stellen. void DevSteps(float dt) { _devTime += dt; var d = _scene!.Duel; if (Perf) { PerfStep(); return; } void Shot(string name) { if (_shots.Add(name)) _capture = name; } if (_scene.InIntro) { if (_devTime > 2.5) Shot("m_champintro"); return; } if (_scene.Tutorial != DuelScene.TutStep.Off) { Shot("t_" + _scene.Tutorial.ToString().ToLowerInvariant()); } if (_devTime > 0.5) Shot("m_countdown"); if (d.Time > 0.6) Shot("m_fight"); if (d.Enemy.State == DuelState.Windup && d.Enemy.StateTime > d.Enemy.Windup * 0.6) Shot("m_telegraph"); if (d.Player.State == DuelState.Strike) Shot("m_strike"); // --record: Bildserie eines ganzen Schlags (Ausholen bis Erholung), für die Prüfung der Animation if (Record && _rec < 0 && d.Player.State == DuelState.Windup && d.Time > 2) _rec = 0; if (_rec >= 0 && _rec < 48 && _capture == null) { _capture = $"rec_{_rec:D2}"; _rec++; } if (d.Player.State == DuelState.Leap && d.Player.StateTime > 0.3) Shot("m_leap"); if (d.Player.State == DuelState.Leap && d.Player.StateTime > 0.52) Shot("m_leap_hit"); if (d.Player.State == DuelState.Super && d.Player.StateTime > 0.35) Shot("m_super_charge"); if (d.Player.State == DuelState.Super && d.Player.StateTime > 1.22) Shot("m_super_hit"); if (d.Player.Rage >= 100) Shot("m_rage_full"); if (d.Enemy.State == DuelState.Hit && d.Enemy.StateTime < 0.03) Shot("m_hit"); if (d.Player.State == DuelState.Block && d.Player.StateTime > 0.1) Shot("m_block"); if (d.Player.State == DuelState.Hit && d.Player.StateTime < 0.03) Shot("m_hurt"); if (_scene.Over && !_shots.Contains("m_ko")) Shot("m_ko"); if (_scene.MissioTime > 2.2f) Shot("m_missio_vote"); if (_scene.MissioTime > 3.6f) Shot("m_missio_choice"); if (_scene.Finished) Shot("m_end"); if (_shots.Contains("m_end") && _capture == null && !_shots.Contains("m_logged")) { _shots.Add("m_logged"); DevShot.Log($"duel done: won={_scene.Won} time={d.Time:0.0}s"); _devTime = 0; } } /// --perf: 15 s Kampf ohne Aufnahmen, Bildzeiten messen (Mittel, 95. Perzentil). static readonly bool Perf = Array.IndexOf(Environment.GetCommandLineArgs(), "--perf") >= 0; static readonly bool Record = Array.IndexOf(Environment.GetCommandLineArgs(), "--record") >= 0; readonly System.Collections.Generic.List _times = new(); int _gcStart = -1, _duelsStarted; void PerfStep() { if (_devTime > 3) { if (_gcStart < 0) { _gcStart = GC.CollectionCount(0); _duelDraw = 0; _duelFrames = 0; } _times.Add(_lastFrameMs); } // nach jedem Kampf sofort ein neuer: misst auch den Ruckler beim Duellstart if (_scene!.Over) { var o = _offer!; EndDuel(); StartDuel(o); _duelsStarted++; } if (_devTime < 18) return; _times.Sort(); double avg = 0; foreach (var t in _times) avg += t; avg /= Math.Max(1, _times.Count); DevShot.Log($"perf {GraphicsDevice.PresentationParameters.BackBufferWidth}x{GraphicsDevice.PresentationParameters.BackBufferHeight}: " + $"avg {avg:0.0} ms ({1000 / avg:0} fps), p95 {_times[(int)(_times.Count * 0.95)]:0.0} ms, p99 {_times[(int)(_times.Count * 0.99)]:0.0} ms, " + $"max {_times[^1]:0.0} ms, draw {_duelDraw / Math.Max(1, _duelFrames):0.00} ms, gc0 {GC.CollectionCount(0) - _gcStart}, " + $"duels restarted {_duelsStarted}, frames {_times.Count}"); Exit(); } double _lastFrameMs; // ── Zeichnen ──────────────────────────────────────────────── protected override void Draw(GameTime gameTime) { _drawWatch.Restart(); if (_frames == 0 && DevShot.Active) DevShot.Log($"timing: first frame {(DateTime.Now - System.Diagnostics.Process.GetCurrentProcess().StartTime).TotalMilliseconds:0} ms after start"); bool capturing = _capture != null; var gd = GraphicsDevice; int w = gd.PresentationParameters.BackBufferWidth, h = gd.PresentationParameters.BackBufferHeight; bool toTarget = _capture != null && DevShot.Dir != null; // nur für Aufnahmen über ein Zwischenbild if (toTarget && (_rt == null || _rt.Width != w || _rt.Height != h)) { _rt?.Dispose(); _rt = new RenderTarget2D(gd, w, h, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8); } // Bild entsteht in einer Zwischenfläche (Kantenglättung), danach Nachleuchten _post.Begin(gd, w, h, AppSettings.AntiAlias); gd.Clear(Color.Black); float scale = Math.Min(w / Camera.W, h / Camera.H); var offset = new Vector2((w - Camera.W * scale) / 2, (h - Camera.H * scale) / 2); var ui = Matrix.CreateScale(scale) * Matrix.CreateTranslation(offset.X, offset.Y, 0); Gfx.Draw.UiScale = scale; if (_model != null) _model.Draw(gd, _sb, scale, offset); else if (_freedom != null) _freedom.Draw(gd, _sb, _fx, scale, offset); else if (_board != null) _board.Draw(_sb, scale, offset); else if (_intro != null) _intro.Draw(_sb, scale, offset); else if (_menu != null) _menu.Draw(_sb, scale, offset); else if (_creator != null) _creator.Draw(gd, _sb, _fx, scale, offset); else if (_scene != null) _scene.Draw(gd, _sb, _fx, scale, offset); else if (_hub != null) { _hub.Draw(gd, _sb, _fx, scale, offset); if (_paused && !_settings.Open) DrawPause(_sb, ui); } // weicher Wechsel zwischen Bildschirmen: neues Bild kommt kurz aus dem Schwarz object? now = (object?)_model ?? _freedom ?? (object?)_board ?? _intro ?? (object?)_menu ?? _creator ?? (object?)_scene ?? _hub; if (!ReferenceEquals(now, _shown)) { _shown = now; _fadeIn = 0; } _fadeIn = Math.Min(1, _fadeIn + gameTime.ElapsedGameTime.TotalSeconds / 0.3); if (_fadeIn < 1) { _sb.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, ui); Gfx.Draw.Rect(_sb, new Gfx.RectangleF(0, 0, Camera.W, Camera.H), Color.Black * (float)(1 - _fadeIn * _fadeIn * (3 - 2 * _fadeIn))); _sb.End(); } if (_settings.Open) _settings.Draw(_sb, scale, offset); bool bloomOn = AppSettings.Bloom && !AppSettings.ReduceMotion && _intro == null; _post.End(gd, _sb, toTarget ? _rt : null, bloomOn ? 1f : 0f); if (toTarget) { gd.SetRenderTarget(null); if (_capture != null && DevShot.Dir != null) { using (var fs = File.Create(Path.Combine(DevShot.Dir, _capture + ".png"))) _rt!.SaveAsPng(fs, w, h); _capture = null; } _sb.Begin(); _sb.Draw(_rt, Vector2.Zero, Color.White); _sb.End(); } _drawMs += _drawWatch.Elapsed.TotalMilliseconds; _frames++; if (capturing) { } // Bilder mit Aufnahme (PNG speichern) nicht mitzählen else if (_scene != null) { _duelDraw += _drawWatch.Elapsed.TotalMilliseconds; _duelFrames++; } else if (_hub != null) { _hubDraw += _drawWatch.Elapsed.TotalMilliseconds; _hubFrames++; } _frameSum += gameTime.ElapsedGameTime.TotalMilliseconds; _lastFrameMs = gameTime.ElapsedGameTime.TotalMilliseconds; base.Draw(gameTime); } } }