From 84fcbee3b6e78ea1983c521b7243f45baa6c3a51 Mon Sep 17 00:00:00 2001 From: Aaron Carter <89698828+atcarter714@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:19:28 -0600 Subject: [PATCH] Give Fleet Battler shipyards, timed research and faction-aware fleets --- samples/FleetBattler/BattleDraw.cs | 2 +- samples/FleetBattler/CommandSelection.cs | 11 +- samples/FleetBattler/Factions.cs | 24 ++ samples/FleetBattler/FleetCombat.cs | 24 +- samples/FleetBattler/FleetGroups.cs | 61 +++++ samples/FleetBattler/FleetHud.cs | 80 ++++-- samples/FleetBattler/FleetSimulation.cs | 54 ++-- samples/FleetBattler/Frontier.cs | 127 +-------- samples/FleetBattler/FrontierHud.cs | 195 +++++++------- samples/FleetBattler/Industry.cs | 178 +++++++++++++ samples/FleetBattler/IndustryHud.cs | 151 +++++++++++ samples/FleetBattler/OperationsFeedback.cs | 32 ++- samples/FleetBattler/OrbitalNavigation.cs | 9 +- samples/FleetBattler/PlanetEconomy.cs | 109 +++----- samples/FleetBattler/PlanetInspector.cs | 112 ++++---- samples/FleetBattler/Program.cs | 208 ++++++++++----- samples/FleetBattler/README.md | 67 ++--- samples/FleetBattler/SiteConstruction.cs | 99 ++++++++ .../FleetQualification.cs | 240 +++++++++++------- .../InteropQualification.csproj | 5 + 20 files changed, 1170 insertions(+), 618 deletions(-) create mode 100644 samples/FleetBattler/Factions.cs create mode 100644 samples/FleetBattler/FleetGroups.cs create mode 100644 samples/FleetBattler/Industry.cs create mode 100644 samples/FleetBattler/IndustryHud.cs create mode 100644 samples/FleetBattler/SiteConstruction.cs diff --git a/samples/FleetBattler/BattleDraw.cs b/samples/FleetBattler/BattleDraw.cs index 212f739..746dd1f 100644 --- a/samples/FleetBattler/BattleDraw.cs +++ b/samples/FleetBattler/BattleDraw.cs @@ -9,7 +9,7 @@ internal static class BattleDraw { internal const uint EffectStride = 32; internal const uint ConstantCount = 20; internal const int RouteSegments = 48, RouteCapacity = RouteSegments + 1; - internal const int SiteEffectCapacity = 2 * CelestialSystem.BodyCount; + internal const int SiteEffectCapacity = (FleetSimulation.FacilityCount + 2) * CelestialSystem.BodyCount; private const int OrbitSegments = 72; internal const int SolarTrackCapacity = (CelestialSystem.BodyCount - CelestialSystem.FrontierBodyCount) * OrbitSegments; diff --git a/samples/FleetBattler/CommandSelection.cs b/samples/FleetBattler/CommandSelection.cs index 6bffdb5..0255786 100644 --- a/samples/FleetBattler/CommandSelection.cs +++ b/samples/FleetBattler/CommandSelection.cs @@ -59,8 +59,11 @@ internal void Click( FleetSimulation fleet, int ship, bool squad, SelectionMode internal void Squadron( FleetSimulation fleet, int squad, SelectionMode mode ) { if ( mode == SelectionMode.Replace ) Clear( ); - for ( int i = 0; i < fleet.Count; ++i ) - if ( fleet.Alive( i ) && fleet.SideOf( i ) == 0 && fleet.SquadronOf( i ) == squad ) Include( fleet, i, mode ); + if ( (uint)squad < (uint)fleet.SquadCount ) { + int id = fleet.FleetId( squad ); + for ( int i = 0; i < fleet.Count; ++i ) + if ( fleet.Alive( i ) && fleet.SideOf( i ) == 0 && fleet.FleetId( fleet.SquadronOf( i ) ) == id ) Include( fleet, i, mode ); + } Prune( fleet ); } @@ -86,7 +89,9 @@ internal static int Hit( FleetSimulation fleet, Vector2 pixel, Matrix4x4 viewPro float best = MathF.Pow( MathF.Max( 11, dimensions.Y * 0.013f ), 2 ); int result = -1; for ( int i = 0; i < fleet.Count; ++i ) { - if ( !fleet.Alive( i ) || fleet.SideOf( i ) != faction ) continue; + if ( !fleet.Alive( i ) ) continue; + int side = fleet.SideOf( i ); + if ( faction == -2 ? !fleet.IsHostile( (int)FactionId.Sol, side ) : faction >= 0 && side != faction ) continue; float distance = Vector2.DistanceSquared( pixel, Project( fleet.VisualPosition( i, interpolation ), viewProjection, dimensions ) ); if ( distance >= best ) continue; best = distance; diff --git a/samples/FleetBattler/Factions.cs b/samples/FleetBattler/Factions.cs new file mode 100644 index 0000000..6826478 --- /dev/null +++ b/samples/FleetBattler/Factions.cs @@ -0,0 +1,24 @@ +using System.Numerics; + +namespace FleetBattler; + +internal enum FactionId { Sol, Raiders, Merchants, Rival, Count } +internal enum Disposition { Allied, Neutral, Hostile } + +internal static class Factions { + internal static string Name( FactionId id ) => id switch { + FactionId.Sol => "SOL AUTHORITY", FactionId.Raiders => "AMBER RAIDERS", + FactionId.Merchants => "FREE MERCHANTS", _ => "RIVAL COMMAND" + }; + + internal static Disposition Attitude( FactionId from, FactionId toward ) => from == toward ? Disposition.Allied + : from == FactionId.Raiders || toward == FactionId.Raiders || + from is FactionId.Sol && toward is FactionId.Rival || from is FactionId.Rival && toward is FactionId.Sol + ? Disposition.Hostile : Disposition.Neutral; + + internal static Vector4 ShipTint( FactionId id ) => id switch { + FactionId.Sol => new( 0.66f, 1.55f, 2.25f, 1.04f ), + FactionId.Merchants => new( 0.82f, 1.42f, 0.97f, 1 ), + _ => new( 2.9f, 0.89f, 0.37f, 1.11f ) + }; +} diff --git a/samples/FleetBattler/FleetCombat.cs b/samples/FleetBattler/FleetCombat.cs index 3b6e4dc..a4d3547 100644 --- a/samples/FleetBattler/FleetCombat.cs +++ b/samples/FleetBattler/FleetCombat.cs @@ -14,15 +14,18 @@ internal sealed partial class FleetSimulation { private readonly ushort[] _railIncoming; private readonly int[] _lastHit; private readonly int[] _nextShot; - private readonly int[] _factionCount = new int[2]; + private readonly int[] _factionCount = new int[(int)FactionId.Count]; private readonly CombatEvent[] _events = new CombatEvent[EffectCapacity]; private int _eventCursor, _eventCount; private readonly record struct CombatEvent( Vector2 From, Vector2 To, int Tick, int Faction, bool Burst, WeaponKind Weapon ); - internal int ActiveCount => CyanCount + AmberCount; + internal int ActiveCount => CyanCount + AmberCount + MerchantCount; internal int CyanCount => _factionCount[0]; - internal int AmberCount => _factionCount[1]; + internal int AmberCount => _factionCount[(int)FactionId.Raiders] + _factionCount[(int)FactionId.Rival]; + internal int MerchantCount => _factionCount[(int)FactionId.Merchants]; + internal FactionId FactionOf( int ship ) => (FactionId)SideOf( ship ); + internal bool IsHostile( int from, int toward ) => Factions.Attitude( (FactionId)from, (FactionId)toward ) == Disposition.Hostile; internal int ShotsFired { get; private set; } internal int ShipsLost { get; private set; } internal int LastEngagementTick { get; private set; } = -10_000; @@ -39,7 +42,7 @@ internal sealed partial class FleetSimulation { internal void Attack( FleetSelection selection, int target ) { if ( Frontier && Role( selection.Squad ) != HullRole.Corvette ) return; - if ( !Alive( target ) || _squads[selection.Squad].Faction == SideOf( target ) ) return; + if ( !Alive( target ) || !IsHostile( _squads[selection.Squad].Faction, SideOf( target ) ) ) return; SetOrder( selection, new Order { Enemy = target + 1, Target = _positions[target], Detached = selection.IsShip } ); @@ -47,12 +50,12 @@ internal void Attack( FleetSelection selection, int target ) { private Vector2 Chase( ref Order order, Vector2 from, int faction, out Vector2 facing ) { int target = order.Enemy - 1; - if ( !Alive( target ) ) { + if ( !Alive( target ) || !IsHostile( faction, SideOf( target ) ) ) { int squad = _squadOfShip[target]; var unit = _squads[squad]; target = -1; for ( int i = unit.First; i < unit.First + unit.Count; ++i ) { - if ( !Alive( i ) ) continue; + if ( !Alive( i ) || !IsHostile( faction, SideOf( i ) ) ) continue; target = i; break; } @@ -117,7 +120,7 @@ private void ResolveVolley( ) { var weapon = Frontier ? design.Weapon : WeaponKind.Pulse; float range = Frontier ? design.Range + (side == 0 && WeaponUpgrade ? 3 : 0) : side == 0 && WeaponUpgrade ? 19 : 16; int preferred = (_shipOrders[ship].Detached ? _shipOrders[ship].Enemy : _squads[_squadOfShip[ship]].Order.Enemy) - 1; - int target = Alive( preferred ) && Vector2.DistanceSquared( _positions[preferred], _positions[ship] ) <= range * range + int target = Alive( preferred ) && IsHostile( side, SideOf( preferred ) ) && Vector2.DistanceSquared( _positions[preferred], _positions[ship] ) <= range * range ? preferred : ClosestHostile( ship, side, range ); if ( target < 0 ) continue; int damage = Frontier ? design.Damage + (side == 0 && WeaponUpgrade ? 4 : 0) : side == 0 ? WeaponUpgrade ? 17 : 13 : 11; @@ -163,8 +166,9 @@ internal void ApplyHullDamage( int ship, int damage ) { private void ClearRetiredOrders( int squad, int first, int count ) { RefreshSurveys( ); - for ( int body = 1; body < _constructionWorkers.Length; ++body ) - if ( _constructionWorkers[body]?.Squad == squad ) AdvanceMine( body ); + for ( int body = 1; body < _bodies.Length; ++body ) + foreach ( var facility in Facilities ) + if ( SiteWorker( body, facility )?.Squad == squad ) CancelSite( body, facility ); for ( int i = 0; i < SquadCount; ++i ) ClearTarget( ref _squads[i].Order, _squads[i].Center ); for ( int ship = 0; ship < Count; ++ship ) ClearTarget( ref _shipOrders[ship], _positions[ship] ); @@ -185,7 +189,7 @@ private int ClosestHostile( int ship, int side, float range ) { for ( int x = Math.Max( 1, cell.X - reach ); x <= Math.Min( _gridSide - 2, cell.X + reach ); ++x ) { int other = _grid[y * _gridSide + x]; for ( int visited = 0; other >= 0 && visited < 8; ++visited, other = _next[other] ) { - if ( SideOf( other ) == side ) continue; + if ( !IsHostile( side, SideOf( other ) ) ) continue; float d = Vector2.DistanceSquared( origin, _positions[other] ); if ( d >= best ) continue; best = d; diff --git a/samples/FleetBattler/FleetGroups.cs b/samples/FleetBattler/FleetGroups.cs new file mode 100644 index 0000000..c7f3746 --- /dev/null +++ b/samples/FleetBattler/FleetGroups.cs @@ -0,0 +1,61 @@ +namespace FleetBattler; + +internal sealed partial class FleetSimulation { + private int _nextFleetId; + internal int FleetId( int squad ) => _squads[squad].FleetId; + internal bool IsFleetLeader( int squad ) { + if ( !Frontier ) return true; + int id = FleetId( squad ); + for ( int i = 0; i < squad; ++i ) + if ( ShipCount( i ) > 0 && FleetId( i ) == id ) return false; + return true; + } + + internal int FleetStrength( int squad ) { + int id = FleetId( squad ), count = 0; + for ( int i = 0; i < SquadCount; ++i ) + if ( FleetId( i ) == id ) count += ShipCount( i ); + return count; + } + + internal bool CanMergeFleets( ReadOnlySpan selected ) { + int first = 0; + for ( int i = 0; i < SquadCount; ++i ) { + if ( !SelectedCombatSquad( i, selected ) ) continue; + int id = FleetId( i ); + if ( first != 0 && first != id ) return true; + first = id; + } + return false; + } + + internal bool MergeFleets( ReadOnlySpan selected ) { + if ( !Frontier || !CanMergeFleets( selected ) ) return false; + Span groups = stackalloc int[SquadCount]; + int count = 0; + for ( int i = 0; i < SquadCount; ++i ) + if ( SelectedCombatSquad( i, selected ) ) groups[count++] = FleetId( i ); + int target = groups[0]; + for ( int i = 0; i < SquadCount; ++i ) + if ( ShipCount( i ) > 0 && groups[..count].Contains( FleetId( i ) ) ) _squads[i].FleetId = target; + return true; + } + + internal bool CanSplitFleets( ReadOnlySpan selected ) { + for ( int i = 0; i < SquadCount; ++i ) + if ( SelectedCombatSquad( i, selected ) && FleetStrength( i ) > ShipCount( i ) ) return true; + return false; + } + + internal bool SplitFleets( ReadOnlySpan selected ) { + if ( !Frontier || !CanSplitFleets( selected ) ) return false; + for ( int i = 0; i < SquadCount; ++i ) + if ( SelectedCombatSquad( i, selected ) && FleetStrength( i ) > ShipCount( i ) ) + _squads[i].FleetId = ++_nextFleetId; + return true; + } + + private bool SelectedCombatSquad( int squad, ReadOnlySpan selected ) => + selected.Length >= Count && IsPlayerSquad( squad ) && ShipCount( squad ) > 0 && + Role( squad ) == HullRole.Corvette && AnySelectedInSquad( squad, selected ); +} diff --git a/samples/FleetBattler/FleetHud.cs b/samples/FleetBattler/FleetHud.cs index f230e71..b719f0f 100644 --- a/samples/FleetBattler/FleetHud.cs +++ b/samples/FleetBattler/FleetHud.cs @@ -5,9 +5,9 @@ namespace FleetBattler; -internal enum PlanetAction { None, Survey, Mine, Lab, Research, Yard, Industry, CancelSurvey, Orbit, Inspect, Depot, Drive, Close, SiteWing, CancelMine, CancelLab, CancelYard, CancelDepot } +internal enum PlanetAction { None, Survey, Mine, Lab, Research, Yard, Industry, CancelSurvey, Orbit, Inspect, Depot, Drive, Close } internal readonly record struct BodyMenu( Vector2 Pixel, int Body ); -internal enum HudAction { None, Panel, Pause, Speed, Galaxy, Wing, Squad, Planet, Context, Command } +internal enum HudAction { None, Panel, Pause, Speed, Galaxy, Wing, Squad, Planet, Context, Command, OpenYard, CloseYard, BuildShip, CancelShip, BuildSite, CancelSite, MergeFleets, SplitFleets } internal readonly record struct HudHit( HudAction Action, int Index = 0 ); internal sealed partial class FleetHud { @@ -76,8 +76,9 @@ float4 PS(Output input) : SV_Target { float2 uv = (tile + lerp(0.02,0.98,input.uv)) / float2(3,2); return float4(pow(saturate(Atlas.Sample(ArtSampler,uv).rgb*input.tint.rgb),1.0/2.2),1); } - uint2 cell = min(uint2(input.uv*float2(5,7)), uint2(4,6)); - uint index = cell.x + cell.y*5; + uint columns = input.bits.z == 7 ? 7 : 5; + uint2 cell = min(uint2(input.uv*float2(columns,7)), uint2(columns-1,6)); + uint index = cell.x + cell.y*columns; uint bits = index < 32 ? input.bits.x : input.bits.y; clip((float)((bits >> (index & 31)) & 1) - 0.5); return input.tint; @@ -95,7 +96,7 @@ internal static PipelineState CreatePipeline( GraphicsDevice device, RootSignatu internal void Record( GraphicsCommandList commands, PipelineState pipeline, GpuResource upload, FleetSimulation fleet, FleetSelection selected, int width, int height, bool oreShort, ReadOnlySpan bodies = default, int selectionCount = -1, int planet = -1, string? notice = null, Vector4? drag = null, Vector2? beacon = null, - ReadOnlySpan selectedShips = default, int speed = 1, bool paused = false, FleetSelection? surveyUnit = null, BodyMenu? menu = null, Vector2? yard = null, CommandTab commandTab = CommandTab.Hidden, int dispatch = 0, ReadOnlySpan sites = default, MapHover hover = default ) { + ReadOnlySpan selectedShips = default, int speed = 1, bool paused = false, FleetSelection? surveyUnit = null, BodyMenu? menu = null, Vector2? yard = null, CommandTab commandTab = CommandTab.Hidden, int dispatch = 0, ReadOnlySpan sites = default, MapHover hover = default, int yardInspector = -1 ) { if ( width < 350 || height < 240 ) return; Begin( width, height ); var layout = new Layout( width / _scale, height / _scale ); @@ -108,7 +109,8 @@ internal void Record( GraphicsCommandList commands, PipelineState pipeline, GpuR PanelAt( 14, 12, layout.Width - 28, 41, SpaceDraw.Cyan ); Text( fleet.SystemName, 23, 20, 1.9f, White ); text.TryWrite( $"ORE {fleet.Ore:D3} SCI {fleet.Science:D3}", out int length ); - Text( text[..length], 23, 39, 1.05f, Label ); + if ( fleet.Frontier ) Wallet( fleet, 23, 38 ); + else Text( text[..length], 23, 39, 1.05f, Label ); Button( layout.ClockX, 19, 64, paused ? "RESUME" : "PAUSE", true, paused ); text.TryWrite( $"{speed}X", out length ); Button( layout.ClockX + 70, 19, 36, text[..length], true ); @@ -116,15 +118,22 @@ internal void Record( GraphicsCommandList commands, PipelineState pipeline, GpuR PanelAt( 14, 63, 157, layout.OutlinerHeight( fleet ), SpaceDraw.Cyan ); Text( "FLEET OUTLINER", 23, 72, 1.35f, White ); - text.TryWrite( $"{fleet.CyanCount} CYAN {fleet.AmberCount} AMBER", out length ); + if ( fleet.Frontier ) text.TryWrite( $"{fleet.CyanCount} SOL / {fleet.AmberCount} HOSTILE", out length ); + else text.TryWrite( $"{fleet.CyanCount} CYAN {fleet.AmberCount} AMBER", out length ); Text( text[..length], 23, 89, 1.05f, Label ); int row = 0; for ( int squad = 0; squad < fleet.SquadCount && row < layout.MaxRows; ++squad ) { - if ( !fleet.IsPlayerSquad( squad ) || fleet.Frontier && fleet.ShipCount( squad ) == 0 ) continue; - int alive = fleet.ShipCount( squad ); + if ( !fleet.IsPlayerSquad( squad ) || fleet.Frontier && !fleet.IsFleetLeader( squad ) ) continue; + int alive = fleet.Frontier ? fleet.FleetStrength( squad ) : fleet.ShipCount( squad ); text.TryWrite( $"{squad + 1:D2} {(fleet.Role( squad ) switch { HullRole.Scout => "SCOUT", HullRole.Miner => "MINER", _ => "CORVETTE" })} {alive:D2}", out length ); + if ( fleet.Frontier && alive > fleet.ShipCount( squad ) ) + text.TryWrite( $"FLEET {fleet.FleetId( squad ):D2} / {alive} HULLS", out length ); bool active = selectionCount != 0 && selected.Squad == squad; - if ( !selectedShips.IsEmpty ) active |= fleet.AnySelectedInSquad( squad, selectedShips ); + if ( !selectedShips.IsEmpty ) { + for ( int member = 0; member < fleet.SquadCount; ++member ) + if ( (member == squad || fleet.Frontier && fleet.FleetId( member ) == fleet.FleetId( squad )) && + fleet.AnySelectedInSquad( member, selectedShips ) ) { active = true; break; } + } float rowTop = 106 + row++ * 24; if ( fleet.Frontier ) { Rect( 23, rowTop, 139, 21, active ? Active : Well ); @@ -133,11 +142,16 @@ internal void Record( GraphicsCommandList commands, PipelineState pipeline, GpuR } else Button( 23, rowTop, 139, text[..length], alive != 0, active ); } + if ( fleet.Frontier && layout.FleetControls( fleet ) + 21 < layout.Bottom ) { + float top = layout.FleetControls( fleet ); + IconButton( 14, top, 76, HudIcon.Merge, "MERGE", fleet.CanMergeFleets( selectedShips ) ); + IconButton( 95, top, 76, HudIcon.Split, "SPLIT", fleet.CanSplitFleets( selectedShips ) ); + } if ( fleet.Frontier && surveyUnit is { } navigator ) FlightCard( layout, fleet, navigator, speed ); float right = layout.Right; PanelAt( right, 63, 171, 76, siteTint ); - if ( fleet.Frontier ) site = fleet.Recovering ? "REBUILD THE FLEET" : fleet.ActiveRaids == 0 ? "SURVEY THE FRONTIER" : fleet.AmberCount > 0 ? "RAID IN PROGRESS" : "RAIDERS CLEARED"; + if ( fleet.Frontier ) site = !fleet.Established ? "NO SOL PRESENCE" : fleet.Recovering ? "REBUILD THE FLEET" : fleet.ActiveRaids == 0 ? "SURVEY THE FRONTIER" : fleet.AmberCount > 0 ? "RAID IN PROGRESS" : "RAIDERS CLEARED"; Text( fleet.Frontier ? "FRONTIER" : "MINING RELAY", right + 9, 72, 1.35f, White ); Text( site, right + 9, 89, 1.1f, siteTint ); float fraction = fleet.CaptureTicks > 0 ? (float)fleet.CaptureTicks / FleetSimulation.CaptureDuration @@ -210,7 +224,7 @@ internal void Record( GraphicsCommandList commands, PipelineState pipeline, GpuR } else Text( "RIGHT CLICK BODY", right + 9, 213, 1, Label ); } - if ( layout.YardVisible && (!fleet.Frontier || planet < 0) ) YardPanel( fleet, right, layout.Bottom - 71, speed ); + if ( layout.YardVisible && !fleet.Frontier ) YardPanel( fleet, right, layout.Bottom - 71, speed ); if ( drag is { } box ) { box /= _scale; @@ -225,21 +239,23 @@ internal void Record( GraphicsCommandList commands, PipelineState pipeline, GpuR int routeTicks = selectionCount > 0 && fleet.Frontier && surveyUnit is not null ? fleet.RouteTicks( selected ) : 0; string? flightStatus = routeTicks > 0 ? $"{PhaseName( fleet.RoutePhase( selected ) )} / ETA {Seconds( routeTicks, speed )} SEC" : null; string instruction = notice ?? (fleet.Recovering ? "FLEET LOST / REBUILD AT HOMEWORLD OR A YARD" : flightStatus ?? (fleet.Lost ? "DEFEAT / CYAN FLEET LOST" : fleet.Won - ? fleet.AmberCount == 0 ? "VICTORY / AMBER DEFEATED" : "VICTORY / WING GOAL MET" - : fleet.InBattle ? "ENGAGEMENT / RIGHT CLICK AMBER TO ATTACK" + ? fleet.Frontier ? "SYSTEM SECURED / CONTINUE COLONY OPERATIONS" : fleet.AmberCount == 0 ? "VICTORY / AMBER DEFEATED" : "VICTORY / WING GOAL MET" + : fleet.InBattle ? "ENGAGEMENT / RIGHT CLICK HOSTILE TO ATTACK" : selectionCount != 0 && fleet.Orbiting( selected ) ? "ORBIT ORDER ACTIVE" : oreShort && fleet.Ore < fleet.CurrentWingCost ? "NEED ORE TO QUEUE A WING" - : fleet.Frontier ? fleet.CompletedSurveys == 0 ? "SELECT SCOUT / RIGHT CLICK A BODY TO SURVEY" : "SELECT A BODY FOR ITS SITE ORDERS" + : fleet.Frontier ? !fleet.Established ? "FREE MERCHANTS / NO SOL PRESENCE" : fleet.CompletedSurveys == 0 ? "SELECT SCOUT / RIGHT CLICK A BODY TO SURVEY" : "SELECT A BODY FOR ITS SITE ORDERS" : fleet.Owner == 0 ? "HOLD THE RELAY TO MINE ORE" : "CAPTURE THE RELAY OR DEFEAT AMBER")); float instructionScale = layout.Width < 530 ? 1 : 1.16f; int instructionCapacity = (int)((layout.Width - 159) / TextWidth( 1, instructionScale )); Text( instruction.AsSpan( 0, Math.Min( instruction.Length, instructionCapacity ) ), 23, layout.Bottom + 9, instructionScale, fleet.Won ? SpaceDraw.Cyan : fleet.Lost ? SpaceDraw.Amber : White ); - Text( layout.Width >= 585 ? "MID PAN / SHIFT MID TILT / F FOCUS / HOME RESET" + Text( fleet.Frontier && layout.Width >= 650 ? "J MERGE / SHIFT J SPLIT / MID PAN / SHIFT MID TILT / HOME RESET" + : layout.Width >= 585 ? "MID PAN / SHIFT MID TILT / F FOCUS / HOME RESET" : "DRAG SELECT / RIGHT CLICK ORDER", 23, layout.Bottom + 31, 1, Label ); Button( layout.Width - 127, layout.Bottom + 14, 104, fleet.Frontier ? "ORDERS" : "QUEUE WING", fleet.Frontier || fleet.CanBuildWing ); if ( fleet.Frontier ) CommandPanel( layout, fleet, commandTab, dispatch, speed ); if ( fleet.Frontier ) OperationsFeedback( layout, fleet, bodies, sites, hover, speed, planet ); + if ( yardInspector >= 0 && fleet.CanOpenYard( yardInspector ) ) DrawShipyard( layout, fleet, yardInspector, speed ); if ( menu is { } popup ) ContextPanel( layout, fleet, popup, surveyUnit, selectionCount != 0 ); Submit( commands, pipeline, upload, width, height ); } @@ -267,8 +283,8 @@ private void PlanetPanel( FleetSimulation fleet, int planet, float right, FleetS ReadOnlySpan surveyLabel = SurveyLabel( status, surveyUnit, line ); Button( right + 9, 189, 153, surveyLabel, !fleet.Lost && (status.SurveyUnit is not null || surveyUnit is { } unit && fleet.CanSurvey( unit, planet )) ); - Button( right + 9, 216, 153, status.MineRemaining == 0 ? "MINE ACTIVE" : status.MineRemaining > 0 ? fleet.MineEnRoute( planet ) ? "MINER EN ROUTE" : "MINE BUILDING" : "MINE / 35 ORE", - status.Surveyed && status.MineRemaining < 0 && fleet.Ore >= FleetSimulation.MineCost && !fleet.Lost && fleet.CanPlaceMine( planet, surveyUnit ) ); + Button( right + 9, 216, 153, status.MineRemaining == 0 ? "MINE ACTIVE" : status.MineRemaining > 0 ? "MINE BUILDING" : "MINE / 35 ORE", + status.Surveyed && status.MineRemaining < 0 && fleet.Ore >= FleetSimulation.MineCost && !fleet.Lost ); Button( right + 9, 243, 153, status.LabRemaining == 0 ? "LAB ACTIVE" : status.LabRemaining > 0 ? "LAB BUILDING" : "LAB / 45 ORE", status.Surveyed && status.LabRemaining < 0 && fleet.Ore >= FleetSimulation.LabCost && !fleet.Lost ); Button( right + 9, 270, 153, fleet.WeaponUpgrade ? "WEAPONS UPGRADED" : "WEAPONS / 30 SCI", @@ -325,10 +341,11 @@ private void ContextPanel( Layout layout, FleetSimulation fleet, BodyMenu menu, Span text = stackalloc char[32]; Button( area.X + 9, area.Y + 71, area.Z - 18, status.SurveyUnit is null ? SurveyLabel( status, unit, text ) : "CANCEL SURVEY", status.SurveyUnit is not null || unit is { } selection && fleet.CanSurvey( selection, menu.Body ) ); - Button( area.X + 9, area.Y + 95, area.Z - 18, fleet.YardAt( menu.Body ) >= 0 ? "SHIPYARD ASSIGNED" : "SHIPYARD / 55 ORE", - (fleet.Frontier ? fleet.YardAt( menu.Body ) < 0 : fleet.YardBody < 0) && status.Surveyed && fleet.Ore >= FleetSimulation.YardCost && !fleet.Lost ); - if ( fleet.Frontier ) Button( area.X + 9, area.Y + 119, area.Z - 18, "PLACE MINE / 35 ORE", - status.MineRemaining < 0 && fleet.Ore >= FleetSimulation.MineCost && fleet.CanPlaceMine( menu.Body, unit ) ); + Button( area.X + 9, area.Y + 95, area.Z - 18, fleet.Frontier ? "ASSIGN SHIPYARD PROJECT" : fleet.YardAt( menu.Body ) >= 0 ? "SHIPYARD ASSIGNED" : "SHIPYARD / 55 ORE", + fleet.Frontier ? fleet.ConstructionBlock( menu.Body, PlanetFacility.Yard, unit ) is null + : fleet.YardBody < 0 && status.Surveyed && fleet.Ore >= FleetSimulation.YardCost && !fleet.Lost ); + if ( fleet.Frontier ) Button( area.X + 9, area.Y + 119, area.Z - 18, "ASSIGN EXTRACTION RIG", + fleet.ConstructionBlock( menu.Body, PlanetFacility.Mine, unit ) is null ); } _overlay = 0; } @@ -351,7 +368,7 @@ private void FacilityMarker( float x, float y, int remaining, Vector4 color ) { Rect( x + 7, y + 3, 2, 1, color ); } - internal static HudHit Hit( Vector2 pixel, int width, int height, FleetSimulation fleet, int planet, BodyMenu? menu = null, CommandTab commandTab = CommandTab.Hidden ) { + internal static HudHit Hit( Vector2 pixel, int width, int height, FleetSimulation fleet, int planet, BodyMenu? menu = null, CommandTab commandTab = CommandTab.Hidden, int yardInspector = -1 ) { if ( width < 350 || height < 240 ) return default; float scale = HudScale( width, height ); var layout = new Layout( width / scale, height / scale ); @@ -374,13 +391,22 @@ internal static HudHit Hit( Vector2 pixel, int width, int height, FleetSimulatio return default; } if ( fleet.Frontier ) { - var command = HitCommand( layout, p, commandTab ); + if ( yardInspector >= 0 && fleet.CanOpenYard( yardInspector ) ) { + var yard = HitShipyard( layout, p, fleet, yardInspector ); + if ( yard.Action != HudAction.None ) return yard; + } + var command = HitCommand( layout, p, fleet, commandTab ); if ( command.Action != HudAction.None ) return command; } if ( fleet.Frontier && planet >= 0 && layout.PlanetVisible ) { var inspector = HitInspector( layout, p, planet, fleet ); if ( inspector.Action != HudAction.None ) return inspector; } + if ( fleet.Frontier && layout.FleetControls( fleet ) + 21 < layout.Bottom ) { + float top = layout.FleetControls( fleet ); + if ( Contains( p, 14, top, 76, 21 ) ) return new( HudAction.MergeFleets ); + if ( Contains( p, 95, top, 76, 21 ) ) return new( HudAction.SplitFleets ); + } if ( !layout.Blocks( p, fleet, planet ) ) return default; if ( Contains( p, layout.ClockX, 19, 64, 21 ) ) return new( HudAction.Pause ); if ( Contains( p, layout.ClockX + 70, 19, 36, 21 ) ) return new( HudAction.Speed ); @@ -391,10 +417,10 @@ internal static HudHit Hit( Vector2 pixel, int width, int height, FleetSimulatio int wanted = (int)(rowY / 24); if ( wanted < layout.MaxRows && rowY % 24 < 21 ) { for ( int squad = 0; squad < fleet.SquadCount; ++squad ) - if ( fleet.IsPlayerSquad( squad ) && (!fleet.Frontier || fleet.ShipCount( squad ) > 0) && wanted-- == 0 ) return new( HudAction.Squad, squad ); + if ( fleet.IsPlayerSquad( squad ) && (!fleet.Frontier || fleet.IsFleetLeader( squad )) && wanted-- == 0 ) return new( HudAction.Squad, squad ); } } - if ( layout.YardVisible && (!fleet.Frontier || planet < 0) && Contains( p, layout.Right + 9, layout.Bottom - 31, 153, 21 ) ) + if ( layout.YardVisible && !fleet.Frontier && Contains( p, layout.Right + 9, layout.Bottom - 31, 153, 21 ) ) return new( HudAction.Planet, (int)PlanetAction.Industry ); if ( !fleet.Frontier && planet > 0 && layout.PlanetVisible && Contains( p, layout.Right + 9, 189, 153, 129 ) ) { float rowY = p.Y - 189; @@ -417,7 +443,7 @@ private readonly partial record struct Layout( float Width, float Height ) { internal float OutlinerHeight( FleetSimulation fleet ) { int count = 0; for ( int i = 0; i < fleet.SquadCount; ++i ) - if ( fleet.IsPlayerSquad( i ) && (!fleet.Frontier || fleet.ShipCount( i ) > 0) ) ++count; + if ( fleet.IsPlayerSquad( i ) && (!fleet.Frontier || fleet.IsFleetLeader( i )) ) ++count; return 46 + 24 * Math.Min( count, MaxRows ); } diff --git a/samples/FleetBattler/FleetSimulation.cs b/samples/FleetBattler/FleetSimulation.cs index a841f74..96de800 100644 --- a/samples/FleetBattler/FleetSimulation.cs +++ b/samples/FleetBattler/FleetSimulation.cs @@ -54,7 +54,7 @@ internal sealed partial class FleetSimulation { private uint _seed; private struct Squad { - internal int First, Count, Faction, Alive; + internal int First, Count, Faction, Alive, FleetId; internal HullRole Role; internal ShipDesign Design; internal Vector2 Home, Center, Direction, Anchor; @@ -111,7 +111,13 @@ internal FleetSimulation( int ships, uint seed, bool rivalPatrol = false, int sy _targetLimit = NavigationRadius - formationRadius * 0.6f; Site = new( BoardRadius * 0.14f, -BoardRadius * 0.07f ); SiteRadius = MathF.Max( 8, BoardRadius * 0.093f ); - if ( frontier ) OpenFrontier( ); + if ( frontier ) { + if ( Solar ) OpenFrontier( ); + else { + int merchant = AddSquad( 1, (int)FactionId.Merchants, _bodies[2].Center + new Vector2( 30, 5 ), HullRole.Freighter ); + Park( merchant, 2 ); + } + } else { AddFleet( cyan, 0 ); _amberFirst = SquadCount; @@ -188,10 +194,16 @@ internal FlightPlan Plan( FleetSelection selected ) { internal int ActiveMiners( ) { int count = 0; for ( int i = 0; i < SquadCount; ++i ) - if ( Role( i ) == HullRole.Miner ) count += ShipCount( i ); + if ( IsPlayerSquad( i ) && Role( i ) == HullRole.Miner ) count += ShipCount( i ); return count; } + internal int FirstPlayerSquad( ) { + for ( int i = 0; i < SquadCount; ++i ) + if ( IsPlayerSquad( i ) && ShipCount( i ) > 0 ) return i; + return -1; + } + internal int ShipCount( int squad ) => _squads[squad].Alive; internal bool IsPlayerSquad( int squad ) => _squads[squad].Faction == 0; internal bool IsScoutSquad( int squad ) => IsPlayerSquad( squad ) && Role( squad ) == HullRole.Scout; @@ -363,6 +375,7 @@ internal void Step( ) { if ( !Frontier ) AdvanceSite( cyan, amber ); AdvancePlanets( ); AdvanceProduction( ); + AdvanceIndustry( ); ++Tick; AdvanceFrontier( ); } @@ -452,17 +465,16 @@ internal int FillInstances( Span destination, FleetSelection selec if ( groupHulls ) { for ( int i = 0; i < SquadCount; ++i ) { if ( IsScoutSquad( i ) ) corvettes -= ShipCount( i ); - if ( groupMiners && Role( i ) == HullRole.Miner ) miners += ShipCount( i ); + if ( groupMiners && Role( i ) is HullRole.Miner or HullRole.Freighter ) miners += ShipCount( i ); } corvettes -= miners; } int index = 0, scoutIndex = corvettes, minerIndex = ActiveCount - miners; for ( int i = 0; i < SquadCount; ++i ) { bool scout = groupHulls && IsScoutSquad( i ); - bool miner = groupMiners && Role( i ) == HullRole.Miner; + bool miner = groupMiners && Role( i ) is HullRole.Miner or HullRole.Freighter; ref readonly var squad = ref _squads[i]; - var tint = squad.Faction == 0 ? new Vector4( 0.66f, 1.55f, 2.25f, 1.04f ) - : new Vector4( 2.9f, 0.89f, 0.37f, 1.11f ); + var tint = Factions.ShipTint( (FactionId)squad.Faction ); int end = squad.First + squad.Count; for ( int ship = squad.First; ship < end; ++ship ) { if ( !Alive( ship ) ) continue; @@ -480,16 +492,20 @@ internal int FillInstances( Span destination, FleetSelection selec internal ulong StateHash( ) { ulong hash = 14695981039346656037; if ( Frontier ) { - Append( (uint)_workerReadyTick ); Append( (uint)_civilianOrder ); Append( (uint)_raidTick ); - Append( (uint)_raidsLaunched ); Append( (uint)_deposits ); Append( _secured ? 1u : 0u ); + Append( (uint)_nextFleetId ); Append( (uint)_raidTick ); Append( (uint)_raidsLaunched ); Append( (uint)_deposits ); Append( _secured ? 1u : 0u ); Append( DriveUpgrade ? 1u : 0u ); Append( (uint)Design.Weapon ); Append( Design.Plating ? 1u : 0u ); - for ( int i = 0; i < QueuedWings; ++i ) { - var job = _wingQueue[i]; - Append( (uint)job.Body ); Append( (uint)job.Cost ); Append( (uint)job.Design.Weapon ); Append( job.Design.Plating ? 1u : 0u ); - } - for ( int i = 1; i < _constructionWorkers.Length; ++i ) { - Append( (uint)(_constructionWorkers[i]?.Squad ?? -1) ); - Append( (uint)(_constructionWorkers[i]?.Ship ?? -1) ); AppendVector( _mineOrbits[i] ); + Append( (uint)Energy ); Append( (uint)ShipsLaunched ); Append( (uint)CorvettesLaunched ); Append( (uint)_researchReady ); Append( ActiveResearch is { } topic ? (uint)topic + 1 : 0 ); + for ( int body = 1; body < _bodies.Length; ++body ) { + Append( (uint)_yardShipReady[body] ); Append( (uint)_yardQueueSizes[body] ); + foreach ( var order in YardQueue( body ) ) { + Append( (uint)order.Hull ); Append( (uint)order.Design.Weapon ); Append( order.Design.Plating ? 1u : 0u ); + Append( (uint)order.Cost.Ore ); Append( (uint)order.Cost.Energy ); Append( (uint)order.Duration ); + } + foreach ( var facility in Facilities ) { + var site = Construction( body, facility ); + Append( (uint)(site.Worker?.Squad ?? -1) ); Append( (uint)(site.Worker?.Ship ?? -1) ); + AppendVector( site.Orbit ); Append( site.Working ? 1u : 0u ); + } } } Append( (uint)SystemIndex ); Append( (uint)Tick ); Append( (uint)Count ); Append( (uint)SquadCount ); Append( _seed ); @@ -500,13 +516,13 @@ internal ulong StateHash( ) { for ( int body = 0; body < _bodies.Length; ++body ) { Append( (uint)(_surveyUnits[body]?.Squad ?? -1) ); Append( (uint)(_surveyUnits[body]?.Ship ?? -1) ); Append( (uint)_survey[body] ); Append( (uint)_mines[body] ); Append( (uint)_labs[body] ); - if ( Frontier ) { Append( (uint)_yards[body] ); Append( (uint)_depots[body] ); } + if ( Frontier ) { Append( (uint)_yards[body] ); Append( (uint)_depots[body] ); Append( (uint)_solarArrays[body] ); } } Append( (uint)Ore ); Append( (uint)WingsBuilt ); Append( (uint)_incomeTicks ); Append( _rivalPatrol ? 1u : 0u ); Append( _battle ? 1u : 0u ); for ( int i = 0; i < SquadCount; ++i ) { ref readonly var squad = ref _squads[i]; Append( (uint)squad.Count ); Append( (uint)squad.Faction ); - if ( Frontier ) { Append( (uint)squad.Role ); Append( (uint)squad.Design.Weapon ); Append( squad.Design.Plating ? 1u : 0u ); } + if ( Frontier ) { Append( (uint)squad.FleetId ); Append( (uint)squad.Role ); Append( (uint)squad.Design.Weapon ); Append( squad.Design.Plating ? 1u : 0u ); } AppendVector( squad.Home ); AppendVector( squad.Center ); AppendVector( squad.Direction ); AppendOrder( squad.Order ); } for ( int i = 0; i < Count; ++i ) { @@ -592,7 +608,7 @@ private void AddFleet( int ships, int faction ) { _previousHeadings[i] = _headings[i] = heading; } _squads[squadIndex] = new( ) { First = first, Count = count, Alive = count, Faction = faction, Home = center, Center = center, - Role = role, Design = design, Anchor = center, Direction = heading, Order = new Order { Target = center } }; + FleetId = ++_nextFleetId, Role = role, Design = design, Anchor = center, Direction = heading, Order = new Order { Target = center } }; if ( squadIndex == SquadCount ) { ++SquadCount; Count += count; diff --git a/samples/FleetBattler/Frontier.cs b/samples/FleetBattler/Frontier.cs index a90a974..676f8d6 100644 --- a/samples/FleetBattler/Frontier.cs +++ b/samples/FleetBattler/Frontier.cs @@ -2,44 +2,30 @@ namespace FleetBattler; -internal enum HullRole : byte { Corvette, Scout, Miner } +internal enum HullRole : byte { Corvette, Scout, Miner, Freighter } internal enum WeaponKind : byte { None, Pulse, Rail } internal enum FrontierEvent : byte { Arrival, Prospect, Distress, Raid, Counterattack, Secured } internal readonly record struct ShipDesign( WeaponKind Weapon, bool Plating ) { internal int Shield => Plating ? 12 : 34; internal int Armor => Plating ? 32 : 10; - internal int Surcharge => Plating ? 8 : 0; - internal int BuildTicks => Plating ? 60 : 0; internal int Range => Weapon == WeaponKind.Rail ? 21 : 16; internal int Reload => Weapon == WeaponKind.Rail ? 64 : 38; internal int Damage => Weapon == WeaponKind.Rail ? 22 : 13; } internal sealed partial class FleetSimulation { - internal const int Homeworld = 1, WorkerCost = 20, WorkerDuration = 240; + internal const int Homeworld = 1; // A one-survivor wing can retain three storage slots while consuming one naval slot. - private const int FrontierCapacity = 320, FrontierWingSize = 3, MaxWorkers = 5; + private const int FrontierCapacity = 320, MaxWorkers = 5; private readonly FrontierEvent[] _dispatches = new FrontierEvent[8]; - private readonly FleetSelection?[] _constructionWorkers = new FleetSelection?[CelestialSystem.BodyCount]; - private readonly Vector2[] _mineOrbits = new Vector2[CelestialSystem.BodyCount]; - private readonly bool[] _buildingMines = new bool[CelestialSystem.BodyCount]; - private int _workerReadyTick, _raidTick, _raidsLaunched, _deposits; + private int _raidTick, _raidsLaunched, _deposits; private int _surveyedProspects; private bool _secured; - private HullRole _civilianOrder; internal bool Frontier { get; } internal int DispatchCount { get; private set; } - internal int WorkerRemaining => Remaining( _workerReadyTick ); internal int Deposits => _deposits; internal int ActiveRaids => _raidsLaunched; - internal bool CanQueueWorker => CanOrderCivilian( HullRole.Miner ); - internal bool CanQueueScout => CanOrderCivilian( HullRole.Scout ); - internal HullRole CivilianOrder => _civilianOrder; - internal bool Recovering => Frontier && CyanCount == 0 && !Won; - internal const int ScoutCost = 24; - private bool CanOrderCivilian( HullRole role ) => Frontier && _workerReadyTick == 0 && - (role == HullRole.Miner ? ActiveMiners( ) < MaxWorkers && Ore >= WorkerCost : - ActiveScouts( ) == 0 && Ore >= ScoutCost); + internal bool Recovering => Established && CyanCount == 0 && !Won; private int ActiveScouts( ) { int count = 0; for ( int i = 0; i < SquadCount; ++i ) @@ -54,18 +40,13 @@ private int ActiveScouts( ) { internal int DepositYield( int body ) => HasDeposit( body ) ? ProspectYield( body ) : 0; private int ProspectYield( int body ) => body == CelestialSystem.OuterBelt ? 20 : (body + SystemIndex) % 2 == 0 ? 12 : 8; - internal void ConfigureDesign( bool weapon ) { - if ( !Frontier ) return; - Design = weapon ? Design with { Weapon = Design.Weapon == WeaponKind.Pulse ? WeaponKind.Rail : WeaponKind.Pulse } - : Design with { Plating = !Design.Plating }; - } - internal void SetWeapon( WeaponKind weapon ) => Design = Design with { Weapon = weapon }; internal void SetPlating( bool plating ) => Design = Design with { Plating = plating }; private void OpenFrontier( ) { _survey[Homeworld] = SurveyDuration; Ore = 50; + Energy = 25; Vector2 home = _bodies[Homeworld].Center + new Vector2( -OrbitRadius( Homeworld, 1 ), 0 ); Park( AddSquad( 1, 0, home, HullRole.Scout ), Homeworld ); Park( AddSquad( 1, 0, home + new Vector2( -5, 5 ), HullRole.Miner ), Homeworld ); @@ -73,86 +54,6 @@ private void OpenFrontier( ) { SendDispatch( FrontierEvent.Arrival ); } - internal bool QueueWorker( ) => QueueCivilian( HullRole.Miner ); - internal bool QueueScout( ) => QueueCivilian( HullRole.Scout ); - internal bool CancelCivilian( ) { - if ( !Frontier || WorkerRemaining <= 0 ) return false; - _workerReadyTick = 0; - Refund( _civilianOrder == HullRole.Miner ? WorkerCost : ScoutCost ); - return true; - } - - private bool QueueCivilian( HullRole role ) { - if ( !CanOrderCivilian( role ) ) return false; - Ore -= role == HullRole.Miner ? WorkerCost : ScoutCost; - _civilianOrder = role; - _workerReadyTick = Tick + WorkerDuration; - return true; - } - - internal bool CanPlaceMine( int body, FleetSelection? unit ) { - if ( !Frontier ) return true; - return HasDeposit( body ) && unit is { } worker && (uint)worker.Squad < (uint)SquadCount && - IsPlayerSquad( worker.Squad ) && Role( worker.Squad ) == HullRole.Miner && - (worker.IsShip ? Alive( worker.Ship ) && SquadronOf( worker.Ship ) == worker.Squad : ShipCount( worker.Squad ) > 0) && - !WorkerAssigned( worker.Squad ) && CanReach( worker, body ); - } - - private bool WorkerAssigned( int squad ) { - foreach ( var assignment in _constructionWorkers ) - if ( assignment?.Squad == squad ) return true; - return false; - } - - private bool AssignMine( int body, FleetSelection? unit ) { - if ( !CanPlaceMine( body, unit ) ) return false; - var worker = unit!.Value; - _constructionWorkers[body] = worker; - var orbit = OrbitalOrder( worker, body, survey: false ); - _mineOrbits[body] = new( orbit.Radius, orbit.Phase + 0.24f ); - SetOrder( worker, orbit ); - return true; - } - - internal bool MineEnRoute( int body ) => - _constructionWorkers[body] is not null && _mines[body] > Tick && !MineOnSite( body ); - private bool MineOnSite( int body ) => _constructionWorkers[body] is { } worker && - InSurveyRange( worker, body ); - - private void AdvanceMine( int body ) { - if ( _constructionWorkers[body] is not { } worker ) return; - bool alive = worker.IsShip ? Alive( worker.Ship ) : ShipCount( worker.Squad ) != 0; - if ( !alive || EffectiveOrder( worker ).Body != body + 1 ) { - CancelSite( body, PlanetFacility.Mine ); - return; - } - if ( !MineOnSite( body ) ) { - ++_mines[body]; - return; - } - if ( !_buildingMines[body] ) { - _buildingMines[body] = true; - ++StartedConstruction; - } - if ( _mines[body] <= Tick + 1 ) _constructionWorkers[body] = null; - } - - internal FleetSelection? SiteWorker( int body ) => _constructionWorkers[body]; - - internal Vector2 SitePosition( int body, PlanetFacility facility, float interpolation ) { - var center = VisualBody( body, interpolation ).Center; - float tick = Math.Max( 0, Tick - 1 + interpolation ); - if ( facility == PlanetFacility.Mine && _mineOrbits[body].X > 0 ) { - var orbit = _mineOrbits[body]; - var (sin, cos) = MathF.SinCos( orbit.Y + tick * OrbitRate( orbit.X ) ); - return center + new Vector2( cos, sin ) * orbit.X; - } - float angularSpeed = facility == PlanetFacility.Yard ? 0.23f : 0.31f; - float phase = facility == PlanetFacility.Lab ? MathF.PI : facility == PlanetFacility.Depot ? MathF.PI / 2 : -MathF.PI / 2; - var (y, x) = MathF.SinCos( tick * (float)StepSeconds * angularSpeed + phase ); - return center + new Vector2( x, y ) * (OrbitRadius( body, 1 ) + (facility == PlanetFacility.Yard ? 4 : 0)); - } - private void RevealProspect( int body ) { ++_surveyedProspects; _deposits |= 1 << body; @@ -160,21 +61,16 @@ private void RevealProspect( int body ) { } private void AdvanceFrontier( ) { - if ( !Frontier ) return; + if ( !Established ) return; if ( Tick % IncomeInterval == 0 && ShipsLost > 0 && Ore < MineCost && !HasOperatingMine( ) ) Ore = Math.Min( MineCost, Ore + 2 ); - if ( _workerReadyTick != 0 && Tick + 1 >= _workerReadyTick ) { - _workerReadyTick = 0; - var origin = _bodies[Homeworld].Center + new Vector2( -OrbitRadius( Homeworld, 1 ), 0 ); - Park( AddSquad( 1, 0, origin, _civilianOrder ), Homeworld ); - } if ( Won ) return; if ( _raidsLaunched == 0 && _raidTick == 0 && HasOperatingMine( ) ) { _raidTick = Tick + (ProspectYield( FirstMineBody( ) ) > 8 ? 840 : 1080); SendDispatch( FrontierEvent.Distress ); } if ( _raidsLaunched == 0 && _raidTick != 0 && Tick >= _raidTick ) LaunchRaid( 2, FrontierEvent.Raid ); - if ( _raidsLaunched == 1 && AmberCount == 0 && WingsBuilt > 0 ) LaunchRaid( 3, FrontierEvent.Counterattack ); + if ( _raidsLaunched == 1 && AmberCount == 0 && CorvettesLaunched > 0 ) LaunchRaid( 3, FrontierEvent.Counterattack ); if ( _raidsLaunched == 2 && AmberCount == 0 ) { _secured = true; SendDispatch( FrontierEvent.Secured ); @@ -183,7 +79,7 @@ private void AdvanceFrontier( ) { var destination = YardBody >= 0 ? Shipyard : FirstMinePosition( ); for ( int i = 0; i < SquadCount; ++i ) { - if ( IsPlayerSquad( i ) || ShipCount( i ) == 0 ) continue; + if ( !IsHostile( (int)FactionId.Sol, _squads[i].Faction ) || ShipCount( i ) == 0 ) continue; int target = -1; float distance = 24 * 24; for ( int ship = 0; ship < Count; ++ship ) { @@ -208,14 +104,15 @@ private int FirstMineBody( ) { private Vector2 FirstMinePosition( ) { int body = FirstMineBody( ); - return body == 0 ? _bodies[Homeworld].Center : _bodies[body].Center + new Vector2( OrbitRadius( body, 1 ), 0 ); + return body == 0 ? _bodies[Homeworld].Center : SitePositionAt( body, PlanetFacility.Mine, Tick, _bodies[body].Center ); } private void LaunchRaid( int count, FrontierEvent incident ) { var target = YardBody >= 0 ? Shipyard : FirstMinePosition( ); var origin = target + new Vector2( target.X < 0 ? 48 : -48, target.Y < 0 ? 35 : -35 ); var design = new ShipDesign( incident == FrontierEvent.Raid ? WeaponKind.Pulse : WeaponKind.Rail, false ); - int squad = AddSquad( count, 1, Vector2.Clamp( origin, new( -BoardRadius + 5 ), new( BoardRadius - 5 ) ), design: design ); + int faction = (int)(incident == FrontierEvent.Raid ? FactionId.Raiders : FactionId.Rival); + int squad = AddSquad( count, faction, Vector2.Clamp( origin, new( -BoardRadius + 5 ), new( BoardRadius - 5 ) ), design: design ); Move( squad, target ); ++_raidsLaunched; SendDispatch( incident ); diff --git a/samples/FleetBattler/FrontierHud.cs b/samples/FleetBattler/FrontierHud.cs index bc048dd..649bfeb 100644 --- a/samples/FleetBattler/FrontierHud.cs +++ b/samples/FleetBattler/FrontierHud.cs @@ -2,152 +2,149 @@ namespace FleetBattler; -internal enum CommandTab { Hidden, Economy, Fleet, Orders, Events } -internal enum CommandAction { Toggle, Economy, Fleet, Orders, Events, Worker, Scout, Drive, Wing, - Pulse, Rail, Shield, Plating, CancelCivilian, CancelFirstWing, CancelSecondWing, Earlier, Later } +internal enum CommandTab { Hidden, Economy, Research, Fleet, Orders, Events } +internal enum CommandAction { Toggle, Economy, Research, Fleet, Orders, Events, + Pulse, Rail, Shield, Plating, StartIndustry, StartWeapons, StartDrive, CancelResearch, Earlier, Later } internal sealed partial class FleetHud { - private const float OfficeWidth = 328; + private const float OfficeWidth = 350; + private static readonly string[] TabNames = ["COLONY", "RESEARCH", "DESIGN", "ORDERS", "LOG"]; + private static readonly HudIcon[] TabIcons = [HudIcon.Colony, HudIcon.Science, HudIcon.Design, HudIcon.Orders, HudIcon.Log]; private static (float X, float Y) CommandOrigin( Layout layout ) => ((layout.Width - OfficeWidth) / 2, 61); - private static float CommandHeight( CommandTab tab ) => tab switch { - CommandTab.Economy => 227, CommandTab.Fleet => 229, CommandTab.Orders => 205, _ => 162 + private static float CommandHeight( CommandTab tab, FleetSimulation fleet ) => tab switch { + CommandTab.Economy => 184, CommandTab.Research => 243, CommandTab.Fleet => 210, + CommandTab.Orders => 82 + Math.Max( 1, YardRows( fleet ) ) * 21, _ => 162 }; + private static int YardRows( FleetSimulation fleet ) { + int count = 0; + for ( int body = 1; body < fleet.Bodies.Length; ++body ) + if ( fleet.CanOpenYard( body ) ) ++count; + return count; + } + private void CommandPanel( Layout layout, FleetSimulation fleet, CommandTab tab, int dispatch, int speed ) { - if ( layout.Width >= 700 ) { - Nav( 0, "COLONY", CommandTab.Economy ); - Nav( 1, "DESIGN", CommandTab.Fleet ); - Nav( 2, "ORDERS", CommandTab.Orders ); - Nav( 3, "LOG", CommandTab.Events ); - } else Button( layout.ClockX - 89, 19, 83, tab == CommandTab.Hidden ? "OPERATIONS" : "CLOSE", true, tab != CommandTab.Hidden ); + if ( layout.Width >= 780 ) { + for ( int i = 0; i < TabNames.Length; ++i ) + IconButton( layout.ClockX - 358 + i * 71, 19, 68, TabIcons[i], TabNames[i], true, (int)tab == i + 1 ); + } else IconButton( layout.ClockX - 89, 19, 83, HudIcon.Colony, tab == CommandTab.Hidden ? "COMMAND" : "CLOSE", true, tab != CommandTab.Hidden ); if ( tab == CommandTab.Hidden ) return; var (x, y) = CommandOrigin( layout ); _overlay = 1; - PanelAt( x, y, OfficeWidth, CommandHeight( tab ), SpaceDraw.Cyan ); - Button( x + 10, y + 8, 71, "COLONY", true, tab == CommandTab.Economy ); - Button( x + 89, y + 8, 71, "DESIGN", true, tab == CommandTab.Fleet ); - Button( x + 168, y + 8, 71, "ORDERS", true, tab == CommandTab.Orders ); - Button( x + 247, y + 8, 71, "LOG", true, tab == CommandTab.Events ); - Span label = stackalloc char[60]; + PanelAt( x, y, OfficeWidth, CommandHeight( tab, fleet ), SpaceDraw.Cyan ); + for ( int i = 0; i < TabNames.Length; ++i ) + IconButton( x + 7 + i * 68, y + 8, 65, TabIcons[i], TabNames[i], true, (int)tab == i + 1 ); + Span label = stackalloc char[56]; switch ( tab ) { case CommandTab.Economy: - Text( "COLONY AND RESEARCH", x + 11, y + 42, 1.25f, White ); - label.TryWrite( $"{fleet.BodyName( FleetSimulation.Homeworld )} / {fleet.Ore} ORE / {fleet.Science} SCI", out int length ); - Text( label[..length], x + 11, y + 62, 1, Label ); - int oreRate = 0, scienceRate = 0; - for ( int body = 1; body < fleet.Bodies.Length; ++body ) { - var status = fleet.Planet( body ); - if ( status.MineRemaining == 0 ) oreRate += fleet.DepositYield( body ); - if ( status.LabRemaining == 0 ) scienceRate += 6; - } - label.TryWrite( $"PER CYCLE +{oreRate} ORE +{scienceRate} SCI", out length ); - Text( label[..length], x + 11, y + 80, 1, Label ); - Button( x + 10, y + 101, 308, "BUILD MINER / 20 ORE", fleet.CanQueueWorker ); - Button( x + 10, y + 130, 308, "REPLACE SCOUT / 24 ORE", fleet.CanQueueScout ); - Button( x + 10, y + 159, 308, fleet.DriveUpgrade ? "LONG BURN DRIVE ONLINE" : "LONG BURN DRIVE / 36 SCI", - !fleet.DriveUpgrade && fleet.Science >= FleetSimulation.DriveCost ); - Text( fleet.WorkerRemaining > 0 ? "CIVILIAN PRODUCTION ACTIVE / ORDERS" : "CLICK A BODY TO MANAGE ITS SITES", - x + 11, y + 195, 1, Label ); + Text( "COLONY ECONOMY", x + 11, y + 42, 1.25f, White ); + Text( "STOCKPILE AND INCOME PER CYCLE", x + 11, y + 62, 1, Label ); + Wallet( fleet, x + 11, y + 81, income: true ); + Text( "ORE / CONSTRUCTION AND HULL MATERIAL", x + 11, y + 103, 1, OreTint ); + Text( "ENERGY / SHIPYARDS AND INDUSTRY", x + 11, y + 119, 1, EnergyTint ); + Text( "SCIENCE / RESEARCH PROJECTS", x + 11, y + 135, 1, ScienceTint ); + if ( fleet.Established ) IconButton( x + 10, y + 153, 328, HudIcon.Yard, "OPEN EARTH CIVILIAN DOCK", true ); + else Text( "NO SOL PRESENCE IN THIS SYSTEM", x + 11, y + 155, 1, Label ); + break; + case CommandTab.Research: + ResearchPanel( x, y, fleet, speed ); break; case CommandTab.Fleet: var design = fleet.Design; Text( "CORVETTE BLUEPRINT", x + 11, y + 41, 1.27f, White ); - Text( "LOADOUT FOR NEW WINGS", x + 11, y + 59, 1, Label ); - Button( x + 10, y + 76, 150, "PULSE / RAPID FIRE", true, design.Weapon == WeaponKind.Pulse ); - Button( x + 168, y + 76, 150, "RAIL / PIERCING", true, design.Weapon == WeaponKind.Rail ); - Button( x + 10, y + 102, 150, "SHIELD GENERATOR", true, !design.Plating ); - Button( x + 168, y + 102, 150, "HEAVY PLATING", true, design.Plating ); - label.TryWrite( $"PER SHIP HULL {FleetSimulation.HullCapacity} SHIELD {design.Shield} ARMOR {design.Armor}", out length ); - Text( label[..length], x + 11, y + 132, 1, Label ); - label.TryWrite( $"{design.Damage} DAMAGE / {design.Range} RANGE / {design.Reload}T RELOAD", out length ); - Text( label[..length], x + 11, y + 149, 1, Label ); - label.TryWrite( $"3 SHIPS / {fleet.CurrentWingCost} ORE / {Seconds( fleet.CurrentWingDuration, speed )} SEC AT {speed}X", out length ); - Text( label[..length], x + 11, y + 168, 1, White ); - if ( fleet.CanBuildWing ) label.TryWrite( $"QUEUE AT {fleet.BodyName( fleet.YardBody )}", out length ); - else length = CopyStatus( fleet.YardRemaining != 0 ? "REQUIRES AN ONLINE SHIPYARD" : "QUEUE / ORE / NAVAL LIMIT", label ); - Button( x + 10, y + 189, 308, label[..length], fleet.CanBuildWing ); + Text( "LOADOUT FOR FUTURE SHIP ORDERS", x + 11, y + 59, 1, Label ); + Button( x + 10, y + 76, 160, "PULSE / RAPID FIRE", true, design.Weapon == WeaponKind.Pulse ); + Button( x + 178, y + 76, 160, "RAIL / PIERCING", true, design.Weapon == WeaponKind.Rail ); + Button( x + 10, y + 102, 160, "SHIELD GENERATOR", true, !design.Plating ); + Button( x + 178, y + 102, 160, "HEAVY PLATING", true, design.Plating ); + label.TryWrite( $"HULL {FleetSimulation.HullCapacity} / SHIELD {design.Shield} / ARMOR {design.Armor}", out int length ); + Text( label[..length], x + 11, y + 133, 1, Label ); + label.TryWrite( $"{design.Damage} DAMAGE / {design.Range} RANGE / {design.Reload}T RELOAD", out length ); + Text( label[..length], x + 11, y + 150, 1, Label ); + Cost( fleet.Hull( HullBlueprint.Corvette ).Cost, x + 12, y + 170 ); + Text( "PER HULL", x + 92, y + 171, 1, White ); + Text( "ORDER THIS DESIGN AT AN ORBITAL SHIPYARD", x + 11, y + 190, 1, Label ); break; case CommandTab.Orders: - Text( "PRODUCTION QUEUE", x + 11, y + 42, 1.25f, White ); + Text( "PRODUCTION SITES", x + 11, y + 42, 1.25f, White ); label.TryWrite( $"NAVAL {fleet.NavalUsed} ACTIVE +{fleet.NavalReserved} QUEUED / {fleet.NavalCapacity}", out length ); Text( label[..length], x + 11, y + 61, 1, Label ); - for ( int i = 0; i < FleetSimulation.WingGoal; ++i ) { - float row = y + 80 + 31 * i; - if ( i >= fleet.WingQueue.Length ) { - Text( i == 0 ? "NO WINGS QUEUED" : "SECOND SLOT OPEN", x + 11, row + 7, 1, Label ); - continue; - } - var job = fleet.WingQueue[i]; - label.TryWrite( $"{fleet.BodyName( job.Body )} {(job.Design.Weapon == WeaponKind.Rail ? "RAIL" : "PULSE")} WING", out length ); - Text( label[..length], x + 11, row, 1, White ); - if ( i == 0 ) label.TryWrite( $"{Seconds( fleet.WingRemaining, speed )} SEC LEFT / {job.Cost} ORE", out length ); - else label.TryWrite( $"WAITING / {job.Cost} ORE", out length ); - Text( label[..length], x + 11, row + 12, 1, Label ); - Button( x + 246, row, 72, "CANCEL", true ); + int row = 0; + for ( int body = 1; body < fleet.Bodies.Length; ++body ) { + if ( !fleet.CanOpenYard( body ) ) continue; + int jobs = fleet.YardQueue( body ).Length; + if ( jobs == 0 ) label.TryWrite( $"{fleet.BodyName( body )} / IDLE", out length ); + else label.TryWrite( $"{fleet.BodyName( body )} / {jobs} QUEUED / {Seconds( fleet.ShipRemaining( body ), speed )} SEC", out length ); + IconButton( x + 10, y + 77 + row++ * 21, 328, HudIcon.Yard, label[..length], true ); } - if ( fleet.WorkerRemaining > 0 ) { - label.TryWrite( $"{(fleet.CivilianOrder == HullRole.Miner ? "MINER" : "SCOUT")} / {Seconds( fleet.WorkerRemaining, speed )} SEC LEFT", out length ); - Text( label[..length], x + 11, y + 150, 1, White ); - Button( x + 246, y + 145, 72, "CANCEL", true ); - } else Text( "CIVILIAN BERTH OPEN", x + 11, y + 150, 1, Label ); - Text( "SITE PROJECTS ARE LISTED ON EACH BODY", x + 11, y + 182, 1, Label ); + if ( row == 0 ) Text( "NO SOL PRODUCTION SITES", x + 11, y + 79, 1, Label ); break; case CommandTab.Events: + if ( fleet.DispatchCount == 0 ) { + Text( "SYSTEM CONTACTS", x + 11, y + 43, 1.25f, White ); + Text( "FREE MERCHANTS / NEUTRAL", x + 11, y + 69, 1, Label ); + Text( "NO SOL PRESENCE OR CAMPAIGN DISPATCHES", x + 11, y + 88, 1, Label ); + break; + } var (title, first, second) = IncidentText( fleet.Dispatch( dispatch ) ); Text( title, x + 11, y + 43, 1.23f, White ); Text( first, x + 11, y + 69, 1, Label ); Text( second, x + 11, y + 88, 1, Label ); Button( x + 10, y + 116, 74, "EARLIER", dispatch > 0 ); - Button( x + 244, y + 116, 74, "LATER", dispatch + 1 < fleet.DispatchCount ); + Button( x + 265, y + 116, 74, "LATER", dispatch + 1 < fleet.DispatchCount ); label.TryWrite( $"{dispatch + 1}/{fleet.DispatchCount}", out length ); - Text( label[..length], x + 148, y + 123, 1, Label ); + Text( label[..length], x + 153, y + 123, 1, Label ); break; } _overlay = 0; - - void Nav( int slot, string name, CommandTab target ) => - Button( layout.ClockX - 312 + slot * 78, 19, 72, name, true, tab == target ); } internal static string IncidentTitle( FrontierEvent incident ) => IncidentText( incident ).Title; private static (string Title, string First, string Second) IncidentText( FrontierEvent incident ) => incident switch { - FrontierEvent.Arrival => ("FRONTIER CHARTER", "SURVEY A MOON OR PLANET WITH YOUR SCOUT", "SEND A MINER TO BUILD ON A DEPOSIT"), - FrontierEvent.Prospect => ("ORE SIGNATURE CONFIRMED", "SELECT A MINER AND INSPECT THE BODY", "PLACE AN EXTRACTION RIG"), - FrontierEvent.Distress => ("DISTRESS SIGNAL", "AMBER HAS NOTICED YOUR EXTRACTION", "BUILD A YARD AND KEEP WORKERS CLEAR"), - FrontierEvent.Raid => ("AMBER RAID INBOUND", "CONTACTS ARE APPROACHING THE YARD", "MOVE CIVILIANS CLEAR AND DEPLOY ESCORTS"), - FrontierEvent.Counterattack => ("AMBER COUNTERATTACK", "RAIL CORVETTES ARE APPROACHING", "RAIL SHOTS BYPASS SHIELDS"), - FrontierEvent.Secured => ("SYSTEM SECURED", "THE RAIDERS HAVE BEEN DRIVEN OFF", "YOUR OUTPOST CAN EXPAND"), + FrontierEvent.Arrival => ("FRONTIER CHARTER", "SURVEY A MOON OR PLANET WITH YOUR SCOUT", "SEND A CONSTRUCTOR TO BUILD ON A DEPOSIT"), + FrontierEvent.Prospect => ("ORE SIGNATURE CONFIRMED", "SELECT A CONSTRUCTOR AND INSPECT THE BODY", "PLACE AN EXTRACTION RIG"), + FrontierEvent.Distress => ("DISTRESS SIGNAL", "RAIDERS HAVE NOTICED YOUR EXTRACTION", "BUILD A SHIPYARD AND KEEP CIVILIANS CLEAR"), + FrontierEvent.Raid => ("AMBER RAID INBOUND", "RAIDERS ARE APPROACHING YOUR SITES", "OPEN A SHIPYARD TO ORDER ESCORTS"), + FrontierEvent.Counterattack => ("RIVAL COMMAND CONTACT", "RAIL CORVETTES ARE APPROACHING", "RAIL SHOTS BYPASS SHIELDS"), + FrontierEvent.Secured => ("SYSTEM SECURED", "HOSTILE CONTACTS HAVE BEEN DRIVEN OFF", "YOUR OUTPOST CAN EXPAND"), _ => throw new ArgumentOutOfRangeException( nameof(incident) ) }; - private static HudHit HitCommand( Layout layout, Vector2 p, CommandTab tab ) { - if ( layout.Width >= 700 ) { - for ( int i = 0; i < 4; ++i ) - if ( Contains( p, layout.ClockX - 312 + i * 78, 19, 72, 21 ) ) + private static HudHit HitCommand( Layout layout, Vector2 p, FleetSimulation fleet, CommandTab tab ) { + if ( layout.Width >= 780 ) { + for ( int i = 0; i < TabNames.Length; ++i ) + if ( Contains( p, layout.ClockX - 358 + i * 71, 19, 68, 21 ) ) return Action( (CommandAction)((int)CommandAction.Economy + i) ); } else if ( Contains( p, layout.ClockX - 89, 19, 83, 21 ) ) return Action( CommandAction.Toggle ); if ( tab == CommandTab.Hidden ) return default; var (x, y) = CommandOrigin( layout ); - if ( !Contains( p, x, y, OfficeWidth, CommandHeight( tab ) ) ) return default; - for ( int i = 0; i < 4; ++i ) - if ( Contains( p, x + 10 + i * 79, y + 8, 71, 21 ) ) + if ( !Contains( p, x, y, OfficeWidth, CommandHeight( tab, fleet ) ) ) return default; + for ( int i = 0; i < TabNames.Length; ++i ) + if ( Contains( p, x + 7 + i * 68, y + 8, 65, 21 ) ) return Action( (CommandAction)((int)CommandAction.Economy + i) ); var relative = p - new Vector2( x, y ); + if ( tab == CommandTab.Research ) { + for ( int i = 0; i < 3; ++i ) { + var topic = (ResearchTopic)i; + if ( !Contains( relative, 270, 102 + i * 53, 64, 21 ) ) continue; + if ( fleet.ActiveResearch == topic ) return Action( CommandAction.CancelResearch ); + if ( fleet.CanResearch( topic ) ) return Action( (CommandAction)((int)CommandAction.StartIndustry + i) ); + } + } + if ( tab == CommandTab.Orders ) { + int row = 0; + for ( int body = 1; body < fleet.Bodies.Length; ++body ) + if ( fleet.CanOpenYard( body ) && Contains( relative, 10, 77 + row++ * 21, 328, 21 ) ) return new( HudAction.OpenYard, body ); + } return tab switch { - CommandTab.Economy when Contains( relative, 10, 101, 308, 21 ) => Action( CommandAction.Worker ), - CommandTab.Economy when Contains( relative, 10, 130, 308, 21 ) => Action( CommandAction.Scout ), - CommandTab.Economy when Contains( relative, 10, 159, 308, 21 ) => Action( CommandAction.Drive ), - CommandTab.Fleet when Contains( relative, 10, 76, 150, 21 ) => Action( CommandAction.Pulse ), - CommandTab.Fleet when Contains( relative, 168, 76, 150, 21 ) => Action( CommandAction.Rail ), - CommandTab.Fleet when Contains( relative, 10, 102, 150, 21 ) => Action( CommandAction.Shield ), - CommandTab.Fleet when Contains( relative, 168, 102, 150, 21 ) => Action( CommandAction.Plating ), - CommandTab.Fleet when Contains( relative, 10, 189, 308, 21 ) => Action( CommandAction.Wing ), - CommandTab.Orders when Contains( relative, 246, 80, 72, 21 ) => Action( CommandAction.CancelFirstWing ), - CommandTab.Orders when Contains( relative, 246, 111, 72, 21 ) => Action( CommandAction.CancelSecondWing ), - CommandTab.Orders when Contains( relative, 246, 145, 72, 21 ) => Action( CommandAction.CancelCivilian ), + CommandTab.Economy when fleet.Established && Contains( relative, 10, 153, 328, 21 ) => new( HudAction.OpenYard, FleetSimulation.Homeworld ), + CommandTab.Fleet when Contains( relative, 10, 76, 160, 21 ) => Action( CommandAction.Pulse ), + CommandTab.Fleet when Contains( relative, 178, 76, 160, 21 ) => Action( CommandAction.Rail ), + CommandTab.Fleet when Contains( relative, 10, 102, 160, 21 ) => Action( CommandAction.Shield ), + CommandTab.Fleet when Contains( relative, 178, 102, 160, 21 ) => Action( CommandAction.Plating ), CommandTab.Events when Contains( relative, 10, 116, 74, 21 ) => Action( CommandAction.Earlier ), - CommandTab.Events when Contains( relative, 244, 116, 74, 21 ) => Action( CommandAction.Later ), + CommandTab.Events when Contains( relative, 265, 116, 74, 21 ) => Action( CommandAction.Later ), _ => new( HudAction.Panel ) }; diff --git a/samples/FleetBattler/Industry.cs b/samples/FleetBattler/Industry.cs new file mode 100644 index 0000000..5663038 --- /dev/null +++ b/samples/FleetBattler/Industry.cs @@ -0,0 +1,178 @@ +using System.Numerics; + +namespace FleetBattler; + +internal readonly record struct ResourceCost( int Ore, int Energy, int Science = 0 ); +internal enum ResearchTopic { Industry, Weapons, Drive } +internal readonly record struct Technology( string Name, string Benefit, ResourceCost Cost, int Duration ); +internal readonly record struct HullPlan( string Name, HullRole Role, ResourceCost Cost, int Duration ); +internal enum HullBlueprint { Scout, Miner, Corvette } +internal readonly record struct ShipyardOrder( HullBlueprint Hull, ShipDesign Design, ResourceCost Cost, int Duration ); +internal readonly record struct YardLaunch( int Body, int Ship, HullBlueprint Hull ); + +internal sealed partial class FleetSimulation { + internal const int YardQueueLimit = 4; + internal const int SolarOutput = 8; + private const int EarthOutput = 3; + + private readonly ShipyardOrder[] _shipOrdersAtYards = new ShipyardOrder[CelestialSystem.BodyCount * YardQueueLimit]; + private readonly int[] _yardQueueSizes = new int[CelestialSystem.BodyCount], _yardShipReady = new int[CelestialSystem.BodyCount]; + private int _navalReserved, _minersReserved, _scoutsReserved; + private int _researchReady; + internal int Energy { get; private set; } + internal bool Established => Frontier && Solar; + internal ResearchTopic? ActiveResearch { get; private set; } + internal int ResearchRemaining => Remaining( _researchReady ); + internal ResearchTopic LastTechnology { get; private set; } + internal int CompletedResearch { get; private set; } + internal YardLaunch LastLaunch { get; private set; } + internal int ShipsLaunched { get; private set; } + internal int CorvettesLaunched { get; private set; } + internal int EnergyIncome => (Established ? EarthOutput : 0) + Online( _solarArrays ) * SolarOutput; + internal int ScienceIncome => Online( _labs ) * 6; + internal int OreIncome { + get { + int sum = 0; + for ( int i = 1; i < _bodies.Length; ++i ) + if ( _mines[i] > 0 && _mines[i] <= Tick ) sum += DepositYield( i ); + return sum; + } + } + + internal static Technology Tech( ResearchTopic topic ) => topic switch { + ResearchTopic.Industry => new( "ORBITAL FABRICATION", "LOWER CORVETTE ORE AND BUILD TIME", new( 0, 12, IndustryCost ), 240 ), + ResearchTopic.Weapons => new( "FIRE CONTROL", "+4 CORVETTE DAMAGE / +3 RANGE", new( 0, 16, UpgradeCost ), 300 ), + ResearchTopic.Drive => new( "LONG BURN DRIVE", "UNLOCK OUTER PLANETS AND KUIPER BELT", new( 0, 20, DriveCost ), 360 ), + _ => throw new ArgumentOutOfRangeException( nameof(topic) ) + }; + + internal bool Researched( ResearchTopic topic ) => topic switch { + ResearchTopic.Industry => IndustryUpgrade, ResearchTopic.Weapons => WeaponUpgrade, _ => DriveUpgrade + }; + + internal bool CanResearch( ResearchTopic topic ) => Frontier && ActiveResearch is null && !Researched( topic ) && + ScienceIncome > 0 && CanAfford( Tech( topic ).Cost ); + + internal bool StartResearch( ResearchTopic topic ) { + if ( !CanResearch( topic ) ) return false; + var tech = Tech( topic ); + Spend( tech.Cost ); + ActiveResearch = topic; + _researchReady = Tick + tech.Duration; + return true; + } + + internal bool CancelResearch( ) { + if ( ActiveResearch is not { } topic ) return false; + Refund( Tech( topic ).Cost ); + ActiveResearch = null; + _researchReady = 0; + return true; + } + + private void AdvanceIndustry( ) { + if ( !Frontier ) return; + if ( (Tick + 1) % IncomeInterval == 0 ) Energy = Math.Min( 999, Energy + EnergyIncome ); + if ( ActiveResearch is { } topic && _researchReady <= Tick + 1 ) { + switch ( topic ) { + case ResearchTopic.Industry: IndustryUpgrade = true; break; + case ResearchTopic.Weapons: WeaponUpgrade = true; break; + case ResearchTopic.Drive: DriveUpgrade = true; break; + } + ActiveResearch = null; + _researchReady = 0; + LastTechnology = topic; + ++CompletedResearch; + } + for ( int body = 1; body < _bodies.Length; ++body ) { + if ( _yardQueueSizes[body] == 0 || _yardShipReady[body] > Tick + 1 ) continue; + var order = YardQueue( body )[0]; + var position = YardPosition( body, Tick + 1 ); + var radial = Vector2.Normalize( position - _bodies[body].Center ); + var arrival = position + radial * (3.5f + ShipsLaunched % 3 * 2.5f); + int squad = AddSquad( 1, (int)FactionId.Sol, arrival, Hull( order.Hull ).Role, order.Design ); + Park( squad, body, Tick + 1 ); + LastLaunch = new( body, _squads[squad].First, order.Hull ); + ++ShipsLaunched; + if ( order.Hull == HullBlueprint.Corvette ) ++CorvettesLaunched; + RemoveShipOrder( body, 0, Tick + 1 ); + } + } + + internal HullPlan Hull( HullBlueprint blueprint ) => blueprint switch { + HullBlueprint.Scout => new( "SURVEY SCOUT", HullRole.Scout, new( 24, 6 ), 240 ), + HullBlueprint.Miner => new( "MINER / CONSTRUCTOR", HullRole.Miner, new( 20, 5 ), 240 ), + HullBlueprint.Corvette => new( "CORVETTE", HullRole.Corvette, + new( (IndustryUpgrade ? 14 : 20) + (Design.Plating ? 3 : 0), Design.Plating ? 10 : 8 ), + (IndustryUpgrade ? 100 : 160) + (Design.Plating ? 20 : 0) ), + _ => throw new ArgumentOutOfRangeException( nameof(blueprint) ) + }; + + internal bool CanOpenYard( int body ) => Frontier && (uint)body < (uint)_bodies.Length && body > 0 && + (YardAt( body ) == 0 || Established && body == Homeworld); + internal ReadOnlySpan YardQueue( int body ) => + _shipOrdersAtYards.AsSpan( body * YardQueueLimit, _yardQueueSizes[body] ); + internal int ShipRemaining( int body ) => Remaining( _yardShipReady[body] ); + + internal string? ShipOrderBlock( int body, HullBlueprint blueprint ) { + if ( !CanOpenYard( body ) ) return "REQUIRES AN ONLINE SHIPYARD"; + if ( _yardQueueSizes[body] == YardQueueLimit ) return "QUEUE FULL"; + if ( blueprint == HullBlueprint.Corvette ) { + if ( YardAt( body ) != 0 ) return "REQUIRES AN ORBITAL SHIPYARD"; + if ( NavalUsed + _navalReserved >= NavalCapacity ) return "NAVAL CAPACITY FULL"; + } + if ( blueprint == HullBlueprint.Scout && ActiveScouts( ) + _scoutsReserved >= 2 ) return "SCOUT LIMIT REACHED"; + if ( blueprint == HullBlueprint.Miner && ActiveMiners( ) + _minersReserved >= MaxWorkers ) return "CONSTRUCTOR LIMIT REACHED"; + var cost = Hull( blueprint ).Cost; + if ( Ore < cost.Ore ) return "INSUFFICIENT ORE"; + if ( Energy < cost.Energy ) return "INSUFFICIENT ENERGY"; + return null; + } + + internal bool QueueShip( int body, HullBlueprint blueprint ) { + if ( ShipOrderBlock( body, blueprint ) is not null ) return false; + var hull = Hull( blueprint ); + int index = _yardQueueSizes[body]++; + _shipOrdersAtYards[body * YardQueueLimit + index] = new( blueprint, Design, hull.Cost, hull.Duration ); + Spend( hull.Cost ); + ReserveShip( blueprint, 1 ); + if ( index == 0 ) _yardShipReady[body] = Tick + hull.Duration; + return true; + } + + internal bool CancelShip( int body, int index ) { + if ( !CanOpenYard( body ) || (uint)index >= (uint)_yardQueueSizes[body] ) return false; + Refund( YardQueue( body )[index].Cost ); + RemoveShipOrder( body, index, Tick ); + return true; + } + + private void RemoveShipOrder( int body, int index, int start ) { + int offset = body * YardQueueLimit; + ReserveShip( _shipOrdersAtYards[offset + index].Hull, -1 ); + int size = --_yardQueueSizes[body]; + _shipOrdersAtYards.AsSpan( offset + index + 1, size - index ).CopyTo( _shipOrdersAtYards.AsSpan( offset + index ) ); + if ( index == 0 ) _yardShipReady[body] = size == 0 ? 0 : start + _shipOrdersAtYards[offset].Duration; + } + + private void ReserveShip( HullBlueprint hull, int delta ) { + switch ( hull ) { + case HullBlueprint.Scout: _scoutsReserved += delta; break; + case HullBlueprint.Miner: _minersReserved += delta; break; + case HullBlueprint.Corvette: _navalReserved += delta; break; + } + } + + internal bool CanAfford( ResourceCost cost ) => Ore >= cost.Ore && Energy >= cost.Energy && Science >= cost.Science; + private void Spend( ResourceCost cost ) { + Ore -= cost.Ore; + Energy -= cost.Energy; + Science -= cost.Science; + } + + private void Refund( ResourceCost cost ) { + Ore = Math.Min( 999, Ore + cost.Ore ); + Energy = Math.Min( 999, Energy + cost.Energy ); + Science = Math.Min( 999, Science + cost.Science ); + } +} diff --git a/samples/FleetBattler/IndustryHud.cs b/samples/FleetBattler/IndustryHud.cs new file mode 100644 index 0000000..49cb3f3 --- /dev/null +++ b/samples/FleetBattler/IndustryHud.cs @@ -0,0 +1,151 @@ +using System.Numerics; + +namespace FleetBattler; + +internal enum HudIcon { Ore, Energy, Science, Colony, Design, Orders, Log, Merge, Split, Yard } + +internal sealed partial class FleetHud { + private static readonly Vector4 OreTint = new( 0.92f, 0.68f, 0.44f, 1 ); + private static readonly Vector4 EnergyTint = new( 0.99f, 0.84f, 0.36f, 1 ); + private static readonly Vector4 ScienceTint = new( 0.48f, 0.85f, 1, 1 ); + private static readonly ulong[] Icons = [ + 0x020e3ae7ddf1c, 0x00820c7e30c30, 0x0d8e7793dce36, 0x1ff1e3eef8e08, 0x08b1f77c70e08, + 0x1fe0dd83760ff, 0x0f913a44e913e, 0x02041cfe20a22, 0x088a08fe70408, 0x18f5ff55ff5e3 + ]; + + private void Icon( HudIcon icon, float x, float y, float size, Vector4 tint ) { + ulong bits = Icons[(int)icon]; + _glyphs[_count++] = new( new Vector4( x, y, size, size ) * _scale, tint, (uint)bits, (uint)(bits >> 32), 7, _overlay ); + } + + private void IconButton( float x, float y, float width, HudIcon icon, ReadOnlySpan title, bool enabled, bool active = false ) { + Rect( x, y, width, 21, active ? Active : Well ); + Vector4 tint = active ? White : enabled ? SpaceDraw.Cyan : Disabled; + Icon( icon, x + 4, y + 5, 11, tint ); + Text( title, x + 19, y + 7, 1, tint ); + } + + private void Wallet( FleetSimulation fleet, float x, float y, bool income = false ) { + Resource( HudIcon.Ore, fleet.Ore, fleet.OreIncome, OreTint, x ); + Resource( HudIcon.Energy, fleet.Energy, fleet.EnergyIncome, EnergyTint, x + (income ? 98 : 55) ); + Resource( HudIcon.Science, fleet.Science, fleet.ScienceIncome, ScienceTint, x + (income ? 196 : 110) ); + + void Resource( HudIcon icon, int balance, int rate, Vector4 tint, float left ) { + Icon( icon, left, y, 10, tint ); + Span line = stackalloc char[18]; + int length; + if ( income ) line.TryWrite( $"{balance} +{rate}", out length ); + else line.TryWrite( $"{balance}", out length ); + Text( line[..length], left + 14, y + 1, 1, tint ); + } + } + + private const float YardWidth = 422, YardTop = 61, YardHeight = 240; + private static float YardLeft( Layout layout ) => (layout.Width - YardWidth) / 2; + + private void DrawShipyard( Layout layout, FleetSimulation fleet, int body, int speed ) { + float x = YardLeft( layout ), y = YardTop; + _overlay = 2; + PanelAt( x, y, YardWidth, YardHeight, EnergyTint ); + Icon( HudIcon.Yard, x + 11, y + 10, 16, EnergyTint ); + Text( fleet.YardAt( body ) == 0 ? "ORBITAL SHIPYARD" : "CIVILIAN DOCK", x + 35, y + 10, 1.45f, White ); + Text( fleet.BodyName( body ), x + 35, y + 32, 1, Label ); + Button( x + 390, y + 8, 22, "X", true ); + Wallet( fleet, x + 216, y + 31 ); + Rect( x + 220, y + 59, 1, 163, Well ); + Text( "SHIP DESIGNS", x + 11, y + 60, 1.15f, White ); + Text( "BUILD QUEUE", x + 233, y + 60, 1.15f, White ); + + Span label = stackalloc char[44]; + int length; + for ( int i = 0; i < 3; ++i ) { + var blueprint = (HullBlueprint)i; + var hull = fleet.Hull( blueprint ); + float row = y + 80 + i * 45; + Rect( x + 10, row, 202, 41, Well ); + Art( HullArt( hull.Role ), x + 11, row + 2, 34, 33 ); + Text( hull.Name, x + 50, row + 5, 1, White ); + string? block = fleet.ShipOrderBlock( body, blueprint ); + Cost( hull.Cost, x + 50, row + 17 ); + if ( block is null ) label.TryWrite( $"{Seconds( hull.Duration, speed )} SEC", out length ); + else length = CopyStatus( block, label ); + Text( label[..length], x + 50, row + 29, 1, block is null ? Label : Disabled ); + if ( block is null ) Button( x + 170, row + 13, 37, "ADD", true ); + } + + var orders = fleet.YardQueue( body ); + for ( int i = 0; i < FleetSimulation.YardQueueLimit; ++i ) { + float row = y + 80 + i * 33; + Rect( x + 232, row, 179, 30, i == 0 && !orders.IsEmpty ? Active : Well ); + if ( i >= orders.Length ) { + Text( i == 0 ? "IDLE" : "OPEN", x + 240, row + 8, 1, Label ); + continue; + } + var order = orders[i]; + Text( order.Hull switch { HullBlueprint.Scout => "SURVEY SCOUT", HullBlueprint.Miner => "CONSTRUCTOR", + _ => order.Design.Weapon == WeaponKind.Rail ? "RAIL CORVETTE" : "PULSE CORVETTE" }, x + 239, row + 4, 1, White ); + int remaining = fleet.ShipRemaining( body ); + if ( i == 0 ) label.TryWrite( $"BUILDING / {Seconds( remaining, speed )} SEC", out length ); + else length = CopyStatus( "WAITING", label ); + Text( label[..length], x + 239, row + 15, 1, Label ); + if ( i == 0 ) Progress( new( x + 239, row + 25 ), 128, 1f - (float)remaining / order.Duration, EnergyTint ); + Button( x + 386, row + 4, 20, "X", true ); + } + Text( "ONE HULL PER ORDER", x + 11, y + 222, 1, Label ); + _overlay = 0; + } + + private static HudHit HitShipyard( Layout layout, Vector2 p, FleetSimulation fleet, int body ) { + float x = YardLeft( layout ), y = YardTop; + if ( !Contains( p, x, y, YardWidth, YardHeight ) ) return default; + if ( Contains( p, x + 390, y + 8, 22, 21 ) ) return new( HudAction.CloseYard ); + for ( int i = 0; i < 3; ++i ) + if ( Contains( p, x + 170, y + 93 + i * 45, 37, 21 ) && fleet.ShipOrderBlock( body, (HullBlueprint)i ) is null ) + return new( HudAction.BuildShip, i ); + for ( int i = 0; i < fleet.YardQueue( body ).Length; ++i ) + if ( Contains( p, x + 386, y + 84 + i * 33, 20, 21 ) ) return new( HudAction.CancelShip, i ); + return new( HudAction.Panel ); + } + + private void Cost( ResourceCost cost, float x, float y ) { + if ( cost.Ore > 0 ) { Value( HudIcon.Ore, cost.Ore, OreTint ); x += 37; } + if ( cost.Energy > 0 ) { Value( HudIcon.Energy, cost.Energy, EnergyTint ); x += 37; } + if ( cost.Science > 0 ) Value( HudIcon.Science, cost.Science, ScienceTint ); + + void Value( HudIcon icon, int amount, Vector4 tint ) { + Icon( icon, x, y, 9, tint ); + Span text = stackalloc char[10]; + text.TryWrite( $"{amount}", out int length ); + Text( text[..length], x + 12, y + 1, 1, tint ); + } + } + + private void ResearchPanel( float x, float y, FleetSimulation fleet, int speed ) { + Text( "RESEARCH PROJECTS", x + 11, y + 42, 1.25f, White ); + Text( fleet.ScienceIncome == 0 ? "BUILD A RESEARCH LAB TO START" : "ONE ACTIVE PROJECT / COST RESERVED ON START", x + 11, y + 60, 1, Label ); + Span line = stackalloc char[40]; + for ( int i = 0; i < 3; ++i ) { + var topic = (ResearchTopic)i; + var tech = FleetSimulation.Tech( topic ); + float row = y + 77 + i * 53; + Rect( x + 10, row, 330, 49, fleet.ActiveResearch == topic ? Active : Well ); + Text( tech.Name, x + 17, row + 6, 1.1f, White ); + Text( tech.Benefit, x + 17, row + 20, 1, Label ); + if ( fleet.Researched( topic ) ) { + Text( "COMPLETE", x + 17, row + 34, 1, SpaceDraw.Cyan ); + continue; + } + if ( fleet.ActiveResearch == topic ) { + line.TryWrite( $"{Seconds( fleet.ResearchRemaining, speed )} SEC LEFT", out int length ); + Text( line[..length], x + 17, row + 33, 1, ScienceTint ); + Progress( new( x + 124, row + 36 ), 105, 1f - (float)fleet.ResearchRemaining / tech.Duration, ScienceTint ); + Button( x + 270, row + 25, 64, "CANCEL", true ); + } else { + Cost( tech.Cost, x + 17, row + 33 ); + line.TryWrite( $"{Seconds( tech.Duration, speed )} SEC AT {speed}X", out int length ); + Text( line[..length], x + 104, row + 34, 1, Label ); + Button( x + 270, row + 25, 64, "START", fleet.CanResearch( topic ) ); + } + } + } +} diff --git a/samples/FleetBattler/OperationsFeedback.cs b/samples/FleetBattler/OperationsFeedback.cs index 68c7195..1a556f9 100644 --- a/samples/FleetBattler/OperationsFeedback.cs +++ b/samples/FleetBattler/OperationsFeedback.cs @@ -2,27 +2,28 @@ namespace FleetBattler; -internal readonly record struct MapSite( Vector2 Pixel, int Body, PlanetFacility Facility, int Remaining, int Duration ); +internal readonly record struct MapSite( Vector2 Pixel, int Body, PlanetFacility Facility, int Remaining, int Duration, bool Producing = false ); internal enum HoverKind { None, Ship, Site, Body } internal readonly record struct MapHover( HoverKind Kind, int Index, Vector2 Target, Vector2 Pointer ); internal sealed partial class FleetHud { - internal static string SiteName( PlanetFacility facility ) => facility switch { - PlanetFacility.Mine => "EXTRACTION RIG", PlanetFacility.Lab => "RESEARCH LAB", - PlanetFacility.Depot => "LOGISTICS DEPOT", _ => "ORBITAL SHIPYARD" - }; + internal static string SiteName( PlanetFacility facility ) => FleetSimulation.Facility( facility ).Name; private void OperationsFeedback( Layout layout, FleetSimulation fleet, ReadOnlySpan bodies, ReadOnlySpan sites, MapHover hover, int speed, int planet ) { foreach ( var site in sites ) { - if ( site.Remaining <= 0 ) continue; + if ( site.Remaining <= 0 ) { + if ( site.Facility == PlanetFacility.Yard ) + MapLabel( site.Pixel, fleet.YardAt( site.Body ) == 0 ? "SHIPYARD" : "CIVILIAN DOCK", layout, fleet, planet ); + continue; + } var point = site.Pixel / _scale; if ( point.X < 28 || point.X >= layout.Width - 28 || point.Y < 70 || point.Y >= layout.Bottom - 17 || layout.Blocks( point, fleet, planet ) ) continue; - bool enRoute = site.Facility == PlanetFacility.Mine && fleet.MineEnRoute( site.Body ); + bool enRoute = !site.Producing && fleet.SiteEnRoute( site.Body, site.Facility ); Progress( point + new Vector2( -19, 12 ), 38, 1 - (float)site.Remaining / site.Duration, enRoute ? Label : SpaceDraw.Amber ); - Text( enRoute ? "EN ROUTE" : site.Facility == PlanetFacility.Yard && fleet.ActiveYard == site.Body ? "YARD WORK" : "BUILD", - point.X - (enRoute ? 24 : 15), point.Y + 18, 1, enRoute ? Label : SpaceDraw.Amber ); + string status = enRoute ? "EN ROUTE" : site.Producing ? "BUILDING SHIP" : "CONSTRUCTION"; + Text( status, point.X - TextWidth( status.Length, 1 ) / 2, point.Y + 18, 1, enRoute ? Label : SpaceDraw.Amber ); } for ( int body = 1; body < bodies.Length; ++body ) { var status = fleet.Planet( body ); @@ -42,14 +43,17 @@ private void OperationsFeedback( Layout layout, FleetSimulation fleet, ReadOnlyS case HoverKind.Ship: int ship = hover.Index; var role = fleet.Role( fleet.SquadronOf( ship ) ); - tint = fleet.SideOf( ship ) == 0 ? SpaceDraw.Cyan : SpaceDraw.Amber; - title.TryWrite( $"{(fleet.SideOf( ship ) == 0 ? "CYAN" : "AMBER")} {(role == HullRole.Scout ? "SCOUT" : role == HullRole.Miner ? "MINER" : "CORVETTE")} {ship + 1}", out titleLength ); - detail.TryWrite( $"HULL {fleet.Hull( ship )} SHIELD {fleet.Shield( ship )} ARMOR {fleet.Armor( ship )}", out detailLength ); + var faction = fleet.FactionOf( ship ); + var attitude = Factions.Attitude( FactionId.Sol, faction ); + tint = attitude == Disposition.Allied ? SpaceDraw.Cyan : attitude == Disposition.Hostile ? SpaceDraw.Amber : SpaceDraw.Neutral; + title.TryWrite( $"{Factions.Name( faction )} / {role.ToString().ToUpperInvariant()}", out titleLength ); + detail.TryWrite( $"{attitude.ToString().ToUpperInvariant()} / HULL {fleet.Hull( ship )} SHIELD {fleet.Shield( ship )} ARMOR {fleet.Armor( ship )}", out detailLength ); break; case HoverKind.Site: var site = sites[hover.Index]; - titleLength = CopyStatus( SiteName( site.Facility ), title ); - if ( site.Facility == PlanetFacility.Mine && fleet.MineEnRoute( site.Body ) ) + titleLength = CopyStatus( site.Facility == PlanetFacility.Yard && fleet.YardAt( site.Body ) != 0 && site.Remaining <= 0 + ? "CIVILIAN DOCK" : SiteName( site.Facility ), title ); + if ( !site.Producing && fleet.SiteEnRoute( site.Body, site.Facility ) ) detailLength = CopyStatus( "CONSTRUCTOR EN ROUTE", detail ); else if ( site.Remaining > 0 ) detail.TryWrite( $"{Seconds( site.Remaining, speed )} SEC LEFT / {fleet.BodyName( site.Body )}", out detailLength ); diff --git a/samples/FleetBattler/OrbitalNavigation.cs b/samples/FleetBattler/OrbitalNavigation.cs index 465dde8..8df13cd 100644 --- a/samples/FleetBattler/OrbitalNavigation.cs +++ b/samples/FleetBattler/OrbitalNavigation.cs @@ -100,18 +100,19 @@ internal bool CopyRoute( FleetSelection unit, Span points, out Vector2 return true; } - private void Park( int squadIndex, int host ) { + private void Park( int squadIndex, int host, int tick = -1 ) { + if ( tick < 0 ) tick = Tick; ref var squad = ref _squads[squadIndex]; var delta = squad.Center - _bodies[host].Center; squad.Order = new( ) { Body = (byte)(host + 1), Phase = MathF.Atan2( delta.Y, delta.X ), Radius = MathF.Max( delta.Length( ), OrbitRadius( host, squad.Alive ) ) }; - squad.Order.Phase -= Tick * OrbitRate( squad.Order.Radius ); - Vector2 center = Berth( squad.Order, Tick, out var tangent ); + squad.Order.Phase -= tick * OrbitRate( squad.Order.Radius ); + Vector2 center = Berth( squad.Order, tick, out var tangent ); squad.Center = squad.Anchor = center; squad.Direction = tangent; for ( int i = squad.First; i < squad.First + squad.Count; ++i ) { _positions[i] = _previousPositions[i] = center + RotateSlot( _offsets[i], tangent ); _headings[i] = _previousHeadings[i] = tangent; - _velocities[i] = (Berth( squad.Order, Tick + 1, out _ ) - center) / (float)StepSeconds; + _velocities[i] = (Berth( squad.Order, tick + 1, out _ ) - center) / (float)StepSeconds; } } diff --git a/samples/FleetBattler/PlanetEconomy.cs b/samples/FleetBattler/PlanetEconomy.cs index 27dd13b..d5f3b17 100644 --- a/samples/FleetBattler/PlanetEconomy.cs +++ b/samples/FleetBattler/PlanetEconomy.cs @@ -2,7 +2,7 @@ namespace FleetBattler; -internal enum PlanetFacility { Mine, Lab, Depot, Yard } +internal enum PlanetFacility { Mine, Lab, Depot, Yard, Solar } internal readonly record struct WingOrder( int Body, ShipDesign Design, int Duration, int Cost ); internal readonly record struct SiteOrder( int Body, PlanetFacility Facility ); @@ -55,7 +55,7 @@ internal int NavalUsed { return used; } } - internal int NavalReserved => QueuedWings * FrontierWingSize; + internal int NavalReserved => Frontier ? _navalReserved : QueuedWings * WingSize; private int Online( ReadOnlySpan projects ) { int count = 0; @@ -64,28 +64,15 @@ private int Online( ReadOnlySpan projects ) { return count; } - private Vector2 YardPosition( int body, int tick ) { - var (sin, cos) = MathF.SinCos( tick * (float)StepSeconds * 0.23f - MathF.PI / 2 ); - return _bodies[body].Center + new Vector2( cos, sin ) * (OrbitRadius( body, 1 ) + 4); - } + private Vector2 YardPosition( int body, int tick ) => + SitePositionAt( body, PlanetFacility.Yard, tick, _bodies[body].Center ); internal int QueuedWings { get; private set; } internal int WingRemaining => Remaining( _wingFinishTick ); - internal int CurrentWingCost => (IndustryUpgrade ? ImprovedWingCost : WingCost) + (Frontier ? Design.Surcharge : 0); - internal int CurrentWingDuration => (IndustryUpgrade ? ImprovedWingDuration : StandardWingDuration) + (Frontier ? Design.BuildTicks : 0); - internal int ActiveYard => QueuedWings == 0 ? -1 : _wingQueue[0].Body; - internal int OrdersAt( int body ) { - int count = 0; - for ( int i = 0; i < QueuedWings; ++i ) - if ( _wingQueue[i].Body == body ) ++count; - return count; - } + internal int CurrentWingCost => IndustryUpgrade ? ImprovedWingCost : WingCost; + internal int CurrentWingDuration => IndustryUpgrade ? ImprovedWingDuration : StandardWingDuration; internal int ActiveWingDuration => QueuedWings == 0 ? 0 : _wingQueue[0].Duration; - internal ShipDesign ActiveWingDesign => _wingQueue[0].Design; - internal bool CanBuildWing => CanQueueWing( YardBody ); - internal bool CanQueueWing( int body ) => (uint)body < (uint)_bodies.Length && YardAt( body ) == 0 && Ore >= CurrentWingCost && - (Frontier ? QueuedWings < _wingQueue.Length && NavalUsed + NavalReserved + FrontierWingSize <= NavalCapacity - : WingsBuilt + QueuedWings < WingGoal && !Lost); - internal ReadOnlySpan WingQueue => _wingQueue.AsSpan( 0, QueuedWings ); + internal bool CanBuildWing => !Frontier && YardRemaining == 0 && Ore >= CurrentWingCost && + WingsBuilt + QueuedWings < WingGoal && !Lost; internal int CompletedSites { get; private set; } internal SiteOrder LastCompletedSite { get; private set; } internal int StartedConstruction { get; private set; } @@ -136,32 +123,26 @@ private bool SquadCanSurvey( int squad ) { return false; } - internal bool BuildYard( int body ) { - if ( body <= 0 || body >= _bodies.Length || _yards[body] != 0 || !Frontier && YardBody >= 0 || !Planet( body ).Surveyed || Lost || Ore < YardCost ) return false; + internal bool BuildYard( int body, FleetSelection? worker = null ) { + if ( Frontier ) return StartConstruction( body, PlanetFacility.Yard, worker ); + if ( body <= 0 || body >= _bodies.Length || _yards[body] != 0 || YardBody >= 0 || !Planet( body ).Surveyed || Lost || Ore < YardCost ) return false; Ore -= YardCost; _yards[body] = Tick + YardDuration; return true; } internal bool ResearchIndustry( ) { + if ( Frontier ) return StartResearch( ResearchTopic.Industry ); if ( IndustryUpgrade || Science < IndustryCost || Lost ) return false; Science -= IndustryCost; IndustryUpgrade = true; return true; } - internal bool ResearchDrive( ) { - if ( !Frontier || DriveUpgrade || Science < DriveCost ) return false; - Science -= DriveCost; - DriveUpgrade = true; - return true; - } - - internal bool QueueWing( int body = -1 ) { - if ( body < 0 ) body = YardBody; - if ( !CanQueueWing( body ) ) return false; + internal bool QueueWing( ) { + if ( !CanBuildWing ) return false; int cost = CurrentWingCost; - _wingQueue[QueuedWings++] = new( body, Design, CurrentWingDuration, cost ); + _wingQueue[QueuedWings++] = new( YardBody, Design, CurrentWingDuration, cost ); Ore -= cost; if ( QueuedWings == 1 ) _wingFinishTick = Tick + _wingQueue[0].Duration; return true; @@ -176,64 +157,47 @@ private void AdvanceProduction( ) { } if ( Tick + 1 < _wingFinishTick ) return; int body = _wingQueue[0].Body; - var arrival = YardPosition( body, Tick + 1 ) + new Vector2( 4 + (Frontier ? WingsBuilt % 2 : WingsBuilt) * 4, 0 ); - int squad = AddSquad( Frontier ? FrontierWingSize : WingSize, 0, arrival, design: _wingQueue[0].Design ); - if ( Frontier ) Park( squad, body ); + var arrival = YardPosition( body, Tick + 1 ) + new Vector2( 4 + WingsBuilt * 4, 0 ); + AddSquad( WingSize, 0, arrival ); ++WingsBuilt; - RemoveWing( 0, Tick + 1 ); - } - - internal bool CancelWing( int index ) { - if ( !Frontier || (uint)index >= (uint)QueuedWings ) return false; - Refund( _wingQueue[index].Cost ); - RemoveWing( index, Tick ); - return true; - } - - private void RemoveWing( int index, int start ) { --QueuedWings; - _wingQueue.AsSpan( index + 1, QueuedWings - index ).CopyTo( _wingQueue.AsSpan( index ) ); - if ( index == 0 ) _wingFinishTick = QueuedWings == 0 ? 0 : start + _wingQueue[0].Duration; + _wingQueue.AsSpan( 1, QueuedWings ).CopyTo( _wingQueue ); + _wingFinishTick = QueuedWings == 0 ? 0 : Tick + 1 + _wingQueue[0].Duration; } internal bool BuildFacility( int body, PlanetFacility facility, FleetSelection? worker = null ) { + if ( Frontier ) return StartConstruction( body, facility, worker ); if ( facility == PlanetFacility.Yard ) return BuildYard( body ); - if ( body <= 0 || body >= _bodies.Length || !Planet( body ).Surveyed || Lost ) return false; - if ( facility == PlanetFacility.Depot && !Frontier ) return false; - var (projects, cost) = SiteProjects( facility ); + if ( body <= 0 || body >= _bodies.Length || !Planet( body ).Surveyed || Lost || + facility is not (PlanetFacility.Mine or PlanetFacility.Lab) ) return false; + var projects = SiteDeadlines( facility ); + int cost = Facility( facility ).Cost.Ore; if ( projects[body] != 0 || Ore < cost ) return false; - if ( Frontier && facility == PlanetFacility.Mine && !AssignMine( body, worker ) ) return false; Ore -= cost; projects[body] = Tick + FacilityDuration; return true; } - internal int SiteRemaining( int body, PlanetFacility facility ) => Remaining( SiteProjects( facility ).Deadlines[body] ); + internal int SiteRemaining( int body, PlanetFacility facility ) => Remaining( SiteDeadlines( facility )[body] ); internal bool CancelSite( int body, PlanetFacility facility ) { if ( !Frontier || body <= 0 || body >= _bodies.Length ) return false; - var (projects, cost) = SiteProjects( facility ); + var projects = SiteDeadlines( facility ); if ( projects[body] <= Tick ) return false; projects[body] = 0; - if ( facility == PlanetFacility.Mine ) { - _constructionWorkers[body] = null; - _buildingMines[body] = false; - } - Refund( cost ); + Construction( body, facility ) = default; + Refund( Facility( facility ).Cost ); return true; } - private (int[] Deadlines, int Cost) SiteProjects( PlanetFacility facility ) => facility switch { - PlanetFacility.Mine => (_mines, MineCost), - PlanetFacility.Lab => (_labs, LabCost), - PlanetFacility.Depot => (_depots, DepotCost), - PlanetFacility.Yard => (_yards, YardCost), + private int[] SiteDeadlines( PlanetFacility facility ) => facility switch { + PlanetFacility.Mine => _mines, PlanetFacility.Lab => _labs, PlanetFacility.Depot => _depots, + PlanetFacility.Yard => _yards, PlanetFacility.Solar => _solarArrays, _ => throw new ArgumentOutOfRangeException( nameof(facility) ) }; - private void Refund( int cost ) => Ore = Math.Min( 999, Ore + cost ); - internal bool ResearchWeapons( ) { + if ( Frontier ) return StartResearch( ResearchTopic.Weapons ); if ( Science < UpgradeCost || WeaponUpgrade || Lost ) return false; Science -= UpgradeCost; WeaponUpgrade = true; @@ -243,7 +207,6 @@ internal bool ResearchWeapons( ) { private void AdvancePlanets( ) { RefreshSurveys( ); for ( int body = 1; body < _bodies.Length; ++body ) { - if ( Frontier ) AdvanceMine( body ); if ( _surveyUnits[body] is { } unit && InSurveyRange( unit, body ) ) { int rate = IsScoutSquad( unit.Squad ) ? 2 : 1; _survey[body] = Math.Min( SurveyDuration, _survey[body] + rate ); @@ -257,10 +220,10 @@ private void AdvancePlanets( ) { } } if ( Frontier ) { - MarkSite( body, PlanetFacility.Mine, _mines[body] ); - MarkSite( body, PlanetFacility.Lab, _labs[body] ); - MarkSite( body, PlanetFacility.Depot, _depots[body] ); - MarkSite( body, PlanetFacility.Yard, _yards[body] ); + foreach ( var facility in Facilities ) { + AdvanceConstruction( body, facility ); + MarkSite( body, facility, SiteDeadlines( facility )[body] ); + } } if ( (Tick + 1) % IncomeInterval != 0 ) continue; if ( _mines[body] > 0 && _mines[body] <= Tick + 1 ) Ore = Math.Min( 999, Ore + (Frontier ? DepositYield( body ) : 8) ); diff --git a/samples/FleetBattler/PlanetInspector.cs b/samples/FleetBattler/PlanetInspector.cs index e67e9a8..9ce94b0 100644 --- a/samples/FleetBattler/PlanetInspector.cs +++ b/samples/FleetBattler/PlanetInspector.cs @@ -31,7 +31,7 @@ private void Art( Tile tile, float x, float y, float width, float height, bool l }; private void FlightCard( Layout layout, FleetSimulation fleet, FleetSelection unit, int speed ) { - float top = 70 + layout.OutlinerHeight( fleet ); + float top = layout.FleetControls( fleet ) + 26; if ( top + 80 >= layout.Bottom ) return; PanelAt( 14, top, 157, 74, SpaceDraw.Cyan ); Text( "FLIGHT PLAN", 23, top + 8, 1.25f, White ); @@ -69,48 +69,49 @@ private void InspectPlanet( Layout layout, FleetSimulation fleet, int body, Flee if ( status.SurveyUnit is not null || !status.Surveyed && unit is { } selected && fleet.CanSurvey( selected, body ) ) Button( x + width - 66, y + 24, 57, status.SurveyUnit is null ? "SCAN" : "CANCEL", true ); - Site( 0, Tile.Mine, "EXTRACTION RIG", status.MineRemaining, FleetSimulation.FacilityDuration, FleetSimulation.MineCost, - status.MineRemaining == 0 ? "ORE PRODUCTION" : fleet.MineEnRoute( body ) ? "MINER EN ROUTE" : null, - fleet.DepositYield( body ), status.Surveyed && fleet.CanPlaceMine( body, unit ) ); - Site( 1, Tile.Lab, "RESEARCH LAB", status.LabRemaining, FleetSimulation.FacilityDuration, FleetSimulation.LabCost, - status.LabRemaining == 0 ? "SCIENCE PRODUCTION" : null, 6, status.Surveyed ); - Site( 2, Tile.Yard, "ORBITAL SHIPYARD", fleet.YardAt( body ), FleetSimulation.YardDuration, FleetSimulation.YardCost, - fleet.YardAt( body ) == 0 ? fleet.ActiveYard == body ? "WING IN PRODUCTION" : fleet.CanQueueWing( body ) ? "QUEUE WING" : "ONLINE / NAVAL CAPACITY" : null, - FleetSimulation.YardNavalCapacity, status.Surveyed ); - Site( 3, Tile.Yard, "LOGISTICS DEPOT", fleet.DepotAt( body ), FleetSimulation.FacilityDuration, FleetSimulation.DepotCost, - fleet.DepotAt( body ) == 0 ? "ONLINE / NAVAL CAPACITY" : null, FleetSimulation.DepotNavalCapacity, status.Surveyed ); - if ( layout.InspectorHeight >= 246 ) { - int active = (status.MineRemaining == 0 ? 1 : 0) + (status.LabRemaining == 0 ? 1 : 0) + - (fleet.YardAt( body ) == 0 ? 1 : 0) + (fleet.DepotAt( body ) == 0 ? 1 : 0); - line.TryWrite( $"SITE OPERATIONS / {active} ONLINE", out length ); - Text( line[..length], x + 10, y + 228, 1.03f, Label ); - } - - void Site( int index, Tile tile, string name, int remaining, int duration, int cost, string? description, int output, bool available ) { - float top = y + SiteTop + index * SiteHeight; - Span details = stackalloc char[44]; + int index = 0; + Span details = stackalloc char[48]; + foreach ( var facility in FleetSimulation.Facilities ) { + float top = y + SiteTop + index++ * layout.InspectorRow; + int remaining = fleet.SiteRemaining( body, facility ); + var plan = FleetSimulation.Facility( facility ); + bool online = remaining == 0, project = remaining > 0; + bool dock = facility == PlanetFacility.Yard && fleet.CanOpenYard( body ); + string? block = remaining < 0 ? fleet.ConstructionBlock( body, facility, unit ) : null; + bool available = remaining < 0 && block is null; + var tile = facility switch { PlanetFacility.Mine => Tile.Mine, PlanetFacility.Lab => Tile.Lab, _ => Tile.Yard }; + Rect( x + 8, top, width - 16, layout.InspectorRow - 3, available || online ? Active : Well ); + Art( tile, x + 9, top + 1, 42, layout.InspectorRow - 5, available || remaining >= 0 ); + Text( plan.Name, x + 57, top + 4, 1, White ); int chars; - bool producing = index == 2 && remaining == 0 && fleet.ActiveYard == body; - bool enabled = remaining < 0 && available && fleet.Ore >= cost || index == 2 && fleet.CanQueueWing( body ); - Rect( x + 8, top, width - 16, 34, enabled ? Active : Well ); - Art( tile, x + 9, top + 1, 48, 32, remaining >= 0 || enabled ); - Text( name, x + 64, top + 4, 1.04f, White ); - if ( producing ) details.TryWrite( $"WING BUILDING / {Seconds( fleet.WingRemaining, speed )} SEC", out chars ); - else if ( remaining > 0 ) details.TryWrite( $"{description ?? "BUILDING"} / {Seconds( remaining, speed )} SEC", out chars ); - else if ( remaining == 0 ) { - if ( index == 2 && fleet.OrdersAt( body ) > 0 ) - details.TryWrite( $"{fleet.OrdersAt( body )} WING WAITING", out chars ); - else if ( description == "QUEUE WING" ) details.TryWrite( $"QUEUE WING / {fleet.CurrentWingCost} ORE", out chars ); - else details.TryWrite( $"{description} / +{output}", out chars ); - } else details.TryWrite( $"{(available ? "BUILD" : index == 0 && status.Surveyed ? "NEEDS DEPOSIT AND MINER" : "SURVEY REQUIRED")} / {cost} ORE", out chars ); - int maxChars = (int)((width - (remaining > 0 ? 97 : 72)) / TextWidth( 1, 1 )); - Text( details[..Math.Min( chars, maxChars )], x + 64, top + 16, 1, enabled ? SpaceDraw.Cyan : Label ); - if ( remaining > 0 ) Button( x + width - 30, top + 5, 20, "X", true ); - if ( remaining > 0 || producing ) { - float fraction = producing ? 1 - (float)fleet.WingRemaining / fleet.ActiveWingDuration : 1 - (float)remaining / duration; - Rect( x + 64, top + 29, width - 74, 2, Panel, 3 ); - if ( fraction > 0 ) Rect( x + 64, top + 29, (width - 74) * fraction, 2, SpaceDraw.Cyan, 5 ); + if ( project ) { + var worker = fleet.SiteWorker( body, facility ); + int id = worker is { IsShip: true } unitWorker ? unitWorker.Ship + 1 : (worker?.Squad ?? -1) + 1; + if ( fleet.SiteEnRoute( body, facility ) ) details.TryWrite( $"EN ROUTE / UNIT {id:D2}", out chars ); + else details.TryWrite( $"UNIT {id:D2} / {Seconds( remaining, speed )} SEC", out chars ); + Button( x + width - 30, top + 3, 20, "X", true ); + } else if ( online ) { + if ( facility == PlanetFacility.Yard ) + details.TryWrite( $"+{FleetSimulation.YardNavalCapacity} NAVAL / {fleet.YardQueue( body ).Length} QUEUED", out chars ); + else { + var (amount, resource) = facility switch { + PlanetFacility.Mine => (fleet.DepositYield( body ), "ORE"), + PlanetFacility.Lab => (6, "SCI"), + PlanetFacility.Solar => (FleetSimulation.SolarOutput, "ENERGY"), + _ => (FleetSimulation.DepotNavalCapacity, "NAVAL") + }; + details.TryWrite( $"+{amount} {resource}{(facility == PlanetFacility.Depot ? "" : " PER CYCLE")}", out chars ); + } + } else { + if ( block is null ) chars = CopyStatus( "BUILD", details ); + else chars = CopyStatus( block, details ); } + int maxChars = (int)((width - (project || dock ? 117 : 67)) / TextWidth( 1, 1 )); + Text( details[..Math.Min( chars, maxChars )], x + 57, top + 17, 1, available || online ? SpaceDraw.Cyan : Label ); + if ( available ) Cost( plan.Cost, x + 93, top + 16 ); + if ( dock && !project ) Button( x + width - 50, top + 5, 42, "OPEN", true ); + if ( project && !fleet.SiteEnRoute( body, facility ) ) + Progress( new( x + 57, top + layout.InspectorRow - 8 ), width - 94, 1f - (float)remaining / plan.Duration, SpaceDraw.Amber ); } } @@ -123,21 +124,16 @@ private static HudHit HitInspector( Layout layout, Vector2 point, int body, Flee if ( !status.Surveyed && Contains( point, x + width - 66, InspectorTop + 24, 57, 21 ) ) return Planet( status.SurveyUnit is null ? PlanetAction.Survey : PlanetAction.CancelSurvey ); float row = point.Y - InspectorTop - SiteTop; - if ( row >= 0 && row < 4 * SiteHeight && row % SiteHeight < 34 && point.X >= x + 8 && point.X < x + width - 8 ) - { - int index = (int)(row / SiteHeight); - if ( point.X >= x + width - 30 && point.X < x + width - 10 && row % SiteHeight is >= 5 and < 26 ) { - var facility = index switch { 0 => PlanetFacility.Mine, 1 => PlanetFacility.Lab, 2 => PlanetFacility.Yard, _ => PlanetFacility.Depot }; - if ( fleet.SiteRemaining( body, facility ) > 0 ) - return Planet( (PlanetAction)((int)PlanetAction.CancelMine + index) ); - } - return Planet( index switch { - 0 => PlanetAction.Mine, 1 => PlanetAction.Lab, - 2 => fleet.YardAt( body ) == 0 ? PlanetAction.SiteWing : PlanetAction.Yard, - _ => PlanetAction.Depot - } ); - } - return new( HudAction.Panel ); + if ( row < 0 || row >= FleetSimulation.FacilityCount * layout.InspectorRow || + row % layout.InspectorRow >= layout.InspectorRow - 3 || point.X < x + 8 || point.X >= x + width - 8 ) + return new( HudAction.Panel ); + var facility = FleetSimulation.Facilities[(int)(row / layout.InspectorRow)]; + int remaining = fleet.SiteRemaining( body, facility ); + if ( remaining > 0 && point.X >= x + width - 30 ) return new( HudAction.CancelSite, (int)facility ); + if ( facility == PlanetFacility.Yard && fleet.CanOpenYard( body ) && remaining <= 0 && (remaining == 0 || point.X >= x + width - 50) ) + return new( HudAction.OpenYard, body ); + if ( remaining >= 0 ) return new( HudAction.Panel ); + return new( HudAction.BuildSite, (int)facility ); static HudHit Planet( PlanetAction action ) => new( HudAction.Planet, (int)action ); } @@ -145,6 +141,8 @@ private static HudHit HitInspector( Layout layout, Vector2 point, int body, Flee private readonly partial record struct Layout { internal float InspectorWidth => Width < 590 ? 227 : 282; internal float InspectorX => Width - InspectorWidth - 14; - internal float InspectorHeight => MathF.Min( 247, Bottom - InspectorTop - 6 ); + internal float InspectorHeight => MathF.Min( 269, Bottom - InspectorTop - 6 ); + internal float InspectorRow => MathF.Min( 38, (InspectorHeight - SiteTop - 7) / FleetSimulation.FacilityCount ); + internal float FleetControls( FleetSimulation fleet ) => 70 + OutlinerHeight( fleet ); } } diff --git a/samples/FleetBattler/Program.cs b/samples/FleetBattler/Program.cs index 48a4a3a..8bf6229 100644 --- a/samples/FleetBattler/Program.cs +++ b/samples/FleetBattler/Program.cs @@ -10,7 +10,7 @@ namespace FleetBattler; internal static class Program { private const float DefaultTilt = 1.068f; - private const int StationSlots = 1 + 4 * (CelestialSystem.BodyCount - 1); + private const int StationSlots = 1 + FleetSimulation.FacilityCount * (CelestialSystem.BodyCount - 1); [STAThread] public static int Main( string[] args ) { @@ -139,7 +139,7 @@ private static DesktopRunResult Present( GraphicsDevice device, PipelineState pi var hud = new FleetHud( atlas ); var display = new FullscreenToggle( ); var selection = new CommandSelection( fleet.Capacity ); - selection.Squadron( fleet, 0, SelectionMode.Replace ); + selection.Squadron( fleet, fleet.FirstPlayerSquad( ), SelectionMode.Replace ); var effects = new BattleEffect[FleetSimulation.EffectCapacity + BattleDraw.RouteCapacity + BattleDraw.SolarTrackCapacity + BattleDraw.SiteEffectCapacity]; int planet = initial.Frontier ? FleetSimulation.Homeworld : -1, shotsHeard = 0, lossesHeard = 0, nextCue = 0; long noticeUntil = 0; @@ -150,6 +150,7 @@ private static DesktopRunResult Present( GraphicsDevice device, PipelineState pi BodyMenu? menu = null; CommandTab commandTab = CommandTab.Hidden; int dispatch = 0, dispatchesSeen = initial.DispatchCount; + int yardInspector = -1, launchesSeen = 0, researchSeen = 0; var clock = new FleetClock( ); bool paused = false; float zoom = initial.Solar ? 0.52f : 0.85f, tilt = DefaultTilt, yaw = 0; @@ -211,7 +212,7 @@ private static DesktopRunResult Present( GraphicsDevice device, PipelineState pi yardState = fleet.YardRemaining; if ( buildsHeard != fleet.StartedConstruction ) { buildsHeard = fleet.StartedConstruction; - Notify( "MINER ON SITE / ASSEMBLING EXTRACTION RIG" ); + Notify( $"CONSTRUCTOR ON SITE / ASSEMBLING {FleetHud.SiteName( fleet.LastStartedSite.Facility )}" ); audio.Cue( "order" ); } if ( sitesHeard != fleet.CompletedSites ) { @@ -220,6 +221,17 @@ private static DesktopRunResult Present( GraphicsDevice device, PipelineState pi Notify( $"{FleetHud.SiteName( site.Facility )} ONLINE / {fleet.BodyName( site.Body )}" ); audio.Cue( "launch" ); } + if ( launchesSeen != fleet.ShipsLaunched ) { + launchesSeen = fleet.ShipsLaunched; + var launch = fleet.LastLaunch; + Notify( $"{fleet.Hull( launch.Hull ).Name} LAUNCHED / {fleet.BodyName( launch.Body )}" ); + audio.Cue( "launch" ); + } + if ( researchSeen != fleet.CompletedResearch ) { + researchSeen = fleet.CompletedResearch; + Notify( $"{FleetSimulation.Tech( fleet.LastTechnology ).Name} RESEARCH COMPLETE" ); + audio.Cue( "launch" ); + } if ( dispatchesSeen < fleet.DispatchCount ) { dispatchesSeen = fleet.DispatchCount; dispatch = dispatchesSeen - 1; @@ -266,26 +278,35 @@ private static DesktopRunResult Present( GraphicsDevice device, PipelineState pi } Vector2? yardPixel = null; for ( int body = 1; body < fleet.Bodies.Length; ++body ) { - if ( fleet.YardAt( body ) >= 0 ) { + if ( !fleet.Frontier ) { + if ( fleet.YardAt( body ) < 0 ) continue; var yard = fleet.SitePosition( body, PlanetFacility.Yard, interpolation ); - if ( body == fleet.YardBody ) yardPixel = CommandSelection.Project( yard, viewProjection, new( viewport.Width, viewport.Height ) ); - RecordSite( body, PlanetFacility.Yard, 0.77f, FleetSimulation.YardDuration, new( 1.8f, 1.42f, 0.57f, 1 ) ); + yardPixel = CommandSelection.Project( yard, viewProjection, new( viewport.Width, viewport.Height ) ); + AddStation( yard, 0.77f, fleet.YardAt( body ), FleetSimulation.YardDuration, new( 1.8f, 1.42f, 0.57f, 1 ) ); + continue; } - if ( !fleet.Frontier ) continue; - RecordSite( body, PlanetFacility.Mine, 0.50f, FleetSimulation.FacilityDuration, new( 1.8f, 1.12f, 0.47f, 1 ) ); - RecordSite( body, PlanetFacility.Lab, 0.46f, FleetSimulation.FacilityDuration, new( 0.57f, 1.3f, 1.8f, 1 ) ); - RecordSite( body, PlanetFacility.Depot, 0.55f, FleetSimulation.FacilityDuration, new( 0.63f, 1.9f, 1.35f, 1 ) ); + foreach ( var facility in FleetSimulation.Facilities ) RecordSite( body, facility ); } - void RecordSite( int body, PlanetFacility facility, float size, int duration, Vector4 tint ) { + void RecordSite( int body, PlanetFacility facility ) { int remaining = fleet.SiteRemaining( body, facility ); - if ( remaining < 0 ) return; + bool yard = facility == PlanetFacility.Yard && fleet.CanOpenYard( body ); + if ( remaining < 0 && !yard ) return; var position = fleet.SitePosition( body, facility, interpolation ); var pixel = CommandSelection.Project( position, viewProjection, new( viewport.Width, viewport.Height ) ); - bool wing = facility == PlanetFacility.Yard && fleet.ActiveYard == body; - screenSites[siteCount++] = new( pixel, body, facility, wing ? fleet.WingRemaining : remaining, - wing ? fleet.ActiveWingDuration : duration ); - if ( facility != PlanetFacility.Mine || !fleet.MineEnRoute( body ) ) AddStation( position, size, remaining, duration, tint ); + int duration = FleetSimulation.Facility( facility ).Duration; + int shipRemaining = yard ? fleet.ShipRemaining( body ) : 0; + bool producing = shipRemaining > 0; + screenSites[siteCount++] = new( pixel, body, facility, producing ? shipRemaining : remaining, + producing ? fleet.YardQueue( body )[0].Duration : duration, producing ); + var (size, tint) = facility switch { + PlanetFacility.Yard => (0.77f, new Vector4( 1.8f, 1.42f, 0.57f, 1 )), + PlanetFacility.Mine => (0.50f, new Vector4( 1.8f, 1.12f, 0.47f, 1 )), + PlanetFacility.Lab => (0.46f, new Vector4( 0.57f, 1.3f, 1.8f, 1 )), + PlanetFacility.Solar => (0.52f, new Vector4( 1.25f, 1.54f, 2f, 1 )), + _ => (0.55f, new Vector4( 0.63f, 1.9f, 1.35f, 1 )) + }; + if ( !fleet.SiteEnRoute( body, facility ) || yard ) AddStation( position, size, Math.Max( 0, remaining ), duration, tint ); } var upload = uploads[frame.FrameSlotIndex]; upload.Write( instances.AsSpan( 0, nextStation ) ); @@ -299,7 +320,7 @@ void AddStation( Vector2 position, float size, int remaining, int duration, Vect if ( !active.IsEmpty ) { FleetDraw.RecordThrusters( frame.Commands, thrust, upload, (uint)active.Length, viewProjection, (float)(fleet.Tick * FleetSimulation.StepSeconds) ); FleetDraw.Record( frame.Commands, pipeline, corvettes, upload, corvetteCount, viewProjection ); - uint miners = fleet.Frontier ? (uint)fleet.ActiveMiners( ) : 0; + uint miners = fleet.Frontier ? (uint)(fleet.MerchantCount + fleet.ActiveMiners( )) : 0; uint scoutsEnd = (uint)active.Length - miners; FleetDraw.Record( frame.Commands, pipeline, scouts, upload, scoutsEnd - corvetteCount, viewProjection, corvetteCount ); FleetDraw.Record( frame.Commands, pipeline, minerMeshes, upload, miners, viewProjection, scoutsEnd ); @@ -311,8 +332,14 @@ void AddStation( Vector2 position, float size, int remaining, int duration, Vect if ( fleet.Frontier ) { float workTime = (fleet.Tick - 1 + interpolation) * (float)FleetSimulation.StepSeconds; for ( int body = 1; body < fleet.Bodies.Length; ++body ) { - if ( fleet.SiteWorker( body ) is { } worker && !fleet.MineEnRoute( body ) ) - WorkBeam( fleet.VisualCenter( worker, interpolation ), fleet.SitePosition( body, PlanetFacility.Mine, interpolation ), 0 ); + foreach ( var facility in FleetSimulation.Facilities ) + if ( fleet.SiteWorker( body, facility ) is { } worker && !fleet.SiteEnRoute( body, facility ) ) + WorkBeam( fleet.VisualCenter( worker, interpolation ), fleet.SitePosition( body, facility, interpolation ), 0 ); + if ( fleet.ShipRemaining( body ) > 0 ) { + var yard = fleet.SitePosition( body, PlanetFacility.Yard, interpolation ); + var (sine, cosine) = MathF.SinCos( workTime * 2 ); + WorkBeam( yard, yard + new Vector2( cosine, sine ) * 3, 0 ); + } if ( fleet.Planet( body ).SurveyUnit is { } scout && fleet.SurveyWorking( body ) ) WorkBeam( fleet.VisualCenter( scout, interpolation ), fleet.VisualBody( body, interpolation ).Center, 1 ); } @@ -330,11 +357,10 @@ void WorkBeam( Vector2 from, Vector2 to, float scanner ) => var drag = dragStart is { } start && IsDrag( start, dragEnd ) ? DragRect( start, dragEnd ) : (Vector4?)null; MapHover hover = default; if ( fleet.Frontier && menu is null && panStart is null && dragStart is null && mouse is { } pointer && - FleetHud.Hit( new( pointer.X, pointer.Y ), viewport.Width, viewport.Height, fleet, planet, commandTab: commandTab ).Action == HudAction.None ) { + FleetHud.Hit( new( pointer.X, pointer.Y ), viewport.Width, viewport.Height, fleet, planet, commandTab: commandTab, yardInspector: yardInspector ).Action == HudAction.None ) { var pixel = new Vector2( pointer.X, pointer.Y ); var dimensions = new Vector2( viewport.Width, viewport.Height ); - int ship = CommandSelection.Hit( fleet, pixel, viewProjection, dimensions, 0, interpolation ); - if ( ship < 0 ) ship = CommandSelection.Hit( fleet, pixel, viewProjection, dimensions, 1, interpolation ); + int ship = CommandSelection.Hit( fleet, pixel, viewProjection, dimensions, -1, interpolation ); if ( ship >= 0 ) hover = new( HoverKind.Ship, ship, CommandSelection.Project( fleet.VisualPosition( ship, interpolation ), viewProjection, dimensions ), pixel ); else if ( PickSite( pixel ) is >= 0 and var site ) @@ -345,7 +371,7 @@ void WorkBeam( Vector2 from, Vector2 to, float scanner ) => hud.Record( frame.Commands, hudPipeline, hudUpload, fleet, selected, viewport.Width, viewport.Height, oreShort, screenBodies.AsSpan( 0, fleet.Bodies.Length ), selection.Count, planet, Environment.TickCount64 < noticeUntil ? notice : null, drag, fleet.Frontier ? null : CommandSelection.Project( fleet.Site, viewProjection, new( viewport.Width, viewport.Height ) ), - selection.Ships, speed, paused, unit, menu, yardPixel, commandTab, dispatch, screenSites.AsSpan( 0, siteCount ), hover ); + selection.Ships, speed, paused, unit, menu, yardPixel, commandTab, dispatch, screenSites.AsSpan( 0, siteCount ), hover, yardInspector ); }, ( window, result ) => { if ( result.Frames == 1 ) { if ( startFullscreen ) display.Toggle( window ); @@ -355,6 +381,7 @@ void WorkBeam( Vector2 from, Vector2 to, float scanner ) => case Keys.F11: display.Toggle( window ); break; case Keys.G: ToggleGalaxy( window ); break; case Keys.Escape when menu is not null: menu = null; break; + case Keys.Escape when yardInspector >= 0: yardInspector = -1; break; case Keys.Escape when commandTab != CommandTab.Hidden: commandTab = CommandTab.Hidden; break; case Keys.Escape when !galaxy: planet = -1; break; case Keys.Home when !galaxy: ResetCamera( ); break; @@ -386,7 +413,13 @@ void WorkBeam( Vector2 from, Vector2 to, float scanner ) => case Keys.L when !galaxy: PlanetOrder( PlanetAction.Lab, planet ); break; case Keys.T when !galaxy: PlanetOrder( PlanetAction.Research, planet ); break; case Keys.I when !galaxy: PlanetOrder( PlanetAction.Industry, planet ); break; + case Keys.B when !galaxy && fleet.Frontier: + if ( fleet.CanOpenYard( planet ) ) OpenYard( planet ); + else if ( fleet.CanOpenYard( fleet.YardBody ) ) OpenYard( fleet.YardBody ); + else if ( fleet.Established ) OpenYard( FleetSimulation.Homeworld ); + break; case Keys.B when !galaxy: QueueWing( ); break; + case Keys.J when !galaxy && fleet.Frontier: OrganizeFleets( e.Shift ); break; default: return; } e.SuppressKeyPress = true; @@ -418,7 +451,7 @@ void WorkBeam( Vector2 from, Vector2 to, float scanner ) => return; } } - var hit = FleetHud.Hit( pointer, viewport.Width, viewport.Height, fleet, planet, commandTab: commandTab ); + var hit = FleetHud.Hit( pointer, viewport.Width, viewport.Height, fleet, planet, commandTab: commandTab, yardInspector: yardInspector ); if ( hit.Action != HudAction.None ) { if ( e.Button == MouseButtons.Left ) { switch ( hit.Action ) { @@ -428,9 +461,23 @@ void WorkBeam( Vector2 from, Vector2 to, float scanner ) => case HudAction.Wing: QueueWing( ); break; case HudAction.Command: Command( (CommandAction)hit.Index ); break; case HudAction.Planet: PlanetOrder( (PlanetAction)hit.Index, planet ); break; + case HudAction.OpenYard: OpenYard( hit.Index ); break; + case HudAction.CloseYard: yardInspector = -1; break; + case HudAction.BuildShip: + var hull = (HullBlueprint)hit.Index; + if ( fleet.QueueShip( yardInspector, hull ) ) { + Notify( $"{fleet.Hull( hull ).Name} QUEUED / {fleet.BodyName( yardInspector )}" ); + audio.Cue( "order" ); + } + break; + case HudAction.CancelShip: CancelOrder( fleet.CancelShip( yardInspector, hit.Index ) ); break; + case HudAction.BuildSite: BuildProject( planet, (PlanetFacility)hit.Index ); break; + case HudAction.CancelSite: CancelOrder( fleet.CancelSite( planet, (PlanetFacility)hit.Index ) ); break; + case HudAction.MergeFleets: OrganizeFleets( false ); break; + case HudAction.SplitFleets: OrganizeFleets( true ); break; case HudAction.Squad when fleet.ShipCount( hit.Index ) > 0: selection.Squadron( fleet, hit.Index, ModifierSelection( ) ); - planet = -1; + planet = yardInspector = -1; if ( e.Clicks >= 2 ) cameraFocus = ClampCamera( fleet.Center( hit.Index ) ); break; } @@ -451,7 +498,7 @@ void WorkBeam( Vector2 from, Vector2 to, float scanner ) => } if ( e.Button != MouseButtons.Right ) return; var dimensions = new Vector2( viewport.Width, viewport.Height ); - int enemy = selection.Count == 0 ? -1 : CommandSelection.Hit( fleet, pointer, viewProjection, dimensions, 1, interpolation ); + int enemy = selection.Count == 0 ? -1 : CommandSelection.Hit( fleet, pointer, viewProjection, dimensions, -2, interpolation ); if ( enemy >= 0 ) { if ( fleet.Frontier && !HasArmedSelection( ) ) { Notify( "SELECT CORVETTES TO ATTACK" ); return; } selection.Issue( fleet, default, hostile: enemy ); @@ -494,9 +541,14 @@ void WorkBeam( Vector2 from, Vector2 to, float scanner ) => lastClickShip = -1; } else { int ship = CommandSelection.Hit( fleet, new( e.X, e.Y ), viewProjection, dimensions, 0, interpolation ); - int hitSite = ship < 0 && fleet.Frontier ? PickSite( new( e.X, e.Y ) ) : -1; + int hitSite = fleet.Frontier ? PickSite( new( e.X, e.Y ) ) : -1; + if ( hitSite >= 0 && screenSites[hitSite] is { Facility: PlanetFacility.Yard } yard && fleet.CanOpenYard( yard.Body ) ) { + OpenYard( yard.Body ); + lastClickShip = -1; + return; + } int hitBody = ship < 0 ? hitSite >= 0 ? screenSites[hitSite].Body : PickBody( e.Location ) : -1; - if ( hitBody >= 0 ) planet = hitBody; + if ( hitBody >= 0 ) { planet = hitBody; yardInspector = -1; } else { long now = Environment.TickCount64; var tolerance = SystemInformation.DoubleClickSize; @@ -515,7 +567,7 @@ void WorkBeam( Vector2 from, Vector2 to, float scanner ) => } }; window.MouseWheel += ( _, e ) => { - if ( galaxy || menu is not null || FleetHud.Hit( new( e.X, e.Y ), viewport.Width, viewport.Height, fleet, planet, commandTab: commandTab ).Action != HudAction.None ) return; + if ( galaxy || menu is not null || FleetHud.Hit( new( e.X, e.Y ), viewport.Width, viewport.Height, fleet, planet, commandTab: commandTab, yardInspector: yardInspector ).Action != HudAction.None ) return; float nextZoom = Math.Clamp( zoom * MathF.Pow( 0.85f, e.Delta / 120f ), 0.12f, fleet.Solar ? 3.8f : fleet.Frontier ? 2.8f : 2.5f ); if ( TryPick( e.Location, viewport, inverseViewProjection, out var anchor ) ) cameraFocus = ClampCamera( cameraFocus + (anchor - cameraFocus) * (1 - nextZoom / zoom) ); @@ -528,7 +580,13 @@ void WorkBeam( Vector2 from, Vector2 to, float scanner ) => if ( result.Frames == 2 ) { display.Toggle( window ); Enter( 2 ); } if ( result.Frames == 4 ) display.Toggle( window ); if ( result.Frames == 5 ) galaxy = true; - if ( result.Frames == 6 ) Enter( 0 ); + if ( result.Frames == 6 ) { + Enter( 0 ); + OpenYard( FleetSimulation.Homeworld ); + if ( !fleet.QueueShip( FleetSimulation.Homeworld, HullBlueprint.Miner ) ) + throw new InvalidOperationException( "View qualification could not place the civilian dock order." ); + } + if ( result.Frames == 7 ) SelectTab( CommandTab.Research ); } } ); if ( resizeTest && slotsUsed != 3 ) @@ -561,8 +619,8 @@ void ToggleGalaxy( Form window ) { void ChangeSpeed( ) => speed = speed == 4 ? 1 : speed * 2; - void QueueWing( int body = -1 ) { - if ( fleet.QueueWing( body ) ) { + void QueueWing( ) { + if ( fleet.QueueWing( ) ) { oreShort = false; Notify( $"CORVETTE WING QUEUED / {fleet.QueuedWings} IN PRODUCTION" ); audio.Cue( "order" ); @@ -571,9 +629,7 @@ void QueueWing( int body = -1 ) { oreShort = fleet.Ore < fleet.CurrentWingCost; Notify( fleet.Lost ? "CYAN FLEET LOST" : fleet.YardRemaining < 0 ? "BUILD AN ORBITAL SHIPYARD FIRST" : fleet.YardRemaining > 0 ? "SHIPYARD UNDER CONSTRUCTION" - : fleet.Frontier && fleet.QueuedWings >= FleetSimulation.WingGoal ? "YARD QUEUE FULL" - : fleet.Frontier && fleet.NavalUsed + fleet.NavalReserved + 3 > fleet.NavalCapacity ? "NAVAL CAPACITY FULL / BUILD YARD OR DEPOT" - : !fleet.Frontier && fleet.WingsBuilt + fleet.QueuedWings >= FleetSimulation.WingGoal ? "WING PRODUCTION LIMIT REACHED" + : fleet.WingsBuilt + fleet.QueuedWings >= FleetSimulation.WingGoal ? "WING PRODUCTION LIMIT REACHED" : $"NEED {fleet.CurrentWingCost} ORE TO QUEUE A WING" ); } @@ -581,8 +637,11 @@ void Enter( int index ) { int ships = initial.Frontier ? FleetSimulation.DefaultShips : initial.Capacity - FleetSimulation.WingSize * FleetSimulation.WingGoal; fleet = systems[index] ??= new FleetSimulation( ships, unchecked(seed + (uint)index * 1177), rivalPatrol: true, system: index, battle: true, frontier: initial.Frontier ); - selection.Squadron( fleet, 0, SelectionMode.Replace ); - planet = fleet.Frontier ? FleetSimulation.Homeworld : -1; + selection.Squadron( fleet, fleet.FirstPlayerSquad( ), SelectionMode.Replace ); + planet = fleet.Established ? FleetSimulation.Homeworld : -1; + yardInspector = -1; + launchesSeen = fleet.ShipsLaunched; + researchSeen = fleet.CompletedResearch; commandTab = CommandTab.Hidden; dispatchesSeen = fleet.DispatchCount; dispatch = Math.Max( 0, dispatchesSeen - 1 ); @@ -612,40 +671,59 @@ bool HasArmedSelection( ) { void Command( CommandAction action ) { switch ( action ) { case CommandAction.Toggle: - commandTab = commandTab == CommandTab.Hidden ? CommandTab.Economy : CommandTab.Hidden; + SelectTab( commandTab == CommandTab.Hidden ? CommandTab.Economy : commandTab ); break; case CommandAction.Economy: SelectTab( CommandTab.Economy ); break; case CommandAction.Fleet: SelectTab( CommandTab.Fleet ); break; case CommandAction.Orders: SelectTab( CommandTab.Orders ); break; case CommandAction.Events: SelectTab( CommandTab.Events ); break; - case CommandAction.Worker: - if ( fleet.QueueWorker( ) ) { - Notify( "MINER QUEUED AT HOMEWORLD" ); + case CommandAction.Research: SelectTab( CommandTab.Research ); break; + case CommandAction.StartIndustry or CommandAction.StartWeapons or CommandAction.StartDrive: + var tech = (ResearchTopic)(action - CommandAction.StartIndustry); + if ( fleet.StartResearch( tech ) ) { + Notify( $"{FleetSimulation.Tech( tech ).Name} RESEARCH STARTED" ); audio.Cue( "order" ); - } else Notify( fleet.WorkerRemaining > 0 ? "MINER ALREADY IN PRODUCTION" - : fleet.Ore < FleetSimulation.WorkerCost ? "NEED 20 ORE FOR A MINER" : "MINER PRODUCTION LIMIT REACHED" ); - break; - case CommandAction.Scout: - Notify( fleet.QueueScout( ) ? "SCOUT QUEUED AT HOMEWORLD" : "SCOUT REPLACEMENT NEEDS 24 ORE AND OPEN QUEUE" ); + } break; - case CommandAction.Drive: PlanetOrder( PlanetAction.Drive, planet ); break; - case CommandAction.Wing: QueueWing( ); break; + case CommandAction.CancelResearch: CancelOrder( fleet.CancelResearch( ) ); break; case CommandAction.Pulse: fleet.SetWeapon( WeaponKind.Pulse ); break; case CommandAction.Rail: fleet.SetWeapon( WeaponKind.Rail ); break; case CommandAction.Shield: fleet.SetPlating( false ); break; case CommandAction.Plating: fleet.SetPlating( true ); break; - case CommandAction.CancelFirstWing: CancelOrder( fleet.CancelWing( 0 ) ); break; - case CommandAction.CancelSecondWing: CancelOrder( fleet.CancelWing( 1 ) ); break; - case CommandAction.CancelCivilian: CancelOrder( fleet.CancelCivilian( ) ); break; case CommandAction.Earlier: dispatch = Math.Max( 0, dispatch - 1 ); break; - case CommandAction.Later: dispatch = Math.Min( fleet.DispatchCount - 1, dispatch + 1 ); break; + case CommandAction.Later: dispatch = Math.Clamp( dispatch + 1, 0, Math.Max( 0, fleet.DispatchCount - 1 ) ); break; } } - void SelectTab( CommandTab tab ) => commandTab = commandTab == tab ? CommandTab.Hidden : tab; + void SelectTab( CommandTab tab ) { + yardInspector = -1; + commandTab = commandTab == tab ? CommandTab.Hidden : tab; + } + + void OpenYard( int body ) { + if ( !fleet.CanOpenYard( body ) ) return; + yardInspector = planet = body; + commandTab = CommandTab.Hidden; + } + + void OrganizeFleets( bool split ) { + bool changed = split ? fleet.SplitFleets( selection.Ships ) : fleet.MergeFleets( selection.Ships ); + Notify( split ? changed ? "FLEET SPLIT INTO INDEPENDENT UNITS" : "SELECT SHIPS IN A MERGED FLEET" + : changed ? "COMBAT GROUPS MERGED" : "SELECT TWO OR MORE COMBAT GROUPS" ); + if ( changed ) audio.Cue( "order" ); + } + + void BuildProject( int body, PlanetFacility facility ) { + var builder = selection.SurveyUnit( fleet ); + if ( fleet.ConstructionBlock( body, facility, builder ) is { } reason ) { Notify( reason ); return; } + if ( builder is { } unit && fleet.BuildFacility( body, facility, unit ) ) { + Notify( $"{UnitName( unit )} DISPATCHED / {FleetHud.SiteName( facility )}" ); + audio.Cue( "order" ); + } + } void CancelOrder( bool canceled ) { if ( !canceled ) return; - Notify( "ORDER CANCELED / ORE RETURNED" ); + Notify( "ORDER CANCELED / COST RETURNED" ); audio.Cue( "order" ); } @@ -658,21 +736,17 @@ void Notify( string text ) { string SelectionName( ) => selection.SurveyUnit( fleet ) is { } unit ? UnitName( unit ) : $"{selection.Count} SHIPS"; void PlanetOrder( PlanetAction action, int body ) { - if ( action == PlanetAction.Inspect ) { planet = body; return; } - if ( action == PlanetAction.Close ) { planet = -1; return; } - if ( action == PlanetAction.SiteWing ) { QueueWing( body ); return; } - if ( action is >= PlanetAction.CancelMine and <= PlanetAction.CancelDepot ) { - var facilityToCancel = action switch { - PlanetAction.CancelMine => PlanetFacility.Mine, - PlanetAction.CancelLab => PlanetFacility.Lab, - PlanetAction.CancelYard => PlanetFacility.Yard, _ => PlanetFacility.Depot - }; - CancelOrder( fleet.CancelSite( body, facilityToCancel ) ); + if ( action == PlanetAction.Inspect ) { planet = body; yardInspector = -1; return; } + if ( action == PlanetAction.Close ) { planet = -1; yardInspector = -1; return; } + if ( fleet.Frontier && action is PlanetAction.Research or PlanetAction.Industry or PlanetAction.Drive ) { + SelectTab( CommandTab.Research ); return; } - if ( action == PlanetAction.Drive ) { - Notify( fleet.DriveUpgrade ? "LONG BURN DRIVE ONLINE" : fleet.ResearchDrive( ) ? "LONG BURN DRIVE ONLINE / OUTER BELT UNLOCKED" - : "LONG BURN DRIVE NEEDS 36 SCIENCE" ); + if ( fleet.Frontier && action is PlanetAction.Yard or PlanetAction.Mine or PlanetAction.Lab or PlanetAction.Depot ) { + BuildProject( body, action switch { + PlanetAction.Yard => PlanetFacility.Yard, PlanetAction.Mine => PlanetFacility.Mine, + PlanetAction.Lab => PlanetFacility.Lab, _ => PlanetFacility.Depot + } ); return; } if ( action == PlanetAction.Orbit ) { diff --git a/samples/FleetBattler/README.md b/samples/FleetBattler/README.md index 0ae1af4..04eff8b 100644 --- a/samples/FleetBattler/README.md +++ b/samples/FleetBattler/README.md @@ -1,53 +1,56 @@ # Fleet Battler -The default Frontier scenario starts at Earth in the Solar System with one science scout, two miners, and 50 ore. Survey a moon or gas giant, build an extraction site, then defend the new settlement when Amber notices the operation. Sol, Caldera, and Nereid each retain their own scenario state when you switch systems. +The default Frontier scenario starts at Earth with one science scout, two constructors, 50 ore, and 25 energy. Sol is the only system with player assets at the start. Caldera and Nereid are unclaimed systems where you can observe neutral Free Merchants. The galaxy map switches views and preserves each system's state. It does not transfer ships between systems. | Control | Action | | --- | --- | -| Click or drag a box | Select Cyan ships. Double-click a ship to select its squadron | -| Fleet outliner | Click a squadron to select it. Double-click to center the camera | -| Time controls / Space / + | Pause or resume, and cycle 1×, 2×, and 4× simulation speed | -| Shift / Ctrl | Add to / toggle the selection. Ctrl+A selects all living Cyan ships | -| Right-click | Move in open space, attack an Amber ship, or open a body’s order menu | +| Click or drag a box | Select Sol ships. Double-click a ship to select its command group | +| Fleet outliner | Select a group. Double-click to center the camera | +| Shift / Ctrl | Add to or toggle the selection. Ctrl+A selects all living Sol ships | +| Merge / Split or J / Shift+J | Merge selected combat groups or split selected squadrons into independent groups | +| Right-click | Plot a transfer, attack a hostile contact, or open a body’s order menu | | R | Return selected ships to their formation slots | -| Click a planet or moon | Inspect its survey and construction status | -| E / N / L / T / I | Assign survey / build mine / build lab / research weapons / research industry | -| Colony / Design / Orders / Log | Build civilian ships and research, select the next wing loadout, manage live production, or review dispatches | +| Click a planet or moon | Inspect the survey, orbital sites, and available actions | +| Click a yard or press B | Open that yard’s design catalog and build queue. B falls back to the first available yard or Earth dock | +| E / N / L / T | Assign a survey / dispatch a constructor for a rig / dispatch one for a lab / open Research | +| Colony / Research / Design / Orders / Log | Inspect resource flows, run research, configure future corvettes, find production sites, and read dispatches | | Tab / Escape | Open Colony or close the current panel | -| Hover a ship, body, or station | See status or combat stats. Click a station to open its body's inspector | +| Hover a ship, body, or station | See its faction and disposition, survey status, or work in progress | +| Space / + | Pause or resume, and cycle 1×, 2×, and 4× | | F4 | Open the latest Frontier dispatch | -| B / Queue Wing | Order a wing from an operational orbital shipyard | | Scroll / middle-drag / arrow keys | Zoom toward the pointer / pan | -| Shift + middle-drag / Home | Tilt and rotate within tactical limits / reset the camera to Earth in Sol | -| F | Focus the inspected body or selected squad | +| Shift + middle-drag / Home | Tilt and rotate / reset the camera | +| F | Focus the inspected body or selected group | | G / F11 / M | Galaxy map / fullscreen / mute | ## Playing Frontier -1. Select the science scout in the fleet outliner. Right-click an unsurveyed body and assign the survey, or use the action in its inspection panel. The flight plan shows the assigned craft's course. A finished survey reveals the local deposit and pays 15 ore. -2. Select a miner, inspect the surveyed body, and choose the **Extraction Rig** card. The miner travels to the construction site before the timer starts. The build reserves 35 ore. Reassigning the miner during construction cancels the build and refunds its cost. The builder stays near the rig and shows a welding beam and progress bar during assembly. The completed mine runs independently. -3. Use **Colony** to order another miner for 20 ore. Build a 55-ore orbital shipyard on a surveyed world. The site grows as it builds and the yard opens production after 24 seconds at 1×. -4. Open **Design** to choose a weapon and defense package for the next three-corvette wing. Pulse cycles quickly and hits shields first. Rail fires farther and bypasses shields. A shield generator recovers after a lull. Heavy plating trades shield capacity for armor and adds 8 ore and four seconds at 1×. -5. Follow the **Log** dispatches as extraction attracts an Amber raid. Richer deposits pay for defenses faster and draw an earlier response. Move miners and the scout clear, deploy escorts, and defeat both waves. An orbital lab generates science for weapons, industry, and drive research. Click a celestial body for site cards that show ore or science output, yard and depot capacity, construction progress, and local ship orders. - -| Order | Ore | Construction at 1× | -| --- | ---: | ---: | -| Homeworld miner | 20 | 16 s | -| Replacement scout | 24 | 16 s | -| Mine | 35 | 12 s after miner arrival | -| Lab | 45 | 12 s | -| Orbital shipyard | 55 | 24 s | -| Logistics depot | 40 | 12 s | -| Three-corvette wing | 60 | 32 s | -| Wing after industry research | 42 | 20 s | - -Each completed shipyard adds six naval slots. Each completed logistics depot adds three. Only living combat hulls and queued wings occupy naval capacity. Click an online yard's card to order from that site. The system can hold two wing orders at once and produces them in order. The queue reserves ore and records the yard, loadout, price, and duration at order time. Cancel production in Orders or a site project from its inspector to return the reserved ore. After a fleet wipe, a surviving yard can launch replacements. The homeworld can replace the scout and miners independently. +1. Assign the science scout to survey a body. Completion reveals its deposit and pays 15 ore. Select a constructor, inspect the surveyed body, and order an **Extraction Rig**. Every facility requires a constructor. Work begins after arrival and shows a welding beam and progress bar. Cancel from the body inspector or redirect the constructor to release the assignment and return the reserved cost. +2. Use Earth's **Civilian Dock** to replace scouts and constructors. Build an **Orbital Shipyard** to unlock corvette production. Select the station in orbit, click **Open** on its body card, or choose it from **Orders**. +3. Select a hull in the shipyard catalog and click **Add**. Each order reserves its own resources and launches one ship. Each yard has four queue slots and works independently. The active row and in-world yard show progress. Canceling returns the order's reserved resources and starts the next job if needed. +4. **Design** configures future corvettes. Pulse strips shields quickly. Rail fires farther and bypasses shields. Plating trades shield capacity for armor and costs 3 more ore, 2 more energy, and 20 more ticks. The yard captures the loadout, cost, and build time when you place an order. +5. In **Research**, choose a project after bringing a lab online. The lab generates science. Each project reserves science and energy, runs on simulation time, and applies its effect at completion. Ore funds structures and hulls. Earth's colony and orbital solar arrays generate energy each income cycle. +6. Follow **Log** as extraction attracts Amber Raiders, followed by Rival Command. Both are hostile to Sol. Free Merchants are neutral to Sol. Group escorts with **Merge** to select and issue orders together, or use **Split** to return them to independent control. + +| Order | Ore | Energy | Time at 1× | +| --- | ---: | ---: | ---: | +| Constructor | 20 | 5 | 16 s | +| Scout | 24 | 6 | 16 s | +| Extraction rig | 35 | 8 | 12 s after arrival | +| Research lab | 45 | 10 | 12 s after arrival | +| Orbital shipyard | 55 | 15 | 24 s after arrival | +| Logistics depot | 40 | 9 | 12 s after arrival | +| Solar array | 28 | 4 | 12 s after arrival | +| Corvette with shield generator | 20 | 8 | 11 s | +| Corvette after industry research | 14 | 8 | 7 s | + +Each completed shipyard adds six naval slots and each completed depot adds three. Living and queued corvettes consume naval capacity. After a wipe, available yards can produce replacements using the same queue. ## Navigation Ships start and launch in host-relative parking orbits. An orbit or survey command targets an intercept on the destination body's future orbit. The dashed route samples the same transfer the ship flies. The diamond marks the rendezvous and the **Flight Plan** card shows the active flight phase and ETA at the current simulation speed. Open-space orders transfer into a stellar parking orbit at the chosen radius. Ships burn, coast, rotate for turnover, and brake before entering the destination orbit. Hull attitude and formation orientation update independently. The route uses fixed samples as the completed portion disappears. -The round-trip operating envelope is enforced before accepting a route. Research **Long Burn Drive** in Economy for 36 science to expand it and reach the outer belt. The Kuiper Belt, Cinder Belt, and Dark Shoal each contain a high-yield prospect. Zoom out to find the outer track. The navigation model uses scaled orbital distances and bounded-burn guidance. Gravity assists and per-ship propellant accounting are future work. +The round-trip operating envelope is enforced before accepting a route. Research **Long Burn Drive** in Research for 36 science and 20 energy to expand it and reach the outer belt. The Kuiper Belt, Cinder Belt, and Dark Shoal each contain a high-yield prospect. Zoom out to find the outer track. The navigation model uses scaled orbital distances and bounded-burn guidance. Gravity assists and per-ship propellant accounting are future work. Sol includes the Sun, eight planets, Earth's Moon, and a Kuiper Belt prospect. The catalog uses rounded planetary semimajor axes and eccentricities from the [JPL J2000 approximate elements](https://ssd.jpl.nasa.gov/planets/approx_pos.html). The tactical projection compresses distance logarithmically and uses illustrative starting phases, radii, and periods. diff --git a/samples/FleetBattler/SiteConstruction.cs b/samples/FleetBattler/SiteConstruction.cs new file mode 100644 index 0000000..d99e81d --- /dev/null +++ b/samples/FleetBattler/SiteConstruction.cs @@ -0,0 +1,99 @@ +using System.Numerics; + +namespace FleetBattler; + +internal readonly record struct FacilityPlan( string Name, ResourceCost Cost, int Duration ); +internal record struct ConstructionSite( FleetSelection? Worker, Vector2 Orbit, bool Working ); + +internal sealed partial class FleetSimulation { + internal const int FacilityCount = 5; + internal static ReadOnlySpan Facilities => [ + PlanetFacility.Mine, PlanetFacility.Lab, PlanetFacility.Yard, PlanetFacility.Depot, PlanetFacility.Solar + ]; + private readonly int[] _solarArrays = new int[CelestialSystem.BodyCount]; + private readonly ConstructionSite[] _siteConstruction = new ConstructionSite[CelestialSystem.BodyCount * FacilityCount]; + internal SiteOrder LastStartedSite { get; private set; } + + internal static FacilityPlan Facility( PlanetFacility facility ) => facility switch { + PlanetFacility.Mine => new( "EXTRACTION RIG", new( MineCost, 8 ), FacilityDuration ), + PlanetFacility.Lab => new( "RESEARCH LAB", new( LabCost, 10 ), FacilityDuration ), + PlanetFacility.Yard => new( "ORBITAL SHIPYARD", new( YardCost, 15 ), YardDuration ), + PlanetFacility.Depot => new( "LOGISTICS DEPOT", new( DepotCost, 9 ), FacilityDuration ), + PlanetFacility.Solar => new( "SOLAR ARRAY", new( 28, 4 ), FacilityDuration ), + _ => throw new ArgumentOutOfRangeException( nameof(facility) ) + }; + + private ref ConstructionSite Construction( int body, PlanetFacility facility ) => + ref _siteConstruction[body * FacilityCount + (int)facility]; + + internal string? ConstructionBlock( int body, PlanetFacility facility, FleetSelection? unit ) { + if ( body <= 0 || body >= _bodies.Length || !Planet( body ).Surveyed ) return "SURVEY THIS BODY FIRST"; + if ( SiteRemaining( body, facility ) >= 0 ) return "SITE ALREADY ASSIGNED"; + if ( facility == PlanetFacility.Mine && !HasDeposit( body ) ) return "NO ORE DEPOSIT"; + if ( unit is not { } worker || !ValidConstructor( worker ) ) return "SELECT A CONSTRUCTOR"; + if ( !CanReach( worker, body ) ) return "OUTSIDE CONSTRUCTOR RANGE"; + foreach ( var assignment in _siteConstruction ) + if ( assignment.Worker?.Squad == worker.Squad ) return "CONSTRUCTOR ALREADY ASSIGNED"; + var cost = Facility( facility ).Cost; + if ( Ore < cost.Ore ) return "INSUFFICIENT ORE"; + if ( Energy < cost.Energy ) return "INSUFFICIENT ENERGY"; + return null; + } + + private bool ValidConstructor( FleetSelection worker ) => (uint)worker.Squad < (uint)SquadCount && + IsPlayerSquad( worker.Squad ) && Role( worker.Squad ) == HullRole.Miner && + (worker.IsShip ? Alive( worker.Ship ) && SquadronOf( worker.Ship ) == worker.Squad : ShipCount( worker.Squad ) > 0); + + private bool StartConstruction( int body, PlanetFacility facility, FleetSelection? unit ) { + if ( ConstructionBlock( body, facility, unit ) is not null ) return false; + var worker = unit!.Value; + var orbit = OrbitalOrder( worker, body, survey: false ); + Construction( body, facility ) = new( worker, new( orbit.Radius, orbit.Phase + 0.24f ), false ); + SetOrder( worker, orbit ); + var plan = Facility( facility ); + Spend( plan.Cost ); + SiteDeadlines( facility )[body] = Tick + plan.Duration; + return true; + } + + internal FleetSelection? SiteWorker( int body, PlanetFacility facility ) => Construction( body, facility ).Worker; + internal bool SiteEnRoute( int body, PlanetFacility facility ) => + SiteWorker( body, facility ) is { } worker && !InSurveyRange( worker, body ); + + private void AdvanceConstruction( int body, PlanetFacility facility ) { + ref var site = ref Construction( body, facility ); + if ( site.Worker is not { } worker ) return; + if ( !ValidConstructor( worker ) || EffectiveOrder( worker ).Body != body + 1 ) { + CancelSite( body, facility ); + return; + } + var deadlines = SiteDeadlines( facility ); + if ( !InSurveyRange( worker, body ) ) { + ++deadlines[body]; + return; + } + if ( !site.Working ) { + site.Working = true; + LastStartedSite = new( body, facility ); + ++StartedConstruction; + } + if ( deadlines[body] <= Tick + 1 ) site.Worker = null; + } + + internal Vector2 SitePosition( int body, PlanetFacility facility, float interpolation ) => + SitePositionAt( body, facility, Math.Max( 0, Tick - 1 + interpolation ), VisualBody( body, interpolation ).Center ); + + private Vector2 SitePositionAt( int body, PlanetFacility facility, float tick, Vector2 center ) { + var orbit = Construction( body, facility ).Orbit; + if ( orbit.X > 0 ) { + var (sin, cos) = MathF.SinCos( orbit.Y + tick * OrbitRate( orbit.X ) ); + return center + new Vector2( cos, sin ) * orbit.X; + } + float phase = facility switch { + PlanetFacility.Lab => MathF.PI, PlanetFacility.Depot => MathF.PI / 2, + PlanetFacility.Solar => MathF.PI / 4, _ => -MathF.PI / 2 + }; + var (y, x) = MathF.SinCos( tick * (float)StepSeconds * 0.23f + phase ); + return center + new Vector2( x, y ) * (OrbitRadius( body, 1 ) + 4); + } +} diff --git a/tests/InteropQualification/FleetQualification.cs b/tests/InteropQualification/FleetQualification.cs index 0892452..ae48b13 100644 --- a/tests/InteropQualification/FleetQualification.cs +++ b/tests/InteropQualification/FleetQualification.cs @@ -254,80 +254,84 @@ private static void VerifyPlanetEconomy( ) { } private static void VerifyFrontier( ) { - const int prospect = 2; + const int home = FleetSimulation.Homeworld, prospect = 2; var fleet = new FleetSimulation( 3, 37, battle: true, frontier: true ); var scout = new FleetSelection( 0, 0 ); var miner = new FleetSelection( 1, 1 ); - Require( fleet.CyanCount == 3 && fleet.AmberCount == 0 && !fleet.Won && fleet.Planet( FleetSimulation.Homeworld ).Surveyed && - fleet.Role( 0 ) == HullRole.Scout && fleet.Role( 1 ) == HullRole.Miner && fleet.Role( 2 ) == HullRole.Miner && - fleet.Dispatch( 0 ) == FrontierEvent.Arrival, "homeworld, science ship and workers open in peacetime" ); - Require( !fleet.QueueWing( ) && !fleet.BuildFacility( prospect, PlanetFacility.Mine, miner ) && - !fleet.BeginSurvey( miner, prospect ) && fleet.BeginSurvey( scout, prospect ), "exploration and production gates enforce roles" ); - Require( fleet.QueueWorker( ) && fleet.Ore == 30 && fleet.WorkerRemaining == FleetSimulation.WorkerDuration && - !fleet.QueueWorker( ) && fleet.CyanCount == 3, "the homeworld charges and schedules a worker" ); - AdvanceUntil( fleet, () => fleet.HasDeposit( prospect ), "scout reaches and surveys the hidden deposit", 1800 ); - Require( fleet.DepositYield( prospect ) == 12 && fleet.Ore == 45 && fleet.Dispatch( 1 ) == FrontierEvent.Prospect && - !fleet.BuildFacility( prospect, PlanetFacility.Mine, scout ), "the survey reveals a specific yield and miners alone can build" ); - Require( fleet.BuildFacility( prospect, PlanetFacility.Mine, miner ) && fleet.Ore == 10 && - fleet.MineEnRoute( prospect ), "placing a mine reserves ore and assigns a named worker" ); - fleet.Step( ); - Require( fleet.Planet( prospect ).MineRemaining == FleetSimulation.FacilityDuration, "travel does not consume construction time" ); - fleet.Move( miner, new( -38, 10 ) ); - fleet.Step( ); - Require( fleet.Planet( prospect ).MineRemaining < 0 && fleet.Ore == 45 && - fleet.BuildFacility( prospect, PlanetFacility.Mine, miner ), "reassigning a worker refunds the unfinished mine" ); + Require( fleet.Established && fleet.CyanCount == 3 && fleet.AmberCount == 0 && !fleet.Won && + fleet.Planet( home ).Surveyed && fleet.Role( 0 ) == HullRole.Scout && fleet.Role( 1 ) == HullRole.Miner && + fleet.Role( 2 ) == HullRole.Miner && fleet.Dispatch( 0 ) == FrontierEvent.Arrival && fleet.Energy == 25, + "Sol starts with the homeworld, scout, two constructors, and energy" ); + for ( int system = 1; system < CelestialSystem.MapPositions.Length; ++system ) { + var remote = new FleetSimulation( 3, 37, system: system, battle: true, frontier: true ); + for ( int i = 0; i < 180; ++i ) remote.Step( ); + Require( !remote.Established && remote.CyanCount == 0 && remote.FirstPlayerSquad( ) == -1 && + remote.MerchantCount == 1 && remote.ActiveCount == 1 && remote.FactionOf( 0 ) == FactionId.Merchants && + remote.Ore == 0 && remote.Energy == 0 && remote.DispatchCount == 0 && !remote.Planet( home ).Surveyed && + !remote.CanOpenYard( home ), "uncolonized systems have neutral traffic and no player assets" ); + } + Require( Factions.Attitude( FactionId.Sol, FactionId.Merchants ) == Disposition.Neutral && + Factions.Attitude( FactionId.Sol, FactionId.Raiders ) == Disposition.Hostile && + Factions.Attitude( FactionId.Sol, FactionId.Rival ) == Disposition.Hostile, "factions distinguish neutral shipping from opponents" ); + + Require( !fleet.QueueShip( home, HullBlueprint.Corvette ) && fleet.QueueShip( home, HullBlueprint.Miner ) && + fleet.YardQueue( home ).Length == 1 && fleet.CyanCount == 3 && fleet.NavalReserved == 0 && + !fleet.BeginSurvey( miner, prospect ) && fleet.BeginSurvey( scout, prospect ), + "the Earth dock builds civilian hulls while the scout discovers deposits" ); + AdvanceUntil( fleet, () => fleet.HasDeposit( prospect ), "the scout reaches and surveys the hidden deposit", 1800 ); + Require( fleet.DepositYield( prospect ) == 12 && fleet.Dispatch( 1 ) == FrontierEvent.Prospect && + !fleet.BuildFacility( prospect, PlanetFacility.Mine, scout ), "the survey reveals a specific yield and scouts cannot construct" ); + Require( fleet.BuildFacility( prospect, PlanetFacility.Mine, miner ), "mining is assigned to a constructor" ); AdvanceUntil( fleet, () => fleet.Planet( prospect ).MineRemaining == 0, "arrival starts and completes construction", 1800 ); - Require( fleet.CyanCount == 4 && fleet.WorkerRemaining < 0 && fleet.Role( 3 ) == HullRole.Miner && - fleet.Dispatch( 2 ) == FrontierEvent.Distress && fleet.AmberCount == 0, "workers launch after construction and mining triggers a warning" ); - fleet.Move( scout, new( -70, 40 ) ); - fleet.Move( miner, new( -70, 45 ) ); - fleet.Move( 2, new( -70, 50 ) ); - fleet.Move( 3, new( -70, 55 ) ); - AdvanceUntil( fleet, () => fleet.Ore >= FleetSimulation.YardCost, "operating mine pays for a yard" ); - int bank = fleet.Ore; - Require( fleet.BuildYard( FleetSimulation.Homeworld ) && fleet.YardRemaining == FleetSimulation.YardDuration && - fleet.Ore == bank - FleetSimulation.YardCost && !fleet.QueueWing( ), "building a yard commits cost and blocks production during construction" ); - fleet.ConfigureDesign( weapon: true ); + Require( fleet.ActiveMiners( ) == 3 && fleet.YardQueue( home ).IsEmpty && fleet.Dispatch( 2 ) == FrontierEvent.Distress, + "the Earth order launches one constructor and mining triggers a warning" ); + AdvanceUntil( fleet, () => fleet.CanAfford( FleetSimulation.Facility( PlanetFacility.Yard ).Cost ), "operating mine pays for an orbital yard" ); + Require( fleet.BuildYard( home, new( 2 ) ) && fleet.YardRemaining == FleetSimulation.YardDuration && + !fleet.QueueShip( home, HullBlueprint.Corvette ), "shipyard construction gates naval production" ); + fleet.SetWeapon( WeaponKind.Rail ); ShipDesign design = fleet.Design; - AdvanceUntil( fleet, () => fleet.CanBuildWing, "mine funds the first corvette wing" ); - bank = fleet.Ore; + AdvanceUntil( fleet, () => fleet.ShipOrderBlock( home, HullBlueprint.Corvette ) is null, "mine funds the first corvette" ); int before = fleet.CyanCount; - Require( fleet.QueueWing( ) && fleet.Ore == bank - 60 && fleet.WingRemaining == 480 && - fleet.CyanCount == before && fleet.ActiveWingDesign == design, "rail design is priced and captured when queued" ); - fleet.ConfigureDesign( weapon: true ); - fleet.ConfigureDesign( weapon: false ); - AdvanceUntil( fleet, () => fleet.WingsBuilt == 1, "first queued wing launches" ); - int corvette = Enumerable.Range( 0, fleet.Count ).First( ship => fleet.Loadout( ship ) == design ); - Require( fleet.ActiveRaids == 1 && fleet.ShipCount( fleet.SquadronOf( corvette ) ) == 3 && - fleet.Shield( corvette ) == 34 && fleet.Armor( corvette ) == 10 && - fleet.CurrentWingCost == 68 && fleet.CurrentWingDuration == 540 && !fleet.Won, "the launch uses the queued loadout and the first raid is in play" ); - - bool sawRailBypass = false, sawPulseAbsorption = false; - int combatLimit = fleet.Tick + 3600; - while ( !fleet.Won && !fleet.Lost && fleet.Tick < combatLimit ) { - if ( fleet.CanBuildWing ) Require( fleet.QueueWing( ), "a second corvette wing can reinforce the defense" ); + var hull = fleet.Hull( HullBlueprint.Corvette ); + Require( fleet.QueueShip( home, HullBlueprint.Corvette ) && fleet.NavalReserved == 1 && + fleet.ShipRemaining( home ) == hull.Duration && fleet.CyanCount == before && + fleet.YardQueue( home )[0].Design == design, "purchase snapshots the design and reserves exactly one hull" ); + fleet.SetWeapon( WeaponKind.Pulse ); + fleet.SetPlating( true ); + AdvanceUntil( fleet, () => fleet.CorvettesLaunched == 1, "first queued corvette launches" ); + int corvette = fleet.LastLaunch.Ship; + Require( fleet.Loadout( corvette ) == design && fleet.ShipCount( fleet.SquadronOf( corvette ) ) == 1 && + fleet.Shield( corvette ) == 34 && fleet.Armor( corvette ) == 10, "the launch uses the purchased loadout" ); + foreach ( var facility in FleetSimulation.Facilities ) + Require( fleet.ConstructionBlock( home, facility, new( fleet.SquadronOf( corvette ), corvette ) ) is not null, + "corvettes cannot construct Frontier facilities" ); + + bool sawRaiders = false, sawRival = false, sawRailBypass = false; + int combatLimit = fleet.Tick + 5200; + while ( !fleet.Won && fleet.Tick < combatLimit ) { + if ( fleet.ShipOrderBlock( home, HullBlueprint.Corvette ) is null ) + Require( fleet.QueueShip( home, HullBlueprint.Corvette ), "the yard can reinforce the defense" ); if ( fleet.Tick % 30 == 0 && fleet.AmberCount > 0 ) { - int target = Enumerable.Range( 0, fleet.Count ).First( ship => fleet.Alive( ship ) && fleet.SideOf( ship ) == 1 ); + int target = Enumerable.Range( 0, fleet.Count ).First( ship => fleet.Alive( ship ) && + Factions.Attitude( FactionId.Sol, fleet.FactionOf( ship ) ) == Disposition.Hostile ); for ( int squad = 0; squad < fleet.SquadCount; ++squad ) if ( fleet.IsPlayerSquad( squad ) && fleet.Role( squad ) == HullRole.Corvette && fleet.ShipCount( squad ) > 0 ) fleet.Attack( new( squad ), target ); } fleet.Step( ); for ( int ship = 0; ship < fleet.Count; ++ship ) { - if ( !fleet.Alive( ship ) || fleet.Role( fleet.SquadronOf( ship ) ) != HullRole.Corvette ) continue; + if ( !fleet.Alive( ship ) ) continue; + var faction = fleet.FactionOf( ship ); var loadout = fleet.Loadout( ship ); - sawRailBypass |= fleet.SideOf( ship ) == 1 && fleet.Armor( ship ) < loadout.Armor && fleet.Shield( ship ) == loadout.Shield; - sawPulseAbsorption |= fleet.SideOf( ship ) == 0 && fleet.ActiveRaids == 1 && - fleet.Shield( ship ) < loadout.Shield && fleet.Armor( ship ) == loadout.Armor; + sawRaiders |= faction == FactionId.Raiders; + sawRival |= faction == FactionId.Rival; + sawRailBypass |= fleet.Role( fleet.SquadronOf( ship ) ) == HullRole.Corvette && + fleet.Armor( ship ) < loadout.Armor && fleet.Shield( ship ) == loadout.Shield; } } - Require( sawRailBypass && sawPulseAbsorption, "rail bypasses shields and pulse strips them before reaching armor" ); - Require( fleet.Won && fleet.ActiveRaids == 2 && fleet.Dispatch( fleet.DispatchCount - 1 ) == FrontierEvent.Secured, - "the player can overcome both escalating raids and secure the frontier" ); - int miners = fleet.ActiveMiners( ); - Require( fleet.QueueWorker( ), "the homeworld can continue growing after victory" ); - AdvanceUntil( fleet, () => fleet.ActiveMiners( ) > miners, "a post-victory worker leaves the queue" ); - Require( fleet.ActiveMiners( ) == miners + 1 && fleet.ActiveRaids == 2, "post-victory production does not restart raids" ); + Require( sawRaiders && sawRival && sawRailBypass && fleet.Won && fleet.ActiveRaids == 2 && + fleet.Dispatch( fleet.DispatchCount - 1 ) == FrontierEvent.Secured, + "pirates and rival military participate in both raids, piercing weapons work, and the frontier can be secured" ); } private static void VerifyFleetRecovery( ) { @@ -337,35 +341,43 @@ private static void VerifyFleetRecovery( ) { AdvanceUntil( fleet, () => fleet.HasDeposit( prospect ), "recovery prospect surveyed", 1800 ); Require( fleet.BuildFacility( prospect, PlanetFacility.Mine, new( 1 ) ), "recovery funding" ); AdvanceUntil( fleet, () => fleet.Ore >= 235, "mine funds fleet and infrastructure", 3000 ); - Require( fleet.BuildYard( home ) && fleet.BuildFacility( home, PlanetFacility.Depot ) && - fleet.BuildYard( prospect ) && fleet.NavalCapacity == 0 && !fleet.CanBuildWing, - "incomplete infrastructure cannot grant capacity" ); - AdvanceUntil( fleet, () => fleet.DepotCount == 1, "logistics depot constructed" ); - Require( fleet.NavalCapacity == FleetSimulation.DepotNavalCapacity && !fleet.CanBuildWing, "depot alone supplies no shipyard" ); + Require( fleet.BuildYard( home, new( 2 ) ) && fleet.BuildYard( prospect, new( 1 ) ) && + !fleet.BuildFacility( home, PlanetFacility.Depot, new( 2 ) ) && fleet.NavalCapacity == 0, + "pending yards grant no capacity and a constructor can only have one assignment" ); AdvanceUntil( fleet, () => fleet.YardCount == 2, "both yards constructed" ); - Require( fleet.NavalCapacity == 15 && fleet.QueueWing( prospect ) && fleet.ActiveYard == prospect && - fleet.QueueWing( home ) && fleet.NavalReserved == 6 && !fleet.CanBuildWing, "queue reserves actual hull slots and stores its yard" ); + Require( fleet.BuildFacility( home, PlanetFacility.Depot, new( 2 ) ), "the free constructor can build logistics infrastructure" ); + AdvanceUntil( fleet, () => fleet.DepotCount == 1, "logistics depot constructed" ); + Require( fleet.NavalCapacity == 15 && fleet.QueueShip( prospect, HullBlueprint.Corvette ) && + fleet.QueueShip( home, HullBlueprint.Corvette ) && fleet.NavalReserved == 2 && + fleet.ShipRemaining( prospect ) == fleet.ShipRemaining( home ), "yards have independent, concurrent build queues" ); for ( int ship = 0; ship < fleet.Count; ++ship ) if ( fleet.SideOf( ship ) == 0 ) fleet.ApplyHullDamage( ship, FleetSimulation.HullCapacity ); - Require( fleet.Recovering && !fleet.Lost && fleet.NavalReserved == 6, "total loss leaves infrastructure and queued orders intact" ); - AdvanceUntil( fleet, () => fleet.WingsBuilt == 2, "both yards can fulfill work after a fleet wipe", 1300 ); - Require( fleet.NavalUsed == 6 && fleet.NavalReserved == 0 && !fleet.Recovering, "launch converts reserved capacity to live hulls" ); + Require( fleet.Recovering && !fleet.Lost && fleet.NavalReserved == 2, "total loss leaves infrastructure and queued orders intact" ); + AdvanceUntil( fleet, () => fleet.ShipsLaunched == 2, "both yards can fulfill work after a fleet wipe", 1300 ); + Require( fleet.NavalUsed == 2 && fleet.NavalReserved == 0 && !fleet.Recovering, "launch converts reserved capacity to live hulls" ); var chosen = new CommandSelection( fleet.Capacity ); chosen.All( fleet ); + int first = fleet.FirstPlayerSquad( ); + Require( fleet.MergeFleets( chosen.Ships ) && fleet.FleetStrength( first ) == 2, "two combat groups merge" ); + chosen.Squadron( fleet, first, SelectionMode.Replace ); + Require( chosen.Count == 2 && fleet.SplitFleets( chosen.Ships ) && fleet.FleetStrength( first ) == 1, + "selecting a merged fleet selects its members and split restores independent commands" ); int storage = fleet.Count; for ( int iteration = 0; iteration < 35; ++iteration ) { for ( int ship = 0; ship < fleet.Count; ++ship ) if ( fleet.SideOf( ship ) == 0 ) fleet.ApplyHullDamage( ship, FleetSimulation.HullCapacity ); - Require( fleet.NavalUsed == 0 && fleet.Recovering && fleet.QueueWing( home ), "losses release naval capacity for every replacement" ); - int built = fleet.WingsBuilt; - AdvanceUntil( fleet, () => fleet.WingsBuilt > built, "replacement wing launches" ); + Require( fleet.NavalUsed == 0 && fleet.Recovering && fleet.QueueShip( home, HullBlueprint.Corvette ), + "losses release naval capacity for every replacement" ); + int built = fleet.ShipsLaunched; + AdvanceUntil( fleet, () => fleet.ShipsLaunched > built, "replacement hull launches" ); } chosen.Prune( fleet ); - Require( chosen.Count == 0 && fleet.Count == storage && fleet.NavalUsed == 3 && fleet.WingsBuilt == 37, + Require( chosen.Count == 0 && fleet.Count == storage && fleet.NavalUsed == 1 && fleet.ShipsLaunched == 37, "replacement recycles storage without inheriting a dead hull's selection" ); - Require( fleet.QueueScout( ), "destroyed scout can be ordered from the homeworld" ); - AdvanceUntil( fleet, () => fleet.WorkerRemaining < 0, "replacement scout launches" ); - Require( fleet.CyanCount == 4 && fleet.IsScoutSquad( 0 ), "replacement civilian restores scouting without occupying naval capacity" ); + Require( fleet.QueueShip( home, HullBlueprint.Scout ), "destroyed scout can be ordered from the homeworld" ); + AdvanceUntil( fleet, () => fleet.YardQueue( home ).IsEmpty, "replacement scout launches" ); + Require( fleet.CyanCount == 2 && fleet.Role( fleet.SquadronOf( fleet.LastLaunch.Ship ) ) == HullRole.Scout, + "replacement civilian restores scouting without occupying naval capacity" ); } private static void VerifyOrbitalTransfers( ) { @@ -375,9 +387,12 @@ private static void VerifyOrbitalTransfers( ) { Require( fleet.Bodies.Length == 11 && fleet.BodyName( 1 ) == "EARTH" && fleet.BodyName( 10 ) == "NEPTUNE" && SolarCatalog.Get( 3 ).Parent == FleetSimulation.Homeworld && !fleet.Orbit( scout, belt ) && !fleet.BeginSurvey( scout, belt ) && !fleet.Move( scout, fleet.Bodies[belt].Center ), "base drive rejects out-of-range orders without changing the orbit" ); - Require( fleet.BuildFacility( FleetSimulation.Homeworld, PlanetFacility.Lab ), "homeworld lab funds navigation research" ); + Require( fleet.BuildFacility( FleetSimulation.Homeworld, PlanetFacility.Lab, new( 1 ) ), "homeworld lab funds navigation research" ); AdvanceUntil( fleet, () => fleet.Science >= FleetSimulation.DriveCost, "lab produces drive research" ); - Require( fleet.ResearchDrive( ) && fleet.BeginSurvey( scout, belt ), "long-burn drive unlocks belt rendezvous" ); + Require( fleet.StartResearch( ResearchTopic.Drive ) && !fleet.DriveUpgrade && !fleet.BeginSurvey( scout, belt ), + "the drive does not unlock at purchase time" ); + AdvanceUntil( fleet, () => fleet.DriveUpgrade, "long-burn drive finishes research" ); + Require( fleet.BeginSurvey( scout, belt ), "long-burn drive unlocks belt rendezvous" ); int end = fleet.Tick + fleet.RouteTicks( scout ); Span route = stackalloc Vector2[17]; Require( fleet.RoutePhase( scout ) == NavigationPhase.Burn && fleet.CopyRoute( scout, route, out var endpoint ) && @@ -409,7 +424,7 @@ private static void VerifyOrbitalTransfers( ) { AdvanceUntil( fleet, () => fleet.HasDeposit( belt ), "survey completes from orbit" ); Require( fleet.DepositYield( belt ) == 20 && MathF.Abs( Vector2.Distance( fleet.Center( scout ), fleet.Bodies[belt].Center ) - radius ) < 0.01f && fleet.Orbit( scout, FleetSimulation.Homeworld ), "scout remains in host-relative orbit and can plot a return" ); - Require( FleetHud.Hit( new( 465, 177 ), 640, 400, fleet, belt ) == new HudHit( HudAction.Planet, (int)PlanetAction.Mine ), + Require( FleetHud.Hit( new( 465, 218 ), 660, 500, fleet, belt ) == new HudHit( HudAction.BuildSite, (int)PlanetFacility.Mine ), "planet inspector site card matches the mine action" ); } @@ -418,35 +433,66 @@ private static void VerifyProjectCancellation( ) { var fleet = new FleetSimulation( 3, 37, frontier: true ); var scout = new FleetSelection( 0 ); var miner = new FleetSelection( 1 ); - int originalOre = fleet.Ore; - Require( fleet.QueueWorker( ) && fleet.CancelCivilian( ) && fleet.WorkerRemaining < 0 && fleet.Ore == originalOre && - !fleet.CancelCivilian( ), "civilian cancellation refunds one order and releases its berth" ); - Require( fleet.BuildFacility( home, PlanetFacility.Lab ) && - FleetHud.Hit( new( 605, 208 ), 640, 400, fleet, home ) == new HudHit( HudAction.Planet, (int)PlanetAction.CancelLab ) && - fleet.CancelSite( home, PlanetFacility.Lab ) && fleet.Ore == originalOre, "site card cancels construction and returns ore" ); + int originalOre = fleet.Ore, originalEnergy = fleet.Energy; + Require( FleetHud.Hit( new( 300, 205 ), 660, 500, fleet, home, yardInspector: home ).Action == HudAction.BuildShip && + FleetHud.Hit( new( 357, 205 ), 660, 500, fleet, home, yardInspector: home ).Action == HudAction.Panel, + "the shipyard design Add button and independent queue row have distinct hit regions" ); + Require( fleet.QueueShip( home, HullBlueprint.Miner ) && fleet.CancelShip( home, 0 ) && + fleet.YardQueue( home ).IsEmpty && fleet.Ore == originalOre && fleet.Energy == originalEnergy && + !fleet.CancelShip( home, 0 ), "civilian cancellation refunds ore and energy and releases the slot" ); + Require( !fleet.BuildFacility( home, PlanetFacility.Lab ) && !fleet.BuildFacility( home, PlanetFacility.Lab, scout ) && + fleet.BuildFacility( home, PlanetFacility.Lab, miner ) && + fleet.CancelSite( home, PlanetFacility.Lab ) && fleet.Ore == originalOre && fleet.Energy == originalEnergy, + "a lab needs a constructor and cancellation refunds both resources" ); + Require( fleet.BeginSurvey( scout, moon ), "survey the Moon to discover a construction site" ); AdvanceUntil( fleet, () => fleet.HasDeposit( moon ), "Moon survey completes", 1800 ); originalOre = fleet.Ore; - Require( fleet.BuildFacility( moon, PlanetFacility.Mine, miner ) && fleet.MineEnRoute( moon ), "mine assigns a traveling constructor" ); + Require( fleet.BuildFacility( moon, PlanetFacility.Mine, miner ) && fleet.SiteEnRoute( moon, PlanetFacility.Mine ), + "mine assigns a traveling constructor" ); + fleet.Step( ); + Require( fleet.SiteRemaining( moon, PlanetFacility.Mine ) == FleetSimulation.FacilityDuration, + "travel does not consume construction time" ); + fleet.Move( miner, new( -38, 10 ) ); + fleet.Step( ); + Require( fleet.SiteRemaining( moon, PlanetFacility.Mine ) < 0 && fleet.Ore == originalOre && + fleet.BuildFacility( moon, PlanetFacility.Mine, miner ), "reassigning a constructor refunds the unfinished facility" ); AdvanceUntil( fleet, () => fleet.StartedConstruction == 1, "mine starts when its constructor reaches the site" ); var site = fleet.SitePosition( moon, PlanetFacility.Mine, 1 ); - Require( fleet.SiteWorker( moon ) == miner && Vector2.Distance( site, fleet.Center( miner ) ) < 6 && - fleet.CancelSite( moon, PlanetFacility.Mine ) && fleet.SiteWorker( moon ) is null && + Require( fleet.SiteWorker( moon, PlanetFacility.Mine ) == miner && Vector2.Distance( site, fleet.Center( miner ) ) < 6 && + fleet.CancelSite( moon, PlanetFacility.Mine ) && fleet.SiteWorker( moon, PlanetFacility.Mine ) is null && fleet.Ore == originalOre && !fleet.CancelSite( moon, PlanetFacility.Mine ), "active mine stays near its builder and can be canceled" ); Require( fleet.BuildFacility( moon, PlanetFacility.Mine, miner ), "canceled mine can be rebuilt" ); - AdvanceUntil( fleet, () => fleet.Ore >= 205, "production cancellation test funds its yard and wings", 4000 ); - Require( fleet.BuildYard( home ), "queue fixture has an orbital yard" ); - AdvanceUntil( fleet, () => fleet.YardCount == 1, "orbital yard comes online" ); + AdvanceUntil( fleet, () => fleet.Ore >= 205, "mine funds production and research", 4000 ); + Require( fleet.BuildYard( home, new( 2 ) ) && fleet.BuildFacility( home, PlanetFacility.Solar, miner ), "build yard and solar array" ); + AdvanceUntil( fleet, () => fleet.YardCount == 1 && fleet.EnergyIncome == 11, "the yard and additional energy income come online" ); + Require( fleet.BuildFacility( home, PlanetFacility.Lab, new( 2 ) ), "build research lab" ); + AdvanceUntil( fleet, () => fleet.CanResearch( ResearchTopic.Industry ), "lab produces science for timed research" ); + int science = fleet.Science; + originalEnergy = fleet.Energy; + Require( fleet.StartResearch( ResearchTopic.Industry ) && !fleet.IndustryUpgrade && + fleet.ResearchRemaining == FleetSimulation.Tech( ResearchTopic.Industry ).Duration && + !fleet.StartResearch( ResearchTopic.Weapons ) && fleet.CancelResearch( ) && fleet.Science == science && + fleet.Energy == originalEnergy, "research is timed and exclusive, and cancellation releases its budget" ); + fleet.SetPlating( true ); - Require( fleet.QueueWing( ), "armored order queued" ); + Require( fleet.QueueShip( home, HullBlueprint.Corvette ), "armored order queued" ); + var armored = fleet.YardQueue( home )[0]; fleet.SetPlating( false ); - Require( fleet.QueueWing( ) && fleet.WingQueue[0].Cost == 68 && fleet.WingQueue[1].Cost == 60, "orders preserve purchase prices" ); + Require( fleet.QueueShip( home, HullBlueprint.Corvette ) && fleet.YardQueue( home )[1].Cost.Ore == 20 && + fleet.StartResearch( ResearchTopic.Industry ), "orders preserve purchase prices while research runs" ); originalOre = fleet.Ore; - Require( fleet.CancelWing( 0 ) && fleet.Ore == originalOre + 68 && fleet.NavalReserved == 3 && - fleet.WingRemaining == FleetSimulation.StandardWingDuration && fleet.WingQueue[0].Cost == 60, - "cancelling active work refunds its snapshot and starts the next job" ); - Require( fleet.CancelWing( 0 ) && fleet.NavalReserved == 0 && fleet.WingRemaining < 0 && !fleet.CancelWing( 0 ) && - !fleet.CancelSite( home, PlanetFacility.Yard ), "completed infrastructure and empty queues reject cancellation" ); + originalEnergy = fleet.Energy; + Require( fleet.CancelShip( home, 0 ) && fleet.Ore == originalOre + armored.Cost.Ore && + fleet.Energy == originalEnergy + armored.Cost.Energy && fleet.NavalReserved == 1 && + fleet.ShipRemaining( home ) == 160 && fleet.YardQueue( home )[0].Cost.Ore == 20, + "canceling active work refunds its snapshot and starts the next job" ); + Require( fleet.CancelShip( home, 0 ) && fleet.NavalReserved == 0 && fleet.YardQueue( home ).IsEmpty && + !fleet.CancelShip( home, 0 ) && !fleet.CancelSite( home, PlanetFacility.Yard ), + "completed infrastructure and empty queues reject cancellation" ); + AdvanceUntil( fleet, () => fleet.IndustryUpgrade, "industrial research completes" ); + Require( fleet.Hull( HullBlueprint.Corvette ).Cost.Ore == 14 && fleet.Hull( HullBlueprint.Corvette ).Duration == 100, + "completed industry research reduces cost and time for new orders" ); } private static void VerifyAudio( ) { diff --git a/tests/InteropQualification/InteropQualification.csproj b/tests/InteropQualification/InteropQualification.csproj index 2b55cf1..0900eb0 100644 --- a/tests/InteropQualification/InteropQualification.csproj +++ b/tests/InteropQualification/InteropQualification.csproj @@ -11,12 +11,17 @@ + + + + +