Run Re-Do
This commit is contained in:
@@ -62,6 +62,15 @@ namespace ProjectM.Server
|
||||
// spawn like CycleRuntime/ThreatState (never on the ghost serializer). RunOutcome is baked on the prefab.
|
||||
ecb.AddComponent(director, new RunPhase { Value = RunPhaseId.Normal });
|
||||
|
||||
// Expedition redesign: run-FSM working state + the co-op route first-commit latch + the persisted
|
||||
// meta counters — ALL added UNCONDITIONALLY at spawn (the CycleRuntime/ThreatState/RunPhase idiom;
|
||||
// D-F2: a New-Game boot must have the components the bank block reads; Continue restores VALUES only,
|
||||
// inside the HasData block — Step 12b). HostSalt starts a fixed non-tick seed lineage (bumped per
|
||||
// launch); SaveData v6 folds persisted RunsCompleted in at restore so cross-session runs diverge.
|
||||
ecb.AddComponent(director, new RunRuntime { HostSalt = 0x5EED0001u });
|
||||
ecb.AddComponent(director, default(RouteCommand));
|
||||
ecb.AddComponent(director, default(MetaCounters));
|
||||
|
||||
// Born-correct load: if the menu staged a save (Continue), apply it AT SPAWN so the director
|
||||
// DR-042 C6c: a NEW game seeds starting Ore below; a restored save (Continue) keeps its ledger.
|
||||
bool restoredLedger = false;
|
||||
@@ -98,6 +107,33 @@ namespace ProjectM.Server
|
||||
// save / New Game = 0 -> InProgress). Independent of the Core -> NOT nested in the CoreIntegrity guard.
|
||||
ecb.SetComponent(director, new RunOutcome { Value = pending.RunOutcome });
|
||||
|
||||
// v6: restore the permanent meta — counters (VALUES only; the component was added
|
||||
// unconditionally above, D-F2), the tier record (SetBuffer replaces the baked-empty
|
||||
// [GhostField] buffer pre-Playback — the StorageEntry idiom — rows VERBATIM incl. unknown
|
||||
// ids), the born-correct RunInfo HUD mirror (the spawn-time exception to RunDirector's
|
||||
// sole-writer rule, like CycleState/RunOutcome above), and the HostSalt fold (cross-session
|
||||
// first-run maps diverge once you've banked clears — the promise at the RunRuntime add).
|
||||
ecb.SetComponent(director, new MetaCounters
|
||||
{
|
||||
RunsCompleted = pending.RunsCompleted,
|
||||
MaxDepthReached = pending.MaxDepthReached,
|
||||
});
|
||||
var metaSrc = SystemAPI.GetBuffer<PendingMetaRow>(pendingEntity);
|
||||
var metaDst = ecb.SetBuffer<MetaTierState>(director);
|
||||
for (int mi = 0; mi < metaSrc.Length; mi++)
|
||||
metaDst.Add(new MetaTierState { ClassId = metaSrc[mi].ClassId, UpgradeId = metaSrc[mi].UpgradeId, Tier = metaSrc[mi].Tier });
|
||||
if (SystemAPI.HasComponent<RunInfo>(spawner.Prefab))
|
||||
{
|
||||
var runInfo = SystemAPI.GetComponent<RunInfo>(spawner.Prefab); // baked Lifecycle=Staging
|
||||
runInfo.RunsCompleted = pending.RunsCompleted;
|
||||
runInfo.MaxDepthReached = pending.MaxDepthReached;
|
||||
ecb.SetComponent(director, runInfo);
|
||||
}
|
||||
ecb.SetComponent(director, new RunRuntime
|
||||
{
|
||||
HostSalt = RunMapMath.Hash(0x5EED0001u, (uint)pending.RunsCompleted + 1u),
|
||||
});
|
||||
|
||||
}
|
||||
ecb.DestroyEntity(pendingEntity);
|
||||
}
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
using ProjectM.Simulation;
|
||||
using Unity.Burst;
|
||||
using Unity.Collections;
|
||||
using Unity.Entities;
|
||||
using Unity.Mathematics;
|
||||
using Unity.Transforms;
|
||||
|
||||
namespace ProjectM.Server
|
||||
{
|
||||
/// <summary>
|
||||
/// Server-only walk-in gate transit: a player who walks within a gate's radius (and whose region matches the
|
||||
/// gate's <see cref="ExpeditionGate.FromRegion"/>) is transited to the gate's ToRegion at its ArrivalPos
|
||||
/// (RegionTag flipped + LocalTransform teleported — GhostRelevancy re-scopes their ghosts, as in
|
||||
/// <c>RegionTransitSystem</c>). Returning to BASE signals the ThreatDirector (a completed expedition can draw a
|
||||
/// retaliation siege) by incrementing <see cref="ProjectM.Simulation.ThreatState.PendingReturns"/>. Plain server
|
||||
/// SimulationSystemGroup, ordered BEFORE CyclePhaseSystem (Gate -> ThreatDirector -> RunState) so the return is
|
||||
/// consumed the same tick. Arrival points are offset from the destination gate so a transited player does not
|
||||
/// immediately re-trigger.
|
||||
/// </summary>
|
||||
[BurstCompile]
|
||||
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
|
||||
[UpdateInGroup(typeof(SimulationSystemGroup))]
|
||||
[UpdateBefore(typeof(CyclePhaseSystem))]
|
||||
public partial struct ExpeditionGateSystem : ISystem
|
||||
{
|
||||
[BurstCompile]
|
||||
public void OnCreate(ref SystemState state)
|
||||
{
|
||||
state.RequireForUpdate<ExpeditionGate>();
|
||||
}
|
||||
|
||||
[BurstCompile]
|
||||
public void OnUpdate(ref SystemState state)
|
||||
{
|
||||
// Snapshot gates once.
|
||||
var gateFrom = new NativeList<byte>(Allocator.Temp);
|
||||
var gateTo = new NativeList<byte>(Allocator.Temp);
|
||||
var gateRadiusSq = new NativeList<float>(Allocator.Temp);
|
||||
var gatePos = new NativeList<float2>(Allocator.Temp);
|
||||
var gateArrival = new NativeList<float3>(Allocator.Temp);
|
||||
foreach (var (gate, xform) in SystemAPI.Query<RefRO<ExpeditionGate>, RefRO<LocalTransform>>())
|
||||
{
|
||||
gateFrom.Add(gate.ValueRO.FromRegion);
|
||||
gateTo.Add(gate.ValueRO.ToRegion);
|
||||
gateRadiusSq.Add(gate.ValueRO.Radius * gate.ValueRO.Radius);
|
||||
gatePos.Add(xform.ValueRO.Position.xz);
|
||||
gateArrival.Add(gate.ValueRO.ArrivalPos);
|
||||
}
|
||||
|
||||
bool returnedToBase = false;
|
||||
foreach (var (region, xform) in
|
||||
SystemAPI.Query<RefRW<RegionTag>, RefRW<LocalTransform>>().WithAll<PlayerTag>())
|
||||
{
|
||||
byte r = region.ValueRO.Region;
|
||||
float2 pp = xform.ValueRO.Position.xz;
|
||||
for (int i = 0; i < gateFrom.Length; i++)
|
||||
{
|
||||
if (gateFrom[i] != r) continue;
|
||||
if (math.distancesq(pp, gatePos[i]) > gateRadiusSq[i]) continue;
|
||||
region.ValueRW.Region = gateTo[i];
|
||||
xform.ValueRW.Position = gateArrival[i];
|
||||
if (gateTo[i] == RegionId.Base)
|
||||
returnedToBase = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
gateFrom.Dispose();
|
||||
gateTo.Dispose();
|
||||
gateRadiusSq.Dispose();
|
||||
gatePos.Dispose();
|
||||
gateArrival.Dispose();
|
||||
|
||||
// A player returned to base from an expedition -> signal the ThreatDirector (it sizes/arms any
|
||||
// retaliation siege). The gate teleports the returner out of its radius, so this fires once per return.
|
||||
if (returnedToBase)
|
||||
{
|
||||
if (SystemAPI.TryGetSingletonEntity<ThreatState>(out var threatEntity))
|
||||
{
|
||||
var threat = SystemAPI.GetComponent<ThreatState>(threatEntity);
|
||||
threat.PendingReturns += 1;
|
||||
threat.ExpeditionsCompleted += 1;
|
||||
SystemAPI.SetComponent(threatEntity, threat);
|
||||
}
|
||||
|
||||
// Once-per-epoch zone-clear reward: a returner BANKS flat Ore to the shared ledger AND advances the
|
||||
// long-arc win meter (DR-042 — EXPEDITION CLEARS, not survived base sieges, are the win-driver:
|
||||
// CyclePhaseSystem no longer credits Charge, so this is the sole PRODUCTION writer of GoalProgress.Charge).
|
||||
// Resolved ONCE here (not per-returner) so two same-tick co-op returns pay exactly once (DR-040 BLOCKER 4)
|
||||
// and gate re-entry before a clear can't farm (MINOR 2). Ore + Charge share the SAME LastRewardedEpoch
|
||||
// latch so they always share fate (never one without the other). The Charge credit is guarded
|
||||
// independently of the ledger so it still lands in ledger-less worlds.
|
||||
if (SystemAPI.HasSingleton<CycleState>())
|
||||
{
|
||||
var cycleEntity = SystemAPI.GetSingletonEntity<CycleState>();
|
||||
var runtime = SystemAPI.GetComponent<CycleRuntime>(cycleEntity);
|
||||
if (runtime.ClearedThisEpoch != 0 && runtime.LastRewardedEpoch != runtime.ExpeditionEpoch)
|
||||
{
|
||||
if (SystemAPI.TryGetSingleton<ZoneEnemyDirector>(out var zoneDir)
|
||||
&& SystemAPI.HasSingleton<ResourceLedger>())
|
||||
{
|
||||
var ledger = SystemAPI.GetBuffer<StorageEntry>(SystemAPI.GetSingletonEntity<ResourceLedger>());
|
||||
StorageMath.Deposit(ledger, (ushort)ResourceId.Ore, zoneDir.RewardOre);
|
||||
}
|
||||
if (SystemAPI.HasComponent<GoalProgress>(cycleEntity))
|
||||
{
|
||||
// +1 toward the goal per cleared expedition, CLAMPED to Target (single production writer).
|
||||
var goal = SystemAPI.GetComponent<GoalProgress>(cycleEntity);
|
||||
goal.Charge = math.min(goal.Charge + 1, goal.Target);
|
||||
SystemAPI.SetComponent(cycleEntity, goal);
|
||||
}
|
||||
// Checkpoint the hard-won clear (replaces the deleted survived-siege autosave in CyclePhaseSystem).
|
||||
if (SystemAPI.HasComponent<SaveRequest>(cycleEntity))
|
||||
SystemAPI.SetComponent(cycleEntity, new SaveRequest { Pending = 1 });
|
||||
runtime.LastRewardedEpoch = runtime.ExpeditionEpoch;
|
||||
SystemAPI.SetComponent(cycleEntity, runtime);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4292536f663eb5c4d92688f6c5bb0368
|
||||
@@ -0,0 +1,61 @@
|
||||
using ProjectM.Simulation;
|
||||
using Unity.Burst;
|
||||
using Unity.Collections;
|
||||
using Unity.Entities;
|
||||
using Unity.NetCode;
|
||||
|
||||
namespace ProjectM.Server
|
||||
{
|
||||
/// <summary>
|
||||
/// Server receiver for <see cref="ReadyToggleRequest"/>: resolves the sender (SourceConnection → NetworkId →
|
||||
/// GhostOwner → player entity, the AbilityUpgradeSystem idiom) and SETS <see cref="PlayerReady.Value"/>.
|
||||
/// Honored ONLY while the run FSM is in Staging or Launching — an un-ready during the Launching countdown is the
|
||||
/// launch-abort escape hatch (RunDirectorSystem reverts to Staging); toggles arriving mid-run are dropped (the
|
||||
/// Returning edge clears every flag anyway). Ordered BEFORE RunDirectorSystem so a toggle lands the same tick the
|
||||
/// ready-count is derived. Plain server group (one-off RPC effects never run in the predicted loop); the request
|
||||
/// entity is ALWAYS destroyed.
|
||||
/// </summary>
|
||||
[BurstCompile]
|
||||
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
|
||||
[UpdateInGroup(typeof(SimulationSystemGroup))]
|
||||
[UpdateBefore(typeof(RunDirectorSystem))]
|
||||
public partial struct ReadyToggleSystem : ISystem
|
||||
{
|
||||
[BurstCompile]
|
||||
public void OnCreate(ref SystemState state)
|
||||
{
|
||||
var builder = new EntityQueryBuilder(Allocator.Temp)
|
||||
.WithAll<ReadyToggleRequest, ReceiveRpcCommandRequest>();
|
||||
state.RequireForUpdate(state.GetEntityQuery(builder));
|
||||
state.RequireForUpdate<RunInfo>();
|
||||
}
|
||||
|
||||
[BurstCompile]
|
||||
public void OnUpdate(ref SystemState state)
|
||||
{
|
||||
byte lifecycle = SystemAPI.GetSingleton<RunInfo>().Lifecycle;
|
||||
bool accept = lifecycle == RunLifecycle.Staging || lifecycle == RunLifecycle.Launching;
|
||||
|
||||
var playerByConn = new NativeHashMap<int, Entity>(8, Allocator.Temp);
|
||||
foreach (var (owner, entity) in
|
||||
SystemAPI.Query<RefRO<GhostOwner>>().WithAll<PlayerTag, PlayerReady>().WithEntityAccess())
|
||||
playerByConn[owner.ValueRO.NetworkId] = entity;
|
||||
|
||||
var ecb = new EntityCommandBuffer(Allocator.Temp);
|
||||
foreach (var (receive, req, requestEntity) in
|
||||
SystemAPI.Query<RefRO<ReceiveRpcCommandRequest>, RefRO<ReadyToggleRequest>>().WithEntityAccess())
|
||||
{
|
||||
var conn = receive.ValueRO.SourceConnection;
|
||||
if (accept
|
||||
&& SystemAPI.HasComponent<NetworkId>(conn)
|
||||
&& playerByConn.TryGetValue(SystemAPI.GetComponent<NetworkId>(conn).Value, out var player))
|
||||
{
|
||||
SystemAPI.SetComponent(player, new PlayerReady { Value = (byte)(req.ValueRO.Ready != 0 ? 1 : 0) });
|
||||
}
|
||||
ecb.DestroyEntity(requestEntity);
|
||||
}
|
||||
ecb.Playback(state.EntityManager);
|
||||
playerByConn.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7392579cf8b92e64f9686b58da99f7c2
|
||||
@@ -0,0 +1,96 @@
|
||||
using ProjectM.Simulation;
|
||||
using Unity.Burst;
|
||||
using Unity.Collections;
|
||||
using Unity.Entities;
|
||||
using Unity.NetCode;
|
||||
|
||||
namespace ProjectM.Server
|
||||
{
|
||||
/// <summary>
|
||||
/// Server receiver for <see cref="RouteSelectRequest"/> — the co-op route choice (any-player-first-commits, the
|
||||
/// operator's locked authority model). Validates each pick server-authoritatively:
|
||||
/// <c>Lifecycle == RouteSelect</c> · run identity <c>(uint)ForRunEpoch == RunRuntime.RunSeed</c> (the Step-8
|
||||
/// review re-mean: the replicated seed IS the run token; the server-only RunEpoch is not client-knowable) ·
|
||||
/// <c>ForLayer == RunInfo.CurrentRoom</c> (the gate's un-incremented cleared layer) · <c>OptionIndex</c> within
|
||||
/// the replicated <c>RouteOptionCount</c> · the SENDER's <see cref="RegionTag"/> is Expedition (N3 — a
|
||||
/// base-bound joiner cannot commit the party's route) · nothing accepted yet this gate.
|
||||
///
|
||||
/// FIRST-COMMIT LATCH: the accepted pick is written to the server-only <see cref="RouteCommand"/> via an
|
||||
/// IMMEDIATE in-place <c>SystemAPI.SetComponent</c> INSIDE the drain loop plus a local accepted flag (the DR-014
|
||||
/// atomicity idiom) — two same-tick picks can never both observe an open gate; a hoisted read would re-create
|
||||
/// the exact N1 race the design review killed. <see cref="RouteCommand.ForRunEpoch"/> is stamped from the TRUE
|
||||
/// server-only epoch (never the client-echoed value). Requests are ALWAYS destroyed. This system writes ONLY
|
||||
/// RouteCommand — RunDirectorSystem stays the sole RunInfo/RunRuntime writer and consumes the latch
|
||||
/// (abort → pick → grace, in that order). Ordered before it so a pick can land the same tick it is consumed;
|
||||
/// NO CyclePhase edge (the room-chain hard rule).
|
||||
/// </summary>
|
||||
[BurstCompile]
|
||||
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
|
||||
[UpdateInGroup(typeof(SimulationSystemGroup))]
|
||||
[UpdateBefore(typeof(RunDirectorSystem))]
|
||||
public partial struct RouteSelectSystem : ISystem
|
||||
{
|
||||
[BurstCompile]
|
||||
public void OnCreate(ref SystemState state)
|
||||
{
|
||||
var builder = new EntityQueryBuilder(Allocator.Temp)
|
||||
.WithAll<RouteSelectRequest, ReceiveRpcCommandRequest>();
|
||||
state.RequireForUpdate(state.GetEntityQuery(builder));
|
||||
state.RequireForUpdate<RunInfo>();
|
||||
state.RequireForUpdate<RunRuntime>();
|
||||
state.RequireForUpdate<RouteCommand>();
|
||||
}
|
||||
|
||||
[BurstCompile]
|
||||
public void OnUpdate(ref SystemState state)
|
||||
{
|
||||
var dirEntity = SystemAPI.GetSingletonEntity<RunInfo>();
|
||||
var info = SystemAPI.GetComponent<RunInfo>(dirEntity);
|
||||
var run = SystemAPI.GetComponent<RunRuntime>(dirEntity);
|
||||
bool gateOpen = info.Lifecycle == RunLifecycle.RouteSelect;
|
||||
|
||||
// Sender-region lookup (N3): connection NetworkId -> the player's CURRENT region. A player entity
|
||||
// without RegionTag simply never enters the map -> its pick is a clean reject, never a throw.
|
||||
var regionByConn = new NativeHashMap<int, byte>(8, Allocator.Temp);
|
||||
foreach (var (owner, region) in
|
||||
SystemAPI.Query<RefRO<GhostOwner>, RefRO<RegionTag>>().WithAll<PlayerTag>())
|
||||
regionByConn[owner.ValueRO.NetworkId] = region.ValueRO.Region;
|
||||
|
||||
// Local accepted flag beside the in-place write = the first-commit latch (nothing else writes
|
||||
// RouteCommand mid-loop; RunDirector's gate-entry clear ran on a previous tick by construction).
|
||||
bool accepted = SystemAPI.GetComponent<RouteCommand>(dirEntity).HasPick != 0;
|
||||
|
||||
var ecb = new EntityCommandBuffer(Allocator.Temp);
|
||||
foreach (var (receive, req, requestEntity) in
|
||||
SystemAPI.Query<RefRO<ReceiveRpcCommandRequest>, RefRO<RouteSelectRequest>>().WithEntityAccess())
|
||||
{
|
||||
var conn = receive.ValueRO.SourceConnection;
|
||||
bool valid = gateOpen
|
||||
&& !accepted
|
||||
&& (uint)req.ValueRO.ForRunEpoch == run.RunSeed
|
||||
&& req.ValueRO.ForLayer == info.CurrentRoom
|
||||
&& req.ValueRO.OptionIndex < info.RouteOptionCount
|
||||
&& SystemAPI.HasComponent<NetworkId>(conn)
|
||||
&& regionByConn.TryGetValue(SystemAPI.GetComponent<NetworkId>(conn).Value, out byte senderRegion)
|
||||
&& senderRegion == RegionId.Expedition;
|
||||
|
||||
if (valid)
|
||||
{
|
||||
// IMMEDIATE in-place commit (never an ECB-deferred write) + the local flag: first pick wins.
|
||||
SystemAPI.SetComponent(dirEntity, new RouteCommand
|
||||
{
|
||||
HasPick = 1,
|
||||
OptionIndex = req.ValueRO.OptionIndex,
|
||||
ForRunEpoch = run.RunEpoch, // the TRUE server epoch — never echo the client value
|
||||
ForLayer = req.ValueRO.ForLayer,
|
||||
});
|
||||
accepted = true;
|
||||
}
|
||||
|
||||
ecb.DestroyEntity(requestEntity);
|
||||
}
|
||||
ecb.Playback(state.EntityManager);
|
||||
regionByConn.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f56898976ef03af499c200e0d6f43b0d
|
||||
@@ -0,0 +1,409 @@
|
||||
using ProjectM.Simulation;
|
||||
using Unity.Burst;
|
||||
using Unity.Collections;
|
||||
using Unity.Entities;
|
||||
using Unity.Mathematics;
|
||||
using Unity.NetCode;
|
||||
using Unity.Transforms;
|
||||
|
||||
namespace ProjectM.Server
|
||||
{
|
||||
/// <summary>
|
||||
/// SOLE writer of the replicated run-lifecycle FSM (<see cref="RunInfo"/>) and its server-only working state
|
||||
/// (<see cref="RunRuntime"/>) — the expedition redesign's counterpart of CyclePhaseSystem's single-writer
|
||||
/// discipline (that system stays the sole writer of the BASE Calm↔Siege posture; the two FSMs are distinct).
|
||||
///
|
||||
/// Step-7 = the REAL LINEAR traversal: Staging (ready-check) → Launching (3-2-1 telegraph, un-ready aborts) →
|
||||
/// InRoom (fight; the clear edge arrives as the replicated <see cref="ExpeditionObjective"/>.State == Cleared,
|
||||
/// consumed ONE-TICK-LATE by construction — RoomEnemyDirectorSystem writes it after this system each tick, so no
|
||||
/// system-ordering back-edge exists) → RoomReward (cleared room TORN DOWN at entry via <see cref="RoomTeardown"/>;
|
||||
/// boon picks gate the exit from Step 10, all-Pending==0 today) → advance (bump room/epoch, flip the ping-pong
|
||||
/// sub-slot, teleport — teardown-at-entry + spawn-on-advance guarantees ≥1 empty tick and exactly ONE room alive)
|
||||
/// → … → Boss clear → Returning (teleport home + the CLEAR-GATED terminal bank) → Staging. Branching route
|
||||
/// choice (RouteSelect) replaces the fixed col-0 advance at Step 8.
|
||||
///
|
||||
/// The terminal bank (once per RunEpoch, equality-latched): ALWAYS records the honest depth
|
||||
/// (max(MaxDepthReached, RoomsClearedThisRun) — never the planned RoomCount) and re-stages; ONLY a genuine
|
||||
/// boss-clear terminal (<see cref="RunRuntime.LastTerminalCleared"/>) credits the win meter
|
||||
/// (<see cref="GoalProgress"/>.Charge, clamped), RunsCompleted, the retaliation inputs
|
||||
/// (<see cref="ThreatState"/>.PendingReturns/ExpeditionsCompleted — carried from the retired gate, C7) and
|
||||
/// requests a save. An abort/wipe banks NOTHING but the depth high-water (D-F3).
|
||||
///
|
||||
/// Ordering: <c>[UpdateBefore(CyclePhaseSystem)]</c> ONLY (GoalReachedSystem is [UpdateAfter(CyclePhaseSystem)] —
|
||||
/// transitively after this system, so the Charge credit lands before it reads the edge). Per the hard rule,
|
||||
/// NOTHING in the room chain adds another CyclePhase edge (a sort cycle is invisible to EditMode and throws only
|
||||
/// at Play world creation).
|
||||
/// </summary>
|
||||
[BurstCompile]
|
||||
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
|
||||
[UpdateInGroup(typeof(SimulationSystemGroup))]
|
||||
[UpdateBefore(typeof(CyclePhaseSystem))]
|
||||
public partial struct RunDirectorSystem : ISystem
|
||||
{
|
||||
/// <summary>"All ready → 3-2-1 → go" telegraph (~3 s @ 60). An un-ready during the countdown aborts.</summary>
|
||||
const uint LaunchCountdownTicks = 180;
|
||||
|
||||
/// <summary>Boon-pick grace (~30 s @ 60): RoomReward advances when every survivor picked OR this elapses
|
||||
/// (the AFK/disconnect backstop; the un-picked-offer policy lands with the boons at Step 10).</summary>
|
||||
const uint RewardGraceTicks = 1800;
|
||||
|
||||
/// <summary>Route-choice grace (~30 s @ 60): the gate auto-picks the LOWEST-INDEX reachable option when it
|
||||
/// elapses (the AFK backstop; an accepted pick always beats a same-tick expiry — review F2).</summary>
|
||||
const uint RouteGraceTicks = 1800;
|
||||
|
||||
EntityQuery m_RoomTagged;
|
||||
|
||||
[BurstCompile]
|
||||
public void OnCreate(ref SystemState state)
|
||||
{
|
||||
state.RequireForUpdate<NetworkTime>();
|
||||
state.RequireForUpdate<RunInfo>();
|
||||
state.RequireForUpdate<RunRuntime>();
|
||||
m_RoomTagged = state.GetEntityQuery(ComponentType.ReadOnly<RoomTag>());
|
||||
}
|
||||
|
||||
[BurstCompile]
|
||||
public void OnUpdate(ref SystemState state)
|
||||
{
|
||||
var serverTick = SystemAPI.GetSingleton<NetworkTime>().ServerTick;
|
||||
if (!serverTick.IsValid)
|
||||
return;
|
||||
uint now = serverTick.TickIndexForValidTick;
|
||||
|
||||
var dirEntity = SystemAPI.GetSingletonEntity<RunInfo>();
|
||||
var info = SystemAPI.GetComponent<RunInfo>(dirEntity);
|
||||
var run = SystemAPI.GetComponent<RunRuntime>(dirEntity);
|
||||
|
||||
float3 baseCenter = new float3(0f, 1f, 0f);
|
||||
if (SystemAPI.TryGetSingleton<BaseAnchor>(out var anchor))
|
||||
baseCenter = BaseGridMath.PlotCenter(anchor);
|
||||
|
||||
// Ready-check + party-presence derivation, shared across the states below. The party is co-located at
|
||||
// base while Staging (the N7 co-location invariant), so live PlayerTag ghosts ARE the roster; a
|
||||
// disconnect drops the counts (LinkedEntityGroup despawn) and the checks re-derive clean.
|
||||
int totalPlayers = 0, readyPlayers = 0, expeditionPlayers = 0;
|
||||
foreach (var (ready, region) in
|
||||
SystemAPI.Query<RefRO<PlayerReady>, RefRO<RegionTag>>().WithAll<PlayerTag>())
|
||||
{
|
||||
totalPlayers++;
|
||||
if (ready.ValueRO.Value != 0) readyPlayers++;
|
||||
if (region.ValueRO.Region == RegionId.Expedition) expeditionPlayers++;
|
||||
}
|
||||
bool allReady = totalPlayers > 0 && readyPlayers == totalPlayers;
|
||||
|
||||
switch (info.Lifecycle)
|
||||
{
|
||||
case RunLifecycle.Staging:
|
||||
{
|
||||
// F2 cross-FSM launch guard: no new run while a final siege arms/runs or the outcome latched.
|
||||
// Guards default OPEN when the server-only markers are absent (EditMode worlds).
|
||||
bool launchAllowed =
|
||||
(!SystemAPI.HasComponent<RunPhase>(dirEntity)
|
||||
|| SystemAPI.GetComponent<RunPhase>(dirEntity).Value == RunPhaseId.Normal)
|
||||
&& (!SystemAPI.HasComponent<RunOutcome>(dirEntity)
|
||||
|| SystemAPI.GetComponent<RunOutcome>(dirEntity).Value == RunOutcomeId.InProgress);
|
||||
|
||||
if (allReady && run.WasAllReady == 0 && launchAllowed)
|
||||
{
|
||||
// Rising edge → Launching. Seed the run: monotonic epoch + per-playthrough salt lineage,
|
||||
// never a tick, never 0, equality-compared downstream.
|
||||
run.RunEpoch += 1;
|
||||
run.HostSalt = RunMapMath.Hash(run.HostSalt, (uint)run.RunEpoch);
|
||||
run.RunSeed = math.max(1u, RunMapMath.Hash((uint)run.RunEpoch, run.HostSalt));
|
||||
run.NodeBudgetRemaining = Tuning.ExpeditionNodeBudget;
|
||||
run.RoomsClearedThisRun = 0;
|
||||
run.BoonPickCounter = 0; // fresh boon-band provenance per run
|
||||
run.LastTerminalCleared = 0;
|
||||
|
||||
var map = RunMapMath.Generate(run.RunSeed);
|
||||
info.RunSeed = run.RunSeed;
|
||||
info.RoomCount = map.LayerCount;
|
||||
info.LaunchTick = TickUtil.NonZero(now + LaunchCountdownTicks);
|
||||
info.Lifecycle = RunLifecycle.Launching;
|
||||
}
|
||||
run.WasAllReady = (byte)(allReady ? 1 : 0);
|
||||
break;
|
||||
}
|
||||
|
||||
case RunLifecycle.Launching:
|
||||
{
|
||||
// Un-ready during the countdown aborts back to Staging (the telegraph's escape hatch).
|
||||
if (!allReady)
|
||||
{
|
||||
info.LaunchTick = 0u;
|
||||
info.Lifecycle = RunLifecycle.Staging;
|
||||
run.WasAllReady = 0;
|
||||
break;
|
||||
}
|
||||
|
||||
bool due = info.LaunchTick == 0u || !new NetworkTick(info.LaunchTick).IsNewerThan(serverTick);
|
||||
if (due)
|
||||
{
|
||||
// Enter room 0 (the guaranteed Combat landing at column 0, sub-slot 0).
|
||||
var map = RunMapMath.Generate(run.RunSeed);
|
||||
EnterRoom(ref state, ref info, ref run, in map, layer: 0, col: 0, baseCenter, bumpEpoch: true);
|
||||
info.LaunchTick = 0u;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case RunLifecycle.InRoom:
|
||||
{
|
||||
// All expedition players gone (disconnect/death-warp edge) → clean abort, no credit.
|
||||
if (expeditionPlayers == 0)
|
||||
{
|
||||
run.LastTerminalCleared = 0;
|
||||
info.Lifecycle = RunLifecycle.Returning;
|
||||
break;
|
||||
}
|
||||
|
||||
// The room clear edge — the replicated objective RoomEnemyDirectorSystem computed LAST tick
|
||||
// (one-tick-late by construction; no ordering back-edge). Teardown happens AT THIS ENTRY, the
|
||||
// next room spawns on the advance tick → ≥1 empty tick, exactly one room alive.
|
||||
if (SystemAPI.HasComponent<ExpeditionObjective>(dirEntity)
|
||||
&& SystemAPI.GetComponent<ExpeditionObjective>(dirEntity).State == ExpeditionObjectiveState.Cleared)
|
||||
{
|
||||
var ecb = new EntityCommandBuffer(Allocator.Temp);
|
||||
RoomTeardown.DestroyRoom(m_RoomTagged, ecb, (byte)(info.CurrentRoom & 0xFF));
|
||||
ecb.Playback(state.EntityManager);
|
||||
ecb.Dispose();
|
||||
|
||||
run.RoomsClearedThisRun += 1;
|
||||
if (info.CurrentRoom >= info.RoomCount - 1)
|
||||
run.LastTerminalCleared = 1; // the Boss fell — a genuine terminal clear
|
||||
run.RewardGraceTick = TickUtil.NonZero(now + RewardGraceTicks);
|
||||
info.Lifecycle = RunLifecycle.RoomReward;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case RunLifecycle.RoomReward:
|
||||
{
|
||||
if (expeditionPlayers == 0 && run.LastTerminalCleared == 0)
|
||||
{
|
||||
info.Lifecycle = RunLifecycle.Returning;
|
||||
break;
|
||||
}
|
||||
|
||||
// Exit gate: every SURVIVING player has picked (BoonOffer.Pending==0 — inert until Step 10)
|
||||
// OR the grace elapsed (wrap-safe IsNewerThan, never raw uint — F4).
|
||||
bool anyPending = false;
|
||||
foreach (var offer in SystemAPI.Query<RefRO<BoonOffer>>().WithAll<PlayerTag>())
|
||||
if (offer.ValueRO.Pending != 0) { anyPending = true; break; }
|
||||
bool graceElapsed = run.RewardGraceTick == 0u
|
||||
|| !new NetworkTick(run.RewardGraceTick).IsNewerThan(serverTick);
|
||||
if (anyPending && !graceElapsed)
|
||||
break;
|
||||
|
||||
run.RewardGraceTick = 0u;
|
||||
if (run.LastTerminalCleared != 0)
|
||||
{
|
||||
info.Lifecycle = RunLifecycle.Returning; // boss cleared — go home a winner
|
||||
}
|
||||
else
|
||||
{
|
||||
// Open the ROUTE GATE (Step 8 — the branching choice): publish the AUTHORITATIVE reachable
|
||||
// options (the client map panel is regen-for-display; the clickable buttons bind to these
|
||||
// bytes). The cleared room is already gone — RouteSelect IS the teardown gap; the next room
|
||||
// materializes only when the choice commits.
|
||||
var map = RunMapMath.Generate(run.RunSeed);
|
||||
int optionCount = RunMapMath.ReachableOptions(in map, info.CurrentRoom, info.CurrentCol,
|
||||
out var cols);
|
||||
if (optionCount == 0)
|
||||
{
|
||||
// Unreachable by construction (every non-terminal node has an out-edge) — a future
|
||||
// generator regression must abort CLEANLY, never wedge on stale options (review F4).
|
||||
info.RouteOptionCount = 0;
|
||||
info.Lifecycle = RunLifecycle.Returning;
|
||||
}
|
||||
else
|
||||
{
|
||||
int nextLayer = info.CurrentRoom + 1;
|
||||
info.RouteOptionCount = (byte)math.min(optionCount, 3);
|
||||
info.RouteOpt0Col = cols.Length > 0 ? cols[0] : (byte)0;
|
||||
info.RouteOpt1Col = cols.Length > 1 ? cols[1] : (byte)0;
|
||||
info.RouteOpt2Col = cols.Length > 2 ? cols[2] : (byte)0;
|
||||
info.RouteOpt0Type = cols.Length > 0 ? map.Node(nextLayer, cols[0]).RoomType : (byte)0;
|
||||
info.RouteOpt1Type = cols.Length > 1 ? map.Node(nextLayer, cols[1]).RoomType : (byte)0;
|
||||
info.RouteOpt2Type = cols.Length > 2 ? map.Node(nextLayer, cols[2]).RoomType : (byte)0;
|
||||
run.RouteGraceTick = TickUtil.NonZero(now + RouteGraceTicks);
|
||||
// Entry-clear: any accepted pick provably belongs to THIS gate (RouteSelectSystem runs
|
||||
// BEFORE this system, so it cannot accept on the entry tick).
|
||||
if (SystemAPI.HasComponent<RouteCommand>(dirEntity))
|
||||
SystemAPI.SetComponent(dirEntity, default(RouteCommand));
|
||||
info.Lifecycle = RunLifecycle.RouteSelect;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case RunLifecycle.RouteSelect:
|
||||
{
|
||||
// Predicate order is LOAD-BEARING (review F2): abort → pick-consume → grace. A same-tick pick
|
||||
// from a vanishing party must never resurrect the run (EnterRoom would conscript base players);
|
||||
// an accepted pick must beat a same-tick grace expiry (the player was told "committed").
|
||||
if (expeditionPlayers == 0)
|
||||
{
|
||||
info.RouteOptionCount = 0; // close the gate ON the abort edge itself (review F3)
|
||||
run.LastTerminalCleared = 0;
|
||||
info.Lifecycle = RunLifecycle.Returning;
|
||||
break;
|
||||
}
|
||||
|
||||
var cmd = SystemAPI.HasComponent<RouteCommand>(dirEntity)
|
||||
? SystemAPI.GetComponent<RouteCommand>(dirEntity)
|
||||
: default;
|
||||
bool routeGraceElapsed = run.RouteGraceTick == 0u
|
||||
|| !new NetworkTick(run.RouteGraceTick).IsNewerThan(serverTick);
|
||||
|
||||
if (cmd.HasPick != 0)
|
||||
{
|
||||
// The party's committed choice (first-accepted-wins latch; any-player-first-commits).
|
||||
byte chosenCol = cmd.OptionIndex == 2 ? info.RouteOpt2Col
|
||||
: cmd.OptionIndex == 1 ? info.RouteOpt1Col : info.RouteOpt0Col;
|
||||
if (SystemAPI.HasComponent<RouteCommand>(dirEntity))
|
||||
SystemAPI.SetComponent(dirEntity, default(RouteCommand));
|
||||
run.RouteGraceTick = 0u;
|
||||
var map = RunMapMath.Generate(run.RunSeed);
|
||||
EnterRoom(ref state, ref info, ref run, in map, info.CurrentRoom + 1, chosenCol, baseCenter, bumpEpoch: true);
|
||||
}
|
||||
else if (routeGraceElapsed)
|
||||
{
|
||||
// AFK backstop: deterministic LOWEST-INDEX reachable option (RouteOpt0 is ascending-first).
|
||||
run.RouteGraceTick = 0u;
|
||||
var map = RunMapMath.Generate(run.RunSeed);
|
||||
EnterRoom(ref state, ref info, ref run, in map, info.CurrentRoom + 1, info.RouteOpt0Col, baseCenter, bumpEpoch: true);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case RunLifecycle.Returning:
|
||||
{
|
||||
// Party teleport HOME + region flip back to Base.
|
||||
int idx = 0;
|
||||
foreach (var (region, xform) in
|
||||
SystemAPI.Query<RefRW<RegionTag>, RefRW<LocalTransform>>().WithAll<PlayerTag>())
|
||||
{
|
||||
region.ValueRW.Region = RegionId.Base;
|
||||
var p = baseCenter;
|
||||
p.x += 1.5f * idx;
|
||||
p.y = xform.ValueRO.Position.y;
|
||||
xform.ValueRW.Position = p;
|
||||
idx++;
|
||||
}
|
||||
|
||||
// THE terminal bank — once per RunEpoch (equality latch, F7), CLEAR-GATED (D-F3).
|
||||
if (run.LastBankedRunEpoch != run.RunEpoch)
|
||||
{
|
||||
run.LastBankedRunEpoch = run.RunEpoch;
|
||||
|
||||
// Always: the honest depth high-water (actual rooms cleared, never the planned count).
|
||||
if (SystemAPI.HasComponent<MetaCounters>(dirEntity))
|
||||
{
|
||||
var meta = SystemAPI.GetComponent<MetaCounters>(dirEntity);
|
||||
meta.MaxDepthReached = math.max(meta.MaxDepthReached, run.RoomsClearedThisRun);
|
||||
if (run.LastTerminalCleared != 0)
|
||||
meta.RunsCompleted += 1;
|
||||
SystemAPI.SetComponent(dirEntity, meta);
|
||||
info.RunsCompleted = meta.RunsCompleted; // HUD mirror
|
||||
info.MaxDepthReached = meta.MaxDepthReached; // HUD mirror
|
||||
}
|
||||
|
||||
// Boss-clear only: the win meter, the retaliation inputs (C7), and a save checkpoint.
|
||||
if (run.LastTerminalCleared != 0)
|
||||
{
|
||||
if (SystemAPI.HasComponent<GoalProgress>(dirEntity))
|
||||
{
|
||||
var goal = SystemAPI.GetComponent<GoalProgress>(dirEntity);
|
||||
goal.Charge = math.min(goal.Charge + 1, goal.Target);
|
||||
SystemAPI.SetComponent(dirEntity, goal);
|
||||
}
|
||||
if (SystemAPI.HasComponent<ThreatState>(dirEntity))
|
||||
{
|
||||
var threat = SystemAPI.GetComponent<ThreatState>(dirEntity);
|
||||
threat.PendingReturns += 1;
|
||||
threat.ExpeditionsCompleted += 1;
|
||||
SystemAPI.SetComponent(dirEntity, threat);
|
||||
}
|
||||
if (SystemAPI.HasComponent<SaveRequest>(dirEntity))
|
||||
SystemAPI.SetComponent(dirEntity, new SaveRequest { Pending = 1 });
|
||||
}
|
||||
}
|
||||
|
||||
// TWO-CHANNEL strip (DR-037): run boons EXPIRE at home — one range-strip clears every
|
||||
// boon-band StatModifier (replicates via the [GhostField] buffer; StatRecompute reverts the
|
||||
// effective stats on both worlds) and zeroes any straggler offer. Class/meta/equip bands are
|
||||
// disjoint and survive. Idempotent — safe on every Returning tick.
|
||||
foreach (var (mods, offer) in
|
||||
SystemAPI.Query<DynamicBuffer<StatModifier>, RefRW<BoonOffer>>().WithAll<PlayerTag>())
|
||||
{
|
||||
TimedModifierUtil.RemoveBySourceIdRange(mods, Tuning.BoonSourceIdBase,
|
||||
Tuning.BoonSourceIdBase + Tuning.BoonSourceIdSpan);
|
||||
offer.ValueRW = default;
|
||||
}
|
||||
|
||||
// Clear EVERY ready flag — the next run needs a fresh, deliberate ready-check from everyone.
|
||||
foreach (var ready in SystemAPI.Query<RefRW<PlayerReady>>().WithAll<PlayerTag>())
|
||||
ready.ValueRW.Value = 0;
|
||||
|
||||
run.RewardGraceTick = 0u;
|
||||
run.RouteGraceTick = 0u; // gate hygiene (review F5): no stale grace into the next run
|
||||
if (SystemAPI.HasComponent<RouteCommand>(dirEntity))
|
||||
SystemAPI.SetComponent(dirEntity, default(RouteCommand)); // no leftover latch either
|
||||
run.WasAllReady = 0;
|
||||
run.LastTerminalCleared = 0;
|
||||
|
||||
info.CurrentRoom = 0;
|
||||
info.RouteOptionCount = 0;
|
||||
info.LaunchTick = 0u;
|
||||
info.Lifecycle = RunLifecycle.Staging;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Single write-back point — RunInfo/RunRuntime are ALWAYS published (F12: the HUD readout can never
|
||||
// freeze stale behind a branch's early-break).
|
||||
SystemAPI.SetComponent(dirEntity, info);
|
||||
SystemAPI.SetComponent(dirEntity, run);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enter room (<paramref name="layer"/>, <paramref name="col"/>): publish the node as the single plan
|
||||
/// authority (<see cref="RunRuntime.CurrentNodeId"/>/<c>CurrentRoomType</c> — the field/enemy directors NEVER
|
||||
/// re-derive it), flip the ping-pong sub-slot, bump <see cref="RunRuntime.RoomEpoch"/> so the room systems
|
||||
/// reseed, and teleport the party onto the new origin (Position write in place — never FromPosition).
|
||||
/// </summary>
|
||||
void EnterRoom(ref SystemState state, ref RunInfo info, ref RunRuntime run, in RunMap map,
|
||||
int layer, int col, float3 baseCenter, bool bumpEpoch)
|
||||
{
|
||||
var node = map.Node(layer, col);
|
||||
run.ActiveSubSlot = (byte)(layer & 1);
|
||||
run.CurrentNodeId = RunMap.NodeId(layer, col);
|
||||
run.CurrentCol = (byte)col;
|
||||
run.CurrentRoomType = node.RoomType;
|
||||
if (bumpEpoch)
|
||||
run.RoomEpoch += 1;
|
||||
|
||||
info.CurrentRoom = layer;
|
||||
info.CurrentCol = (byte)col;
|
||||
info.CurrentRoomType = node.RoomType;
|
||||
info.CurrentBiome = node.Biome;
|
||||
info.RouteOptionCount = 0;
|
||||
|
||||
float3 roomOrigin = RegionMath.ExpeditionRoomOrigin(baseCenter, run.ActiveSubSlot);
|
||||
int idx = 0;
|
||||
foreach (var (region, xform) in
|
||||
SystemAPI.Query<RefRW<RegionTag>, RefRW<LocalTransform>>().WithAll<PlayerTag>())
|
||||
{
|
||||
region.ValueRW.Region = RegionId.Expedition;
|
||||
var p = roomOrigin;
|
||||
p.x += 1.5f * idx; // small spread so kinematic capsules don't stack
|
||||
p.y = xform.ValueRO.Position.y;
|
||||
xform.ValueRW.Position = p;
|
||||
idx++;
|
||||
}
|
||||
|
||||
info.Lifecycle = RunLifecycle.InRoom;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b7c36de338378264e9aa0ad2c2512e7f
|
||||
@@ -11,8 +11,9 @@ namespace ProjectM.Server
|
||||
/// Server-only composite ThreatDirector — the data-driven base-attack SCHEDULER. It owns the decision of WHEN
|
||||
/// and HOW BIG a siege is; <see cref="CyclePhaseSystem"/> owns the Calm↔Siege transition. The single documented
|
||||
/// hand-off is <see cref="ThreatState.PendingSiegeSize"/> (this system sets it; CyclePhaseSystem consumes it).
|
||||
/// This slice wires ONE source — POST-EXPEDITION retaliation: a player returning to base (counted as
|
||||
/// <see cref="ThreatState.PendingReturns"/> by <see cref="ExpeditionGateSystem"/>) arms a siege of
|
||||
/// This slice wires ONE source — POST-EXPEDITION retaliation: a completed RUN (banked on the boss-clear
|
||||
/// return by <see cref="RunDirectorSystem"/> into <see cref="ThreatState.PendingReturns"/> — the retired
|
||||
/// walk-in ExpeditionGateSystem's carry, Step 11) arms a siege ofe of
|
||||
/// <see cref="ThreatConfig.SizeBase"/> Husks after a <see cref="ThreatConfig.PostExpeditionDelayTicks"/>
|
||||
/// telegraph. The Heat/Schedule sources are reserved (config baked-but-inert) so they drop in additively with
|
||||
/// no re-bake. It also enforces a BOUNDED siege lifetime (<see cref="ThreatConfig.SiegeTimeoutTicks"/>): an
|
||||
@@ -24,7 +25,7 @@ namespace ProjectM.Server
|
||||
[BurstCompile]
|
||||
[WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
|
||||
[UpdateInGroup(typeof(SimulationSystemGroup))]
|
||||
[UpdateAfter(typeof(ExpeditionGateSystem))]
|
||||
[UpdateAfter(typeof(RunDirectorSystem))]
|
||||
[UpdateBefore(typeof(CyclePhaseSystem))]
|
||||
public partial struct ThreatDirectorSystem : ISystem
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user