Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(verse): add the bot brain, tactics, EQS and match learning (#1135)
Ruben Lütked2f9be691fb1
diff --git a/unreal/Verse/Source/VerseBot/Private/Audit/VerseBotFireAudit.cpp b/unreal/Verse/Source/VerseBot/Private/Audit/VerseBotFireAudit.cppnew file mode 100644index 0000000000..6092f0b350--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Audit/VerseBotFireAudit.cpp@@ -0,0 +1,191 @@+#include "Audit/VerseBotFireAudit.h"++#include "Bot/VerseBotTier.h"++namespace VerseBot+{+ const TCHAR* FireModeName(EVerseBotFireMode Mode)+ {+ switch (Mode)+ {+ case EVerseBotFireMode::Unclassified: return TEXT("unclassified");+ case EVerseBotFireMode::Visible: return TEXT("visible");+ case EVerseBotFireMode::Suppression: return TEXT("suppression");+ case EVerseBotFireMode::Prefire: return TEXT("prefire");+ case EVerseBotFireMode::WallShot: return TEXT("wall_shot");+ }+ return TEXT("unclassified");+ }+}++FString FVerseBotFireAudit::ToLogLine() const+{+ FString Ids;+ for (int32 i = 0; i < PerceptIds.Num(); ++i)+ {+ if (i > 0)+ {+ Ids += TEXT(",");+ }+ Ids += FString::Printf(TEXT("%u"), PerceptIds[i]);+ }+ return FString::Printf(TEXT("VerseBotFire t=%u mode=%s visible=%d percepts=%s mass=%.3f age=%.2f"), ServerTimeMs,+ VerseBot::FireModeName(Mode), bTargetVisible ? 1 : 0, *Ids, BeliefMassAtAim, SupportAgeS);+}++float FVerseBotFireClassifier::MinBelief(const UVerseBotTier& Tier)+{+ return FMath::Max(Tier.WallbangMinBelief, float(UVerseBotTier::WallbangMinBeliefFloor));+}++float FVerseBotFireClassifier::MaxSourceAgeS(const UVerseBotTier& Tier)+{+ return FMath::Min(Tier.WallbangMaxSourceAgeS, float(UVerseBotTier::WallbangMaxSourceAgeCapS));+}++bool FVerseBotFireClassifier::HasWallShotAuthority(const FVerseBotFireEvidence& E, const UVerseBotTier& Tier)+{+ const float MaxAge = MaxSourceAgeS(Tier);+ // Aim point: inside TopCluster, or within 2 sd of a heard percept younger than the age cap.+ const bool bNearHeard = E.HeardAgeS <= MaxAge && E.HeardSdCm > 0.f+ && FVector::Dist(E.AimPoint, E.HeardLocation) <= 2.f * E.HeardSdCm;+ if (!E.bAimInTopCluster && !bNearHeard)+ {+ return false;+ }+ // Belief: supported mass only; prior-only (and learned) mass never authorises.+ if (E.bPriorOnly || E.SupportedMassAtAim < MinBelief(Tier))+ {+ return false;+ }+ if (E.SupportAgeS > MaxAge)+ {+ return false;+ }+ // Path: enough damage left through at most 3 believed pieces.+ return E.TracePieces <= MaxPieces && E.TraceDamageFrac >= Tier.WallbangMinDamageFrac;+}++EVerseBotFireMode FVerseBotFireClassifier::Classify(const FVerseBotFireEvidence& E, const UVerseBotTier& Tier)+{+ if (E.bTargetSpawnProtected)+ {+ return EVerseBotFireMode::Unclassified;+ }+ if (E.bTargetVisible)+ {+ return EVerseBotFireMode::Visible;+ }+ if (E.SinceSightLostS <= SuppressionS && FVector::Dist(E.AimPoint, E.LastSeenLocation) <= SuppressionRadiusCm)+ {+ return EVerseBotFireMode::Suppression;+ }+ if (E.bPrefireRolled && E.bAimAtPeekEdge && E.HeardAgeS <= PrefireHeardMaxAgeS+ && FVector::Dist(E.HeardLocation, E.AimPoint) <= PrefireEdgeRadiusCm+ && E.SupportedMassAtAim >= MinBelief(Tier))+ {+ return EVerseBotFireMode::Prefire;+ }+ if (HasWallShotAuthority(E, Tier))+ {+ return EVerseBotFireMode::WallShot;+ }+ return EVerseBotFireMode::Unclassified;+}++FVerseBotFireAudit FVerseBotFireClassifier::MakeAudit(const FVerseBotFireEvidence& E, EVerseBotFireMode Mode)+{+ FVerseBotFireAudit A;+ MakeAuditInto(E, Mode, A);+ return A;+}++void FVerseBotFireClassifier::MakeAuditInto(const FVerseBotFireEvidence& E, EVerseBotFireMode Mode, FVerseBotFireAudit& A)+{+ A.PerceptIds.Reset();+ A.ServerTimeMs = E.ServerTimeMs;+ A.Mode = Mode;+ A.bTargetVisible = E.bTargetVisible;+ if (E.SightPerceptId != 0 && (Mode == EVerseBotFireMode::Visible || Mode == EVerseBotFireMode::Suppression))+ {+ A.PerceptIds.Add(E.SightPerceptId);+ }+ if (Mode == EVerseBotFireMode::Prefire || Mode == EVerseBotFireMode::WallShot)+ {+ // The percepts behind the belief at the aim point: the newest heard and the last sighting.+ if (E.HeardPerceptId != 0)+ {+ A.PerceptIds.Add(E.HeardPerceptId);+ }+ if (E.SightPerceptId != 0)+ {+ A.PerceptIds.Add(E.SightPerceptId);+ }+ }+ A.BeliefMassAtAim = E.MassAtAim;+ A.SupportAgeS = E.SupportAgeS;+}++FVerseBotFireAuditLog::FVerseBotFireAuditLog()+{+ Entries.Reserve(RingCapacity);+}++void FVerseBotFireAuditLog::Reset()+{+ // Keep the allocations: a new match fills the same slots.+ Entries.Reset();+ Head = 0;+ Total = 0;+ Blocked = 0;+ FMemory::Memzero(ByMode);+}++FVerseBotFireAudit& FVerseBotFireAuditLog::NextSlot()+{+ if (bCaptureAll || Entries.Num() < RingCapacity)+ {+ return Entries.AddDefaulted_GetRef();+ }+ FVerseBotFireAudit& Slot = Entries[Head];+ Head = (Head + 1) % RingCapacity;+ return Slot;+}++void FVerseBotFireAuditLog::Add(const FVerseBotFireAudit& Audit)+{+ NextSlot() = Audit;+ ++Total;+ ++ByMode[int32(Audit.Mode)];+}++void FVerseBotFireAuditLog::Add(const FVerseBotFireEvidence& E, EVerseBotFireMode Mode)+{+ FVerseBotFireClassifier::MakeAuditInto(E, Mode, NextSlot());+ ++Total;+ ++ByMode[int32(Mode)];+}++TArray<FVerseBotFireAudit> FVerseBotFireAuditLog::GetEntries() const+{+ TArray<FVerseBotFireAudit> Out;+ Out.Reserve(Entries.Num());+ // In ring mode Head is the oldest slot once the ring is full.+ const int32 Start = (!bCaptureAll && Entries.Num() == RingCapacity) ? Head : 0;+ for (int32 i = 0; i < Entries.Num(); ++i)+ {+ Out.Add(Entries[(Start + i) % Entries.Num()]);+ }+ return Out;+}++FString FVerseBotFireAuditLog::ToText() const+{+ FString Out;+ for (const FVerseBotFireAudit& A : GetEntries())+ {+ Out += A.ToLogLine();+ Out += TEXT("\n");+ }+ return Out;+}diff --git a/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotAimDriver.cpp b/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotAimDriver.cppnew file mode 100644index 0000000000..4c953ae16d--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotAimDriver.cpp@@ -0,0 +1,43 @@+#include "Brain/VerseBotAimDriver.h"++#include "Bot/VerseBotTier.h"++void FVerseBotFollowAim::Reset(uint64 Seed, const UVerseBotTier& Tier)+{+ ReactionS = Tier.ReactionMs.X / 1000.f;+ TurnRateDegS = Tier.TurnRateDegS;+ FireTolerance = Tier.FireTolerance;+ SinceAcquireS = 0.f;+}++FVerseBotAimResult FVerseBotFollowAim::Step(const FVerseSelfPercept& Self, const FVerseBotAimRequest& Request, float DtS)+{+ FVerseBotAimResult R;+ if (!Request.bHasTarget)+ {+ SinceAcquireS = 0.f;+ return R;+ }+ if (Request.bNewTarget)+ {+ // A reaction the brain already waited is not waited again.+ SinceAcquireS = Request.ReactionRemainingS >= 0.f ? FMath::Max(ReactionS - Request.ReactionRemainingS, 0.f) : 0.f;+ }+ SinceAcquireS += DtS;++ const FVector ToTarget = Request.TargetPoint - Self.EyeLocation;+ const FRotator Want = ToTarget.Rotation();+ const FRotator Delta = (Want - Self.ViewRotation).GetNormalized();+ const float MaxStep = TurnRateDegS * DtS;+ const bool bReacting = SinceAcquireS < ReactionS;+ const float Pitch = bReacting ? 0.f : FMath::Clamp(float(Delta.Pitch), -MaxStep, MaxStep);+ const float Yaw = bReacting ? 0.f : FMath::Clamp(float(Delta.Yaw), -MaxStep, MaxStep);+ R.LookDeltaDeg = FVector2f(Pitch, Yaw);++ const FRotator After(Self.ViewRotation.Pitch + Pitch, Self.ViewRotation.Yaw + Yaw, 0.f);+ const FVector Axis = After.Vector();+ const FVector Dir = ToTarget.GetSafeNormal();+ R.ErrorDeg = FMath::RadiansToDegrees(FMath::Acos(FMath::Clamp(float(FVector::DotProduct(Axis, Dir)), -1.f, 1.f)));+ R.bOnTarget = !bReacting && R.ErrorDeg <= FireTolerance * FMath::Max(Request.TargetHalfWidthDeg, 0.1f);+ return R;+}diff --git a/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotBelief.cpp b/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotBelief.cppnew file mode 100644index 0000000000..c370c504be--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotBelief.cpp@@ -0,0 +1,463 @@+#include "Brain/VerseBotBelief.h"++#include "Learning/VerseBotMatchMemory.h"+#include "VerseGameplayTags.h"++namespace+{+ /** Typical opponent speed for predict (4.2), cm/s. */+ constexpr float TypicalSpeedCmS = 450.f;+ /** TopCluster disc radius (4.3), cm. */+ constexpr float TopRadiusCm = 300.f;+ /** Sighting replaces the belief with sd 0.5 m (4.2). */+ constexpr float SightSdCm = 50.f;+ /** Heard likelihood floor (4.2). */+ constexpr float HeardEps = 0.02f;+ /** Spawn prior sd 1.5 m and weights 0.5 / 0.3 / 0.2 (4.2 kill feed). */+ constexpr float SpawnSdCm = 150.f;+ constexpr float SpawnWeights[3] = {0.5f, 0.3f, 0.2f};+ /** The wedge of a hurt or bolt percept, placed along the line at a typical range. */+ constexpr float WedgeRangeCm = 1500.f;+ constexpr float WedgeSdCm = 600.f;+ /** Clear (4.2): Pd 0.95 within 30 m; the coarse belief has no sight test, so it clears softly. */+ constexpr float ClearHalfAngleDeg = 55.f;+ constexpr float ClearRangeCm = 1500.f;+ constexpr float ClearPerStep = 0.12f;+ constexpr float MinWeight = 0.002f;+ constexpr float BeliefLevelCm = 400.f;+ /** Learned priors (7.2): zone-transition weight 0.5 and a 1 % heatmap mix. */+ constexpr float ZoneTransitionGain = 0.5f;+ constexpr float HeatPriorMix = 0.01f;+ constexpr float HeatPriorSdCm = 150.f;++ EVerseArenaLevel LevelOf(const FVector& L)+ {+ const int32 Level = FMath::Clamp(FMath::FloorToInt32(L.Z / BeliefLevelCm), 0, 2);+ return EVerseArenaLevel(Level);+ }+}++void FVerseBotCoarseBelief::Reset()+{+ Hyps.Reset();+ Pieces.Reset();+ Cached = FVerseBotBeliefSummary();+ bDead = false;+ bReload = false;+ NowS = 0.f;+ LastSeenS = -1.0e6f;+ LastSeen = FVector::ZeroVector;+ FacingYaw = 0.f;+ FacingTimeS = -1.0e6f;+ OpponentHealth = 1.f;+ ShotsSinceReload = 0;+}++void FVerseBotCoarseBelief::NoteOwnPieceChange(uint16 PieceIndex, EVersePieceState NewState)+{+ Pieces.Add(PieceIndex, NewState);+}++EVersePieceState FVerseBotCoarseBelief::GetPieceBelief(uint16 PieceIndex) const+{+ const EVersePieceState* S = Pieces.Find(PieceIndex);+ return S ? *S : EVersePieceState::Intact;+}++float FVerseBotCoarseBelief::DiscMass(const FHypothesis& H, const FVector& Location, float RadiusCm)+{+ const float Sd2 = FMath::Max(H.SdCm * H.SdCm, 1.f);+ const float R2 = RadiusCm * RadiusCm;+ const float D2 = float(FVector::DistSquared2D(H.Center, Location));+ const float Inside = 1.f - FMath::Exp(-R2 / (2.f * Sd2));+ const float Off = FMath::Exp(-D2 / (2.f * (Sd2 + 0.5f * R2)));+ return H.Weight * Inside * Off;+}++void FVerseBotCoarseBelief::AddHypothesis(const FHypothesis& H)+{+ if (Hyps.Num() >= MaxHypotheses)+ {+ int32 Low = 0;+ for (int32 i = 1; i < Hyps.Num(); ++i)+ {+ if (Hyps[i].Weight < Hyps[Low].Weight)+ {+ Low = i;+ }+ }+ Hyps.RemoveAt(Low);+ }+ Hyps.Add(H);+}++void FVerseBotCoarseBelief::Normalise()+{+ float Sum = 0.f;+ for (const FHypothesis& H : Hyps)+ {+ Sum += H.Weight;+ }+ if (Sum <= 0.f)+ {+ Hyps.Reset();+ return;+ }+ // Mass below 1 is "somewhere else" (the unexplored rest of the arena); only an excess is scaled.+ if (Sum > 1.f)+ {+ for (FHypothesis& H : Hyps)+ {+ H.Weight /= Sum;+ }+ }+ Hyps.RemoveAll([](const FHypothesis& H) { return H.Weight < MinWeight; });+}++void FVerseBotCoarseBelief::Step(const FVersePerceptFrame& Frame, float DtS, const FVerseBotMatchMemory* Memory, TConstArrayView<FVector> Spawns)+{+ NowS = float(Frame.ServerTimeMs) / 1000.f;+ const FVerseSelfPercept& Self = Frame.Self;++ // Kill feed and hit markers (3.3, 4.2).+ for (const FVerseHudEvent& E : Frame.Hud)+ {+ switch (E.Kind)+ {+ case EVerseHudEventKind::Kill:+ if (E.VictimId != SelfId)+ {+ bDead = true;+ Hyps.Reset();+ }+ break;+ case EVerseHudEventKind::KillMarker:+ bDead = true;+ Hyps.Reset();+ break;+ case EVerseHudEventKind::OpponentRespawned:+ {+ bDead = false;+ Hyps.Reset();+ OpponentHealth = 1.f;+ ShotsSinceReload = 0;+ bReload = false;+ // Public rule: the spawn farthest from the bot; top 3 weighted 0.5 / 0.3 / 0.2.+ TArray<FVector> Ranked(Spawns.GetData(), Spawns.Num());+ Ranked.Sort([&Self](const FVector& A, const FVector& B)+ { return FVector::DistSquared(A, Self.Location) > FVector::DistSquared(B, Self.Location); });+ for (int32 i = 0; i < FMath::Min(3, Ranked.Num()); ++i)+ {+ FHypothesis H;+ H.Center = Ranked[i];+ H.SdCm = SpawnSdCm;+ H.Weight = SpawnWeights[i];+ H.Level = LevelOf(Ranked[i]);+ H.Support = ESupport::Inferred;+ H.SupportTimeS = NowS;+ Hyps.Add(H);+ }+ break;+ }+ case EVerseHudEventKind::HitMarker:+ OpponentHealth = FMath::Max(0.f, OpponentHealth - 0.25f);+ break;+ case EVerseHudEventKind::HeadshotMarker:+ OpponentHealth = FMath::Max(0.f, OpponentHealth - 0.5f);+ break;+ }+ }++ // Predict: diffuse at the typical speed, drift with the believed velocity.+ for (FHypothesis& H : Hyps)+ {+ H.Center += H.Velocity * DtS;+ H.Velocity *= FMath::Exp(-DtS);+ H.SdCm = FMath::Sqrt(H.SdCm * H.SdCm + FMath::Square(TypicalSpeedCmS * DtS) * 4.f);+ // Learned zone-transition prior (7.2): the mass leans toward the zone the person most+ // often moves on to from here, by 0.5 x the transition probability of the typical speed.+ FVector NextZone;+ float Prob = 0.f;+ if (Memory && Memory->PredictNextZone(H.Center, NextZone, Prob))+ {+ H.Center += (NextZone - H.Center).GetSafeNormal2D() * (ZoneTransitionGain * Prob * TypicalSpeedCmS * DtS);+ }+ }++ const FVerseSightPercept* Sight = nullptr;+ for (const FVerseSightPercept& S : Frame.Sightings)+ {+ if (S.VisibleMask != 0)+ {+ Sight = &S;+ break;+ }+ }++ if (Sight && !bDead)+ {+ // Sighting replaces the grid (4.2).+ Hyps.Reset();+ FHypothesis H;+ H.Center = Sight->PelvisLocation;+ H.SdCm = SightSdCm;+ H.Weight = 1.f;+ H.Level = LevelOf(Sight->PelvisLocation);+ H.Support = ESupport::Seen;+ H.SupportTimeS = NowS;+ H.Velocity = Sight->Velocity;+ Hyps.Add(H);+ LastSeen = Sight->PelvisLocation;+ LastSeenS = NowS;+ FacingYaw = Sight->FacingYawDeg;+ FacingTimeS = NowS;+ if (Sight->bReloading)+ {+ bReload = true;+ ShotsSinceReload = 0;+ }+ }+ else if (!bDead)+ {+ // Clear: mass in the view cone loses weight (no sighting there).+ const FVector Axis = Self.ViewRotation.Vector();+ const float CosHalf = FMath::Cos(FMath::DegreesToRadians(ClearHalfAngleDeg));+ for (FHypothesis& H : Hyps)+ {+ const FVector To = H.Center - Self.EyeLocation;+ const float Dist = float(To.Size());+ if (Dist < ClearRangeCm && Dist > 1.f && float(FVector::DotProduct(To / Dist, Axis)) > CosHalf)+ {+ H.Weight *= 1.f - ClearPerStep;+ }+ }+ }++ if (!bDead)+ {+ for (const FVerseHeardPercept& Heard : Frame.Heard)+ {+ const float SdCm = FMath::Max(Heard.ErrorSdM * VerseBot::CmPerM, 30.f);+ float Best = 0.f;+ int32 BestIndex = INDEX_NONE;+ for (int32 i = 0; i < Hyps.Num(); ++i)+ {+ FHypothesis& H = Hyps[i];+ const float S2 = SdCm * SdCm + H.SdCm * H.SdCm;+ const float L = FMath::Exp(-float(FVector::DistSquared2D(H.Center, Heard.Location)) / (2.f * S2));+ const float LevelW = H.Level == Heard.LevelGuess ? 0.9f : 0.1f;+ H.Weight *= HeardEps + L * LevelW;+ if (L > Best)+ {+ Best = L;+ BestIndex = i;+ }+ }+ if (BestIndex != INDEX_NONE && Best > 0.1f)+ {+ // Fuse (product of Gaussians).+ FHypothesis& H = Hyps[BestIndex];+ const float A = H.SdCm * H.SdCm;+ const float B = SdCm * SdCm;+ H.Center = (H.Center * B + Heard.Location * A) / (A + B);+ H.SdCm = FMath::Sqrt(A * B / (A + B));+ H.Support = ESupport::Heard;+ H.SupportTimeS = NowS;+ }+ else+ {+ FHypothesis H;+ H.Center = Heard.Location;+ H.SdCm = SdCm;+ H.Weight = 0.6f;+ H.Level = Heard.LevelGuess;+ H.Support = ESupport::Heard;+ H.SupportTimeS = NowS;+ AddHypothesis(H);+ }+ if (Heard.Noise == VerseTags::Noise_Shot)+ {+ ++ShotsSinceReload;+ bReload = false;+ }+ else if (Heard.Noise == VerseTags::Noise_Reload)+ {+ bReload = true;+ ShotsSinceReload = 0;+ }+ Normalise();+ }++ auto AddWedge = [this](const FVector& From, const FVector& Toward)+ {+ FHypothesis H;+ H.Center = From + Toward.GetSafeNormal() * WedgeRangeCm;+ H.SdCm = WedgeSdCm;+ H.Weight = 0.5f;+ H.Level = LevelOf(H.Center);+ H.Support = ESupport::Inferred;+ H.SupportTimeS = NowS;+ AddHypothesis(H);+ };+ if (Frame.bHasHurt && !Sight)+ {+ AddWedge(Self.EyeLocation, Frame.Hurt.IncomingDirection);+ }+ if (!Sight)+ {+ for (const FVerseBoltPercept& Bolt : Frame.Bolts)+ {+ AddWedge(Bolt.Position, -Bolt.Direction);+ }+ }+ }++ Normalise();+ if (Memory && !bDead && !Sight)+ {+ // Normalise (4.2): 1 % of the learned position heatmap is mixed in, as prior-only mass+ // (it never supports a wall shot or a prefire, 7.3).+ FVector Hot;+ float Share = 0.f;+ if (Memory->HottestCell(FVerseBotMatchMemory::ELayer::Position, NowS, Hot, Share))+ {+ FHypothesis* Existing = Hyps.FindByPredicate([&Hot](const FHypothesis& H)+ { return H.Support == ESupport::Prior && FVector::DistSquared2D(H.Center, Hot) < 100.f * 100.f; });+ if (Existing)+ {+ Existing->Weight = FMath::Max(Existing->Weight, HeatPriorMix);+ }+ else+ {+ FHypothesis H;+ H.Center = Hot;+ H.SdCm = HeatPriorSdCm;+ H.Weight = HeatPriorMix;+ H.Level = LevelOf(Hot);+ H.Support = ESupport::Prior;+ AddHypothesis(H);+ }+ }+ }+ Refresh(NowS);+ if (Sight)+ {+ Cached.State = EVerseBeliefState::Known;+ }+}++void FVerseBotCoarseBelief::Refresh(float InNowS)+{+ FVerseBotBeliefSummary S;+ S.FacingYawDeg = FacingYaw;+ S.FacingAgeS = InNowS - FacingTimeS;+ S.bReloadNoticed = bReload;+ S.SinceSightingS = InNowS - LastSeenS;+ S.LastSeenLocation = LastSeen;+ S.OpponentHealthFrac = OpponentHealth;+ S.OpponentShotsSinceReload = ShotsSinceReload;+ if (bDead || Hyps.Num() == 0)+ {+ S.State = bDead ? EVerseBeliefState::Dead : EVerseBeliefState::Lost;+ Cached = S;+ return;+ }+ int32 Top = 0;+ float TopMass = -1.f;+ for (int32 i = 0; i < Hyps.Num(); ++i)+ {+ const float M = MassWithin(Hyps[i].Center, TopRadiusCm);+ if (M > TopMass)+ {+ TopMass = M;+ Top = i;+ }+ }+ S.TopCenter = Hyps[Top].Center;+ S.TopLevel = Hyps[Top].Level;+ S.Confidence = FMath::Clamp(TopMass, 0.f, 1.f);+ S.Velocity = Hyps[Top].Velocity;+ float NewestSupport = -1.0e6f;+ bool bSupported = false;+ for (const FHypothesis& H : Hyps)+ {+ if (DiscMass(H, S.TopCenter, TopRadiusCm) > 0.05f * FMath::Max(TopMass, 0.01f)+ && (H.Support == ESupport::Seen || H.Support == ESupport::Heard))+ {+ bSupported = true;+ NewestSupport = FMath::Max(NewestSupport, H.SupportTimeS);+ }+ }+ S.bPriorOnly = !bSupported;+ S.SupportAgeS = bSupported ? InNowS - NewestSupport : 1.0e6f;+ FVector Mean = FVector::ZeroVector;+ for (const FHypothesis& H : Hyps)+ {+ Mean += H.Center * H.Weight;+ }+ float Var = 0.f;+ for (const FHypothesis& H : Hyps)+ {+ Var += H.Weight * (H.SdCm * H.SdCm + float(FVector::DistSquared2D(H.Center, Mean)));+ }+ S.SpreadCm = FMath::Sqrt(Var);+ S.State = S.Confidence >= 0.5f ? EVerseBeliefState::Tracked+ : S.Confidence >= 0.2f ? EVerseBeliefState::Rough+ : EVerseBeliefState::Lost;+ Cached = S;+}++float FVerseBotCoarseBelief::MassWithin(const FVector& Location, float RadiusCm) const+{+ float M = 0.f;+ for (const FHypothesis& H : Hyps)+ {+ M += DiscMass(H, Location, RadiusCm);+ }+ return M;+}++float FVerseBotCoarseBelief::SupportedMassWithin(const FVector& Location, float RadiusCm) const+{+ float M = 0.f;+ for (const FHypothesis& H : Hyps)+ {+ if (H.Support == ESupport::Seen || H.Support == ESupport::Heard)+ {+ M += DiscMass(H, Location, RadiusCm);+ }+ }+ return M;+}++void FVerseBotCoarseBelief::TopCells(int32 N, TArray<FVector>& Out) const+{+ Out.Reset();+ TArray<int32, TInlineAllocator<MaxHypotheses>> Order;+ for (int32 i = 0; i < Hyps.Num(); ++i)+ {+ Order.Add(i);+ }+ Order.Sort([this](int32 A, int32 B) { return Hyps[A].Weight != Hyps[B].Weight ? Hyps[A].Weight > Hyps[B].Weight : A < B; });+ for (int32 i : Order)+ {+ if (Out.Num() >= N)+ {+ return;+ }+ Out.Add(Hyps[i].Center);+ }+ // Fill with points one sd around the strongest hypotheses.+ static const FVector Ring[4] = {FVector(1, 0, 0), FVector(0, 1, 0), FVector(-1, 0, 0), FVector(0, -1, 0)};+ for (int32 i : Order)+ {+ for (const FVector& R : Ring)+ {+ if (Out.Num() >= N)+ {+ return;+ }+ Out.Add(Hyps[i].Center + R * FMath::Min(Hyps[i].SdCm, 300.f));+ }+ }+}diff --git a/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotBrainCore.cpp b/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotBrainCore.cppnew file mode 100644index 0000000000..26ad1bc7de--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotBrainCore.cpp@@ -0,0 +1,1045 @@+#include "Brain/VerseBotBrainCore.h"++#include "Bot/VerseBotTier.h"+#include "VerseGameplayTags.h"++namespace+{+ /** Belief step rate (bot.md 2): 10 Hz plus at once on a positive percept. */+ constexpr float BeliefStepS = 0.1f;+ /** Attack bonus on an acquired sighting (5.2). */+ constexpr float AcquireBonus = 0.4f;+ /** Contact lost after 3 s ends an engagement (7.1). */+ constexpr float EngagementLostS = 3.f;+ /** Stuck: wants to move, moved less than 0.5 m in 3 s (BG12). */+ constexpr float StuckWindowS = 3.f;+ constexpr float StuckMinMoveCm = 50.f;+ constexpr float StuckReplanS = 1.f;+ constexpr float StuckTargetMinCm = 150.f;+ /** Knife reflex inside 2 m frontal, finisher reflex inside 1.5 m rear or flank (5.2). */+ constexpr float KnifeRangeCm = 200.f;+ constexpr float FinisherRangeCm = 150.f;+ constexpr float WaypointReachCm = 30.f;+ constexpr float BrainChestCm = 120.f;+ /** A sighting starting within 1.5 m of a cover edge counts as a peek there (7.1). */+ constexpr float PeekEdgeRadiusCm = 150.f;+ constexpr float InCoverCm = 90.f;+ /** Knife reflex only on an opponent inside the bot's view cone (5.2 "frontal", 3.1 cone). */+ constexpr float KnifeFrontalHalfAngleDeg = 55.f;+ /** Reaction floor 0.6 x mean (8.1); fewer visible samples than this is a partial exposure. */+ constexpr float ReactionFloorFrac = 0.6f;+ constexpr int32 PartialExposureSamples = 4;+ /** Prefire fires into the edge only right after the sound; the aim must sit on the edge. */+ constexpr float PrefireFireAgeS = 0.6f;+ constexpr float PrefireAimCm = 50.f;++ const FVerseSightPercept* FirstVisible(const FVersePerceptFrame& F)+ {+ for (const FVerseSightPercept& S : F.Sightings)+ {+ if (S.VisibleMask != 0)+ {+ return &S;+ }+ }+ return nullptr;+ }++ uint32 MaskBits(EVerseInputButton B) { return uint32(B); }+}++FVerseBotBrainCore::FVerseBotBrainCore()+ : Belief(MakeUnique<FVerseBotCoarseBelief>())+ , Aim(MakeUnique<FVerseBotFollowAim>())+{+}++FVerseBotBrainCore::~FVerseBotBrainCore() = default;++void FVerseBotBrainCore::Init(const UVerseBotTier& InTier, const FConfig& InConfig)+{+ Config = InConfig;+ Tier = &InTier;+ DecisionRng = FVerseRng(Config.Seed, 1, EVerseRngSalt::Brain);+ TacticsRng = FVerseRng(Config.Seed, 2, EVerseRngSalt::Brain);+ ReflexRng = FVerseRng(Config.Seed, 3, EVerseRngSalt::Brain);+ ReactRng = FVerseRng(Config.Seed, 4, EVerseRngSalt::Brain);+ bRawHadSighting = false;+ bSightHeld = false;+ SightReactUntilS = -1.f;+ bHurtPending = false;+ HurtReactUntilS = -1.f;+ PendingHurt = FVerseHurtPercept();+ HealthBeforeHurt = 0.f;+ LastRawHealth = -1.f;+ Job = FQueryJob();+ QuerySlices = 0;+ QueryBudgetStops = 0;+ Memory->Reset();+ Memory->Configure(InTier);+ Memory->SetEnabled(Config.bLearning);+ Audit.Reset();+ Belief->Reset();+ if (bCoarseBelief)+ {+ static_cast<FVerseBotCoarseBelief*>(Belief.Get())->SetSelfId(Config.SelfId);+ }+ Aim->Reset(FVerseRng::Mix(Config.Seed ^ 0xA1u), InTier);+ TacticsMem.Reset();+ Cache.Reset();+ Selector.Reset(EVerseBotState::Search, 0.f);+ Pending.Reset();+ Path = FVerseBotPath();+ PathTarget = FVector(1.0e9);+ PathIndex = 0;+ NowS = 0.f;+ LastThinkS = -1.f;+ NextDecisionS = 0.f;+ NextBeliefStepS = 0.f;+ LastBeliefStepS = 0.f;+ DecisionIndex = 0;+ FMemory::Memzero(StateCounts);+ FMemory::Memzero(StuckByState);+ bHadSighting = false;+ LastSightingS = -1.0e6f;+ bWasAlive = false;+ LastMagazine = -1;+ LastHurtS = -1.0e6f;+ AttackBonusUntilS = -1.f;+ bInEngagement = false;+ bFirstContactDone = false;+ StuckEvents = 0;+ bStuckCounted = false;+ PrevButtons = 0;+ LastHeardS = -1.0e6f;+ LastSightRecordS = -1.0e6f;+ LastOpponentKillS = -1.0e6f;+ bPistolRolled = bPistolChosen = bKnifeRolled = bKnifeChosen = false;+ QueryCursor = 0;+ PathDecision = -1;+ LastSeenLocation = FVector::ZeroVector;+ LastSightPerceptId = 0;+ LastHeard = FVerseHeardPercept();+ SightingThisTick = FVerseSightPercept();+ bSightingThisTick = false;+ EngagementRangeCm = 0.f;+ EngagementLastS = -1.0e6f;+ LastPersonZone = INDEX_NONE;+ StuckRef = FVector::ZeroVector;+ StuckSinceS = 0.f;+ bStuckReplanned = false;+ bNavFailCounted = false;+ NavFailures = 0;+ VisibleBurst = 0;+ BurstRestUntilS = 0.f;+ BeliefSummary = FVerseBotBeliefSummary();+ Spawns.Reset();+ bSpawnsFetched = false;+}++void FVerseBotBrainCore::SetTier(const UVerseBotTier& InTier)+{+ Tier = &InTier;+ Memory->Configure(InTier);+ Aim->Reset(FVerseRng::Mix(Config.Seed ^ uint64(DecisionIndex)), InTier);+}++void FVerseBotBrainCore::SetBelief(TUniquePtr<IVerseBotBelief> InBelief)+{+ if (InBelief)+ {+ Belief = MoveTemp(InBelief);+ bCoarseBelief = false;+ }+}++void FVerseBotBrainCore::SetAimDriver(TUniquePtr<IVerseBotAimDriver> InAim)+{+ if (InAim)+ {+ Aim = MoveTemp(InAim);+ if (Tier)+ {+ Aim->Reset(FVerseRng::Mix(Config.Seed ^ 0xA1u), *Tier);+ }+ }+}++void FVerseBotBrainCore::UseMemory(FVerseBotMatchMemory& InMemory)+{+ Memory = &InMemory;+ if (Tier)+ {+ Memory->Configure(*Tier);+ }+ Memory->SetEnabled(Config.bLearning);+}++void FVerseBotBrainCore::ResetMatch()+{+ Memory->Reset();+ Belief->Reset();+ Audit.Reset();+ TacticsMem.Reset();+ Cache.Reset();+ Pending.Reset();+ Job.bActive = false;+ Path = FVerseBotPath();+ Selector.Reset(EVerseBotState::Search, NowS);+ bInEngagement = false;+ bFirstContactDone = false;+}++FVerseBotPresentation FVerseBotBrainCore::GetPresentation() const+{+ FVerseBotPresentation P;+ P.State = Selector.Current();+ P.StateTag = VerseBot::StateTag(P.State);+ P.HoldPhase = TacticsMem.HoldPhase;+ P.bHasCoverSpot = TacticsMem.bHasCover;+ P.CoverSpot = TacticsMem.Cover.Location;+ P.bHasPeekPoint = TacticsMem.bHasPeek;+ P.PeekPoint = TacticsMem.Peek.Eye;+ const FVerseBotBeliefSummary S = Belief->Summary();+ P.BeliefTop = S.TopCenter;+ P.Confidence = S.Confidence;+ return P;+}++void FVerseBotBrainCore::OnOwnDeath()+{+ // Tree stops; belief and plan cleared; match memory kept (5.2).+ Belief->Reset();+ TacticsMem.Reset();+ Cache.Reset();+ Pending.Reset();+ Job.bActive = false;+ Path = FVerseBotPath();+ PathTarget = FVector(1.0e9);+ bRawHadSighting = false;+ bSightHeld = false;+ SightReactUntilS = -1.f;+ bHurtPending = false;+ if (bInEngagement)+ {+ Memory->RecordEngagementEnd(EngagementRangeCm, true);+ bInEngagement = false;+ }+}++void FVerseBotBrainCore::OnOwnRespawn()+{+ Selector.Force(EVerseBotState::Search, NowS);+ TacticsVisibleReset();+ bFirstContactDone = false;+ NextDecisionS = NowS;+}++void FVerseBotBrainCore::TacticsVisibleReset()+{+ bHadSighting = false;+ LastSightingS = -1.0e6f;+ AttackBonusUntilS = -1.f;+ VisibleBurst = 0;+}++void FVerseBotBrainCore::BuildContext(const FVersePerceptFrame& Frame, IVerseBotWorldQueries& World)+{+ const UVerseBotTier& T = *Tier;+ FVerseBotQueryContext& Q = Ctx.Query;+ Q.Self = &Frame.Self;+ Q.Belief = &BeliefSummary;+ Q.BeliefMap = Belief.Get();+ Q.World = &World;+ Q.Memory = Memory->IsEnabled() ? Memory : nullptr;+ Q.Tier = Tier;+ Q.NowS = NowS;+ Q.Weapon = World.GetOwnWeapon();+ Q.RecentPeekEdges = TacticsMem.RecentPeekEdges;+ Q.PreferredRangeCm = VerseBotTactics::PreferredBandCm(T, Q.Memory);++ Ctx.Frame = &Frame;+ Ctx.Cache = &Cache;+ Ctx.Sighting = bSightingThisTick ? &SightingThisTick : nullptr;+ Ctx.RecentHeardAgeS = NowS - LastHeardS;+ Ctx.RecentHeard = Ctx.RecentHeardAgeS <= 2.f ? &LastHeard : nullptr;+ const FVerseSelfPercept& S = Frame.Self;+ Ctx.HealthFrac = S.MaxHealth > 0.f ? FMath::Clamp(S.Health / S.MaxHealth, 0.f, 1.f) : 1.f;+ const int32 MagSize = FMath::Max(Q.Weapon.MagazineSize, 1);+ Ctx.MagazineFrac = FMath::Clamp(float(S.Magazine) / float(MagSize), 0.f, 1.f);+ Ctx.bPistolLow = S.ActiveSlot == EVerseLoadoutSlot::Secondary ? Ctx.MagazineFrac < 0.2f : S.Reserve <= 0;+ Ctx.SinceSightS = NowS - LastSightingS;+ Ctx.SinceHurtS = NowS - LastHurtS;+ Ctx.bBulwarkReady = S.GadgetCharges[0] > 0 && S.GadgetCooldownS[0] <= 0.f;+ Ctx.bBreachReady = S.GadgetCharges[1] > 0 && S.GadgetCooldownS[1] <= 0.f;+ Ctx.bInCover = TacticsMem.bHasCover && float(FVector::Dist2D(TacticsMem.Cover.Location, S.Location)) < InCoverCm;++ // Wall-shot authority on the cached spot (4.5), rechecked against the current belief.+ Ctx.bWallbangAuthorised = false;+ if (Cache.Wallbang.bFound && Ctx.Sighting == nullptr)+ {+ FVerseBotFireEvidence& E = Ctx.WallbangEvidence;+ E = FVerseBotFireEvidence();+ E.AimPoint = BeliefSummary.TopCenter + FVector(0, 0, BrainChestCm);+ E.bAimInTopCluster = true;+ E.TraceDamageFrac = Cache.Wallbang.DamageFrac;+ E.TracePieces = Cache.Wallbang.Pieces;+ E.MassAtAim = Belief->MassWithin(E.AimPoint, FVerseBotFireClassifier::MassRadiusCm);+ E.SupportedMassAtAim = Belief->SupportedMassWithin(E.AimPoint, FVerseBotFireClassifier::MassRadiusCm);+ E.SupportAgeS = BeliefSummary.SupportAgeS;+ E.bPriorOnly = BeliefSummary.bPriorOnly;+ Ctx.bWallbangAuthorised = FVector::Dist(Cache.Wallbang.AimPoint, E.AimPoint) < FVerseBotFireClassifier::MassRadiusCm+ && FVerseBotFireClassifier::HasWallShotAuthority(E, T);+ }+}++void FVerseBotBrainCore::UpdateLearning(const FVersePerceptFrame& Frame)+{+ if (!Memory->IsEnabled())+ {+ return;+ }+ // Learned from percepts only (7).+ if (bSightingThisTick)+ {+ const FVector P = SightingThisTick.PelvisLocation;+ const bool bStart = !bHadSighting;+ if (bStart || NowS - LastSightRecordS >= 0.1f)+ {+ LastSightRecordS = NowS;+ Memory->RecordSighting(P, NowS, !bFirstContactDone);+ bFirstContactDone = true;+ const int32 Zone = WorldThisTick->GetZoneId(P);+ Memory->RecordZone(Zone, P, NowS);+ }+ if (bStart && Ctx.SinceSightS > 1.f)+ {+ TArray<FVerseBotCoverPoint> Edges;+ WorldThisTick->GetCoverPoints(P, PeekEdgeRadiusCm, Edges);+ for (const FVerseBotCoverPoint& E : Edges)+ {+ if (E.EdgeId != INDEX_NONE)+ {+ const EVerseBotPeekType Type = SightingThisTick.LeanQuantized < -20 ? EVerseBotPeekType::LeanLeft+ : SightingThisTick.LeanQuantized > 20 ? EVerseBotPeekType::LeanRight+ : SightingThisTick.Velocity.Z > 150.f ? EVerseBotPeekType::JumpPeek+ : SightingThisTick.Stance == EVerseStance::Crouch ? EVerseBotPeekType::CrouchRise+ : EVerseBotPeekType::StepOut;+ Memory->RecordPeek(E.EdgeId, Type, NowS);+ break;+ }+ }+ }+ if (Frame.bHasHurt || Frame.Bolts.Num() > 0)+ {+ Memory->RecordShotFrom(P, NowS, true);+ }+ if (SightingThisTick.Stance == EVerseStance::Slide)+ {+ Memory->RecordHabit(TEXT("slide"));+ }+ if (SightingThisTick.Stance == EVerseStance::Prone)+ {+ Memory->RecordHabit(TEXT("prone"));+ }+ bInEngagement = true;+ EngagementRangeCm = float(FVector::Dist(P, Frame.Self.Location));+ EngagementLastS = NowS;+ }+ else if (bInEngagement && NowS - EngagementLastS > EngagementLostS)+ {+ // Contact lost: no winner (7.1 counts wins on a kill or the bot's death only).+ Memory->RecordEngagementNoDecision(EngagementRangeCm);+ bInEngagement = false;+ }+ for (const FVerseHeardPercept& H : Frame.Heard)+ {+ Memory->RecordHeard(H.Location, NowS);+ if (H.Noise == VerseTags::Noise_Shot)+ {+ Memory->RecordShotFrom(H.Location, NowS, false);+ }+ else if (H.Noise == VerseTags::Noise_Gadget_BulwarkDeploy)+ {+ Memory->RecordHabit(TEXT("bulwark"));+ }+ else if (H.Noise == VerseTags::Noise_Finisher)+ {+ Memory->RecordHabit(TEXT("finisher"));+ }+ else if (H.Noise == VerseTags::Noise_Reload && NowS - LastOpponentKillS < 3.f)+ {+ Memory->RecordHabit(TEXT("after_kill_reload"));+ }+ }+ for (const FVerseHudEvent& E : Frame.Hud)+ {+ if (E.Kind == EVerseHudEventKind::Kill && E.VictimId != Config.SelfId)+ {+ LastOpponentKillS = NowS;+ if (bInEngagement)+ {+ Memory->RecordEngagementEnd(EngagementRangeCm, false);+ bInEngagement = false;+ }+ }+ }+}++bool FVerseBotBrainCore::ForcedTriggers(const FVersePerceptFrame& Frame, float (&Bonus)[VerseBot::NumStates])+{+ bool bForce = false;+ // Sighting acquired (after reaction): force, Attack +0.4.+ if (bSightingThisTick && !bHadSighting)+ {+ bForce = true;+ AttackBonusUntilS = NowS + 0.05f;+ }+ if (NowS <= AttackBonusUntilS)+ {+ Bonus[int32(EVerseBotState::Attack)] += AcquireBonus;+ }+ // Sight lost: 0.35 s suppression, then a decision.+ if (!bSightingThisTick && bHadSighting)+ {+ NextDecisionS = FMath::Min(NextDecisionS, NowS + FVerseBotFireClassifier::SuppressionS);+ }+ // Hit taken: force, Retreat and Hold + damage / max health.+ if (Frame.bHasHurt)+ {+ bForce = true;+ const float Frac = Frame.Self.MaxHealth > 0.f ? Frame.Hurt.Damage / Frame.Self.MaxHealth : 0.f;+ Bonus[int32(EVerseBotState::Retreat)] += Frac;+ Bonus[int32(EVerseBotState::Hold)] += Frac;+ LastHurtS = NowS;+ }+ // Magazine empty.+ if (LastMagazine > 0 && Frame.Self.Magazine == 0)+ {+ bForce = true;+ }+ LastMagazine = Frame.Self.Magazine;+ return bForce;+}++void FVerseBotBrainCore::Decide(bool bInterrupt, const float (&Bonus)[VerseBot::NumStates])+{+ const UVerseBotTier& T = *Tier;+ Ctx.Query.bIgnoreLearned = DecisionRng.Chance(T.ExplorationRate);+ float Util[VerseBot::NumStates];+ VerseBotTactics::Utilities(Ctx, Util);+ const FVerseBotUtilitySelector::FDecision D = Selector.Decide(Util, Bonus, T.UtilityNoise, bInterrupt, NowS, DecisionRng);+ if (D.bChanged)+ {+ VerseBotTactics::Enter(D.State, Ctx, TacticsMem, TacticsRng);+ }+ ++StateCounts[int32(D.State)];+ ++DecisionIndex;+ NextDecisionS = NowS + T.DecisionMs / 1000.f * float(VerseBot::Jitter(DecisionRng, 0.8, 1.2));++ // Schedule EQS: at most 2 in flight (the running slice counts); round-robin over the wanted+ // list so every query refreshes.+ TArray<EVerseBotQuery, TInlineAllocator<8>> Wanted;+ VerseBotTactics::WantedQueries(D.State, Ctx, Wanted);+ auto InFlight = [this]() { return Pending.Num() + (Job.bActive ? 1 : 0); };+ auto Queued = [this](EVerseBotQuery Q) { return Pending.Contains(Q) || (Job.bActive && Job.Query == Q); };+ if (Wanted.Num() > 0 && InFlight() < 2)+ {+ // The current state's own query (first) always goes in; the rest rotate.+ if (!Queued(Wanted[0]))+ {+ Pending.Add(Wanted[0]);+ }+ for (int32 i = 0; i < Wanted.Num() && InFlight() < 2; ++i)+ {+ const EVerseBotQuery Q = Wanted[(QueryCursor + i) % Wanted.Num()];+ if (!Queued(Q))+ {+ Pending.Add(Q);+ QueryCursor = (QueryCursor + i + 1) % FMath::Max(1, Wanted.Num());+ break;+ }+ }+ }+}++void FVerseBotBrainCore::StartQuery(EVerseBotQuery Query)+{+ Job.bActive = true;+ Job.Query = Query;+ Job.Self = *Ctx.Query.Self;+ Job.Belief = BeliefSummary;+ Job.From = TacticsMem.bHasCover ? TacticsMem.Cover : Cache.GetCover(EVerseBotCoverMode::Near).Point;+ Job.Ctx = Ctx.Query;+ Job.Ctx.Self = &Job.Self;+ Job.Ctx.Belief = &Job.Belief;+ Job.Slice = FVerseBotEqsSlice();+ Job.Cover = FVerseBotCoverResult();+ Job.Peek = FVerseBotPeekResult();+ Job.Wallbang = FVerseBotWallbangResult();+ Job.Breach = FVerseBotBreachResult();+ Job.Finisher = FVerseBotFinisherResult();+}++void FVerseBotBrainCore::RunScheduledQuery()+{+ // One slice per tick under the cost budget; a query resumes where it stopped (bot.md 2).+ if (!Job.bActive)+ {+ if (Pending.Num() == 0)+ {+ return;+ }+ const EVerseBotQuery Q = Pending[0];+ Pending.RemoveAt(0);+ StartQuery(Q);+ }+ FVerseBotQueryContext& C = Job.Ctx;+ C.World = WorldThisTick;+ C.BeliefMap = Belief.Get();+ C.Memory = Memory->IsEnabled() ? Memory : nullptr;+ Job.Slice.BeginSlice(QueryUnitsPerTick);+ ++QuerySlices;+ switch (Job.Query)+ {+ case EVerseBotQuery::CoverNear: VerseBotEqs::CoverSlice(C, EVerseBotCoverMode::Near, Job.Slice, Job.Cover); break;+ case EVerseBotQuery::CoverFar: VerseBotEqs::CoverSlice(C, EVerseBotCoverMode::Far, Job.Slice, Job.Cover); break;+ case EVerseBotQuery::CoverFlank: VerseBotEqs::CoverSlice(C, EVerseBotCoverMode::Flank, Job.Slice, Job.Cover); break;+ case EVerseBotQuery::CoverBulwark: VerseBotEqs::CoverSlice(C, EVerseBotCoverMode::Bulwark, Job.Slice, Job.Cover); break;+ case EVerseBotQuery::PeekCorner: VerseBotEqs::PeekCornerSlice(C, Job.From, Job.Slice, Job.Peek); break;+ case EVerseBotQuery::WallbangSpot: VerseBotEqs::WallbangSpotSlice(C, Job.Slice, Job.Wallbang); break;+ case EVerseBotQuery::BreachSpot: VerseBotEqs::BreachSpotSlice(C, Job.Slice, Job.Breach); break;+ case EVerseBotQuery::FinisherApproach: VerseBotEqs::FinisherApproachSlice(C, Job.Slice, Job.Finisher); break;+ default: Job.Slice.bDone = true; break;+ }+ if (!Job.Slice.bDone)+ {+ ++QueryBudgetStops;+ return;+ }+ switch (Job.Query)+ {+ case EVerseBotQuery::CoverNear: Cache.Cover[int32(EVerseBotCoverMode::Near)] = Job.Cover; break;+ case EVerseBotQuery::CoverFar: Cache.Cover[int32(EVerseBotCoverMode::Far)] = Job.Cover; break;+ case EVerseBotQuery::CoverFlank: Cache.Cover[int32(EVerseBotCoverMode::Flank)] = Job.Cover; break;+ case EVerseBotQuery::CoverBulwark: Cache.Cover[int32(EVerseBotCoverMode::Bulwark)] = Job.Cover; break;+ case EVerseBotQuery::PeekCorner: Cache.Peek = Job.Peek; break;+ case EVerseBotQuery::WallbangSpot: Cache.Wallbang = Job.Wallbang; break;+ case EVerseBotQuery::BreachSpot: Cache.Breach = Job.Breach; break;+ case EVerseBotQuery::FinisherApproach: Cache.Finisher = Job.Finisher; break;+ default: break;+ }+ if (Job.Query != EVerseBotQuery::Count)+ {+ Cache.ProducedAt[int32(Job.Query)] = DecisionIndex;+ }+ Job.bActive = false;+}++float FVerseBotBrainCore::SampleReactionS(float Mul)+{+ const UVerseBotTier& T = *Tier;+ const float Mean = T.ReactionMs.X;+ const float Ms = FMath::Max(float(ReactRng.Gaussian(Mean, T.ReactionMs.Y)), ReactionFloorFrac * Mean);+ return Ms * Mul / 1000.f;+}++const FVersePerceptFrame& FVerseBotBrainCore::GateStimuli(const FVersePerceptFrame& Raw)+{+ const UVerseBotTier& T = *Tier;+ if (LastRawHealth < 0.f)+ {+ LastRawHealth = Raw.Self.Health;+ }+ // Sighting acquired: the decision layer, the reflexes and the belief get it only after the+ // sampled reaction (peripheral and partial exposure slower, 8.1). A sighting that ends inside+ // its reaction was never acted on.+ const FVerseSightPercept* RawSight = FirstVisible(Raw);+ if (RawSight && !bRawHadSighting)+ {+ float Mul = 1.f;+ if (RawSight->bPeripheral)+ {+ Mul *= T.PeripheralReactionMul;+ }+ if (FMath::CountBits(uint64(RawSight->VisibleMask)) <= PartialExposureSamples)+ {+ Mul *= T.PartialExposureAcquireMul;+ }+ SightReactUntilS = NowS + SampleReactionS(Mul);+ }+ bRawHadSighting = RawSight != nullptr;+ bSightHeld = RawSight != nullptr && NowS < SightReactUntilS;++ // Hit taken: the forced decision and its bonuses wait the reaction too; meanwhile the HUD health+ // reads as before the hit so no scheduled decision answers it early.+ if (Raw.bHasHurt)+ {+ if (!bHurtPending)+ {+ bHurtPending = true;+ HurtReactUntilS = NowS + SampleReactionS(1.f);+ PendingHurt = Raw.Hurt;+ HealthBeforeHurt = LastRawHealth;+ }+ else+ {+ const float Damage = PendingHurt.Damage + Raw.Hurt.Damage;+ PendingHurt = Raw.Hurt;+ PendingHurt.Damage = Damage;+ }+ }+ LastRawHealth = Raw.Self.Health;+ const bool bReleaseHurt = bHurtPending && NowS >= HurtReactUntilS;+ if (!bSightHeld && !bHurtPending)+ {+ return Raw;+ }+ GatedFrame = Raw;+ if (bSightHeld)+ {+ GatedFrame.Sightings.Reset();+ }+ if (bReleaseHurt)+ {+ GatedFrame.bHasHurt = true;+ GatedFrame.Hurt = PendingHurt;+ bHurtPending = false;+ }+ else+ {+ GatedFrame.bHasHurt = false;+ GatedFrame.Self.Health = FMath::Max(HealthBeforeHurt, Raw.Self.Health);+ }+ return GatedFrame;+}++void FVerseBotBrainCore::UpdatePrefire(FVerseBotIntent& Intent)+{+ FVerseBotTacticsMemory& M = TacticsMem;+ M.bPrefireActive = false;+ if (bSightingThisTick)+ {+ // A sighting ends the approach.+ M.bPrefireRollDone = false;+ M.PrefireEdge = INDEX_NONE;+ return;+ }+ const FVerseHeardPercept* Heard = Ctx.RecentHeard;+ const EVerseBotState State = Selector.Current();+ const bool bStateMay = State == EVerseBotState::Hold || State == EVerseBotState::Search || State == EVerseBotState::Flank+ || State == EVerseBotState::Attack;+ if (!Heard || !bStateMay || BeliefSummary.State == EVerseBeliefState::Dead)+ {+ return;+ }+ const UVerseBotTier& T = *Tier;+ if (LastHeardS == NowS || M.PrefireEdge == INDEX_NONE)+ {+ // The peek edge the sound is near: the person's top two learned edges first (7.2), else the+ // nearest edge of the static arena data.+ TArray<FVerseBotCoverPoint> Edges;+ WorldThisTick->GetCoverPoints(Heard->Location, FVerseBotFireClassifier::PrefireEdgeRadiusCm, Edges);+ TArray<int32> Learned;+ if (Ctx.Query.Memory && !Ctx.Query.bIgnoreLearned)+ {+ Ctx.Query.Memory->TopPeekEdges(2, Learned);+ }+ const FVerseBotCoverPoint* Pick = nullptr;+ float PickScore = 1.0e9f;+ for (const FVerseBotCoverPoint& E : Edges)+ {+ const FVector Point = E.Location + FVector(0, 0, BrainChestCm);+ if (E.EdgeId == INDEX_NONE || float(FVector::Dist(Point, Heard->Location)) > FVerseBotFireClassifier::PrefireEdgeRadiusCm)+ {+ continue;+ }+ const int32 Rank = Learned.IndexOfByKey(E.EdgeId);+ const float Score = (Rank == INDEX_NONE ? 1.0e6f : float(Rank) * 1.0e5f) + float(FVector::Dist2D(Point, BeliefSummary.TopCenter));+ if (Score < PickScore)+ {+ PickScore = Score;+ Pick = &E;+ }+ }+ const int32 Edge = Pick ? Pick->EdgeId : INDEX_NONE;+ if (Edge != M.PrefireEdge)+ {+ // A new edge is a new approach: one roll each (8.4).+ M.bPrefireRollDone = false;+ }+ M.PrefireEdge = Edge;+ M.PrefirePoint = Pick ? Pick->Location + FVector(0, 0, BrainChestCm) : FVector::ZeroVector;+ }+ if (M.PrefireEdge == INDEX_NONE)+ {+ return;+ }+ // Belief mass at the edge from perceived support only (learned mass never authorises, 7.3).+ if (Belief->SupportedMassWithin(M.PrefirePoint, FVerseBotFireClassifier::MassRadiusCm) < FVerseBotFireClassifier::MinBelief(T))+ {+ return;+ }+ if (!M.bPrefireRollDone)+ {+ M.bPrefireRollDone = true;+ M.bPrefireRolled = ReflexRng.Chance(T.PrefireChance);+ }+ if (!M.bPrefireRolled)+ {+ return;+ }+ M.bPrefireActive = true;+ Intent.bHasLookTarget = true;+ Intent.LookTarget = M.PrefirePoint;+ Intent.bAds = true;+ Intent.bWantFire = Ctx.RecentHeardAgeS <= PrefireFireAgeS;+}++void FVerseBotBrainCore::Reflexes(FVerseBotIntent& Intent)+{+ const UVerseBotTier& T = *Tier;+ const FVerseSelfPercept& S = *Ctx.Query.Self;+ if (!bSightingThisTick)+ {+ bPistolRolled = false;+ bKnifeRolled = false;+ return;+ }+ const FVector Opp = SightingThisTick.PelvisLocation;+ const float Dist = float(FVector::Dist2D(Opp, S.Location));+ // Spawn protection (opponent, visible): hold fire, pre-aim.+ if (SightingThisTick.bSpawnProtected)+ {+ Intent.bWantFire = false;+ Intent.bHasLookTarget = true;+ Intent.LookTarget = Opp + FVector(0, 0, BrainChestCm - 70.f);+ return;+ }+ // Finisher: within 1.5 m in the opponent's rear or flank arc, in every state.+ const FVector OppFacing = FRotator(0.f, SightingThisTick.FacingYawDeg, 0.f).Vector();+ const FVector OppToBot = (S.Location - Opp).GetSafeNormal2D();+ const float OffDeg = FMath::RadiansToDegrees(FMath::Acos(FMath::Clamp(float(FVector::DotProduct(OppFacing, OppToBot)), -1.f, 1.f)));+ if (Dist <= FinisherRangeCm && OffDeg > 60.f && WorldThisTick->CanActivateFinisher())+ {+ Intent.bMelee = true;+ Intent.bWantFire = false;+ return;+ }+ // Knife: within 2 m frontal (inside the bot's view cone), magazine empty or the KnifeChoice roll.+ const FVector ToOpp = (Opp - S.Location).GetSafeNormal2D();+ const FVector ViewAxis = S.ViewRotation.Vector().GetSafeNormal2D();+ const float FrontDeg = FMath::RadiansToDegrees(FMath::Acos(FMath::Clamp(float(FVector::DotProduct(ViewAxis, ToOpp)), -1.f, 1.f)));+ if (Dist <= KnifeRangeCm && FrontDeg <= KnifeFrontalHalfAngleDeg)+ {+ if (!bKnifeRolled)+ {+ bKnifeRolled = true;+ bKnifeChosen = ReflexRng.Chance(T.KnifeChoice);+ }+ if (S.Magazine == 0 || bKnifeChosen)+ {+ Intent.bMelee = true;+ Intent.bWantFire = false;+ return;+ }+ }+ else+ {+ bKnifeRolled = false;+ }+ // Magazine empty with a target in sight: pistol with PistolSwitchChance, else Retreat.+ if (S.Magazine == 0 && S.ActiveSlot == EVerseLoadoutSlot::Primary)+ {+ if (!bPistolRolled)+ {+ bPistolRolled = true;+ bPistolChosen = ReflexRng.Chance(T.PistolSwitchChance);+ if (!bPistolChosen)+ {+ Selector.Force(EVerseBotState::Retreat, NowS);+ VerseBotTactics::Enter(EVerseBotState::Retreat, Ctx, TacticsMem, TacticsRng);+ }+ }+ if (bPistolChosen)+ {+ Intent.bSwitchSecondary = true;+ }+ }+}++void FVerseBotBrainCore::ApplyFireGate(FVerseBotIntent& Intent, const FVerseBotAimResult& AimResult)+{+ if (!Intent.bWantFire || !Intent.bHasLookTarget)+ {+ Intent.bWantFire = false;+ return;+ }+ const UVerseBotTier& T = *Tier;+ FVerseBotFireEvidence E;+ E.ServerTimeMs = FrameThisTick->ServerTimeMs;+ E.AimPoint = Intent.LookTarget;+ E.bTargetVisible = bSightingThisTick && !SightingThisTick.bSpawnProtected+ && float(FVector::Dist(Intent.LookTarget, SightingThisTick.PelvisLocation)) < 200.f;+ E.SightPerceptId = bSightingThisTick ? SightingThisTick.PerceptId : LastSightPerceptId;+ E.bTargetSpawnProtected = bSightingThisTick && SightingThisTick.bSpawnProtected;+ E.SinceSightLostS = bSightingThisTick ? 0.f : NowS - LastSightingS;+ E.LastSeenLocation = LastSeenLocation + FVector(0, 0, BrainChestCm - 70.f);+ E.HeardAgeS = NowS - LastHeardS;+ E.HeardLocation = LastHeard.Location;+ E.HeardSdCm = LastHeard.ErrorSdM * VerseBot::CmPerM;+ E.HeardPerceptId = LastHeard.PerceptId;+ E.MassAtAim = Belief->MassWithin(E.AimPoint, FVerseBotFireClassifier::MassRadiusCm);+ E.SupportedMassAtAim = Belief->SupportedMassWithin(E.AimPoint, FVerseBotFireClassifier::MassRadiusCm);+ E.SupportAgeS = BeliefSummary.SupportAgeS;+ E.bPriorOnly = BeliefSummary.bPriorOnly;+ E.bAimInTopCluster = float(FVector::Dist2D(E.AimPoint, BeliefSummary.TopCenter)) <= 300.f;+ const FVerseBotTacticsMemory& M = TacticsMem;+ E.bPrefireRolled = M.bPrefireActive && M.bPrefireRolled;+ E.bAimAtPeekEdge = M.bPrefireActive && float(FVector::Dist(E.AimPoint, M.PrefirePoint)) <= PrefireAimCm;+ if (!E.bTargetVisible && E.SinceSightLostS > FVerseBotFireClassifier::SuppressionS)+ {+ const FVerseBotBoltTrace Trace = WorldThisTick->TraceBolt(FrameThisTick->Self.EyeLocation, E.AimPoint, Ctx.Query.Weapon);+ E.TraceDamageFrac = Trace.DamageFrac;+ E.TracePieces = Trace.Pieces;+ }+ const EVerseBotFireMode Mode = FVerseBotFireClassifier::Classify(E, T);+ const bool bAimed = AimResult.bOnTarget || (Mode != EVerseBotFireMode::Visible && AimResult.ErrorDeg < 2.f);+ if (Mode == EVerseBotFireMode::Unclassified)+ {+ // Counted apart: a fire intent without a mode of 8.4 never reaches the trigger.+ Audit.AddBlocked();+ Intent.bWantFire = false;+ return;+ }+ if (!bAimed)+ {+ Intent.bWantFire = false;+ return;+ }+ Audit.Add(E, Mode);+}++FVector FVerseBotBrainCore::NextWaypoint(const FVector& Target, bool bCrouch)+{+ const FVector Self = FrameThisTick->Self.Location;+ // Re-plan on a new target (> 1 m away from the old one) or on a new decision.+ if (FVector::DistSquared(Target, PathTarget) > 100.f * 100.f || PathDecision != DecisionIndex)+ {+ Path = WorldThisTick->FindPath(Self, Target, bCrouch);+ PathTarget = Target;+ PathIndex = 0;+ PathDecision = DecisionIndex;+ }+ if (!Path.bValid || Path.Waypoints.Num() == 0)+ {+ // No nav to the target: stand and let the next decision pick another (BG12 nav failure).+ if (PathDecision == DecisionIndex && !bNavFailCounted)+ {+ ++NavFailures;+ bNavFailCounted = true;+ NextDecisionS = FMath::Min(NextDecisionS, NowS + 0.2f);+ TacticsMem.bHasSearchTarget = false;+ TacticsMem.bHasFlankPoint = false;+ }+ return Self;+ }+ bNavFailCounted = false;+ while (PathIndex < Path.Waypoints.Num() - 1 && FVector::Dist2D(Path.Waypoints[PathIndex], Self) < WaypointReachCm)+ {+ ++PathIndex;+ }+ return Path.Waypoints[PathIndex];+}++FVerseInputFrame FVerseBotBrainCore::ToInput(const FVerseBotIntent& Intent, const FVerseBotAimResult& AimResult, uint32 ServerTimeMs)+{+ FVerseInputFrame F;+ F.ServerTimeMs = ServerTimeMs;+ const FVerseSelfPercept& S = FrameThisTick->Self;+ FVector2f Move = FVector2f::ZeroVector;+ if (Intent.bHasMoveTarget)+ {+ const FVector Way = NextWaypoint(Intent.MoveTarget, Intent.Stance == EVerseStance::Crouch);+ const FVector Dir = Way.Equals(S.Location) ? FVector::ZeroVector : (Way - S.Location).GetSafeNormal2D();+ const FVector Local = FRotator(0.f, S.ViewRotation.Yaw, 0.f).UnrotateVector(Dir);+ Move = FVector2f(float(Local.X), float(Local.Y));+ }+ if (Intent.Strafe != 0)+ {+ Move.Y = FMath::Clamp(Move.Y + 0.8f * float(Intent.Strafe), -1.f, 1.f);+ }+ const float Len = Move.Size();+ if (Len > 1.f)+ {+ Move /= Len;+ }+ if (Intent.bWalk)+ {+ Move *= 0.45f;+ }+ F.Move = Move;+ F.LookDeltaDeg = AimResult.LookDeltaDeg;++ uint32 B = 0;+ if (Intent.bWantFire) B |= MaskBits(EVerseInputButton::Fire);+ if (Intent.bAds && !Intent.bSprint && !Intent.bSlide) B |= MaskBits(EVerseInputButton::Ads);+ if (Intent.bReload) B |= MaskBits(EVerseInputButton::Reload);+ if (Intent.bMelee) B |= MaskBits(EVerseInputButton::Melee);+ if (Intent.bJump) B |= MaskBits(EVerseInputButton::Jump);+ if (Intent.Stance == EVerseStance::Crouch || Intent.bSlide) B |= MaskBits(EVerseInputButton::Crouch);+ if (Intent.Stance == EVerseStance::Prone) B |= MaskBits(EVerseInputButton::Prone);+ if ((Intent.bSprint || Intent.bSlide) && !Intent.bWantFire && Move.X > 0.5f) B |= MaskBits(EVerseInputButton::Sprint);+ if (Intent.Lean < 0) B |= MaskBits(EVerseInputButton::LeanLeft);+ if (Intent.Lean > 0) B |= MaskBits(EVerseInputButton::LeanRight);+ if (Intent.bGadgetA) B |= MaskBits(EVerseInputButton::GadgetA);+ if (Intent.bGadgetB) B |= MaskBits(EVerseInputButton::GadgetB);+ if (Intent.bSwitchSecondary) B |= MaskBits(EVerseInputButton::SlotSecondary);+ if (Intent.bSwitchPrimary) B |= MaskBits(EVerseInputButton::SlotPrimary);+ F.Buttons = B;+ F.Pressed = B & ~PrevButtons;+ PrevButtons = B;+ return F;+}++FVerseInputFrame FVerseBotBrainCore::Think(const FVersePerceptFrame& RawFrame, IVerseBotWorldQueries& World)+{+ check(Tier);+ NowS = float(RawFrame.ServerTimeMs) / 1000.f;+ // Reaction (8.1, 5.2): from here on the brain sees a stimulus only once its reaction elapsed.+ const FVersePerceptFrame& Frame = GateStimuli(RawFrame);+ const float Dt = LastThinkS < 0.f ? 1.f / 60.f : FMath::Max(NowS - LastThinkS, 0.f);+ LastThinkS = NowS;+ WorldThisTick = &World;+ FrameThisTick = &Frame;+ if (!bSpawnsFetched)+ {+ World.GetSpawnPoints(Spawns);+ bSpawnsFetched = true;+ }++ const bool bAlive = Frame.Self.Phase == EVerseCombatPhase::Alive || Frame.Self.Phase == EVerseCombatPhase::FinisherAttacker;+ if (!bAlive)+ {+ if (bWasAlive)+ {+ OnOwnDeath();+ }+ bWasAlive = false;+ PrevButtons = 0;+ FVerseInputFrame Idle;+ Idle.ServerTimeMs = Frame.ServerTimeMs;+ return Idle;+ }+ if (!bWasAlive)+ {+ if (DecisionIndex > 0)+ {+ OnOwnRespawn();+ }+ bWasAlive = true;+ }++ // Percepts of this frame.+ const FVerseSightPercept* Sight = FirstVisible(Frame);+ bSightingThisTick = Sight != nullptr;+ if (Sight)+ {+ SightingThisTick = *Sight;+ }+ if (Frame.Heard.Num() > 0)+ {+ LastHeard = Frame.Heard.Last();+ LastHeardS = NowS;+ }++ // Belief: 10 Hz, at once on a positive percept.+ const bool bPositive = Sight || Frame.Heard.Num() > 0 || Frame.bHasHurt || Frame.Bolts.Num() > 0 || Frame.Hud.Num() > 0;+ if (bPositive || NowS >= NextBeliefStepS)+ {+ Belief->Step(Frame, NowS - LastBeliefStepS, Memory->IsEnabled() ? Memory : nullptr, Spawns);+ LastBeliefStepS = NowS;+ NextBeliefStepS = NowS + BeliefStepS;+ }+ BeliefSummary = Belief->Summary();++ BuildContext(Frame, World);+ UpdateLearning(Frame);++ float Bonus[VerseBot::NumStates] = {};+ const bool bForce = ForcedTriggers(Frame, Bonus);+ if (bForce || NowS >= NextDecisionS)+ {+ Decide(bForce, Bonus);+ }+ else+ {+ RunScheduledQuery();+ }++ FVerseBotIntent Intent = VerseBotTactics::Tick(Selector.Current(), Ctx, TacticsMem, TacticsRng);+ UpdatePrefire(Intent);+ if (TacticsMem.bBreachPlanted && NowS - TacticsMem.BreachPlantedS >= 2.5f && Belief->GetPieceBelief(TacticsMem.BreachPiece) == EVersePieceState::Intact)+ {+ // Own action (destruction 6.2): the bot knows its own charge went off.+ Belief->NoteOwnPieceChange(TacticsMem.BreachPiece, EVersePieceState::Breached);+ }+ Reflexes(Intent);++ // Aim.+ FVerseBotAimRequest AimReq;+ AimReq.bHasTarget = Intent.bHasLookTarget;+ AimReq.TargetPoint = Intent.LookTarget;+ AimReq.bNewTarget = bSightingThisTick && !bHadSighting;+ // The reaction was spent in the gate above; the aim starts at once.+ AimReq.ReactionRemainingS = 0.f;+ const float TargetDist = FMath::Max(float(FVector::Dist(Intent.LookTarget, Frame.Self.EyeLocation)), 100.f);+ AimReq.TargetHalfWidthDeg = FMath::RadiansToDegrees(FMath::Atan(25.f / TargetDist));+ const FVerseBotAimResult AimResult = Aim->Step(Frame.Self, AimReq, Dt);+ ApplyFireGate(Intent, AimResult);++ // Health: stuck events.+ if (Intent.bHasMoveTarget && Path.bValid && FVector::Dist2D(Intent.MoveTarget, Frame.Self.Location) > StuckTargetMinCm)+ {+ if (FVector::Dist2D(Frame.Self.Location, StuckRef) > StuckMinMoveCm)+ {+ StuckRef = Frame.Self.Location;+ StuckSinceS = NowS;+ bStuckCounted = false;+ bStuckReplanned = false;+ }+ else+ {+ if (NowS - StuckSinceS > StuckReplanS && !bStuckReplanned)+ {+ // No progress: drop the move targets and re-plan on the next tick (6.1 path invalidation).+ bStuckReplanned = true;+ TacticsMem.bHasSearchTarget = false;+ TacticsMem.bHasFlankPoint = false;+ PathTarget = FVector(1.0e9);+ NextDecisionS = NowS;+ }+ if (NowS - StuckSinceS > StuckWindowS && !bStuckCounted)+ {+ ++StuckEvents;+ ++StuckByState[int32(Selector.Current())];+ bStuckCounted = true;+ }+ }+ }+ else+ {+ StuckRef = Frame.Self.Location;+ StuckSinceS = NowS;+ bStuckReplanned = false;+ }++ if (Sight)+ {+ LastSightingS = NowS;+ LastSeenLocation = Sight->PelvisLocation;+ LastSightPerceptId = Sight->PerceptId;+ }+ bHadSighting = bSightingThisTick;+ return ToInput(Intent, AimResult, Frame.ServerTimeMs);+}diff --git a/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotReplay.cpp b/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotReplay.cppnew file mode 100644index 0000000000..13f23cf120--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotReplay.cpp@@ -0,0 +1,362 @@+#include "Brain/VerseBotReplay.h"++#include <type_traits>++namespace+{+ enum class ECall : uint8+ {+ TestSight = 1,+ TraceBolt,+ FindPath,+ GetCoverPoints,+ GetPieces,+ GetSpawnPoints,+ GetZoneId,+ GetOwnWeapon,+ CanActivateFinisher+ };++ template <typename T>+ void Put(TArray<uint8>& Out, const T& Value)+ {+ static_assert(std::is_trivially_copyable_v<T>, "plain values only");+ const int32 At = Out.AddUninitialized(sizeof(T));+ FMemory::Memcpy(Out.GetData() + At, &Value, sizeof(T));+ }++ void PutVector(TArray<uint8>& Out, const FVector& V)+ {+ Put(Out, V.X);+ Put(Out, V.Y);+ Put(Out, V.Z);+ }++ uint32 HashVector(uint32 H, const FVector& V)+ {+ H = HashCombineFast(H, GetTypeHash(V.X));+ H = HashCombineFast(H, GetTypeHash(V.Y));+ return HashCombineFast(H, GetTypeHash(V.Z));+ }++ uint32 HashWeapon(uint32 H, const FVerseBotWeaponInfo& W)+ {+ H = HashCombineFast(H, GetTypeHash(W.Damage));+ H = HashCombineFast(H, GetTypeHash(W.PenetrationPower));+ H = HashCombineFast(H, GetTypeHash(W.MagazineSize));+ return HashCombineFast(H, GetTypeHash(W.HoleRadiusMm));+ }++ void Begin(TArray<uint8>& Tape, ECall Call, uint32 ArgHash)+ {+ Put(Tape, uint8(Call));+ Put(Tape, ArgHash);+ }++ void PutCover(TArray<uint8>& Out, const FVerseBotCoverPoint& C)+ {+ Put(Out, C.Id);+ PutVector(Out, C.Location);+ Put(Out, uint8(C.bHigh));+ Put(Out, uint8(C.bBulwarkSpot));+ Put(Out, C.EdgeId);+ PutVector(Out, C.Facing);+ Put(Out, C.MaterialProtection);+ Put(Out, int32(C.DependsOnPieces.Num()));+ for (uint16 P : C.DependsOnPieces)+ {+ Put(Out, P);+ }+ }++ void PutPiece(TArray<uint8>& Out, const FVerseBotPieceInfo& P)+ {+ Put(Out, P.PieceIndex);+ PutVector(Out, P.Center);+ PutVector(Out, P.Normal);+ Put(Out, uint8(P.bBreachable));+ Put(Out, uint8(P.bPenetrable));+ }+}++void FVerseBotTape::AppendOutput(TArray<uint8>& Out, const FVerseInputFrame& Frame)+{+ Put(Out, Frame.Move.X);+ Put(Out, Frame.Move.Y);+ Put(Out, Frame.LookDeltaDeg.X);+ Put(Out, Frame.LookDeltaDeg.Y);+ Put(Out, Frame.Buttons);+ Put(Out, Frame.Pressed);+ Put(Out, Frame.ServerTimeMs);+}++// Recording++bool FVerseBotRecordingQueries::TestSight(const FVector& Eye, const FVector& Target)+{+ const bool R = Inner.TestSight(Eye, Target);+ Begin(Tape, ECall::TestSight, HashVector(HashVector(0, Eye), Target));+ Put(Tape, uint8(R));+ return R;+}++FVerseBotBoltTrace FVerseBotRecordingQueries::TraceBolt(const FVector& Origin, const FVector& Target, const FVerseBotWeaponInfo& Weapon)+{+ const FVerseBotBoltTrace R = Inner.TraceBolt(Origin, Target, Weapon);+ Begin(Tape, ECall::TraceBolt, HashWeapon(HashVector(HashVector(0, Origin), Target), Weapon));+ Put(Tape, R.DamageFrac);+ Put(Tape, R.Pieces);+ return R;+}++FVerseBotPath FVerseBotRecordingQueries::FindPath(const FVector& From, const FVector& To, bool bCrouch)+{+ const FVerseBotPath R = Inner.FindPath(From, To, bCrouch);+ Begin(Tape, ECall::FindPath, HashCombineFast(HashVector(HashVector(0, From), To), uint32(bCrouch)));+ Put(Tape, uint8(R.bValid));+ Put(Tape, R.LengthCm);+ Put(Tape, int32(R.Waypoints.Num()));+ for (const FVector& W : R.Waypoints)+ {+ PutVector(Tape, W);+ }+ return R;+}++void FVerseBotRecordingQueries::GetCoverPoints(const FVector& Center, float RadiusCm, TArray<FVerseBotCoverPoint>& Out)+{+ Inner.GetCoverPoints(Center, RadiusCm, Out);+ Begin(Tape, ECall::GetCoverPoints, HashCombineFast(HashVector(0, Center), GetTypeHash(RadiusCm)));+ Put(Tape, int32(Out.Num()));+ for (const FVerseBotCoverPoint& C : Out)+ {+ PutCover(Tape, C);+ }+}++void FVerseBotRecordingQueries::GetPieces(const FVector& Center, float RadiusCm, TArray<FVerseBotPieceInfo>& Out)+{+ Inner.GetPieces(Center, RadiusCm, Out);+ Begin(Tape, ECall::GetPieces, HashCombineFast(HashVector(0, Center), GetTypeHash(RadiusCm)));+ Put(Tape, int32(Out.Num()));+ for (const FVerseBotPieceInfo& P : Out)+ {+ PutPiece(Tape, P);+ }+}++void FVerseBotRecordingQueries::GetSpawnPoints(TArray<FVector>& Out)+{+ Inner.GetSpawnPoints(Out);+ Begin(Tape, ECall::GetSpawnPoints, 0);+ Put(Tape, int32(Out.Num()));+ for (const FVector& S : Out)+ {+ PutVector(Tape, S);+ }+}++int32 FVerseBotRecordingQueries::GetZoneId(const FVector& Location)+{+ const int32 R = Inner.GetZoneId(Location);+ Begin(Tape, ECall::GetZoneId, HashVector(0, Location));+ Put(Tape, R);+ return R;+}++FVerseBotWeaponInfo FVerseBotRecordingQueries::GetOwnWeapon()+{+ const FVerseBotWeaponInfo R = Inner.GetOwnWeapon();+ Begin(Tape, ECall::GetOwnWeapon, 0);+ Put(Tape, R.Damage);+ Put(Tape, R.PenetrationPower);+ Put(Tape, R.MagazineSize);+ Put(Tape, R.HoleRadiusMm);+ return R;+}++bool FVerseBotRecordingQueries::CanActivateFinisher()+{+ const bool R = Inner.CanActivateFinisher();+ Begin(Tape, ECall::CanActivateFinisher, 0);+ Put(Tape, uint8(R));+ return R;+}++// Replay++template <typename T>+T FVerseBotReplayQueries::Read()+{+ T Value{};+ if (bDiverged || Offset + int32(sizeof(T)) > Tape.Num())+ {+ bDiverged = true;+ return Value;+ }+ FMemory::Memcpy(&Value, Tape.GetData() + Offset, sizeof(T));+ Offset += sizeof(T);+ return Value;+}++bool FVerseBotReplayQueries::Begin(uint8 CallId, uint32 ArgHash)+{+ if (bDiverged)+ {+ return false;+ }+ const uint8 Id = Read<uint8>();+ const uint32 Hash = Read<uint32>();+ if (bDiverged || Id != CallId || Hash != ArgHash)+ {+ bDiverged = true;+ return false;+ }+ ++Calls;+ return true;+}++bool FVerseBotReplayQueries::TestSight(const FVector& Eye, const FVector& Target)+{+ if (!Begin(uint8(ECall::TestSight), HashVector(HashVector(0, Eye), Target)))+ {+ return false;+ }+ return Read<uint8>() != 0;+}++FVerseBotBoltTrace FVerseBotReplayQueries::TraceBolt(const FVector& Origin, const FVector& Target, const FVerseBotWeaponInfo& Weapon)+{+ FVerseBotBoltTrace R;+ if (!Begin(uint8(ECall::TraceBolt), HashWeapon(HashVector(HashVector(0, Origin), Target), Weapon)))+ {+ return R;+ }+ R.DamageFrac = Read<float>();+ R.Pieces = Read<int32>();+ return R;+}++FVerseBotPath FVerseBotReplayQueries::FindPath(const FVector& From, const FVector& To, bool bCrouch)+{+ FVerseBotPath R;+ if (!Begin(uint8(ECall::FindPath), HashCombineFast(HashVector(HashVector(0, From), To), uint32(bCrouch))))+ {+ return R;+ }+ R.bValid = Read<uint8>() != 0;+ R.LengthCm = Read<float>();+ const int32 N = Read<int32>();+ for (int32 i = 0; i < N && !bDiverged; ++i)+ {+ const double X = Read<double>(), Y = Read<double>(), Z = Read<double>();+ R.Waypoints.Add(FVector(X, Y, Z));+ }+ return R;+}++void FVerseBotReplayQueries::GetCoverPoints(const FVector& Center, float RadiusCm, TArray<FVerseBotCoverPoint>& Out)+{+ Out.Reset();+ if (!Begin(uint8(ECall::GetCoverPoints), HashCombineFast(HashVector(0, Center), GetTypeHash(RadiusCm))))+ {+ return;+ }+ const int32 N = Read<int32>();+ for (int32 i = 0; i < N && !bDiverged; ++i)+ {+ FVerseBotCoverPoint C;+ C.Id = Read<int32>();+ {+ const double X = Read<double>(), Y = Read<double>(), Z = Read<double>();+ C.Location = FVector(X, Y, Z);+ }+ C.bHigh = Read<uint8>() != 0;+ C.bBulwarkSpot = Read<uint8>() != 0;+ C.EdgeId = Read<int32>();+ {+ const double X = Read<double>(), Y = Read<double>(), Z = Read<double>();+ C.Facing = FVector(X, Y, Z);+ }+ C.MaterialProtection = Read<float>();+ const int32 D = Read<int32>();+ for (int32 j = 0; j < D && !bDiverged; ++j)+ {+ C.DependsOnPieces.Add(Read<uint16>());+ }+ Out.Add(C);+ }+}++void FVerseBotReplayQueries::GetPieces(const FVector& Center, float RadiusCm, TArray<FVerseBotPieceInfo>& Out)+{+ Out.Reset();+ if (!Begin(uint8(ECall::GetPieces), HashCombineFast(HashVector(0, Center), GetTypeHash(RadiusCm))))+ {+ return;+ }+ const int32 N = Read<int32>();+ for (int32 i = 0; i < N && !bDiverged; ++i)+ {+ FVerseBotPieceInfo P;+ P.PieceIndex = Read<uint16>();+ {+ const double X = Read<double>(), Y = Read<double>(), Z = Read<double>();+ P.Center = FVector(X, Y, Z);+ }+ {+ const double X = Read<double>(), Y = Read<double>(), Z = Read<double>();+ P.Normal = FVector(X, Y, Z);+ }+ P.bBreachable = Read<uint8>() != 0;+ P.bPenetrable = Read<uint8>() != 0;+ Out.Add(P);+ }+}++void FVerseBotReplayQueries::GetSpawnPoints(TArray<FVector>& Out)+{+ Out.Reset();+ if (!Begin(uint8(ECall::GetSpawnPoints), 0))+ {+ return;+ }+ const int32 N = Read<int32>();+ for (int32 i = 0; i < N && !bDiverged; ++i)+ {+ const double X = Read<double>(), Y = Read<double>(), Z = Read<double>();+ Out.Add(FVector(X, Y, Z));+ }+}++int32 FVerseBotReplayQueries::GetZoneId(const FVector& Location)+{+ if (!Begin(uint8(ECall::GetZoneId), HashVector(0, Location)))+ {+ return INDEX_NONE;+ }+ return Read<int32>();+}++FVerseBotWeaponInfo FVerseBotReplayQueries::GetOwnWeapon()+{+ FVerseBotWeaponInfo R;+ if (!Begin(uint8(ECall::GetOwnWeapon), 0))+ {+ return R;+ }+ R.Damage = Read<float>();+ R.PenetrationPower = Read<float>();+ R.MagazineSize = Read<int32>();+ R.HoleRadiusMm = Read<uint8>();+ return R;+}++bool FVerseBotReplayQueries::CanActivateFinisher()+{+ if (!Begin(uint8(ECall::CanActivateFinisher), 0))+ {+ return false;+ }+ return Read<uint8>() != 0;+}diff --git a/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotTypes.cpp b/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotTypes.cppnew file mode 100644index 0000000000..5086262b3a--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotTypes.cpp@@ -0,0 +1,37 @@+#include "Brain/VerseBotTypes.h"++#include "VerseGameplayTags.h"+#include "VerseRng.h"++double VerseBot::Jitter(FVerseRng& Rng, double Min, double Max)+{+ return Rng.Range(Min, Max);+}++namespace VerseBot+{+ FGameplayTag StateTag(EVerseBotState State)+ {+ const TConstArrayView<FGameplayTag> Tags = VerseTags::AllBotStateTags();+ const int32 Index = int32(State);+ return Tags.IsValidIndex(Index) ? Tags[Index] : FGameplayTag();+ }++ const TCHAR* StateName(EVerseBotState State)+ {+ switch (State)+ {+ case EVerseBotState::Attack: return TEXT("attack");+ case EVerseBotState::Hold: return TEXT("hold");+ case EVerseBotState::Flank: return TEXT("flank");+ case EVerseBotState::StalkForFinisher: return TEXT("stalk_for_finisher");+ case EVerseBotState::Retreat: return TEXT("retreat");+ case EVerseBotState::Reload: return TEXT("reload");+ case EVerseBotState::DeployBulwark: return TEXT("deploy_bulwark");+ case EVerseBotState::Breach: return TEXT("breach");+ case EVerseBotState::Wallbang: return TEXT("wallbang");+ case EVerseBotState::Search: return TEXT("search");+ }+ return TEXT("unknown");+ }+}diff --git a/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotUtility.cpp b/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotUtility.cppnew file mode 100644index 0000000000..964605fb9b--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Brain/VerseBotUtility.cpp@@ -0,0 +1,54 @@+#include "Brain/VerseBotUtility.h"++void FVerseBotUtilitySelector::Reset(EVerseBotState Start, float NowS)+{+ CurrentState = Start;+ EnteredAtS = NowS;+}++void FVerseBotUtilitySelector::Force(EVerseBotState State, float NowS)+{+ CurrentState = State;+ EnteredAtS = NowS;+}++FVerseBotUtilitySelector::FDecision FVerseBotUtilitySelector::Decide(const float (&Utilities)[VerseBot::NumStates],+ const float (&Bonus)[VerseBot::NumStates], float UtilityNoise, bool bInterrupt, float NowS, FVerseRng& Rng)+{+ FDecision D;+ const int32 Cur = int32(CurrentState);+ int32 Best = -1;+ float BestScore = -1.0e9f;+ for (int32 i = 0; i < VerseBot::NumStates; ++i)+ {+ // One draw per state per decision, always, so the stream does not depend on which states run.+ const float Noise = float(Rng.Range(0.0, FMath::Max(UtilityNoise, 0.f)));+ if (Utilities[i] < 0.f)+ {+ D.Scores[i] = -1.0e9f;+ continue;+ }+ const float Score = Utilities[i] + Noise + Bonus[i] + (i == Cur ? Hysteresis : 0.f);+ D.Scores[i] = Score;+ if (Score > BestScore)+ {+ BestScore = Score;+ Best = i;+ }+ }+ const bool bDwelling = (NowS - EnteredAtS) < MinDwellS && !bInterrupt;+ const bool bCurrentRunnable = Utilities[Cur] >= 0.f;+ if (Best < 0 || (bDwelling && bCurrentRunnable))+ {+ D.State = CurrentState;+ return D;+ }+ D.State = EVerseBotState(Best);+ D.bChanged = D.State != CurrentState;+ if (D.bChanged)+ {+ CurrentState = D.State;+ EnteredAtS = NowS;+ }+ return D;+}diff --git a/unreal/Verse/Source/VerseBot/Private/Controller/VerseBotController.cpp b/unreal/Verse/Source/VerseBot/Private/Controller/VerseBotController.cppnew file mode 100644index 0000000000..9023c0dd38--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Controller/VerseBotController.cpp@@ -0,0 +1,307 @@+#include "Controller/VerseBotController.h"++#include "Bot/VerseBotAdaptiveConfig.h"+#include "Bot/VerseBotTier.h"+#include "Brain/VerseBotBrainCore.h"+#include "Controller/VerseBotEngineQueries.h"+#include "Engine/World.h"+#include "GameFramework/GameStateBase.h"+#include "GameFramework/Pawn.h"+#include "GameFramework/PlayerState.h"+#include "Kismet/GameplayStatics.h"+#include "Learning/VerseBotMatchMemory.h"+#include "UObject/UnrealType.h"+#include "VerseLog.h"++namespace+{+ const FName BotTierField(TEXT("BotTier"));+ const FName BotSkillField(TEXT("BotEffectiveSkill"));++ float SkillOf(FName TierId)+ {+ if (TierId == TEXT("elite")) return 1.f;+ if (TierId == TEXT("hard")) return 0.5f;+ return 0.f;+ }+}++AVerseBotController::AVerseBotController()+{+ PrimaryActorTick.bCanEverTick = true;+ PrimaryActorTick.bStartWithTickEnabled = true;+}++AVerseBotController::~AVerseBotController() = default;++FName AVerseBotController::ParseBotTierOption(const FString& Options)+{+ const FString Value = UGameplayStatics::ParseOption(Options, TEXT("BotTier")).ToLower();+ if (Value == TEXT("normal") || Value == TEXT("hard") || Value == TEXT("elite") || Value == TEXT("adaptive"))+ {+ return FName(*Value);+ }+ return NAME_None;+}++bool AVerseBotController::WriteBotIdentity(const UStruct* Type, void* Container, FName InTier, float InSkill)+{+ if (!Type || !Container)+ {+ return false;+ }+ FNameProperty* TierProp = FindFProperty<FNameProperty>(Type, BotTierField);+ FFloatProperty* SkillProp = FindFProperty<FFloatProperty>(Type, BotSkillField);+ if (!TierProp || !SkillProp)+ {+ return false;+ }+ TierProp->SetPropertyValue_InContainer(Container, InTier);+ SkillProp->SetPropertyValue_InContainer(Container, InSkill);+ return true;+}++void AVerseBotController::EnsureBrain()+{+ if (!MatchMemory)+ {+ MatchMemory = NewObject<UVerseBotMatchMemory>(this);+ }+ if (!DefaultQueries)+ {+ DefaultQueries = MakeUnique<FVerseBotEngineQueries>(*this);+ }+ if (!Brain)+ {+ Brain = MakeUnique<FVerseBotBrainCore>();+ Brain->UseMemory(MatchMemory->Get());+ }+}++const UVerseBotTier* AVerseBotController::EffectiveTier()+{+ if (!Tier)+ {+ // Default: the hard tier's start values (README: the bot is much stronger than a person).+ UVerseBotTier* Hard = NewObject<UVerseBotTier>(this);+ UVerseBotTier::ApplyStartValues(TEXT("hard"), *Hard);+ Tier = Hard;+ }+ if (!bAdaptive)+ {+ return Tier;+ }+ // Adaptive: interpolate normal / hard / elite at s (9.2).+ UVerseBotTier* Normal = NewObject<UVerseBotTier>(this);+ UVerseBotTier* Hard = NewObject<UVerseBotTier>(this);+ UVerseBotTier* Elite = NewObject<UVerseBotTier>(this);+ UVerseBotTier::ApplyStartValues(TEXT("normal"), *Normal);+ UVerseBotTier::ApplyStartValues(TEXT("hard"), *Hard);+ UVerseBotTier::ApplyStartValues(TEXT("elite"), *Elite);+ if (!InterpolatedTier)+ {+ InterpolatedTier = NewObject<UVerseBotTier>(this);+ }+ UVerseBotAdaptiveConfig::InterpolateTier(*Normal, *Hard, *Elite, EffectiveSkill, *InterpolatedTier);+ return InterpolatedTier;+}++void AVerseBotController::SetTier(const UVerseBotTier* InTier)+{+ const bool bChanged = InTier != Tier;+ Tier = InTier;+ if (!bAdaptive && Tier)+ {+ EffectiveSkill = SkillOf(Tier->TierId);+ }+ if (bChanged)+ {+ ResetMatch();+ }+ WriteIdentity();+}++void AVerseBotController::SetAdaptive(bool bInAdaptive)+{+ if (bInAdaptive == bAdaptive)+ {+ return;+ }+ bAdaptive = bInAdaptive;+ if (bAdaptive)+ {+ EffectiveSkill = GetDefault<UVerseBotAdaptiveConfig>()->StartSkill;+ }+ else if (Tier)+ {+ EffectiveSkill = SkillOf(Tier->TierId);+ }+ ResetMatch();+ WriteIdentity();+}++void AVerseBotController::SetPendingSkill(float S)+{+ PendingSkill = FMath::Clamp(S, 0.f, 1.f);+}++FVerseBotPresentation AVerseBotController::GetPresentation() const+{+ return Brain ? Brain->GetPresentation() : FVerseBotPresentation();+}++void AVerseBotController::ReceivePerceptFrame(const FVersePerceptFrame& Frame)+{+ PendingFrame = Frame;+ bHasFrame = true;+ LastRealFrame = Frame;+ bHasRealFrame = true;+}++void AVerseBotController::ResetMatch()+{+ EnsureBrain();+ const UVerseBotTier* T = EffectiveTier();+ FVerseBotBrainCore::FConfig Config;+ Seed = FixedSeed != 0 ? FixedSeed : FVerseRng::Mix(uint64(GetUniqueID()) ^ (uint64(FPlatformTime::Cycles64()) << 1));+ Config.Seed = Seed;+ Config.SelfId = PlayerState ? PlayerState->GetPlayerId() : 0;+ MatchMemory->ResetMatch();+ Brain->Init(*T, Config);+ Brain->UseMemory(MatchMemory->Get());+ bBrainReady = true;+}++uint32 AVerseBotController::WorldServerTimeMs() const+{+ const UWorld* World = GetWorld();+ if (!World)+ {+ return LastThinkMs;+ }+ const AGameStateBase* GameState = World->GetGameState();+ const double Seconds = GameState ? GameState->GetServerWorldTimeSeconds() : World->GetTimeSeconds();+ return uint32(FMath::Max(Seconds, 0.0) * 1000.0);+}++FVersePerceptFrame AVerseBotController::SelfRefreshedFrame(uint32 ServerTimeMs) const+{+ // The own HUD of the last service frame (3.3) with the own pose refreshed; no percepts, so+ // nothing new about the opponent and no stimulus is replayed.+ FVersePerceptFrame F;+ F.ServerTimeMs = ServerTimeMs;+ F.Self = LastRealFrame.Self;+ if (const APawn* P = GetPawn())+ {+ F.Self.Location = P->GetActorLocation();+ F.Self.Velocity = P->GetVelocity();+ F.Self.EyeLocation = P->GetPawnViewLocation();+ F.Self.ViewRotation = GetControlRotation();+ }+ else+ {+ F.Self.Phase = EVerseCombatPhase::Dead;+ }+ return F;+}++void AVerseBotController::ApplyInput(const FVerseInputFrame& Frame)+{+ LastInput = Frame;+ FRotator Control = GetControlRotation();+ Control.Pitch = FMath::ClampAngle(Control.Pitch + Frame.LookDeltaDeg.X, -89.f, 89.f);+ Control.Yaw = FRotator::NormalizeAxis(Control.Yaw + Frame.LookDeltaDeg.Y);+ SetControlRotation(Control);+ if (APawn* P = GetPawn())+ {+ const FRotator YawOnly(0.f, Control.Yaw, 0.f);+ const FVector Forward = YawOnly.Vector();+ const FVector Right = FRotationMatrix(YawOnly).GetUnitAxis(EAxis::Y);+ P->AddMovementInput(Forward, Frame.Move.X);+ P->AddMovementInput(Right, Frame.Move.Y);+ }+ OnInputFrame.Broadcast(Frame);+}++void AVerseBotController::WriteIdentity()+{+ if (!PlayerState)+ {+ return;+ }+ const FName TierName = bAdaptive ? FName(TEXT("adaptive")) : (Tier ? Tier->TierId : FName(TEXT("hard")));+ WriteBotIdentity(PlayerState->GetClass(), PlayerState, TierName, EffectiveSkill);+}++void AVerseBotController::PostInitializeComponents()+{+ Super::PostInitializeComponents();+ // A bot is a player: it gets an ordinary player state on the server (B1).+ if (HasAuthority() && GetWorld() && GetWorld()->IsGameWorld() && !PlayerState)+ {+ InitPlayerState();+ }+}++void AVerseBotController::OnPossess(APawn* InPawn)+{+ Super::OnPossess(InPawn);+ if (!bBrainReady)+ {+ ResetMatch();+ }+ // Adaptive s is applied at the bot's respawn only (9.2).+ if (bAdaptive && PendingSkill >= 0.f && Brain)+ {+ EffectiveSkill = PendingSkill;+ PendingSkill = -1.f;+ Brain->SetTier(*EffectiveTier());+ }+ WriteIdentity();+}++void AVerseBotController::OnUnPossess()+{+ Super::OnUnPossess();+}++void AVerseBotController::EndPlay(const EEndPlayReason::Type Reason)+{+ // Verse.exe exit or level change: the match memory is dropped (7.3, B8).+ if (MatchMemory)+ {+ MatchMemory->ResetMatch();+ }+ Brain.Reset();+ bBrainReady = false;+ Super::EndPlay(Reason);+}++void AVerseBotController::Tick(float DeltaSeconds)+{+ Super::Tick(DeltaSeconds);+ if (!HasAuthority())+ {+ return;+ }+ if (!bBrainReady)+ {+ ResetMatch();+ }+ // Without any service frame the bot has no HUD to act on (health, magazine): it waits.+ if (!bHasRealFrame)+ {+ return;+ }+ FVersePerceptFrame Frame = bHasFrame ? PendingFrame : SelfRefreshedFrame(WorldServerTimeMs());+ bHasFrame = false;+ // One monotonic clock for the brain: a frame never moves time backward.+ Frame.ServerTimeMs = FMath::Max(Frame.ServerTimeMs, LastThinkMs);+ LastThinkMs = Frame.ServerTimeMs;+ IVerseBotWorldQueries& Queries = QueriesOverride ? *QueriesOverride : *DefaultQueries;+ const FVerseInputFrame Input = Brain->Think(Frame, Queries);+ if (GetPawn())+ {+ ApplyInput(Input);+ }+}diff --git a/unreal/Verse/Source/VerseBot/Private/Controller/VerseBotEngineQueries.cpp b/unreal/Verse/Source/VerseBot/Private/Controller/VerseBotEngineQueries.cppnew file mode 100644index 0000000000..441ea83616--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Controller/VerseBotEngineQueries.cpp@@ -0,0 +1,187 @@+#include "Controller/VerseBotEngineQueries.h"++#include "CollisionQueryParams.h"+#include "Components/PrimitiveComponent.h"+#include "Engine/World.h"+#include "EngineUtils.h"+#include "GameFramework/Controller.h"+#include "GameFramework/Pawn.h"+#include "GameFramework/PlayerStart.h"+#include "VerseCollision.h"++namespace+{+ constexpr ECollisionChannel VerseSightChannel = VerseCollision::Sight;+}++bool FVerseBotEngineQueries::SegmentHitsBox(const FBox& Box, const FVector& From, const FVector& To)+{+ if (!Box.IsValid)+ {+ return false;+ }+ if (Box.IsInside(From) || Box.IsInside(To))+ {+ return true;+ }+ const FVector Delta = To - From;+ if (Delta.IsNearlyZero())+ {+ return false;+ }+ return FMath::LineBoxIntersection(Box, From, To, Delta);+}++void FVerseBotEngineQueries::CachePieceBounds(UWorld& World)+{+ if (CachedWorld.Get() == &World)+ {+ return;+ }+ CachedWorld = &World;+ PieceBounds.Reset();+ GlassBounds.Reset();+ // Static arena geometry only: pawns are skipped outright (F1), pieces are found by profile.+ for (TActorIterator<AActor> It(&World); It; ++It)+ {+ if (It->IsA<APawn>())+ {+ continue;+ }+ TInlineComponentArray<UPrimitiveComponent*> Prims(*It);+ for (const UPrimitiveComponent* Prim : Prims)+ {+ const FName Profile = Prim ? Prim->GetCollisionProfileName() : NAME_None;+ if (Profile == VerseCollision::Profile::Destructible || Profile == VerseCollision::Profile::ProxyOnly)+ {+ PieceBounds.Add(Prim->Bounds.GetBox());+ }+ else if (Profile == VerseCollision::Profile::Glass)+ {+ GlassBounds.Add(Prim->Bounds.GetBox());+ }+ }+ }+}++bool FVerseBotEngineQueries::GlassCrossed(const FVector& From, const FVector& To) const+{+ for (const FBox& Box : GlassBounds)+ {+ if (SegmentHitsBox(Box, From, To))+ {+ return true;+ }+ }+ return false;+}++int32 FVerseBotEngineQueries::PiecesCrossed(const FVector& From, const FVector& To)+{+ int32 N = 0;+ for (const FBox& Box : PieceBounds)+ {+ N += SegmentHitsBox(Box, From, To) ? 1 : 0;+ }+ return N;+}++bool FVerseBotEngineQueries::TraceSight(UWorld& World, const FVector& From, const FVector& To) const+{+ // VerseSight only: pawns (own and opponent) ignore the channel, so no capsule is ever read.+ FCollisionQueryParams Params(SCENE_QUERY_STAT(VerseBotSight), false);+ FHitResult Hit;+ return World.LineTraceSingleByChannel(Hit, From, To, VerseSightChannel, Params);+}++bool FVerseBotEngineQueries::TestSight(const FVector& Eye, const FVector& Target)+{+ const AController* C = Owner.Get();+ UWorld* World = C ? C->GetWorld() : nullptr;+ if (!World)+ {+ return false;+ }+ CachePieceBounds(*World);+ // Believed-intact pieces are opaque (no piece belief yet): never the server's current proxy.+ if (PiecesCrossed(Eye, Target) > 0)+ {+ return false;+ }+ return !TraceSight(*World, Eye, Target);+}++FVerseBotBoltTrace FVerseBotEngineQueries::TraceBolt(const FVector& Origin, const FVector& Target, const FVerseBotWeaponInfo& Weapon)+{+ FVerseBotBoltTrace R;+ const AController* C = Owner.Get();+ UWorld* World = C ? C->GetWorld() : nullptr;+ if (!World)+ {+ return R;+ }+ CachePieceBounds(*World);+ // No penetration data until IVersePenetrationQuery is wired (WP05/WP06): a believed piece on the+ // line is counted and stops the bolt, so no wall shot is ever authorised by this stand-in.+ R.Pieces = PiecesCrossed(Origin, Target);+ if (R.Pieces > 0 || GlassCrossed(Origin, Target))+ {+ R.DamageFrac = 0.f;+ return R;+ }+ // Glass is handled above (it stops bolts, sight passes it); the rest blocks both alike.+ R.DamageFrac = TraceSight(*World, Origin, Target) ? 0.f : 1.f;+ return R;+}++FVerseBotPath FVerseBotEngineQueries::FindPath(const FVector& From, const FVector& To, bool bCrouch)+{+ FVerseBotPath P;+ P.bValid = true;+ P.LengthCm = float(FVector::Dist(From, To));+ P.Waypoints.Add(To);+ return P;+}++void FVerseBotEngineQueries::GetCoverPoints(const FVector& Center, float RadiusCm, TArray<FVerseBotCoverPoint>& Out)+{+ Out.Reset();+}++void FVerseBotEngineQueries::GetPieces(const FVector& Center, float RadiusCm, TArray<FVerseBotPieceInfo>& Out)+{+ Out.Reset();+}++void FVerseBotEngineQueries::GetSpawnPoints(TArray<FVector>& Out)+{+ Out.Reset();+ const AController* C = Owner.Get();+ UWorld* World = C ? C->GetWorld() : nullptr;+ if (!World)+ {+ return;+ }+ for (TActorIterator<APlayerStart> It(World); It; ++It)+ {+ Out.Add(It->GetActorLocation());+ }+ Out.Sort([](const FVector& A, const FVector& B) { return A.X != B.X ? A.X < B.X : A.Y < B.Y; });+}++int32 FVerseBotEngineQueries::GetZoneId(const FVector& Location)+{+ const int32 X = FMath::FloorToInt32(Location.X / 1000.f);+ const int32 Y = FMath::FloorToInt32(Location.Y / 1000.f);+ return (X & 0xff) | ((Y & 0xff) << 8);+}++FVerseBotWeaponInfo FVerseBotEngineQueries::GetOwnWeapon()+{+ return FVerseBotWeaponInfo();+}++bool FVerseBotEngineQueries::CanActivateFinisher()+{+ return false;+}diff --git a/unreal/Verse/Source/VerseBot/Private/Controller/VerseBotEngineQueries.h b/unreal/Verse/Source/VerseBot/Private/Controller/VerseBotEngineQueries.hnew file mode 100644index 0000000000..167192c5b8--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Controller/VerseBotEngineQueries.h@@ -0,0 +1,54 @@+#pragma once++#include "Brain/VerseBotWorldQueries.h"+#include "CoreMinimal.h"+#include "Engine/EngineTypes.h"+#include "UObject/WeakObjectPtr.h"++class UWorld;+class AController;++/**+ * The controller's default world queries until the producers land. Every answer is public map+ * knowledge or the bot's own state (bot.md 3.3):+ * - Sight and bolt traces run on the VerseSight channel only (pawns ignore it, so no opponent+ * truth) and treat every destructible piece as its believed state. Without WP06/WP07+ * piece belief that is Intact for every piece: a segment that crosses a piece's intact bounds is+ * blocked, whatever the server's current proxy shows, so a hole the bot never perceived never+ * opens a line (DR6, F7). Glass follows the channel rules (sight passes, bolts stop).+ * - No world: every line is blocked.+ * - Paths are straight lines until NavigationSystem is linked (CCR #1162); no cover or piece data+ * (WP11 arena data, WP06 pieces); spawn points from the level's player starts; zones a 10 m grid.+ */+class FVerseBotEngineQueries final : public IVerseBotWorldQueries+{+public:+ explicit FVerseBotEngineQueries(AController& InOwner) : Owner(&InOwner) {}++ virtual bool TestSight(const FVector& Eye, const FVector& Target) override;+ virtual FVerseBotBoltTrace TraceBolt(const FVector& Origin, const FVector& Target, const FVerseBotWeaponInfo& Weapon) override;+ virtual FVerseBotPath FindPath(const FVector& From, const FVector& To, bool bCrouch) override;+ virtual void GetCoverPoints(const FVector& Center, float RadiusCm, TArray<FVerseBotCoverPoint>& Out) override;+ virtual void GetPieces(const FVector& Center, float RadiusCm, TArray<FVerseBotPieceInfo>& Out) override;+ virtual void GetSpawnPoints(TArray<FVector>& Out) override;+ virtual int32 GetZoneId(const FVector& Location) override;+ virtual FVerseBotWeaponInfo GetOwnWeapon() override;+ virtual bool CanActivateFinisher() override;++ /** True when the segment crosses the box (the believed-intact piece rule). */+ static bool SegmentHitsBox(const FBox& Box, const FVector& From, const FVector& To);++private:+ /** Pieces crossed by the segment, counted against their intact bounds. */+ int32 PiecesCrossed(const FVector& From, const FVector& To);+ void CachePieceBounds(UWorld& World);+ bool GlassCrossed(const FVector& From, const FVector& To) const;+ bool TraceSight(UWorld& World, const FVector& From, const FVector& To) const;++ TWeakObjectPtr<AController> Owner;+ /** Intact bounds of every destructible piece, taken once per world before any can break. */+ TArray<FBox> PieceBounds;+ /** Glazing bounds: sight passes them on VerseSight, bolts stop. */+ TArray<FBox> GlassBounds;+ TWeakObjectPtr<UWorld> CachedWorld;+};diff --git a/unreal/Verse/Source/VerseBot/Private/Eqs/VerseBeliefNavFilter.cpp b/unreal/Verse/Source/VerseBot/Private/Eqs/VerseBeliefNavFilter.cppnew file mode 100644index 0000000000..b94b4d0133--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Eqs/VerseBeliefNavFilter.cpp@@ -0,0 +1,35 @@+#include "Eqs/VerseBeliefNavFilter.h"++#include "Bot/VerseBotTier.h"+#include "Brain/VerseBotBelief.h"++bool FVerseBeliefNavFilter::IsOpen(EVersePieceState State)+{+ return State == EVersePieceState::Breached || State == EVersePieceState::Destroyed;+}++bool FVerseBeliefNavFilter::IsUsableInState(EVerseNavPieceRelation Relation, EVersePieceState BelievedState)+{+ switch (Relation)+ {+ case EVerseNavPieceRelation::None:+ return true;+ case EVerseNavPieceRelation::OpenedBy:+ // Breach openings exist for the bot only once it believes the piece open.+ return IsOpen(BelievedState);+ case EVerseNavPieceRelation::StandsOn:+ // A catwalk believed standing is used until the bot sees it gone.+ return BelievedState != EVersePieceState::Destroyed;+ }+ return true;+}++bool FVerseBeliefNavFilter::IsUsable(EVerseNavPieceRelation Relation, uint16 PieceIndex, const IVerseBotBelief& Belief)+{+ return Relation == EVerseNavPieceRelation::None || IsUsableInState(Relation, Belief.GetPieceBelief(PieceIndex));+}++float FVerseBeliefNavFilter::LinkCost(float BaseCost, const UVerseBotTier& Tier)+{+ return BaseCost * FMath::Max(Tier.NavLinkCostMul, 0.f);+}diff --git a/unreal/Verse/Source/VerseBot/Private/Eqs/VerseBotEqs.cpp b/unreal/Verse/Source/VerseBot/Private/Eqs/VerseBotEqs.cppnew file mode 100644index 0000000000..f64ee0d0a8--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Eqs/VerseBotEqs.cpp@@ -0,0 +1,644 @@+#include "Eqs/VerseBotEqs.h"++#include "Audit/VerseBotFireAudit.h"+#include "Bot/VerseBotTier.h"+#include "Eqs/VerseBeliefNavFilter.h"+#include "Learning/VerseBotMatchMemory.h"++namespace+{+ using FLayer = FVerseBotMatchMemory::ELayer;++ /** Candidate cap per query (budget, bot.md 2: EQS 0.2 ms amortised). */+ constexpr int32 MaxCoverCandidates = 10;+ constexpr int32 MaxWallbangCandidates = 6;+ constexpr int32 MaxBreachCandidates = 6;+ /** Chest height of a believed opponent, cm above the cell. */+ constexpr float EqsChestCm = 120.f;+ /** Radius of the learned danger sample around a point, cm. */+ constexpr float LearnRadiusCm = 500.f;+ /** A peek edge counts as near TopCluster within 6 m (prefire radius, 8.4). */+ constexpr float WatchEdgeRadiusCm = 600.f;+ /** A flank point cuts the person's route within 8 m of it (7.2). */+ constexpr float RouteCutCm = 800.f;++ float LearnedWeight(const FVerseBotQueryContext& Ctx, float Samples)+ {+ return (Ctx.bIgnoreLearned || !Ctx.Memory) ? 0.f : Ctx.Memory->Weight(Samples);+ }++ /** Runs one sliced query to the end with no budget (the synchronous forms). */+ template <typename R, typename F>+ R RunToEnd(F&& RunSlice)+ {+ FVerseBotEqsSlice S;+ R Result;+ S.BeginSlice(MAX_int32);+ RunSlice(S, Result);+ return Result;+ }++ bool PieceBelievedBroken(const FVerseBotQueryContext& Ctx, uint16 Piece)+ {+ const EVersePieceState S = Ctx.BeliefMap->GetPieceBelief(Piece);+ return S == EVersePieceState::Holed || S == EVersePieceState::Breached || S == EVersePieceState::Destroyed;+ }++ /** Share of a path's waypoints the believed opponent can see (path exposure). */+ float PathExposure(const FVerseBotQueryContext& Ctx, const FVerseBotPath& Path, float EyeCm)+ {+ if (Path.Waypoints.Num() == 0)+ {+ return 0.f;+ }+ const FVector Top = Ctx.Belief->TopCenter + FVector(0, 0, VerseBotEqs::StandEyeCm);+ int32 Seen = 0;+ int32 Tested = 0;+ const int32 Step = FMath::Max(1, Path.Waypoints.Num() / 3);+ for (int32 i = 0; i < Path.Waypoints.Num(); i += Step)+ {+ ++Tested;+ Seen += Ctx.World->TestSight(Top, Path.Waypoints[i] + FVector(0, 0, EyeCm)) ? 1 : 0;+ }+ return Tested > 0 ? float(Seen) / float(Tested) : 0.f;+ }++ template <typename T, typename F>+ void SortByDistance(TArray<T>& Items, const FVector& From, F&& LocationOf)+ {+ Items.StableSort([&](const T& A, const T& B)+ { return FVector::DistSquared(LocationOf(A), From) < FVector::DistSquared(LocationOf(B), From); });+ }+}++namespace VerseBotEqs+{+ FVector BeliefTop(const FVerseBotQueryContext& Ctx)+ {+ return Ctx.Belief->TopCenter;+ }++ void BeliefCells(const FVerseBotQueryContext& Ctx, TArray<FVector>& Out)+ {+ Ctx.BeliefMap->TopCells(8, Out);+ }++ FVector BeliefFacing(const FVerseBotQueryContext& Ctx)+ {+ return FRotator(0.f, Ctx.Belief->FacingYawDeg, 0.f).Vector();+ }++ float Blend(float Base, float Learned, float W)+ {+ const float Wc = FMath::Clamp(W, 0.f, float(UVerseBotTier::LearnWeightMaxCap));+ return (1.f - Wc) * Base + Wc * Learned;+ }++ float OffFacingDeg(const FVerseBotQueryContext& Ctx, const FVector& Point)+ {+ const FVector To = (Point - Ctx.Belief->TopCenter).GetSafeNormal2D();+ const FVector Facing = BeliefFacing(Ctx);+ return FMath::RadiansToDegrees(FMath::Acos(FMath::Clamp(float(FVector::DotProduct(To, Facing)), -1.f, 1.f)));+ }++ bool HiddenFromBelief(const FVerseBotQueryContext& Ctx, const FVector& Point, TConstArrayView<FVector> Cells, bool bLowCover)+ {+ const FVector BotEye = Point + FVector(0, 0, bLowCover ? CrouchEyeCm : StandEyeCm);+ for (const FVector& Cell : Cells)+ {+ if (Ctx.World->TestSight(Cell + FVector(0, 0, StandEyeCm), BotEye)+ || Ctx.World->TestSight(Cell + FVector(0, 0, CrouchEyeCm), BotEye))+ {+ return false;+ }+ }+ return true;+ }+++ float DistToSegment2D(const FVector& Point, const FVector& A, const FVector& B)+ {+ const FVector P(Point.X, Point.Y, 0.f), A2(A.X, A.Y, 0.f), B2(B.X, B.Y, 0.f);+ return float(FMath::PointDistToSegment(P, A2, B2));+ }++ FVerseBotCoverResult Cover(const FVerseBotQueryContext& Ctx, EVerseBotCoverMode Mode)+ {+ return RunToEnd<FVerseBotCoverResult>([&](FVerseBotEqsSlice& S, FVerseBotCoverResult& R) { CoverSlice(Ctx, Mode, S, R); });+ }++ void CoverSlice(const FVerseBotQueryContext& InCtx, EVerseBotCoverMode Mode, FVerseBotEqsSlice& Slice, FVerseBotCoverResult& Result)+ {+ FVerseBotMeteredWorld Metered(*InCtx.World, Slice);+ FVerseBotQueryContext Ctx = InCtx;+ Ctx.World = &Metered;+ const FVector Self = Ctx.Self->Location;+ const FVector Top = Ctx.Belief->TopCenter;+ TArray<FVerseBotCoverPoint> Points;+ Ctx.World->GetCoverPoints(Self, CoverRadiusCm, Points);+ SortByDistance(Points, Self, [](const FVerseBotCoverPoint& P) { return P.Location; });+ TArray<FVector> Cells;+ BeliefCells(Ctx, Cells);+ // Flank (7.2): prefer points that cut the person's most used route.+ FVector RouteA = FVector::ZeroVector;+ FVector RouteB = FVector::ZeroVector;+ float RouteSamples = 0.f;+ const bool bRoute = Mode == EVerseBotCoverMode::Flank && Ctx.Memory && Ctx.Memory->MostUsedRouteSegment(RouteA, RouteB, RouteSamples);++ for (int32 i = Slice.Next; i < Points.Num(); ++i)+ {+ if (Slice.Tested >= MaxCoverCandidates)+ {+ break;+ }+ if (Slice.OutOfBudget(i))+ {+ Slice.Next = i;+ return;+ }+ const FVerseBotCoverPoint& P = Points[i];+ if (Mode == EVerseBotCoverMode::Bulwark ? !P.bBulwarkSpot : false)+ {+ continue;+ }+ bool bBroken = false;+ for (uint16 Piece : P.DependsOnPieces)+ {+ bBroken |= PieceBelievedBroken(Ctx, Piece);+ }+ if (bBroken)+ {+ continue;+ }+ ++Slice.Tested;+ const FVerseBotPath Path = Ctx.World->FindPath(Self, P.Location, false);+ if (!Path.bValid || Path.LengthCm > CoverRadiusCm)+ {+ continue;+ }+ // A Bulwark brings its own cover; every other point must hide the bot from the belief.+ if (Mode != EVerseBotCoverMode::Bulwark && !HiddenFromBelief(Ctx, P.Location, Cells, !P.bHigh))+ {+ continue;+ }+ ++Result.Candidates;+ const float DistTop = float(FVector::Dist2D(P.Location, Top));+ float Base = -0.35f * Path.LengthCm / CoverRadiusCm;+ Base -= 0.25f * PathExposure(Ctx, Path, StandEyeCm);+ switch (Mode)+ {+ case EVerseBotCoverMode::Near:+ case EVerseBotCoverMode::Bulwark:+ Base -= 0.2f * FMath::Abs(DistTop - Ctx.PreferredRangeCm) / FMath::Max(Ctx.PreferredRangeCm, 100.f);+ break;+ case EVerseBotCoverMode::Far:+ Base += 0.3f * FMath::Min(DistTop / 3000.f, 1.f);+ break;+ case EVerseBotCoverMode::Flank:+ {+ const float Off = OffFacingDeg(Ctx, P.Location);+ Base += 0.4f * FMath::Clamp(1.f - FMath::Abs(Off - 110.f) / 70.f, 0.f, 1.f);+ Base -= 0.1f * FMath::Abs(DistTop - Ctx.PreferredRangeCm) / FMath::Max(Ctx.PreferredRangeCm, 100.f);+ break;+ }+ }+ Base += 0.15f * FMath::Clamp(P.MaterialProtection, 0.f, 1.f);+ Base += P.EdgeId != INDEX_NONE ? 0.1f : 0.f;++ float Samples = 0.f;+ float Learned = Base;+ if (Ctx.Memory)+ {+ Samples = Ctx.Memory->SamplesNear(FLayer::Shooting, P.Location, LearnRadiusCm, Ctx.NowS);+ const float Danger = Ctx.Memory->HeatShare(FLayer::Shooting, P.Location, LearnRadiusCm, Ctx.NowS);+ Learned = Base - FMath::Clamp(Danger * 2.f, 0.f, 1.f);+ if (bRoute)+ {+ const float Cut = FMath::Clamp(1.f - DistToSegment2D(P.Location, RouteA, RouteB) / RouteCutCm, 0.f, 1.f);+ Learned += 0.6f * Cut;+ Samples += RouteSamples;+ }+ }+ const float Score = Blend(Base, Learned, LearnedWeight(Ctx, Samples));+ if (Score > Slice.BestScore)+ {+ Slice.BestScore = Score;+ Result.bFound = true;+ Result.Point = P;+ Result.Score = Score;+ }+ }+ Slice.Next = Points.Num();+ Slice.bDone = true;+ }++ FVerseBotPeekResult PeekCorner(const FVerseBotQueryContext& Ctx, const FVerseBotCoverPoint& From)+ {+ return RunToEnd<FVerseBotPeekResult>([&](FVerseBotEqsSlice& S, FVerseBotPeekResult& R) { PeekCornerSlice(Ctx, From, S, R); });+ }++ void PeekCornerSlice(const FVerseBotQueryContext& InCtx, const FVerseBotCoverPoint& From, FVerseBotEqsSlice& Slice, FVerseBotPeekResult& Best)+ {+ FVerseBotMeteredWorld Metered(*InCtx.World, Slice);+ FVerseBotQueryContext Ctx = InCtx;+ Ctx.World = &Metered;+ struct FCandidate+ {+ EVerseBotPeekType Type;+ float Lateral;+ float EyeCm;+ float Exposure;+ };+ const UVerseBotTier& Tier = *Ctx.Tier;+ TArray<FCandidate, TInlineAllocator<10>> Candidates;+ Candidates.Add({EVerseBotPeekType::LeanLeft, -45.f, StandEyeCm, 0.3f});+ Candidates.Add({EVerseBotPeekType::LeanRight, 45.f, StandEyeCm, 0.3f});+ if (!From.bHigh)+ {+ Candidates.Add({EVerseBotPeekType::CrouchRise, 0.f, StandEyeCm, 0.5f});+ }+ for (const float Step : {120.f, 200.f, 280.f})+ {+ const float Exposure = 0.6f + 0.2f * (Step - 120.f) / 80.f;+ Candidates.Add({EVerseBotPeekType::StepOut, -Step, StandEyeCm, Exposure});+ Candidates.Add({EVerseBotPeekType::StepOut, Step, StandEyeCm, Exposure});+ }+ Candidates.Add({EVerseBotPeekType::JumpPeek, 0.f, StandEyeCm + 60.f, 0.7f});++ const FVector Facing = From.Facing.GetSafeNormal2D();+ const FVector Right = FVector::CrossProduct(FVector::UpVector, Facing).GetSafeNormal();+ const FVector Top = Ctx.Belief->TopCenter + FVector(0, 0, EqsChestCm);+ const FVector ViewAxis = Ctx.Self->ViewRotation.Vector();++ int32 Repeats = 0;+ for (int32 Edge : Ctx.RecentPeekEdges)+ {+ Repeats += (Edge != INDEX_NONE && Edge == From.EdgeId) ? 1 : 0;+ }++ // Learned peek habits (7.2): the person's most used peek edge near TopCluster.+ bool bWatch = false;+ FVector Watch = FVector::ZeroVector;+ int32 WatchEdge = INDEX_NONE;+ float WatchShare = 0.f;+ float WatchSamples = 0.f;+ if (Ctx.Memory && !Ctx.bIgnoreLearned)+ {+ TArray<int32> TopEdges;+ Ctx.Memory->TopPeekEdges(2, TopEdges);+ if (TopEdges.Num() > 0)+ {+ TArray<FVerseBotCoverPoint> Near;+ Ctx.World->GetCoverPoints(Ctx.Belief->TopCenter, WatchEdgeRadiusCm, Near);+ for (int32 Edge : TopEdges)+ {+ const FVerseBotCoverPoint* P = Near.FindByPredicate([Edge](const FVerseBotCoverPoint& C) { return C.EdgeId == Edge; });+ if (P)+ {+ bWatch = true;+ Watch = P->Location + FVector(0, 0, EqsChestCm);+ WatchEdge = Edge;+ WatchShare = Ctx.Memory->PeekShare(Edge, WatchSamples);+ break;+ }+ }+ }+ }+ const float WatchW = bWatch ? LearnedWeight(Ctx, WatchSamples) : 0.f;++ for (int32 i = Slice.Next; i < Candidates.Num(); ++i)+ {+ if (Slice.OutOfBudget(i))+ {+ Slice.Next = i;+ return;+ }+ const FCandidate& C = Candidates[i];+ const FVector Stand = From.Location + Right * C.Lateral;+ const FVector Eye = Stand + FVector(0, 0, C.EyeCm);+ if (!Ctx.World->TestSight(Eye, Top))+ {+ continue;+ }+ const FVector Dir = (Top - Eye).GetSafeNormal();+ const float Angle = FMath::RadiansToDegrees(FMath::Acos(FMath::Clamp(float(FVector::DotProduct(Dir, ViewAxis)), -1.f, 1.f)));+ float Base = -0.4f * C.Exposure - 0.2f * Angle / 180.f;+ switch (C.Type)+ {+ case EVerseBotPeekType::LeanLeft:+ case EVerseBotPeekType::LeanRight:+ Base += 0.2f * Tier.LeanUse;+ break;+ case EVerseBotPeekType::CrouchRise:+ Base += 0.2f * Tier.CrouchPeekUse;+ break;+ default:+ break;+ }+ Base -= Tier.PeekRepeatPenalty * float(Repeats) / 3.f;++ float Samples = 0.f;+ float Learned = Base;+ bool bSeesWatch = false;+ if (Ctx.Memory)+ {+ // Avoid angles the person holds (they fire from there), prefer peeks onto their frequent spots.+ Samples = Ctx.Memory->SamplesNear(FLayer::Position, Ctx.Belief->TopCenter, LearnRadiusCm, Ctx.NowS)+ + Ctx.Memory->SamplesNear(FLayer::Shooting, Ctx.Belief->TopCenter, LearnRadiusCm, Ctx.NowS);+ const float Frequent = Ctx.Memory->HeatShare(FLayer::Position, Ctx.Belief->TopCenter, LearnRadiusCm, Ctx.NowS);+ const float Held = Ctx.Memory->HeatShare(FLayer::Shooting, Ctx.Belief->TopCenter, LearnRadiusCm, Ctx.NowS);+ Learned = Base + 0.5f * Frequent - 0.5f * Held * C.Exposure;+ if (bWatch)+ {+ // A peek that sees the edge the person keeps appearing at (PeekShare).+ bSeesWatch = Ctx.World->TestSight(Eye, Watch);+ Learned += bSeesWatch ? 0.8f * WatchShare : 0.f;+ Samples += WatchSamples;+ }+ }+ const float Score = Blend(Base, Learned, LearnedWeight(Ctx, Samples));+ if (Score > Slice.BestScore)+ {+ Slice.BestScore = Score;+ Best.bFound = true;+ Best.Type = C.Type;+ Best.StandPoint = Stand;+ Best.Eye = Eye;+ Best.Score = Score;+ Best.bHasWatch = bSeesWatch;+ Best.WatchPoint = bSeesWatch ? Watch : FVector::ZeroVector;+ Best.WatchEdge = bSeesWatch ? WatchEdge : INDEX_NONE;+ Best.WatchRepeekShare = bSeesWatch ? Ctx.Memory->RepeekShare(WatchEdge) : 0.f;+ Best.WatchWeight = bSeesWatch ? WatchW : 0.f;+ }+ }+ Slice.Next = Candidates.Num();+ Slice.bDone = true;+ }++ FVerseBotWallbangResult WallbangSpot(const FVerseBotQueryContext& Ctx)+ {+ return RunToEnd<FVerseBotWallbangResult>([&](FVerseBotEqsSlice& S, FVerseBotWallbangResult& R) { WallbangSpotSlice(Ctx, S, R); });+ }++ void WallbangSpotSlice(const FVerseBotQueryContext& InCtx, FVerseBotEqsSlice& Slice, FVerseBotWallbangResult& Best)+ {+ FVerseBotMeteredWorld Metered(*InCtx.World, Slice);+ FVerseBotQueryContext Ctx = InCtx;+ Ctx.World = &Metered;+ const FVerseBotBeliefSummary& B = *Ctx.Belief;+ if (B.State == EVerseBeliefState::Dead || B.bPriorOnly)+ {+ Slice.bDone = true;+ return;+ }+ const FVector Aim = B.TopCenter + FVector(0, 0, EqsChestCm);+ TArray<FVector, TInlineAllocator<8>> Spots;+ Spots.Add(Ctx.Self->Location);+ TArray<FVerseBotCoverPoint> Points;+ Ctx.World->GetCoverPoints(Ctx.Self->Location, 800.f, Points);+ SortByDistance(Points, Ctx.Self->Location, [](const FVerseBotCoverPoint& P) { return P.Location; });+ for (const FVerseBotCoverPoint& P : Points)+ {+ if (Spots.Num() >= MaxWallbangCandidates)+ {+ break;+ }+ Spots.Add(P.Location);+ }+ TArray<FVector> Cells;+ BeliefCells(Ctx, Cells);++ for (int32 i = Slice.Next; i < Spots.Num(); ++i)+ {+ if (Slice.OutOfBudget(i))+ {+ Slice.Next = i;+ return;+ }+ const FVector Spot = Spots[i];+ const FVector Eye = Spot + FVector(0, 0, StandEyeCm);+ if (Ctx.World->TestSight(Eye, Aim))+ {+ continue; // In sight: not a wall shot.+ }+ const FVerseBotBoltTrace Trace = Ctx.World->TraceBolt(Eye, Aim, Ctx.Weapon);+ if (Trace.Pieces <= 0)+ {+ continue;+ }+ FVerseBotFireEvidence E;+ E.AimPoint = Aim;+ E.bAimInTopCluster = true;+ E.TraceDamageFrac = Trace.DamageFrac;+ E.TracePieces = Trace.Pieces;+ E.MassAtAim = Ctx.BeliefMap->MassWithin(Aim, FVerseBotFireClassifier::MassRadiusCm);+ E.SupportedMassAtAim = Ctx.BeliefMap->SupportedMassWithin(Aim, FVerseBotFireClassifier::MassRadiusCm);+ E.SupportAgeS = B.SupportAgeS;+ E.bPriorOnly = B.bPriorOnly;+ if (!FVerseBotFireClassifier::HasWallShotAuthority(E, *Ctx.Tier))+ {+ continue;+ }+ const bool bHidden = HiddenFromBelief(Ctx, Spot, Cells, false);+ const float Score = E.SupportedMassAtAim + 0.5f * Trace.DamageFrac - (bHidden ? 0.f : 0.3f)+ - 0.1f * float(FVector::Dist(Spot, Ctx.Self->Location)) / 800.f;+ if (Score > Slice.BestScore)+ {+ Slice.BestScore = Score;+ Best.bFound = true;+ Best.FireFrom = Spot;+ Best.AimPoint = Aim;+ Best.DamageFrac = Trace.DamageFrac;+ Best.Pieces = Trace.Pieces;+ Best.Score = Score;+ }+ }+ Slice.Next = Spots.Num();+ Slice.bDone = true;+ }++ FVerseBotBreachResult BreachSpot(const FVerseBotQueryContext& Ctx)+ {+ return RunToEnd<FVerseBotBreachResult>([&](FVerseBotEqsSlice& S, FVerseBotBreachResult& R) { BreachSpotSlice(Ctx, S, R); });+ }++ void BreachSpotSlice(const FVerseBotQueryContext& InCtx, FVerseBotEqsSlice& Slice, FVerseBotBreachResult& Best)+ {+ FVerseBotMeteredWorld Metered(*InCtx.World, Slice);+ FVerseBotQueryContext Ctx = InCtx;+ Ctx.World = &Metered;+ const FVerseBotBeliefSummary& B = *Ctx.Belief;+ if (B.State == EVerseBeliefState::Dead)+ {+ Slice.bDone = true;+ return;+ }+ const FVector Self = Ctx.Self->Location;+ TArray<FVerseBotPieceInfo> Pieces;+ Ctx.World->GetPieces(Self, BreachRadiusCm, Pieces);+ SortByDistance(Pieces, Self, [](const FVerseBotPieceInfo& P) { return P.Center; });+ TArray<FVector> Cells;+ BeliefCells(Ctx, Cells);+ if (!Slice.bScratchSet)+ {+ const FVerseBotPath Direct = Ctx.World->FindPath(Self, B.TopCenter, false);+ Slice.Scratch = Direct.bValid ? Direct.LengthCm : 2.f * float(FVector::Dist(Self, B.TopCenter)) + 2000.f;+ Slice.bScratchSet = true;+ }+ const float DirectLen = Slice.Scratch;++ TPair<int32, int32> Route(INDEX_NONE, INDEX_NONE);+ if (Ctx.Memory)+ {+ Route = Ctx.Memory->MostUsedRoute();+ }++ for (int32 i = Slice.Next; i < Pieces.Num(); ++i)+ {+ if (Slice.OutOfBudget(i))+ {+ Slice.Next = i;+ return;+ }+ const FVerseBotPieceInfo& P = Pieces[i];+ if (!P.bBreachable || Ctx.BeliefMap->GetPieceBelief(P.PieceIndex) != EVersePieceState::Intact)+ {+ continue;+ }+ if (++Slice.Tested > MaxBreachCandidates)+ {+ break;+ }+ const FVector N = P.Normal.GetSafeNormal2D();+ const float Side = FVector::DotProduct(Self - P.Center, N) >= 0.f ? 1.f : -1.f;+ const FVector Plant = P.Center + N * Side * 60.f;+ const FVector Wait = P.Center + N * Side * (BreachSelfDamageRadiusCm + 60.f);+ // The far side must face the belief, or the breach opens nothing useful.+ if (FVector::DotProduct(B.TopCenter - P.Center, N) * Side >= 0.f)+ {+ continue;+ }+ if (float(FVector::Dist(Wait, P.Center)) <= BreachSelfDamageRadiusCm)+ {+ continue;+ }+ if (!HiddenFromBelief(Ctx, Plant, Cells, false))+ {+ continue;+ }+ const FVerseBotPath ToPlant = Ctx.World->FindPath(Self, Plant, false);+ if (!ToPlant.bValid)+ {+ continue;+ }+ const float Through = ToPlant.LengthCm + float(FVector::Dist(Plant, B.TopCenter));+ const float Shortening = (DirectLen - Through) / 2000.f;+ const float Angle = OffFacingDeg(Ctx, P.Center) / 180.f;+ const float NoiseDist = float(FVector::Dist(Plant, B.TopCenter));+ const float Noise = NoiseDist < 1000.f ? 0.3f * (1.f - NoiseDist / 1000.f) : 0.f;+ const float SpreadGrowth = 450.f * BreachFuseS / 2000.f;+ const float Base = Shortening + 0.3f * Angle - Noise - 0.2f * SpreadGrowth * (1.f - B.Confidence);++ float Learned = Base;+ float Samples = 0.f;+ if (Ctx.Memory && Route.Key != INDEX_NONE)+ {+ const int32 Zone = Ctx.World->GetZoneId(P.Center);+ Samples = 6.f * Ctx.Memory->ZoneTransitionProb(Route.Key, Route.Value) + 1.f;+ Learned = Base + ((Zone == Route.Key || Zone == Route.Value) ? 0.5f : 0.f);+ }+ const float Score = Blend(Base, Learned, LearnedWeight(Ctx, Samples));+ if (Score > Slice.BestScore && Shortening > -0.5f)+ {+ Slice.BestScore = Score;+ Best.bFound = true;+ Best.PieceIndex = P.PieceIndex;+ Best.PlantPoint = Plant;+ Best.WaitPoint = Wait;+ Best.Score = Score;+ }+ }+ Slice.Next = Pieces.Num();+ Slice.bDone = true;+ }++ FVerseBotFinisherResult FinisherApproach(const FVerseBotQueryContext& Ctx)+ {+ return RunToEnd<FVerseBotFinisherResult>([&](FVerseBotEqsSlice& S, FVerseBotFinisherResult& R) { FinisherApproachSlice(Ctx, S, R); });+ }++ void FinisherApproachSlice(const FVerseBotQueryContext& InCtx, FVerseBotEqsSlice& Slice, FVerseBotFinisherResult& Best)+ {+ FVerseBotMeteredWorld Metered(*InCtx.World, Slice);+ FVerseBotQueryContext Ctx = InCtx;+ Ctx.World = &Metered;+ const FVerseBotBeliefSummary& B = *Ctx.Belief;+ const UVerseBotTier& Tier = *Ctx.Tier;+ if (B.State == EVerseBeliefState::Dead || B.Confidence < Tier.FinisherCommitConfidence)+ {+ Slice.bDone = true;+ return;+ }+ const FVector Facing = BeliefFacing(Ctx);+ const FVector TopEye = B.TopCenter + FVector(0, 0, StandEyeCm);+ const float CosCone = FMath::Cos(FMath::DegreesToRadians(BelievedViewHalfAngleDeg));+ static constexpr float RelDegs[5] = {130.f, 155.f, 180.f, 205.f, 230.f};+ for (int32 i = Slice.Next; i < 5; ++i)+ {+ if (Slice.OutOfBudget(i))+ {+ Slice.Next = i;+ return;+ }+ const FVector Dir = Facing.RotateAngleAxis(RelDegs[i], FVector::UpVector);+ const FVector Point = B.TopCenter + Dir * (FinisherRangeCm * 0.8f);+ if (OffFacingDeg(Ctx, Point) <= FinisherArcDeg)+ {+ continue;+ }+ const FVerseBotPath Path = Ctx.World->FindPath(Ctx.Self->Location, Point, true);+ if (!Path.bValid)+ {+ continue;+ }+ const float Arrival = Path.LengthCm / CrouchSpeedCmS;+ if (Arrival > Tier.MaxStalkS)+ {+ continue;+ }+ // The whole crouch path stays outside the believed view cone (or out of its sight).+ bool bExposed = false;+ int32 InCone = 0;+ for (const FVector& W : Path.Waypoints)+ {+ const FVector To = (W - B.TopCenter).GetSafeNormal2D();+ if (float(FVector::DotProduct(To, Facing)) > CosCone)+ {+ ++InCone;+ if (Ctx.World->TestSight(TopEye, W + FVector(0, 0, CrouchEyeCm)))+ {+ bExposed = true;+ break;+ }+ }+ }+ if (bExposed)+ {+ continue;+ }+ const float Score = -Path.LengthCm / 1000.f - 0.2f * float(InCone) / FMath::Max(1, Path.Waypoints.Num());+ if (Score > Slice.BestScore)+ {+ Slice.BestScore = Score;+ Best.bFound = true;+ Best.Approach = Point;+ Best.PathLengthCm = Path.LengthCm;+ Best.ArrivalS = Arrival;+ Best.Score = Score;+ }+ }+ Slice.Next = 5;+ Slice.bDone = true;+ }+}diff --git a/unreal/Verse/Source/VerseBot/Private/Learning/VerseBotMatchMemory.cpp b/unreal/Verse/Source/VerseBot/Private/Learning/VerseBotMatchMemory.cppnew file mode 100644index 0000000000..04b8d78eeb--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Learning/VerseBotMatchMemory.cpp@@ -0,0 +1,426 @@+#include "Learning/VerseBotMatchMemory.h"++#include "Bot/VerseBotTier.h"++namespace+{+ constexpr float CellCm = 100.f;+ /** Weights of 7.1: sighted 1, heard 0.3, first contact 2. */+ constexpr float SightWeight = 1.f;+ constexpr float HeardWeight = 0.3f;+ constexpr float FirstContactWeight = 2.f;+ /** Fast re-peek threshold (7.1). */+ constexpr float FastRepeekS = 3.f;+ /** Height of one arena level, cm (3 levels). */+ constexpr float MemoryLevelCm = 400.f;++ int64 RouteKey(int32 From, int32 To)+ {+ return (int64(uint32(From)) << 32) | int64(uint32(To));+ }+}++int32 FVerseBotMatchMemory::RangeBin(float RangeCm)+{+ const float M = RangeCm / VerseBot::CmPerM;+ if (M < 5.f) return 0;+ if (M < 10.f) return 1;+ if (M < 20.f) return 2;+ if (M < 35.f) return 3;+ return 4;+}++float FVerseBotMatchMemory::RangeBinCentreCm(int32 Bin)+{+ static constexpr float Centres[NumRangeBins] = {3.f, 7.5f, 15.f, 27.5f, 40.f};+ return Centres[FMath::Clamp(Bin, 0, NumRangeBins - 1)] * VerseBot::CmPerM;+}++void FVerseBotMatchMemory::Configure(const UVerseBotTier& Tier)+{+ LearnWeightMax = FMath::Min(Tier.LearnWeightMax, float(UVerseBotTier::LearnWeightMaxCap));+ LearnSamplesHalf = FMath::Max(Tier.LearnSamplesHalf, 0.001f);+ HabitHalfLifeS = FMath::Max(Tier.HabitHalfLifeS, 1.f);+}++void FVerseBotMatchMemory::Reset()+{+ for (int32 i = 0; i < 2; ++i)+ {+ Layers[i].Reset();+ LayerTotal[i] = FCell();+ }+ Peeks.Reset();+ PeekTotal = 0.f;+ for (FRangeBin& Bin : Ranges)+ {+ Bin = FRangeBin();+ }+ Routes.Reset();+ RouteOut.Reset();+ LastZone = INDEX_NONE;+ Habits.Reset();+ Centroids.Reset();+}++bool FVerseBotMatchMemory::IsEmpty() const+{+ bool bRanges = true;+ for (const FRangeBin& Bin : Ranges)+ {+ bRanges &= Bin.Engagements == 0 && Bin.NoDecision == 0;+ }+ return Layers[0].Num() == 0 && Layers[1].Num() == 0 && Peeks.Num() == 0 && Routes.Num() == 0 && Habits.Num() == 0+ && Centroids.Num() == 0+ && bRanges && LastZone == INDEX_NONE && LayerTotal[0].Value == 0.f && LayerTotal[1].Value == 0.f;+}++FIntVector FVerseBotMatchMemory::CellOf(const FVector& Location)+{+ return FIntVector(FMath::FloorToInt32(Location.X / CellCm), FMath::FloorToInt32(Location.Y / CellCm),+ FMath::FloorToInt32(Location.Z / MemoryLevelCm));+}++float FVerseBotMatchMemory::Decay(float DtS) const+{+ return DtS <= 0.f ? 1.f : FMath::Pow(0.5f, DtS / HabitHalfLifeS);+}++float FVerseBotMatchMemory::Decayed(const FCell& Cell, float NowS) const+{+ return Cell.Value * Decay(NowS - Cell.TimeS);+}++void FVerseBotMatchMemory::AddHeat(ELayer Layer, const FVector& Location, float Amount, float NowS)+{+ if (!bEnabled)+ {+ return;+ }+ FCell& C = Layers[int32(Layer)].FindOrAdd(CellOf(Location));+ C.Value = Decayed(C, NowS) + Amount;+ C.TimeS = NowS;+ FCell& T = LayerTotal[int32(Layer)];+ T.Value = Decayed(T, NowS) + Amount;+ T.TimeS = NowS;+}++void FVerseBotMatchMemory::RecordSighting(const FVector& Location, float NowS, bool bFirstContact)+{+ AddHeat(ELayer::Position, Location, bFirstContact ? FirstContactWeight : SightWeight, NowS);+}++void FVerseBotMatchMemory::RecordHeard(const FVector& Location, float NowS)+{+ AddHeat(ELayer::Position, Location, HeardWeight, NowS);+}++void FVerseBotMatchMemory::RecordShotFrom(const FVector& Location, float NowS, bool bSeen)+{+ AddHeat(ELayer::Shooting, Location, bSeen ? SightWeight : HeardWeight, NowS);+}++void FVerseBotMatchMemory::RecordPeek(int32 EdgeId, EVerseBotPeekType Type, float NowS)+{+ if (!bEnabled || EdgeId == INDEX_NONE)+ {+ return;+ }+ FPeekHabit& H = Peeks.FindOrAdd(EdgeId);+ H.Appearances += 1.f;+ H.FastRepeeks += (NowS - H.LastS) < FastRepeekS ? 1.f : 0.f;+ H.JumpPeeks += Type == EVerseBotPeekType::JumpPeek ? 1.f : 0.f;+ H.LeanPeeks += (Type == EVerseBotPeekType::LeanLeft || Type == EVerseBotPeekType::LeanRight) ? 1.f : 0.f;+ H.LastS = NowS;+ PeekTotal += 1.f;+}++void FVerseBotMatchMemory::RecordEngagementEnd(float RangeCm, bool bPersonWon)+{+ if (!bEnabled)+ {+ return;+ }+ FRangeBin& Bin = Ranges[RangeBin(RangeCm)];+ ++Bin.Engagements;+ Bin.PersonWins += bPersonWon ? 1 : 0;+}++void FVerseBotMatchMemory::RecordEngagementNoDecision(float RangeCm)+{+ if (bEnabled)+ {+ ++Ranges[RangeBin(RangeCm)].NoDecision;+ }+}++void FVerseBotMatchMemory::RecordZone(int32 ZoneId, const FVector& Location, float NowS)+{+ if (bEnabled && ZoneId != INDEX_NONE)+ {+ FZoneCentroid& C = Centroids.FindOrAdd(ZoneId);+ C.Sum += Location;+ C.Count += 1.f;+ }+ RecordZone(ZoneId, NowS);+}++void FVerseBotMatchMemory::RecordZone(int32 ZoneId, float NowS)+{+ if (!bEnabled || ZoneId == INDEX_NONE || ZoneId == LastZone)+ {+ return;+ }+ if (LastZone != INDEX_NONE)+ {+ Routes.FindOrAdd(RouteKey(LastZone, ZoneId)) += 1.f;+ RouteOut.FindOrAdd(LastZone) += 1.f;+ }+ LastZone = ZoneId;+}++void FVerseBotMatchMemory::RecordHabit(FName Habit)+{+ if (bEnabled)+ {+ ++Habits.FindOrAdd(Habit);+ }+}++float FVerseBotMatchMemory::Heat(ELayer Layer, const FVector& Location, float NowS) const+{+ const FCell* C = Layers[int32(Layer)].Find(CellOf(Location));+ return C ? Decayed(*C, NowS) : 0.f;+}++float FVerseBotMatchMemory::SamplesNear(ELayer Layer, const FVector& Location, float RadiusCm, float NowS) const+{+ const int32 R = FMath::CeilToInt32(RadiusCm / CellCm);+ const FIntVector Centre = CellOf(Location);+ const TMap<FIntVector, FCell>& Map = Layers[int32(Layer)];+ float Sum = 0.f;+ for (int32 dx = -R; dx <= R; ++dx)+ {+ for (int32 dy = -R; dy <= R; ++dy)+ {+ if (dx * dx + dy * dy > R * R)+ {+ continue;+ }+ if (const FCell* C = Map.Find(Centre + FIntVector(dx, dy, 0)))+ {+ Sum += Decayed(*C, NowS);+ }+ }+ }+ return Sum;+}++float FVerseBotMatchMemory::HeatShare(ELayer Layer, const FVector& Location, float RadiusCm, float NowS) const+{+ const float Total = Decayed(LayerTotal[int32(Layer)], NowS);+ return Total > KINDA_SMALL_NUMBER ? FMath::Clamp(SamplesNear(Layer, Location, RadiusCm, NowS) / Total, 0.f, 1.f) : 0.f;+}++float FVerseBotMatchMemory::Weight(float Samples) const+{+ if (!bEnabled || Samples <= 0.f)+ {+ return 0.f;+ }+ const float Max = FMath::Min(LearnWeightMax, float(UVerseBotTier::LearnWeightMaxCap));+ return Max * Samples / (Samples + LearnSamplesHalf);+}++float FVerseBotMatchMemory::ZoneTransitionProb(int32 FromZone, int32 ToZone) const+{+ const float* Out = RouteOut.Find(FromZone);+ const float* N = Routes.Find(RouteKey(FromZone, ToZone));+ return (Out && N && *Out > 0.f) ? *N / *Out : 0.f;+}++int32 FVerseBotMatchMemory::MostLikelyNextZone(int32 FromZone) const+{+ int32 Best = INDEX_NONE;+ float BestN = 0.f;+ for (const TPair<int64, float>& R : Routes)+ {+ const int32 From = int32(uint32(R.Key >> 32));+ const int32 To = int32(uint32(R.Key & 0xffffffff));+ if (From == FromZone && (R.Value > BestN || (R.Value == BestN && To < Best)))+ {+ Best = To;+ BestN = R.Value;+ }+ }+ return Best;+}++TPair<int32, int32> FVerseBotMatchMemory::MostUsedRoute() const+{+ TPair<int32, int32> Best(INDEX_NONE, INDEX_NONE);+ float BestN = 0.f;+ for (const TPair<int64, float>& R : Routes)+ {+ if (R.Value > BestN)+ {+ BestN = R.Value;+ Best = TPair<int32, int32>(int32(uint32(R.Key >> 32)), int32(uint32(R.Key & 0xffffffff)));+ }+ }+ return Best;+}++float FVerseBotMatchMemory::PeekShare(int32 EdgeId, float& OutSamples) const+{+ const FPeekHabit* H = Peeks.Find(EdgeId);+ OutSamples = H ? H->Appearances : 0.f;+ return (H && PeekTotal > 0.f) ? H->Appearances / PeekTotal : 0.f;+}++float FVerseBotMatchMemory::RepeekShare(int32 EdgeId) const+{+ const FPeekHabit* H = Peeks.Find(EdgeId);+ return (H && H->Appearances > 0.f) ? H->FastRepeeks / H->Appearances : 0.f;+}++void FVerseBotMatchMemory::TopPeekEdges(int32 N, TArray<int32>& Out) const+{+ Out.Reset();+ TArray<TPair<int32, float>> All;+ for (const TPair<int32, FPeekHabit>& P : Peeks)+ {+ All.Emplace(P.Key, P.Value.Appearances);+ }+ All.Sort([](const TPair<int32, float>& A, const TPair<int32, float>& B)+ { return A.Value != B.Value ? A.Value > B.Value : A.Key < B.Key; });+ for (int32 i = 0; i < FMath::Min(N, All.Num()); ++i)+ {+ Out.Add(All[i].Key);+ }+}++int32 FVerseBotMatchMemory::RangeBinShift(float PreferredRangeCm) const+{+ if (!bEnabled)+ {+ return 0;+ }+ const int32 Home = RangeBin(PreferredRangeCm);+ int32 Best = Home;+ float BestShare = 2.f;+ for (int32 Bin = FMath::Max(0, Home - 1); Bin <= FMath::Min(NumRangeBins - 1, Home + 1); ++Bin)+ {+ const FRangeBin& R = Ranges[Bin];+ if (R.Engagements < 3)+ {+ continue;+ }+ const float Share = float(R.PersonWins) / float(R.Engagements);+ if (Share < BestShare - 1e-6f || (FMath::IsNearlyEqual(Share, BestShare, 1e-6f) && Bin == Home))+ {+ BestShare = Share;+ Best = Bin;+ }+ }+ return FMath::Clamp(Best - Home, -1, 1);+}++int32 FVerseBotMatchMemory::HabitCount(FName Habit) const+{+ const int32* N = Habits.Find(Habit);+ return N ? *N : 0;+}++bool FVerseBotMatchMemory::ZoneCentroid(int32 ZoneId, FVector& Out) const+{+ const FZoneCentroid* C = Centroids.Find(ZoneId);+ if (!C || C->Count <= 0.f)+ {+ return false;+ }+ Out = C->Sum / C->Count;+ return true;+}++bool FVerseBotMatchMemory::PredictNextZone(const FVector& From, FVector& OutTarget, float& OutProb) const+{+ OutProb = 0.f;+ if (!bEnabled)+ {+ return false;+ }+ // The zone of From: the nearest centroid within 10 m (zones are arena data the memory only+ // knows through the person's perceived positions).+ int32 FromZone = INDEX_NONE;+ float BestD2 = 1000.f * 1000.f;+ for (const TPair<int32, FZoneCentroid>& Z : Centroids)+ {+ if (Z.Value.Count <= 0.f)+ {+ continue;+ }+ const float D2 = float(FVector::DistSquared2D(Z.Value.Sum / Z.Value.Count, From));+ if (D2 < BestD2 || (D2 == BestD2 && Z.Key < FromZone))+ {+ BestD2 = D2;+ FromZone = Z.Key;+ }+ }+ if (FromZone == INDEX_NONE)+ {+ return false;+ }+ const int32 Next = MostLikelyNextZone(FromZone);+ if (Next == INDEX_NONE || !ZoneCentroid(Next, OutTarget))+ {+ return false;+ }+ OutProb = ZoneTransitionProb(FromZone, Next);+ return OutProb > 0.f;+}++bool FVerseBotMatchMemory::MostUsedRouteSegment(FVector& OutFrom, FVector& OutTo, float& OutSamples) const+{+ OutSamples = 0.f;+ const TPair<int32, int32> Route = MostUsedRoute();+ if (Route.Key == INDEX_NONE || !ZoneCentroid(Route.Key, OutFrom) || !ZoneCentroid(Route.Value, OutTo))+ {+ return false;+ }+ const float* N = Routes.Find(RouteKey(Route.Key, Route.Value));+ OutSamples = N ? *N : 0.f;+ return OutSamples > 0.f;+}++bool FVerseBotMatchMemory::HottestCell(ELayer Layer, float NowS, FVector& OutLocation, float& OutShare) const+{+ OutShare = 0.f;+ const float Total = Decayed(LayerTotal[int32(Layer)], NowS);+ if (Total <= KINDA_SMALL_NUMBER)+ {+ return false;+ }+ float Best = 0.f;+ FIntVector BestCell(0);+ bool bFound = false;+ for (const TPair<FIntVector, FCell>& C : Layers[int32(Layer)])+ {+ const float V = Decayed(C.Value, NowS);+ const bool bTieBreak = V == Best && bFound+ && (C.Key.X < BestCell.X || (C.Key.X == BestCell.X && (C.Key.Y < BestCell.Y || (C.Key.Y == BestCell.Y && C.Key.Z < BestCell.Z))));+ if (V > Best || bTieBreak)+ {+ Best = V;+ BestCell = C.Key;+ bFound = true;+ }+ }+ if (!bFound)+ {+ return false;+ }+ OutLocation = FVector((float(BestCell.X) + 0.5f) * CellCm, (float(BestCell.Y) + 0.5f) * CellCm, float(BestCell.Z) * MemoryLevelCm);+ OutShare = FMath::Clamp(Best / Total, 0.f, 1.f);+ return true;+}diff --git a/unreal/Verse/Source/VerseBot/Private/Tactics/VerseBotTactics.cpp b/unreal/Verse/Source/VerseBot/Private/Tactics/VerseBotTactics.cppnew file mode 100644index 0000000000..7add2a6a09--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tactics/VerseBotTactics.cpp@@ -0,0 +1,629 @@+#include "Tactics/VerseBotTactics.h"++#include "Bot/VerseBotTier.h"+#include "Learning/VerseBotMatchMemory.h"++namespace+{+ constexpr float TacticsChestCm = 120.f;+ constexpr float ArriveCm = 70.f;+ /** Sound discipline applies when TopCluster is within 15 m (8.3). */+ constexpr float QuietRangeCm = 1500.f;+ /** DeployBulwark: no cover within 6 m (5.1). */+ constexpr float BulwarkNoCoverCm = 600.f;+ /** Flank window without sight (5.1). */+ constexpr float FlankMinS = 1.5f, FlankMaxS = 8.f;+ /** Stalk: Spread below 2 m, facing seen less than 2 s ago (5.1). */+ constexpr float StalkSpreadCm = 200.f, StalkFacingAgeS = 2.f;+ constexpr float BreachFuseS = 2.5f;+ /** Search (5.1): cells below this mass are not worth a walk; arena points within 4 m count as searched. */+ constexpr float SearchMinMass = 0.05f;+ constexpr float SearchVisitCm = 400.f;+ constexpr float SearchRadiusCm = 6000.f;+ constexpr float SearchRetargetS = 8.f;+ constexpr int32 SearchPathChecks = 5;++ using EState = EVerseBotState;++ bool BeliefUsable(const FVerseBotBeliefSummary& B)+ {+ return B.State == EVerseBeliefState::Known || B.State == EVerseBeliefState::Tracked || B.State == EVerseBeliefState::Rough;+ }++ FVector Chest(const FVector& Pelvis) { return Pelvis + FVector(0, 0, TacticsChestCm - 70.f); }++ /** The believed opponent faces away from the bot: the bot is more than 100 deg off its facing. */+ bool FacingAway(const FVerseBotTacticsContext& Ctx)+ {+ return VerseBotEqs::OffFacingDeg(Ctx.Query, Ctx.Query.Self->Location) > VerseBotEqs::FinisherArcDeg;+ }++ bool Quiet(const FVerseBotTacticsContext& Ctx)+ {+ const float D = float(FVector::Dist2D(Ctx.Query.Self->Location, Ctx.Query.Belief->TopCenter));+ return D < QuietRangeCm && Ctx.Query.Tier->SoundDiscipline >= 0.5f;+ }++ float RollRange(FVerseRng& Rng, float Min, float Max) { return float(Rng.Range(Min, Max)); }+}++namespace VerseBotTactics+{+ float PeekHoldScale(const FVerseBotPeekResult& Peek)+ {+ if (!Peek.bHasWatch)+ {+ return 1.f;+ }+ return 1.f + 2.f * FMath::Clamp(Peek.WatchWeight, 0.f, float(UVerseBotTier::LearnWeightMaxCap)) * FMath::Clamp(Peek.WatchRepeekShare, 0.f, 1.f);+ }++ float PreferredBandCm(const UVerseBotTier& Tier, const FVerseBotMatchMemory* Memory)+ {+ const float Base = Tier.PreferredRangeM * VerseBot::CmPerM;+ const int32 Shift = Memory ? Memory->RangeBinShift(Base) : 0;+ return Shift == 0 ? Base : FVerseBotMatchMemory::RangeBinCentreCm(FVerseBotMatchMemory::RangeBin(Base) + Shift);+ }++ void Utilities(const FVerseBotTacticsContext& Ctx, float (&Out)[VerseBot::NumStates])+ {+ for (float& U : Out)+ {+ U = -1.f;+ }+ const UVerseBotTier& T = *Ctx.Query.Tier;+ const FVerseBotBeliefSummary& B = *Ctx.Query.Belief;+ const FVerseBotQueryCache& C = *Ctx.Cache;+ const bool bSight = Ctx.Sighting != nullptr;+ const bool bRecentSight = Ctx.SinceSightS < 0.5f;+ const bool bUsable = BeliefUsable(B);+ const float DistTop = float(FVector::Dist2D(Ctx.Query.Self->Location, B.TopCenter));+ const float Lead = Ctx.HealthFrac - B.OpponentHealthFrac;+ const bool bLow = Ctx.HealthFrac < 0.35f && Ctx.HealthFrac <= B.OpponentHealthFrac;+ const bool bAmmoLow = Ctx.MagazineFrac < 0.1f && Ctx.bPistolLow;+ const FVerseBotCoverResult& Near = C.GetCover(EVerseBotCoverMode::Near);+ const bool bNearCoverClose = Near.bFound && float(FVector::Dist(Near.Point.Location, Ctx.Query.Self->Location)) <= BulwarkNoCoverCm;++ // Attack: known or seen < 0.5 s ago; + health lead; + Aggression.+ if (bSight || bRecentSight)+ {+ Out[int32(EState::Attack)] = 0.6f + 0.3f * T.Aggression + 0.3f * Lead - (Ctx.MagazineFrac <= 0.f ? 0.4f : 0.f);+ }++ // Hold: tracked belief moving toward the bot, good cover with a sightline; + CoverUse.+ if (Near.bFound && (bUsable || bSight) && B.State != EVerseBeliefState::Dead)+ {+ const FVector ToBot = (Ctx.Query.Self->Location - B.TopCenter).GetSafeNormal2D();+ const bool bApproach = FVector::DotProduct(B.Velocity.GetSafeNormal2D(), ToBot) > 0.3f;+ Out[int32(EState::Hold)] = 0.3f + 0.5f * T.CoverUse + (bApproach ? 0.15f : 0.f)+ + (B.State == EVerseBeliefState::Tracked ? 0.1f : 0.f) - (bSight ? 0.1f : 0.f);+ }++ // Flank: tracked or rough, no sight 1.5-8 s; opponent holding still; + FlankUse.+ if ((B.State == EVerseBeliefState::Tracked || B.State == EVerseBeliefState::Rough) && !bSight+ && Ctx.SinceSightS >= FlankMinS && Ctx.SinceSightS <= FlankMaxS)+ {+ const bool bStill = B.Velocity.Size2D() < 100.f;+ Out[int32(EState::Flank)] = 0.3f + 0.6f * T.FlankUse + (bStill ? 0.15f : 0.f)+ + (C.GetCover(EVerseBotCoverMode::Flank).bFound ? 0.05f : 0.f);+ }++ // StalkForFinisher: tracked, Spread < 2 m, static or facing away; hidden approach exists; + StalkUse.+ if (B.State == EVerseBeliefState::Tracked && !bSight && B.SpreadCm < StalkSpreadCm && C.Finisher.bFound)+ {+ const bool bStill = B.Velocity.Size2D() < 100.f;+ const bool bAway = (B.FacingAgeS < StalkFacingAgeS && FacingAway(Ctx)) || B.bReloadNoticed;+ if (bStill || bAway)+ {+ Out[int32(EState::StalkForFinisher)] = 0.4f + 0.8f * T.StalkUse + (bAway ? 0.1f : 0.f);+ }+ }++ // Retreat: own health low vs the estimate, or magazine and pistol both low; + CoverUse.+ if (bLow || bAmmoLow)+ {+ Out[int32(EState::Retreat)] = 0.5f + 0.5f * T.CoverUse + 0.3f * (1.f - Ctx.HealthFrac);+ }++ // Reload: magazine at or below the tactical fraction, no sight, threat low or in cover.+ if (Ctx.MagazineFrac <= T.TacticalReloadAtFrac && !bSight && Ctx.Query.Self->Reserve > 0)+ {+ const bool bSafe = B.Confidence < 0.5f || DistTop > QuietRangeCm || Ctx.bInCover || !bUsable;+ const bool bEmpty = Ctx.MagazineFrac <= 0.f;+ if (bSafe || bEmpty || T.ReloadOnlyWhenSafe < 0.5f)+ {+ Out[int32(EState::Reload)] = (bEmpty ? 0.9f : 0.5f) + 0.4f * (1.f - Ctx.MagazineFrac) + (Ctx.bInCover ? 0.1f * T.ReloadOnlyWhenSafe : 0.f);+ }+ }++ // DeployBulwark: wants to hold or retreat but no cover within 6 m; charge available; + BulwarkUse.+ if (Ctx.bBulwarkReady && !bNearCoverClose && (bUsable || bSight || bLow))+ {+ Out[int32(EState::DeployBulwark)] = 0.35f + 0.6f * T.BulwarkUse;+ }++ // Breach: a believed-intact breachable piece shortens the path or opens an angle; + BreachUse.+ if (Ctx.bBreachReady && C.Breach.bFound && bUsable && !bSight)+ {+ Out[int32(EState::Breach)] = 0.25f + 0.6f * T.BreachUse + 0.2f * FMath::Clamp(C.Breach.Score, 0.f, 1.f);+ }++ // Wallbang: authority holds, bot unseen; + WallbangUse.+ if (Ctx.bWallbangAuthorised && !bSight && Ctx.SinceHurtS > 1.f)+ {+ Out[int32(EState::Wallbang)] = 0.45f + 0.6f * T.WallbangUse;+ }++ // Search: belief rough or lost (or the opponent is respawning).+ {+ const float Base = B.State == EVerseBeliefState::Lost ? 0.7f+ : B.State == EVerseBeliefState::Dead ? 0.6f+ : B.State == EVerseBeliefState::Rough ? 0.45f+ : 0.15f;+ Out[int32(EState::Search)] = bSight ? 0.05f : Base;+ }+ }++ void Enter(EVerseBotState State, const FVerseBotTacticsContext& Ctx, FVerseBotTacticsMemory& Mem, FVerseRng& Rng)+ {+ const FVerseBotQueryCache& C = *Ctx.Cache;+ switch (State)+ {+ case EState::Hold:+ Mem.HoldPhase = EVerseBotHoldPhase::Go;+ Mem.bHasCover = C.GetCover(EVerseBotCoverMode::Near).bFound;+ Mem.Cover = C.GetCover(EVerseBotCoverMode::Near).Point;+ Mem.bHasPeek = false;+ break;+ case EState::Retreat:+ Mem.bHasCover = C.GetCover(EVerseBotCoverMode::Far).bFound || C.GetCover(EVerseBotCoverMode::Near).bFound;+ Mem.Cover = C.GetCover(EVerseBotCoverMode::Far).bFound ? C.GetCover(EVerseBotCoverMode::Far).Point : C.GetCover(EVerseBotCoverMode::Near).Point;+ break;+ case EState::Reload:+ Mem.bHasCover = C.GetCover(EVerseBotCoverMode::Near).bFound;+ Mem.Cover = C.GetCover(EVerseBotCoverMode::Near).Point;+ break;+ case EState::DeployBulwark:+ Mem.bHasCover = C.GetCover(EVerseBotCoverMode::Bulwark).bFound;+ Mem.Cover = C.GetCover(EVerseBotCoverMode::Bulwark).Point;+ break;+ case EState::Flank:+ {+ const FVerseBotCoverResult& F = C.GetCover(EVerseBotCoverMode::Flank);+ if (F.bFound)+ {+ Mem.FlankPoint = F.Point.Location;+ }+ else+ {+ // A point 90-130 deg off the believed facing at the preferred range.+ const FVector Facing = VerseBotEqs::BeliefFacing(Ctx.Query);+ const float Side = Rng.Chance(0.5) ? 1.f : -1.f;+ const FVector Dir = Facing.RotateAngleAxis(Side * RollRange(Rng, 90.f, 130.f), FVector::UpVector);+ Mem.FlankPoint = Ctx.Query.Belief->TopCenter + Dir * Ctx.Query.PreferredRangeCm;+ }+ Mem.bHasFlankPoint = true;+ break;+ }+ case EState::StalkForFinisher:+ Mem.StalkStartS = Ctx.Query.NowS;+ break;+ case EState::Breach:+ Mem.bBreachPlanted = false;+ Mem.BreachPiece = C.Breach.PieceIndex;+ break;+ case EState::Wallbang:+ Mem.BurstShots = 0;+ Mem.BurstPauseUntilS = 0.f;+ break;+ case EState::Search:+ Mem.bHasSearchTarget = false;+ Mem.bSearchVerifying = false;+ Mem.SearchQueue.Reset();+ break;+ case EState::Attack:+ Mem.StrafeSign = Rng.Chance(0.5) ? 1 : -1;+ Mem.StrafeUntilS = Ctx.Query.NowS + RollRange(Rng, Ctx.Query.Tier->StrafeMs.X, Ctx.Query.Tier->StrafeMs.Y) / 1000.f;+ break;+ default:+ break;+ }+ }++ FVerseBotIntent Tick(EVerseBotState State, const FVerseBotTacticsContext& Ctx, FVerseBotTacticsMemory& Mem, FVerseRng& Rng)+ {+ FVerseBotIntent I;+ const UVerseBotTier& T = *Ctx.Query.Tier;+ const FVerseBotBeliefSummary& B = *Ctx.Query.Belief;+ const FVerseSelfPercept& Self = *Ctx.Query.Self;+ const float Now = Ctx.Query.NowS;+ const FVector TopChest = B.TopCenter + FVector(0, 0, TacticsChestCm);++ auto LookAtBelief = [&]()+ {+ I.bHasLookTarget = B.State != EVerseBeliefState::Lost && B.State != EVerseBeliefState::Dead;+ I.LookTarget = TopChest;+ };+ auto MoveTo = [&](const FVector& Target)+ {+ I.bHasMoveTarget = float(FVector::Dist2D(Target, Self.Location)) > ArriveCm;+ I.MoveTarget = Target;+ return !I.bHasMoveTarget;+ };++ switch (State)+ {+ case EState::Attack:+ {+ const FVector Target = Ctx.Sighting ? Chest(Ctx.Sighting->PelvisLocation) : Chest(B.LastSeenLocation);+ I.bHasLookTarget = true;+ I.LookTarget = Target;+ I.bWantFire = true;+ const float Dist = float(FVector::Dist2D(Target, Self.Location));+ I.bAds = Dist > T.AdsRangeM * VerseBot::CmPerM;+ if (Now >= Mem.StrafeUntilS)+ {+ Mem.StrafeSign = -Mem.StrafeSign;+ Mem.StrafeUntilS = Now + RollRange(Rng, T.StrafeMs.X, T.StrafeMs.Y) / 1000.f;+ }+ I.Strafe = Mem.StrafeSign;+ // Hold the preferred band; close in only with a reason (reloading, low, out of range).+ const bool bReason = (Ctx.Sighting && Ctx.Sighting->bReloading) || B.OpponentHealthFrac < 0.35f+ || Dist > 1.4f * Ctx.Query.PreferredRangeCm;+ const FVector Away = (Self.Location - Target).GetSafeNormal2D();+ if (bReason)+ {+ MoveTo(Target + Away * 0.6f * Ctx.Query.PreferredRangeCm);+ }+ else if (Dist < 0.6f * Ctx.Query.PreferredRangeCm)+ {+ MoveTo(Self.Location + Away * 300.f);+ }+ break;+ }+ case EState::Hold:+ {+ LookAtBelief();+ if (!Mem.bHasCover)+ {+ I.bWantFire = Ctx.Sighting != nullptr;+ break;+ }+ switch (Mem.HoldPhase)+ {+ case EVerseBotHoldPhase::Go:+ if (MoveTo(Mem.Cover.Location))+ {+ Mem.HoldPhase = EVerseBotHoldPhase::Hide;+ Mem.PhaseUntilS = Now + RollRange(Rng, HideMinS, HideMaxS);+ }+ I.bSprint = !Quiet(Ctx) && FVector::Dist2D(Mem.Cover.Location, Self.Location) > 600.f;+ I.bWalk = Quiet(Ctx);+ break;+ case EVerseBotHoldPhase::Hide:+ MoveTo(Mem.Cover.Location);+ I.Stance = Mem.Cover.bHigh ? EVerseStance::Stand : EVerseStance::Crouch;+ I.bWantFire = false;+ if (Now >= Mem.PhaseUntilS && Ctx.MagazineFrac > T.TacticalReloadAtFrac && Ctx.HealthFrac > 0.3f+ && Ctx.Cache->Peek.bFound)+ {+ Mem.HoldPhase = EVerseBotHoldPhase::Peek;+ Mem.bHasPeek = true;+ Mem.Peek = Ctx.Cache->Peek;+ Mem.PhaseUntilS = Now + RollRange(Rng, PeekMinS, PeekMaxS) * PeekHoldScale(Mem.Peek);+ if (Mem.RecentPeekEdges.Num() >= 3)+ {+ Mem.RecentPeekEdges.RemoveAt(0);+ }+ Mem.RecentPeekEdges.Add(Mem.Cover.EdgeId);+ }+ else if (Now >= Mem.PhaseUntilS)+ {+ Mem.PhaseUntilS = Now + RollRange(Rng, HideMinS, HideMaxS);+ }+ break;+ case EVerseBotHoldPhase::Peek:+ MoveTo(Mem.Peek.StandPoint);+ I.bAds = true;+ if (Mem.Peek.bHasWatch && Ctx.Sighting == nullptr)+ {+ // Pre-aim the edge the person keeps peeking from (learned, 7.2).+ I.bHasLookTarget = true;+ I.LookTarget = Mem.Peek.WatchPoint;+ }+ I.bWantFire = Ctx.Sighting != nullptr;+ switch (Mem.Peek.Type)+ {+ case EVerseBotPeekType::LeanLeft: I.Lean = -1; break;+ case EVerseBotPeekType::LeanRight: I.Lean = 1; break;+ case EVerseBotPeekType::JumpPeek: I.bJump = true; break;+ default: break;+ }+ if (Now >= Mem.PhaseUntilS)+ {+ Mem.HoldPhase = EVerseBotHoldPhase::Hide;+ Mem.PhaseUntilS = Now + RollRange(Rng, HideMinS, HideMaxS);+ }+ break;+ }+ break;+ }+ case EState::Flank:+ {+ LookAtBelief();+ if (Mem.bHasFlankPoint)+ {+ MoveTo(Mem.FlankPoint);+ }+ I.bWalk = Quiet(Ctx);+ I.bSprint = !I.bWalk;+ I.bWantFire = Ctx.Sighting != nullptr;+ break;+ }+ case EState::StalkForFinisher:+ {+ LookAtBelief();+ const FVerseBotFinisherResult& F = Ctx.Cache->Finisher;+ I.Stance = EVerseStance::Crouch;+ I.bWalk = true;+ if (F.bFound)+ {+ MoveTo(F.Approach);+ }+ // The melee press becomes the finisher when the rules allow it (combat-state 7.2).+ if (float(FVector::Dist2D(B.TopCenter, Self.Location)) <= VerseBotEqs::FinisherRangeCm && Ctx.Query.World->CanActivateFinisher())+ {+ I.bMelee = true;+ }+ break;+ }+ case EState::Retreat:+ {+ LookAtBelief();+ if (Mem.bHasCover)+ {+ MoveTo(Mem.Cover.Location);+ }+ I.bSprint = true;+ I.bReload = Ctx.Sighting == nullptr && Ctx.MagazineFrac < 1.f;+ I.bWantFire = Ctx.Sighting != nullptr && Ctx.MagazineFrac > 0.f;+ break;+ }+ case EState::Reload:+ {+ LookAtBelief();+ const bool bCoverClose = Mem.bHasCover && float(FVector::Dist2D(Mem.Cover.Location, Self.Location)) < 600.f;+ if (bCoverClose && !Ctx.bInCover)+ {+ MoveTo(Mem.Cover.Location);+ }+ I.Stance = (Mem.bHasCover && !Mem.Cover.bHigh && Ctx.bInCover) ? EVerseStance::Crouch : EVerseStance::Stand;+ I.bReload = true;+ break;+ }+ case EState::DeployBulwark:+ {+ LookAtBelief();+ const bool bThere = !Mem.bHasCover || MoveTo(Mem.Cover.Location);+ if (bThere && !Mem.bBulwarkDeployed && Ctx.bBulwarkReady)+ {+ I.bGadgetA = true;+ Mem.bBulwarkDeployed = true;+ Mem.BulwarkDeployedS = Now;+ }+ if (Mem.bBulwarkDeployed)+ {+ I.Stance = EVerseStance::Crouch;+ I.bWantFire = Ctx.Sighting != nullptr;+ }+ break;+ }+ case EState::Breach:+ {+ const FVerseBotBreachResult& Br = Ctx.Cache->Breach;+ if (!Mem.bBreachPlanted)+ {+ if (Br.bFound && MoveTo(Br.PlantPoint))+ {+ I.bHasLookTarget = true;+ I.LookTarget = Br.PlantPoint;+ I.bGadgetB = true;+ Mem.bBreachPlanted = true;+ Mem.BreachPlantedS = Now;+ Mem.BreachPiece = Br.PieceIndex;+ }+ I.bWalk = Quiet(Ctx);+ }+ else if (Now - Mem.BreachPlantedS < BreachFuseS + 0.3f)+ {+ // Step back out of the self-damage radius and wait for the detonation.+ MoveTo(Br.bFound ? Br.WaitPoint : Self.Location);+ LookAtBelief();+ }+ else+ {+ // Through the opening toward the belief.+ LookAtBelief();+ MoveTo(B.TopCenter);+ I.bWantFire = Ctx.Sighting != nullptr;+ }+ break;+ }+ case EState::Wallbang:+ {+ const FVerseBotWallbangResult& W = Ctx.Cache->Wallbang;+ I.bHasLookTarget = true;+ I.LookTarget = W.bFound ? W.AimPoint : TopChest;+ if (W.bFound)+ {+ MoveTo(W.FireFrom);+ }+ // Bursts; authority is re-checked by the fire gate on every shot.+ if (Now >= Mem.BurstPauseUntilS)+ {+ I.bWantFire = true;+ if (++Mem.BurstShots >= FMath::Max(1, T.MaxBurstShots) * 6)+ {+ Mem.BurstShots = 0;+ Mem.BurstPauseUntilS = Now + 0.4f;+ }+ }+ break;+ }+ case EState::Search:+ {+ const bool bArrived = Mem.bHasSearchTarget && float(FVector::Dist2D(Mem.SearchTarget, Self.Location)) < ArriveCm * 3.f;+ if (Mem.bSearchVerifying)+ {+ // One path check per tick (path budget): the next ranked point a path reaches.+ if (Mem.SearchQueueIndex < Mem.SearchQueue.Num())+ {+ const FVector Candidate = Mem.SearchQueue[Mem.SearchQueueIndex++];+ if (Ctx.Query.World->FindPath(Self.Location, Candidate, false).bValid)+ {+ Mem.SearchTarget = Candidate;+ Mem.bHasSearchTarget = true;+ Mem.bSearchVerifying = false;+ }+ }+ if (Mem.bSearchVerifying && Mem.SearchQueueIndex >= Mem.SearchQueue.Num())+ {+ Mem.SearchTarget = Self.Location + Self.ViewRotation.Vector().GetSafeNormal2D() * 1200.f;+ Mem.bHasSearchTarget = true;+ Mem.bSearchVerifying = false;+ }+ }+ else if (!Mem.bHasSearchTarget || bArrived || Now >= Mem.SearchUntilS)+ {+ if (bArrived || Now >= Mem.SearchUntilS)+ {+ // Mark the arena points around the reached (or abandoned) target as searched.+ TArray<FVerseBotCoverPoint> Near;+ Ctx.Query.World->GetCoverPoints(Mem.SearchTarget, SearchVisitCm, Near);+ for (const FVerseBotCoverPoint& P : Near)+ {+ Mem.Visited.Add(P.Id, Now);+ }+ }+ // Highest belief mass per path metre among the top cells.+ TArray<FVector> Cells;+ Ctx.Query.BeliefMap->TopCells(8, Cells);+ float Best = -1.f;+ for (const FVector& Cell : Cells)+ {+ const float Mass = Ctx.Query.BeliefMap->MassWithin(Cell, 300.f);+ if (Mass < SearchMinMass || float(FVector::Dist2D(Cell, Self.Location)) < ArriveCm * 3.f)+ {+ continue;+ }+ const float Len = FMath::Max(float(FVector::Dist(Cell, Self.Location)), 100.f) / VerseBot::CmPerM;+ const float V = Mass / Len;+ if (V > Best)+ {+ Best = V;+ Mem.SearchTarget = Cell;+ }+ }+ if (Best < 0.f)+ {+ // The rest of the mass is unexplored arena: the least recently searched point+ // per metre of distance (static arena data, 3.3).+ TArray<FVerseBotCoverPoint> Points;+ Ctx.Query.World->GetCoverPoints(Self.Location, SearchRadiusCm, Points);+ TArray<TPair<float, FVector>, TInlineAllocator<64>> Ranked;+ for (const FVerseBotCoverPoint& P : Points)+ {+ const float* Last = Mem.Visited.Find(P.Id);+ const float Age = Last ? Now - *Last : 120.f;+ const float Dist = float(FVector::Dist2D(P.Location, Self.Location)) / VerseBot::CmPerM;+ if (Dist < 3.f)+ {+ continue;+ }+ Ranked.Emplace(FMath::Min(Age, 120.f) / (Dist + 8.f) + float(Rng.Range(0.0, 0.01)), P.Location);+ }+ Ranked.StableSort([](const TPair<float, FVector>& A, const TPair<float, FVector>& B) { return A.Key > B.Key; });+ // The best few by gain that a path actually reaches, checked one per tick.+ Mem.SearchQueue.Reset();+ for (int32 i = 0; i < FMath::Min(Ranked.Num(), SearchPathChecks); ++i)+ {+ Mem.SearchQueue.Add(Ranked[i].Value);+ }+ Mem.SearchQueueIndex = 0;+ Mem.bSearchVerifying = true;+ Mem.bHasSearchTarget = false;+ }+ else+ {+ Mem.bHasSearchTarget = true;+ }+ Mem.SearchUntilS = Now + SearchRetargetS;+ }+ if (Mem.bHasSearchTarget)+ {+ MoveTo(Mem.SearchTarget);+ }+ // Sweep the view to clear cells.+ Mem.SearchSweepPhase += 0.05f;+ const FVector Ahead = Mem.bHasSearchTarget ? (Mem.SearchTarget - Self.Location).GetSafeNormal2D() : Self.ViewRotation.Vector().GetSafeNormal2D();+ const FVector Sweep = Ahead.RotateAngleAxis(40.f * FMath::Sin(Mem.SearchSweepPhase), FVector::UpVector);+ I.bHasLookTarget = true;+ I.LookTarget = Self.EyeLocation + Sweep * 1000.f;+ I.bWalk = Quiet(Ctx);+ I.Stance = (I.bWalk && T.SoundDiscipline >= 0.8f) ? EVerseStance::Crouch : EVerseStance::Stand;+ I.bWantFire = Ctx.Sighting != nullptr;+ break;+ }+ }+ return I;+ }++ void WantedQueries(EVerseBotState Current, const FVerseBotTacticsContext& Ctx, TArray<EVerseBotQuery, TInlineAllocator<8>>& Out)+ {+ Out.Reset();+ const FVerseBotBeliefSummary& B = *Ctx.Query.Belief;+ const UVerseBotTier& T = *Ctx.Query.Tier;+ auto Add = [&Out](EVerseBotQuery Q) { Out.AddUnique(Q); };+ switch (Current)+ {+ case EState::Hold: Add(EVerseBotQuery::PeekCorner); Add(EVerseBotQuery::CoverNear); break;+ case EState::Retreat: Add(EVerseBotQuery::CoverFar); break;+ case EState::Flank: Add(EVerseBotQuery::CoverFlank); break;+ case EState::StalkForFinisher: Add(EVerseBotQuery::FinisherApproach); break;+ case EState::Breach: Add(EVerseBotQuery::BreachSpot); break;+ case EState::Wallbang: Add(EVerseBotQuery::WallbangSpot); break;+ case EState::DeployBulwark: Add(EVerseBotQuery::CoverBulwark); break;+ default: break;+ }+ if (B.State == EVerseBeliefState::Dead)+ {+ return;+ }+ Add(EVerseBotQuery::CoverNear);+ const bool bUsable = BeliefUsable(B);+ if (bUsable && Ctx.Sighting == nullptr)+ {+ if (T.WallbangUse > 0.f && !B.bPriorOnly)+ {+ Add(EVerseBotQuery::WallbangSpot);+ }+ if (B.SpreadCm < StalkSpreadCm * 1.5f && B.Confidence >= T.FinisherCommitConfidence)+ {+ Add(EVerseBotQuery::FinisherApproach);+ }+ Add(EVerseBotQuery::CoverFlank);+ if (Ctx.bBreachReady && T.BreachUse > 0.f)+ {+ Add(EVerseBotQuery::BreachSpot);+ }+ }+ if (Ctx.HealthFrac < 0.5f || Ctx.MagazineFrac < 0.2f)+ {+ Add(EVerseBotQuery::CoverFar);+ }+ if (Ctx.bBulwarkReady && T.BulwarkUse > 0.f)+ {+ Add(EVerseBotQuery::CoverBulwark);+ }+ }+}diff --git a/unreal/Verse/Source/VerseBot/Private/Tests/Audit/VerseBotAuditTest.cpp b/unreal/Verse/Source/VerseBot/Private/Tests/Audit/VerseBotAuditTest.cppnew file mode 100644index 0000000000..3fd3eed744--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tests/Audit/VerseBotAuditTest.cpp@@ -0,0 +1,220 @@+#include "Audit/VerseBotFireAudit.h"+#include "Bot/VerseBotTier.h"+#include "Misc/AutomationTest.h"+#include "Tests/Brain/Fakes/FakeVerseDuelSim.h"+#include "Tests/Brain/VerseBotTestProof.h"++#if WITH_DEV_AUTOMATION_TESTS++#define VERSE_BOT_TEST_FLAGS (EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++// 8.10: the F4 classifier (bot.md 8.4) and the log format.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotAuditClassifierTest, "Verse.Bot.Audit.Classifier", VERSE_BOT_TEST_FLAGS)++bool FVerseBotAuditClassifierTest::RunTest(const FString& Parameters)+{+ UVerseBotTier* T = NewObject<UVerseBotTier>();+ UVerseBotTier::ApplyStartValues(TEXT("hard"), *T);+ using EMode = EVerseBotFireMode;+ {+ FVerseBotFireEvidence E;+ E.bTargetVisible = true;+ TestEqual(TEXT("visible"), FVerseBotFireClassifier::Classify(E, *T), EMode::Visible);+ E.bTargetSpawnProtected = true;+ TestEqual(TEXT("never at a spawn-protected target"), FVerseBotFireClassifier::Classify(E, *T), EMode::Unclassified);+ }+ {+ FVerseBotFireEvidence E;+ E.SinceSightLostS = 0.3f;+ E.LastSeenLocation = FVector(1000.f, 0.f, 100.f);+ E.AimPoint = FVector(1150.f, 0.f, 100.f);+ TestEqual(TEXT("suppression inside 0.35 s and 2 m"), FVerseBotFireClassifier::Classify(E, *T), EMode::Suppression);+ E.SinceSightLostS = 0.36f;+ TestEqual(TEXT("no suppression after 0.35 s"), FVerseBotFireClassifier::Classify(E, *T), EMode::Unclassified);+ E.SinceSightLostS = 0.3f;+ E.AimPoint = FVector(1250.f, 0.f, 100.f);+ TestEqual(TEXT("no suppression beyond 2 m"), FVerseBotFireClassifier::Classify(E, *T), EMode::Unclassified);+ }+ {+ FVerseBotFireEvidence E;+ E.bPrefireRolled = true;+ E.bAimAtPeekEdge = true;+ E.HeardAgeS = 1.5f;+ E.HeardLocation = FVector(500.f, 0.f, 0.f);+ E.AimPoint = FVector(900.f, 0.f, 0.f);+ E.SupportedMassAtAim = 0.5f;+ TestEqual(TEXT("prefire"), FVerseBotFireClassifier::Classify(E, *T), EMode::Prefire);+ E.HeardAgeS = 2.5f;+ TestEqual(TEXT("no prefire on an old sound"), FVerseBotFireClassifier::Classify(E, *T), EMode::Unclassified);+ E.HeardAgeS = 1.5f;+ E.SupportedMassAtAim = 0.3f;+ TestEqual(TEXT("no prefire below WallbangMinBelief"), FVerseBotFireClassifier::Classify(E, *T), EMode::Unclassified);+ }+ {+ FVerseBotFireEvidence E;+ E.bAimInTopCluster = true;+ E.bPriorOnly = false;+ E.SupportedMassAtAim = 0.5f;+ E.SupportAgeS = 2.f;+ E.TraceDamageFrac = 0.6f;+ E.TracePieces = 1;+ TestEqual(TEXT("wall shot with authority"), FVerseBotFireClassifier::Classify(E, *T), EMode::WallShot);+ E.bPriorOnly = true;+ TestEqual(TEXT("prior-only mass never authorises"), FVerseBotFireClassifier::Classify(E, *T), EMode::Unclassified);+ }+ {+ FVerseBotFireEvidence E;+ E.ServerTimeMs = 1234;+ E.bTargetVisible = true;+ E.SightPerceptId = 42;+ E.MassAtAim = 0.75f;+ E.SupportAgeS = 0.f;+ const FVerseBotFireAudit A = FVerseBotFireClassifier::MakeAudit(E, EMode::Visible);+ TestEqual(TEXT("log line"), A.ToLogLine(), FString(TEXT("VerseBotFire t=1234 mode=visible visible=1 percepts=42 mass=0.750 age=0.00")));+ }+ return true;+}++// A8.3 / F4 at the shot event: every round the bot's weapon fired over 1,000 bouts has an audit+// record of that tick, no record is unclassified, and an independent pass over the percepts the+// sim delivered re-derives each record's mode (fire intents the gate blocked are reported apart).+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotAuditBoutsTest, "Verse.Bot.Audit.Bouts", VERSE_BOT_TEST_FLAGS)++namespace VerseBotAuditTest+{+ using FSim = FFakeVerseDuelSim;++ /** The independent re-check of one record against the delivered percepts (8.4 windows). */+ bool Recheck(const FVerseBotFireAudit& A, const FSim::FShot& Shot, const TMap<uint32, FSim::FDelivered>& Delivered)+ {+ auto AgeMs = [&](uint32 Id, FSim::EDelivered Kind, uint32& OutAge) -> bool+ {+ const FSim::FDelivered* D = Delivered.Find(Id);+ if (!D || D->Kind != Kind || D->TimeMs > Shot.TimeMs)+ {+ return false;+ }+ OutAge = Shot.TimeMs - D->TimeMs;+ return true;+ };+ uint32 Age = 0;+ switch (A.Mode)+ {+ case EVerseBotFireMode::Visible:+ // A sighting delivered this very tick, and the fair sight rule held (sim truth).+ return A.bTargetVisible && Shot.bBotSawOpponent && A.PerceptIds.Num() > 0+ && AgeMs(A.PerceptIds[0], FSim::EDelivered::Sight, Age) && Age == 0;+ case EVerseBotFireMode::Suppression:+ // A sighting delivered at most 0.35 s (+ one tick) before the shot.+ return A.PerceptIds.Num() > 0 && AgeMs(A.PerceptIds[0], FSim::EDelivered::Sight, Age) && Age <= 350 + 17;+ case EVerseBotFireMode::Prefire:+ // A heard percept of the last 2 s backs it.+ for (uint32 Id : A.PerceptIds)+ {+ if (AgeMs(Id, FSim::EDelivered::Heard, Age) && Age <= 2000)+ {+ return true;+ }+ }+ return false;+ case EVerseBotFireMode::WallShot:+ // A seen or heard percept within the contract's 4 s source-age cap backs it.+ for (uint32 Id : A.PerceptIds)+ {+ if ((AgeMs(Id, FSim::EDelivered::Heard, Age) || AgeMs(Id, FSim::EDelivered::Sight, Age)) && Age <= 4000)+ {+ return true;+ }+ }+ return false;+ default:+ return false;+ }+ }+}++bool FVerseBotAuditBoutsTest::RunTest(const FString& Parameters)+{+ using namespace VerseBotAuditTest;+ constexpr int32 TargetBouts = 1000;+ int32 Bouts = 0;+ int64 Shots = 0;+ int64 ShotsWithoutRecord = 0;+ int64 Records = 0;+ int64 Unclassified = 0;+ int64 RecheckFailures = 0;+ int64 Blocked = 0;+ int64 ByMode[5] = {};+ FString Sample;+ FString FirstFailure;+ const FName Tiers[3] = {TEXT("normal"), TEXT("hard"), TEXT("elite")};+ for (int32 Run = 0; Bouts < TargetBouts && Run < 400; ++Run)+ {+ FSim::FConfig Cfg;+ Cfg.Seed = 9000 + Run;+ FSim Sim(Tiers[Run % 3], Cfg);+ Sim.bRecordShots = true;+ Sim.Brain.GetFireAudit().SetCaptureAll(true);+ // One run: up to 5 bouts or 4 minutes.+ for (int32 t = 0; t < 4 * 60 * 60 && Sim.Kills() < 5; ++t)+ {+ Sim.Tick();+ }+ Bouts += Sim.Kills();+ const FVerseBotFireAuditLog& Log = Sim.Brain.GetFireAudit();+ const TArray<FVerseBotFireAudit> Entries = Log.GetEntries();+ Records += Entries.Num();+ Blocked += Log.BlockedCount();+ TMap<uint32, int32> ByTime;+ for (int32 i = 0; i < Entries.Num(); ++i)+ {+ ByTime.Add(Entries[i].ServerTimeMs, i);+ Unclassified += Entries[i].Mode == EVerseBotFireMode::Unclassified ? 1 : 0;+ }+ for (const FSim::FShot& Shot : Sim.Shots)+ {+ ++Shots;+ const int32* Index = ByTime.Find(Shot.TimeMs);+ if (!Index)+ {+ ++ShotsWithoutRecord;+ continue;+ }+ const FVerseBotFireAudit& A = Entries[*Index];+ ++ByMode[int32(A.Mode)];+ if (!Recheck(A, Shot, Sim.Delivered))+ {+ ++RecheckFailures;+ if (FirstFailure.IsEmpty())+ {+ FirstFailure = A.ToLogLine();+ }+ }+ }+ if (Sample.IsEmpty() && Entries.Num() > 0)+ {+ for (int32 i = 0; i < FMath::Min(20, Entries.Num()); ++i)+ {+ Sample += Entries[i].ToLogLine() + TEXT("\n");+ }+ }+ }+ TestTrue(TEXT("1,000 bouts played"), Bouts >= TargetBouts);+ TestTrue(TEXT("the bot fired"), Shots > 0);+ TestEqual(TEXT("every fired round has an audit record of its tick"), ShotsWithoutRecord, int64(0));+ TestEqual(TEXT("0 unclassified records"), Unclassified, int64(0));+ TestEqual(TEXT("the independent pass re-derives every fired round's mode"), RecheckFailures, int64(0));+ if (!FirstFailure.IsEmpty())+ {+ AddInfo(FString::Printf(TEXT("first recheck failure: %s"), *FirstFailure));+ }+ VerseBotTestProof::Write(TEXT("8.10"), TEXT("f4_fire_audit.json"),+ FString::Printf(TEXT("{\n \"test\": \"F4\",\n \"bouts\": %d,\n \"shotsFired\": %lld,\n \"shotsWithoutRecord\": %lld,\n \"records\": %lld,\n \"unclassified\": %lld,\n \"recheckFailures\": %lld,\n \"blockedFireIntents\": %lld,\n \"shotsVisible\": %lld,\n \"shotsSuppression\": %lld,\n \"shotsPrefire\": %lld,\n \"shotsWallShot\": %lld\n}\n"),+ Bouts, Shots, ShotsWithoutRecord, Records, Unclassified, RecheckFailures, Blocked, ByMode[1], ByMode[2], ByMode[3], ByMode[4]));+ VerseBotTestProof::Write(TEXT("8.10"), TEXT("fire_audit_sample.log"), Sample);+ AddInfo(FString::Printf(TEXT("F4: %d bouts, %lld rounds fired, %lld without record, %lld recheck failures, %lld blocked intents"),+ Bouts, Shots, ShotsWithoutRecord, RecheckFailures, Blocked));+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseBot/Private/Tests/Brain/Fakes/FakeVerseBotWorld.h b/unreal/Verse/Source/VerseBot/Private/Tests/Brain/Fakes/FakeVerseBotWorld.hnew file mode 100644index 0000000000..b13b76c7ee--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tests/Brain/Fakes/FakeVerseBotWorld.h@@ -0,0 +1,344 @@+#pragma once++#if WITH_DEV_AUTOMATION_TESTS++#include "Bot/VerseBotTier.h"+#include "Brain/VerseBotBelief.h"+#include "Brain/VerseBotWorldQueries.h"+#include "CoreMinimal.h"++/**+ * A box-wall arena that answers IVerseBotWorldQueries (WP08 fake of the world queries: the WP06+ * piece belief, the Recast path and the WP11 arena data). Walls are axis-aligned boxes on the floor;+ * a wall can be a destructible piece (penetrable, breachable). Sight and bolt traces are exact+ * segment-box tests, paths go straight or around one wall corner.+ */+class FFakeVerseBotWorldQueries final : public IVerseBotWorldQueries+{+public:+ struct FWall+ {+ FBox Box;+ int32 PieceIndex = INDEX_NONE;+ bool bPenetrable = false;+ bool bBreachable = false;+ bool bOpen = false;+ };++ TArray<FWall> Walls;+ TArray<FVector> Spawns;+ TArray<FVerseBotCoverPoint> Cover;+ bool bFinisherReady = true;+ FVerseBotWeaponInfo Weapon;+ int32 Calls = 0;++ /** Wall from (X0, Y0) to (X1, Y1) in metres, Height metres. */+ int32 AddWall(float X0, float Y0, float X1, float Y1, float HeightM, int32 Piece = INDEX_NONE, bool bPen = false, bool bBreach = false)+ {+ FWall W;+ W.Box = FBox(FVector(FMath::Min(X0, X1) * 100.f, FMath::Min(Y0, Y1) * 100.f, 0.f),+ FVector(FMath::Max(X0, X1) * 100.f, FMath::Max(Y0, Y1) * 100.f, HeightM * 100.f));+ W.PieceIndex = Piece;+ W.bPenetrable = bPen;+ W.bBreachable = bBreach;+ return Walls.Add(W);+ }++ /** Cover points on both long sides of every wall, one per end (edges) and one in the middle. */+ void BuildCover()+ {+ Cover.Reset();+ int32 Id = 0;+ for (int32 w = 0; w < Walls.Num(); ++w)+ {+ const FWall& W = Walls[w];+ const FVector C = W.Box.GetCenter();+ const FVector E = W.Box.GetExtent();+ const bool bAlongX = E.X >= E.Y;+ const FVector Along = bAlongX ? FVector(1, 0, 0) : FVector(0, 1, 0);+ const FVector Normal = bAlongX ? FVector(0, 1, 0) : FVector(1, 0, 0);+ const float Half = float(bAlongX ? E.X : E.Y);+ const float Thick = float(bAlongX ? E.Y : E.X);+ for (const float Side : {-1.f, 1.f})+ {+ for (const float T : {-0.8f, 0.f, 0.8f})+ {+ FVerseBotCoverPoint P;+ P.Id = Id++;+ P.Location = FVector(C.X, C.Y, 0.f) + Along * (T * Half) + Normal * Side * (Thick + 60.f);+ P.bHigh = W.Box.Max.Z >= 160.f;+ P.Facing = -Normal * Side;+ P.EdgeId = T != 0.f ? P.Id : INDEX_NONE;+ P.MaterialProtection = W.bPenetrable ? 0.4f : 1.f;+ P.bBulwarkSpot = false;+ if (W.PieceIndex != INDEX_NONE)+ {+ P.DependsOnPieces.Add(uint16(W.PieceIndex));+ }+ Cover.Add(P);+ }+ }+ }+ // Open-ground Bulwark spots on a 10 m grid.+ for (int32 x = -2; x <= 2; ++x)+ {+ for (int32 y = -2; y <= 2; ++y)+ {+ FVerseBotCoverPoint P;+ P.Id = Id++;+ P.Location = FVector(x * 1000.f, y * 800.f, 0.f);+ P.bBulwarkSpot = true;+ P.bHigh = true;+ if (!Blocked(P.Location + FVector(0, 0, 50), P.Location + FVector(0, 0, 50)))+ {+ Cover.Add(P);+ }+ }+ }+ }++ /** True when the segment enters a closed wall (Penetrable filter: -1 any, 0 solid only, 1 penetrable only). */+ bool Blocked(const FVector& A, const FVector& B, int32 Penetrable = -1, int32* OutCount = nullptr) const+ {+ int32 Count = 0;+ for (const FWall& W : Walls)+ {+ if (W.bOpen)+ {+ continue;+ }+ if (Penetrable == 0 && W.bPenetrable) continue;+ if (Penetrable == 1 && !W.bPenetrable) continue;+ if (SegmentHitsBox(A, B, W.Box))+ {+ ++Count;+ if (!OutCount)+ {+ return true;+ }+ }+ }+ if (OutCount)+ {+ *OutCount = Count;+ }+ return Count > 0;+ }++ static bool SegmentHitsBox(const FVector& A, const FVector& B, const FBox& Box)+ {+ if (A.Equals(B))+ {+ return Box.IsInside(A);+ }+ return FMath::LineBoxIntersection(Box, A, B, B - A);+ }++ bool IsWalkable(const FVector& P) const+ {+ for (const FWall& W : Walls)+ {+ if (!W.bOpen && W.Box.ExpandBy(FVector(30.f, 30.f, 0.f)).IsInsideOrOnXY(P))+ {+ return false;+ }+ }+ return FMath::Abs(P.X) < 2600.f && FMath::Abs(P.Y) < 2100.f;+ }++ bool ClearWalk(const FVector& A, const FVector& B) const+ {+ const FVector Lift(0, 0, 50.f);+ for (const FWall& W : Walls)+ {+ if (!W.bOpen && SegmentHitsBox(A + Lift, B + Lift, W.Box.ExpandBy(FVector(30.f, 30.f, 0.f))))+ {+ return false;+ }+ }+ return true;+ }++ virtual bool TestSight(const FVector& Eye, const FVector& Target) override+ {+ ++Calls;+ return !Blocked(Eye, Target);+ }++ virtual FVerseBotBoltTrace TraceBolt(const FVector& Origin, const FVector& Target, const FVerseBotWeaponInfo& InWeapon) override+ {+ ++Calls;+ FVerseBotBoltTrace R;+ if (Blocked(Origin, Target, 0))+ {+ R.DamageFrac = 0.f;+ R.Pieces = 9;+ return R;+ }+ int32 N = 0;+ Blocked(Origin, Target, 1, &N);+ R.Pieces = N;+ R.DamageFrac = FMath::Pow(0.6f, float(N));+ return R;+ }++ virtual FVerseBotPath FindPath(const FVector& From, const FVector& To, bool bCrouch) override+ {+ ++Calls;+ FVerseBotPath P;+ const FVector F(From.X, From.Y, 0.f), T(To.X, To.Y, 0.f);+ if (!IsWalkable(T))+ {+ return P; // no nav at the target+ }+ if (ClearWalk(F, T))+ {+ P.bValid = true;+ P.Waypoints.Add(T);+ P.LengthCm = float(FVector::Dist2D(F, T));+ return P;+ }+ float Best = 1.0e9f;+ FVector BestCorner = T;+ for (const FWall& W : Walls)+ {+ if (W.bOpen)+ {+ continue;+ }+ const FBox E = W.Box.ExpandBy(FVector(70.f, 70.f, 0.f));+ const FVector Corners[4] = {FVector(E.Min.X, E.Min.Y, 0), FVector(E.Min.X, E.Max.Y, 0), FVector(E.Max.X, E.Min.Y, 0), FVector(E.Max.X, E.Max.Y, 0)};+ for (const FVector& C : Corners)+ {+ if (IsWalkable(C) && ClearWalk(F, C) && ClearWalk(C, T))+ {+ const float L = float(FVector::Dist2D(F, C) + FVector::Dist2D(C, T));+ if (L < Best)+ {+ Best = L;+ BestCorner = C;+ }+ }+ }+ }+ if (Best < 1.0e9f)+ {+ P.bValid = true;+ P.Waypoints.Add(BestCorner);+ P.Waypoints.Add(T);+ P.LengthCm = Best;+ }+ return P;+ }++ virtual void GetCoverPoints(const FVector& Center, float RadiusCm, TArray<FVerseBotCoverPoint>& Out) override+ {+ ++Calls;+ Out.Reset();+ for (const FVerseBotCoverPoint& P : Cover)+ {+ if (FVector::Dist2D(P.Location, Center) <= RadiusCm)+ {+ Out.Add(P);+ }+ }+ }++ virtual void GetPieces(const FVector& Center, float RadiusCm, TArray<FVerseBotPieceInfo>& Out) override+ {+ ++Calls;+ Out.Reset();+ for (const FWall& W : Walls)+ {+ if (W.PieceIndex == INDEX_NONE || FVector::Dist2D(W.Box.GetCenter(), Center) > RadiusCm)+ {+ continue;+ }+ FVerseBotPieceInfo P;+ P.PieceIndex = uint16(W.PieceIndex);+ P.Center = FVector(W.Box.GetCenter().X, W.Box.GetCenter().Y, 100.f);+ const FVector E = W.Box.GetExtent();+ P.Normal = E.X >= E.Y ? FVector(0, 1, 0) : FVector(1, 0, 0);+ P.bBreachable = W.bBreachable;+ P.bPenetrable = W.bPenetrable;+ Out.Add(P);+ }+ }++ virtual void GetSpawnPoints(TArray<FVector>& Out) override+ {+ ++Calls;+ Out = Spawns;+ }++ virtual int32 GetZoneId(const FVector& Location) override+ {+ ++Calls;+ const int32 X = FMath::Clamp(FMath::FloorToInt32((Location.X + 2500.f) / 1000.f), 0, 4);+ const int32 Y = FMath::Clamp(FMath::FloorToInt32((Location.Y + 2000.f) / 1000.f), 0, 3);+ return Y * 5 + X;+ }++ virtual FVerseBotWeaponInfo GetOwnWeapon() override+ {+ ++Calls;+ return Weapon;+ }++ virtual bool CanActivateFinisher() override+ {+ ++Calls;+ return bFinisherReady;+ }++ /** The standard WP08 fixture: a 50 x 40 m arena with high walls, low cover and two breachable panels. */+ static void BuildStandardArena(FFakeVerseBotWorldQueries& W)+ {+ W.Walls.Reset();+ W.AddWall(-12.f, -1.f, -11.6f, 9.f, 3.f);+ W.AddWall(11.6f, -9.f, 12.f, 1.f, 3.f);+ W.AddWall(-4.f, 6.f, 4.f, 6.4f, 3.f, 1, true, true);+ W.AddWall(-4.f, -6.4f, 4.f, -6.f, 3.f, 2, true, true);+ W.AddWall(-1.f, -1.f, 1.f, 1.f, 1.f);+ W.AddWall(-20.f, -14.f, -16.f, -13.6f, 3.f);+ W.AddWall(16.f, 13.6f, 20.f, 14.f, 3.f);+ W.AddWall(-20.f, 10.f, -19.6f, 16.f, 1.f);+ W.AddWall(19.6f, -16.f, 20.f, -10.f, 1.f);+ W.Spawns = {FVector(-2200.f, -1700.f, 0.f), FVector(2200.f, 1700.f, 0.f), FVector(-2200.f, 1700.f, 0.f),+ FVector(2200.f, -1700.f, 0.f), FVector(0.f, 1700.f, 0.f), FVector(0.f, -1700.f, 0.f)};+ W.BuildCover();+ }+};++/** A scripted belief (WP07 fake): every derived value is set by the test. */+class FFakeVerseBotBelief final : public IVerseBotBelief+{+public:+ FVerseBotBeliefSummary S;+ float Mass = 0.f;+ float SupportedMass = 0.f;+ TArray<FVector> Cells;+ TMap<uint16, EVersePieceState> PieceStates;++ virtual void Reset() override {}+ virtual void Step(const FVersePerceptFrame&, float, const FVerseBotMatchMemory*, TConstArrayView<FVector>) override {}+ virtual void NoteOwnPieceChange(uint16 PieceIndex, EVersePieceState NewState) override { PieceStates.Add(PieceIndex, NewState); }+ virtual FVerseBotBeliefSummary Summary() const override { return S; }+ virtual float MassWithin(const FVector& L, float R) const override { return FVector::Dist2D(L, S.TopCenter) <= R + 300.f ? Mass : 0.f; }+ virtual float SupportedMassWithin(const FVector& L, float R) const override { return FVector::Dist2D(L, S.TopCenter) <= R + 300.f ? SupportedMass : 0.f; }+ virtual void TopCells(int32 N, TArray<FVector>& Out) const override+ {+ Out = Cells.Num() > 0 ? Cells : TArray<FVector>({S.TopCenter});+ if (Out.Num() > N)+ {+ Out.SetNum(N);+ }+ }+ virtual EVersePieceState GetPieceBelief(uint16 PieceIndex) const override+ {+ const EVersePieceState* St = PieceStates.Find(PieceIndex);+ return St ? *St : EVersePieceState::Intact;+ }+};++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseBot/Private/Tests/Brain/Fakes/FakeVerseDuelSim.h b/unreal/Verse/Source/VerseBot/Private/Tests/Brain/Fakes/FakeVerseDuelSim.hnew file mode 100644index 0000000000..147e80a0bc--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tests/Brain/Fakes/FakeVerseDuelSim.h@@ -0,0 +1,457 @@+#pragma once++#if WITH_DEV_AUTOMATION_TESTS++#include "Bot/VersePerceptTypes.h"+#include "Brain/VerseBotBrainCore.h"+#include "Brain/VerseBotReplay.h"+#include "CoreMinimal.h"+#include "Tests/Brain/Fakes/FakeVerseBotWorld.h"+#include "VerseGameplayTags.h"+#include "VerseRng.h"++/**+ * A world-free 1v1 at 60 Hz for WP08's tests (the WP07 perception, WP09 aim, WP01/WP02 pawn and+ * WP10 harness fakes in one): it moves the bot's fake pawn from the input frame, scripts the+ * opponent, and builds the bot's percept frames with the fair rules of bot.md 3 (55 deg cone and+ * line of sight for sight, audibility ranges and error for hearing, hurt percepts, HUD events).+ * The brain never sees the opponent's state except through those frames.+ */+class FFakeVerseDuelSim+{+public:+ enum class EModel : uint8+ {+ /** Walks a loop of waypoints, runs (audible), fights on sight. */+ Patrol,+ /** Avoids every fight: hides at a far spot, crouch-walks, never fires (BG12 hider). */+ Hider,+ /** Silent and still at a fixed spot (F3). */+ Still+ };++ struct FConfig+ {+ uint64 Seed = 1;+ EModel Model = EModel::Patrol;+ FVector StillSpot = FVector(0.f, 1000.f, 0.f);+ float BotHitChance = 0.3f;+ float OpponentHitChance = 0.22f;+ };++ FFakeVerseBotWorldQueries World;+ FVerseBotBrainCore Brain;+ FConfig Config;+ UVerseBotTier* Tier = nullptr;++ // Truth (sim only; the brain never reads it).+ FVector BotPos, BotVel = FVector::ZeroVector;+ FRotator BotView = FRotator::ZeroRotator;+ float BotHealth = 100.f;+ int32 BotMag = 30, BotReserve = 90;+ float BotDeadUntil = -1.f;+ FVector OppPos, OppVel = FVector::ZeroVector;+ float OppYaw = 0.f;+ float OppHealth = 100.f;+ float OppDeadUntil = -1.f;+ float OppSawBotAt = -1.f;+ float OppNextShot = 0.f;+ float BotNextShot = 0.f;+ int32 OppWaypoint = 0;+ uint32 TimeMs = 0;+ uint32 NextPerceptId = 1;+ float NextFootstepS = 0.f;+ FVerseRng Rng;++ // Results+ int32 BotKills = 0, OppKills = 0;+ int32 Ticks = 0;+ int32 VisibleTicks = 0;+ int32 FireTicks = 0;+ float LifeStartS = 0.f;+ bool bContactThisLife = false;+ TArray<float> TimeToContactS;+ TArray<double> ThinkUs;+ bool bMeasure = false;+ TArray<FVersePerceptFrame> RecordedFrames;+ bool bRecordFrames = false;+ TArray<uint8> Outputs;+ bool bRecordOutputs = false;++ /** F4 evidence at the shot event: every round the bot's weapon fired, and every percept the+ * sim delivered (id -> kind, time), so a test can re-check each audit record on its own. */+ enum class EDelivered : uint8 { Sight, Heard };+ struct FDelivered+ {+ EDelivered Kind = EDelivered::Sight;+ uint32 TimeMs = 0;+ };+ struct FShot+ {+ uint32 TimeMs = 0;+ /** The fair sight rule held at the shot tick (truth, sim only). */+ bool bBotSawOpponent = false;+ };+ bool bRecordShots = false;+ TArray<FShot> Shots;+ TMap<uint32, FDelivered> Delivered;++ static constexpr int32 BotId = 1;+ static constexpr int32 OppId = 2;++ FFakeVerseDuelSim(FName TierId, const FConfig& InConfig)+ : Config(InConfig)+ , Rng(InConfig.Seed, 7, EVerseRngSalt::Harness)+ {+ FFakeVerseBotWorldQueries::BuildStandardArena(World);+ Tier = NewObject<UVerseBotTier>();+ Tier->AddToRoot();+ UVerseBotTier::ApplyStartValues(TierId, *Tier);+ FVerseBotBrainCore::FConfig BC;+ BC.Seed = InConfig.Seed;+ BC.SelfId = BotId;+ Brain.Init(*Tier, BC);+ BotPos = World.Spawns[0];+ OppPos = Config.Model == EModel::Still ? Config.StillSpot : World.Spawns[1];+ BotView = (OppPos - BotPos).Rotation();+ BotView.Pitch = 0.f;+ BotView.Yaw += 90.f;+ }++ ~FFakeVerseDuelSim()+ {+ if (Tier)+ {+ Tier->RemoveFromRoot();+ }+ }++ FFakeVerseDuelSim(const FFakeVerseDuelSim&) = delete;+ FFakeVerseDuelSim& operator=(const FFakeVerseDuelSim&) = delete;++ float Now() const { return float(TimeMs) / 1000.f; }++ FVector BotEye() const { return BotPos + FVector(0, 0, 165.f); }+ FVector OppPelvis() const { return OppPos + FVector(0, 0, 95.f); }++ bool BotSeesOpp() const+ {+ if (OppDeadUntil > Now())+ {+ return false;+ }+ const FVector To = OppPelvis() + FVector(0, 0, 40.f) - BotEye();+ const float Angle = FMath::RadiansToDegrees(FMath::Acos(FMath::Clamp(float(FVector::DotProduct(To.GetSafeNormal(), BotView.Vector())), -1.f, 1.f)));+ const bool bClose = To.Size2D() < 200.f;+ return (Angle <= 55.f || bClose) && !World.Blocked(BotEye(), OppPelvis() + FVector(0, 0, 40.f));+ }++ bool OppSeesBot() const+ {+ const FVector To = BotEye() - (OppPos + FVector(0, 0, 165.f));+ const FVector Facing = FRotator(0.f, OppYaw, 0.f).Vector();+ const float Angle = FMath::RadiansToDegrees(FMath::Acos(FMath::Clamp(float(FVector::DotProduct(To.GetSafeNormal2D(), Facing)), -1.f, 1.f)));+ return Angle <= 55.f && !World.Blocked(OppPos + FVector(0, 0, 165.f), BotEye());+ }++ FVector FarthestSpawnFrom(const FVector& From)+ {+ FVector Best = World.Spawns[0];+ float BestD = -1.f;+ for (const FVector& S : World.Spawns)+ {+ const float D = float(FVector::Dist2D(S, From));+ if (D > BestD)+ {+ BestD = D;+ Best = S;+ }+ }+ return Best;+ }++ void MoveOpponent(float Dt)+ {+ if (Config.Model == EModel::Still)+ {+ OppVel = FVector::ZeroVector;+ return;+ }+ static const FVector Loop[6] = {FVector(-1800, -1000, 0), FVector(-500, 1200, 0), FVector(1500, 900, 0),+ FVector(1800, -1200, 0), FVector(300, -1500, 0), FVector(-1500, 300, 0)};+ FVector Target = Loop[OppWaypoint % 6];+ float Speed = 450.f;+ if (Config.Model == EModel::Hider)+ {+ // Hide behind the wall farthest from the bot and crouch-walk (silent, 2 m/s).+ Target = BotPos.X > 0.f ? FVector(-1900.f, -1500.f, 0.f) : FVector(1900.f, 1500.f, 0.f);+ Speed = 200.f;+ }+ const FVerseBotPath Path = World.FindPath(OppPos, Target, false);+ const FVector Way = Path.bValid && Path.Waypoints.Num() > 0 ? Path.Waypoints[0] : Target;+ const FVector Dir = (Way - OppPos).GetSafeNormal2D();+ if (FVector::Dist2D(OppPos, Target) < 80.f)+ {+ ++OppWaypoint;+ OppVel = FVector::ZeroVector;+ return;+ }+ const FVector Next = OppPos + Dir * Speed * Dt;+ if (World.IsWalkable(Next))+ {+ OppPos = Next;+ OppVel = Dir * Speed;+ if (!(OppSawBotAt >= 0.f))+ {+ OppYaw = float(Dir.Rotation().Yaw);+ }+ }+ else+ {+ ++OppWaypoint;+ }+ }++ /** One 60 Hz tick: percepts, brain, apply input, opponent, combat. */+ void Tick()+ {+ const float Dt = 1.f / 60.f;+ TimeMs += 17;+ const float T = Now();+ FVersePerceptFrame F;+ F.ServerTimeMs = TimeMs;+ F.Hud = MoveTemp(PendingHud);+ PendingHud.Reset();++ // Respawns.+ if (BotDeadUntil >= 0.f && T >= BotDeadUntil)+ {+ BotDeadUntil = -1.f;+ BotHealth = 100.f;+ BotMag = 30;+ BotReserve = 90;+ BotPos = FarthestSpawnFrom(OppPos);+ LifeStartS = T;+ bContactThisLife = false;+ }+ if (OppDeadUntil >= 0.f && T >= OppDeadUntil)+ {+ OppDeadUntil = -1.f;+ OppHealth = 100.f;+ OppPos = Config.Model == EModel::Still ? Config.StillSpot : FarthestSpawnFrom(BotPos);+ LifeStartS = T;+ bContactThisLife = false;+ FVerseHudEvent E;+ E.Kind = EVerseHudEventKind::OpponentRespawned;+ E.ServerTimeMs = TimeMs;+ F.Hud.Add(E);+ }+ const bool bBotAlive = BotDeadUntil < 0.f;+ const bool bOppAlive = OppDeadUntil < 0.f;++ // Own HUD.+ FVerseSelfPercept& S = F.Self;+ S.Health = BotHealth;+ S.MaxHealth = 100.f;+ S.Magazine = BotMag;+ S.bChambered = BotMag > 0;+ S.Reserve = BotReserve;+ S.GadgetCharges[0] = 1;+ S.GadgetCharges[1] = 2;+ S.Location = BotPos;+ S.Velocity = BotVel;+ S.EyeLocation = BotEye();+ S.ViewRotation = BotView;+ S.Phase = bBotAlive ? EVerseCombatPhase::Alive : EVerseCombatPhase::Dead;++ // Sight (3.1).+ const bool bSees = bBotAlive && bOppAlive && BotSeesOpp();+ if (bSees)+ {+ FVerseSightPercept P;+ P.PerceptId = NextPerceptId++;+ P.PelvisLocation = OppPelvis();+ P.Velocity = OppVel;+ P.FacingYawDeg = OppYaw;+ P.VisibleMask = 0xff;+ F.Sightings.Add(P);+ ++VisibleTicks;+ if (!bContactThisLife)+ {+ bContactThisLife = true;+ TimeToContactS.Add(T - LifeStartS);+ }+ }+ // Hearing (3.2): run footsteps within 10 m every 0.4 s; error sd base + per-metre.+ if (bBotAlive && bOppAlive && OppVel.Size2D() > 300.f && T >= NextFootstepS)+ {+ NextFootstepS = T + 0.4f;+ const float D = float(FVector::Dist(OppPos, BotPos)) / 100.f;+ if (D <= 10.f)+ {+ FVerseHeardPercept H;+ H.PerceptId = NextPerceptId++;+ H.Noise = VerseTags::Noise_Footstep_Run;+ H.ErrorSdM = (Tier->HearingErrorBaseM + Tier->HearingErrorPerM * D) * 1.3f;+ const FVector2D Disk = Rng.UnitDisk();+ H.Location = OppPos + FVector(Disk.X, Disk.Y, 0.f) * H.ErrorSdM * 100.f;+ H.ServerTimeMs = TimeMs;+ F.Heard.Add(H);+ }+ }++ // Opponent shoots on sight after a 0.3 s reaction.+ if (bBotAlive && bOppAlive && Config.Model == EModel::Patrol && OppSeesBot())+ {+ if (OppSawBotAt < 0.f)+ {+ OppSawBotAt = T;+ }+ OppYaw = float((BotPos - OppPos).Rotation().Yaw);+ if (T - OppSawBotAt > 0.3f && T >= OppNextShot)+ {+ OppNextShot = T + 0.1f;+ const float D = float(FVector::Dist(OppPos, BotPos)) / 100.f;+ FVerseHeardPercept H;+ H.PerceptId = NextPerceptId++;+ H.Noise = VerseTags::Noise_Shot;+ H.ErrorSdM = Tier->HearingErrorBaseM + Tier->HearingErrorPerM * D;+ const FVector2D Disk = Rng.UnitDisk();+ H.Location = OppPos + FVector(Disk.X, Disk.Y, 0.f) * H.ErrorSdM * 100.f;+ H.ServerTimeMs = TimeMs;+ F.Heard.Add(H);+ if (Rng.Chance(Config.OpponentHitChance))+ {+ BotHealth -= 25.f;+ F.bHasHurt = true;+ F.Hurt.PerceptId = NextPerceptId++;+ F.Hurt.Damage = 25.f;+ F.Hurt.IncomingDirection = (OppPos - BotPos).GetSafeNormal().RotateAngleAxis(float(Rng.Range(-8.0, 8.0)), FVector::UpVector);+ F.Hurt.ServerTimeMs = TimeMs;+ if (BotHealth <= 0.f)+ {+ ++OppKills;+ BotDeadUntil = T + 3.f;+ FVerseHudEvent E;+ E.Kind = EVerseHudEventKind::Kill;+ E.KillerId = OppId;+ E.VictimId = BotId;+ E.ServerTimeMs = TimeMs;+ F.Hud.Add(E);+ }+ }+ }+ }+ else+ {+ OppSawBotAt = -1.f;+ }++ // Brain.+ if (bRecordFrames)+ {+ RecordedFrames.Add(F);+ }+ if (bRecordShots)+ {+ for (const FVerseSightPercept& P : F.Sightings)+ {+ Delivered.Add(P.PerceptId, FDelivered{EDelivered::Sight, TimeMs});+ }+ for (const FVerseHeardPercept& H : F.Heard)+ {+ Delivered.Add(H.PerceptId, FDelivered{EDelivered::Heard, TimeMs});+ }+ }+ const double T0 = bMeasure ? FPlatformTime::Seconds() : 0.0;+ const FVerseInputFrame In = Brain.Think(F, World);+ if (bMeasure)+ {+ ThinkUs.Add((FPlatformTime::Seconds() - T0) * 1.0e6);+ }+ if (In.IsHeld(EVerseInputButton::Fire))+ {+ ++FireTicks;+ }+ if (bRecordOutputs)+ {+ FVerseBotTape::AppendOutput(Outputs, In);+ }++ // Apply the bot's input to its fake pawn (the same path a person uses).+ if (BotDeadUntil < 0.f)+ {+ BotView.Pitch = FMath::Clamp(float(BotView.Pitch) + In.LookDeltaDeg.X, -89.f, 89.f);+ BotView.Yaw = FRotator::NormalizeAxis(float(BotView.Yaw) + In.LookDeltaDeg.Y);+ const FRotator Yaw(0.f, BotView.Yaw, 0.f);+ const float Speed = In.IsHeld(EVerseInputButton::Sprint) ? 650.f : In.IsHeld(EVerseInputButton::Crouch) ? 200.f : 450.f;+ const FVector Wish = Yaw.RotateVector(FVector(In.Move.X, In.Move.Y, 0.f)) * Speed;+ // Slide along walls like a character movement component: full step, else one axis.+ const FVector Steps[3] = {Wish * Dt, FVector(Wish.X, 0.f, 0.f) * Dt, FVector(0.f, Wish.Y, 0.f) * Dt};+ BotVel = FVector::ZeroVector;+ for (const FVector& Step : Steps)+ {+ if (!Step.IsNearlyZero() && World.IsWalkable(BotPos + Step))+ {+ BotPos += Step;+ BotVel = Step / Dt;+ break;+ }+ }+ if (In.WasPressed(EVerseInputButton::Reload) && BotMag < 30 && BotReserve > 0)+ {+ const int32 Need = FMath::Min(30 - BotMag, BotReserve);+ BotMag += Need;+ BotReserve -= Need;+ }+ if (In.IsHeld(EVerseInputButton::Fire) && BotMag > 0 && T >= BotNextShot)+ {+ BotNextShot = T + 0.1f;+ --BotMag;+ if (bRecordShots)+ {+ Shots.Add(FShot{TimeMs, bSees});+ }+ if (bSees && OppDeadUntil < 0.f && Rng.Chance(Config.BotHitChance))+ {+ OppHealth -= 25.f;+ FVerseHudEvent E;+ E.Kind = OppHealth <= 0.f ? EVerseHudEventKind::KillMarker : EVerseHudEventKind::HitMarker;+ E.ServerTimeMs = TimeMs;+ PendingHud.Add(E);+ if (OppHealth <= 0.f)+ {+ ++BotKills;+ OppDeadUntil = T + 3.f;+ FVerseHudEvent K;+ K.Kind = EVerseHudEventKind::Kill;+ K.KillerId = BotId;+ K.VictimId = OppId;+ K.ServerTimeMs = TimeMs;+ PendingHud.Add(K);+ }+ }+ }+ }+ if (OppDeadUntil < 0.f)+ {+ MoveOpponent(Dt);+ }+ ++Ticks;+ }++ /** HUD events raised by the bot's own shots reach it on the next frame. */+ TArray<FVerseHudEvent> PendingHud;++ void Run(int32 NumTicks)+ {+ for (int32 i = 0; i < NumTicks; ++i)+ {+ Tick();+ }+ }++ int32 Kills() const { return BotKills + OppKills; }+};++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseBot/Private/Tests/Brain/VerseBotReactionTest.cpp b/unreal/Verse/Source/VerseBot/Private/Tests/Brain/VerseBotReactionTest.cppnew file mode 100644index 0000000000..525d2dc79c--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tests/Brain/VerseBotReactionTest.cpp@@ -0,0 +1,210 @@+#include "Bot/VerseBotTier.h"+#include "Brain/VerseBotBrainCore.h"+#include "Controller/VerseBotEngineQueries.h"+#include "Misc/AutomationTest.h"+#include "Tests/Brain/Fakes/FakeVerseBotWorld.h"+#include "VerseGameplayTags.h"++#if WITH_DEV_AUTOMATION_TESTS++#define VERSE_BOT_TEST_FLAGS (EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++namespace VerseBotReactionTest+{+ constexpr uint32 TickMs = 17;++ FVersePerceptFrame BaseFrame(uint32 TimeMs, const FVector& At, const FRotator& View, float Health)+ {+ FVersePerceptFrame F;+ F.ServerTimeMs = TimeMs;+ F.Self.Health = Health;+ F.Self.MaxHealth = 100.f;+ F.Self.Magazine = 30;+ F.Self.bChambered = true;+ F.Self.Reserve = 90;+ F.Self.Location = At;+ F.Self.EyeLocation = At + FVector(0, 0, 165.f);+ F.Self.ViewRotation = View;+ F.Self.Phase = EVerseCombatPhase::Alive;+ return F;+ }++ bool SameOutput(const FVerseInputFrame& A, const FVerseInputFrame& B)+ {+ return A.Buttons == B.Buttons && A.Pressed == B.Pressed && A.Move == B.Move && A.LookDeltaDeg == B.LookDeltaDeg;+ }++ enum class EStimulus : uint8 { Sighting, CloseSighting, Hurt };++ /**+ * Two brains, same seed: B never gets the stimulus, A gets it from tick Start on. Returns the+ * ticks A held the stimulus back, and whether every output and state was identical meanwhile.+ */+ struct FResult+ {+ int32 PendingTicks = 0;+ bool bIdenticalWhilePending = true;+ bool bReactedAfter = false;+ };++ FResult Run(EStimulus Stimulus, uint64 Seed, UVerseBotTier& Tier)+ {+ FFakeVerseBotWorldQueries WorldA, WorldB;+ FFakeVerseBotWorldQueries::BuildStandardArena(WorldA);+ FFakeVerseBotWorldQueries::BuildStandardArena(WorldB);+ FVerseBotBrainCore A, B;+ FVerseBotBrainCore::FConfig Config;+ Config.Seed = Seed;+ Config.SelfId = 1;+ A.Init(Tier, Config);+ B.Init(Tier, Config);+ const FVector At(-2200.f, -1700.f, 0.f);+ const FVector Opp = Stimulus == EStimulus::CloseSighting ? At + FVector(150.f, 0.f, 0.f) : At + FVector(900.f, 0.f, 0.f);+ const FRotator View(0.f, 0.f, 0.f);+ constexpr int32 Start = 60;+ FResult R;+ bool bReleased = false;+ for (int32 t = 0; t < Start + 90; ++t)+ {+ const uint32 Ms = TickMs * uint32(t + 1);+ const bool bOn = t >= Start;+ FVersePerceptFrame FB = BaseFrame(Ms, At, View, 100.f);+ FVersePerceptFrame FA = BaseFrame(Ms, At, View, (bOn && Stimulus == EStimulus::Hurt) ? 75.f : 100.f);+ if (bOn && Stimulus != EStimulus::Hurt)+ {+ FVerseSightPercept S;+ S.PerceptId = 1000 + t;+ S.PelvisLocation = Opp + FVector(0, 0, 95.f);+ S.FacingYawDeg = 180.f;+ S.VisibleMask = 0xff;+ FA.Sightings.Add(S);+ }+ if (t == Start && Stimulus == EStimulus::Hurt)+ {+ FA.bHasHurt = true;+ FA.Hurt.PerceptId = 5000;+ FA.Hurt.Damage = 25.f;+ FA.Hurt.IncomingDirection = FVector(1, 0, 0);+ FA.Hurt.ServerTimeMs = Ms;+ }+ const FVerseInputFrame OA = A.Think(FA, WorldA);+ const FVerseInputFrame OB = B.Think(FB, WorldB);+ if (!bOn)+ {+ continue;+ }+ if (A.IsReactionPending() && !bReleased)+ {+ ++R.PendingTicks;+ R.bIdenticalWhilePending &= SameOutput(OA, OB) && A.GetState() == B.GetState() && A.GetDecisionCount() == B.GetDecisionCount();+ }+ else+ {+ bReleased = true;+ // The answer: a forced re-decide on release, or different input or state.+ R.bReactedAfter |= A.GetDecisionCount() != B.GetDecisionCount() || !SameOutput(OA, OB) || A.GetState() != B.GetState();+ }+ }+ return R;+ }+}++// 5.2 / 8.1: a first sighting or a hit taken changes no button and no state before the sampled+// reaction; the knife reflex at 1.5 m waits for it too.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotReactionGateTest, "Verse.Bot.Brain.ReactionGate", VERSE_BOT_TEST_FLAGS)++bool FVerseBotReactionGateTest::RunTest(const FString& Parameters)+{+ using namespace VerseBotReactionTest;+ UVerseBotTier* Tier = NewObject<UVerseBotTier>();+ Tier->AddToRoot();+ UVerseBotTier::ApplyStartValues(TEXT("elite"), *Tier);+ Tier->KnifeChoice = 1.f;+ const int32 FloorTicks = FMath::FloorToInt32(0.6f * Tier->ReactionMs.X / float(TickMs)) - 1;+ const TCHAR* Names[3] = {TEXT("sighting"), TEXT("close sighting"), TEXT("hurt")};+ for (int32 k = 0; k < 3; ++k)+ {+ for (uint64 Seed = 1; Seed <= 5; ++Seed)+ {+ const FResult R = Run(EStimulus(k), Seed, *Tier);+ TestTrue(FString::Printf(TEXT("%s seed %llu: reaction held at least the floor (%d ticks >= %d)"), Names[k], Seed, R.PendingTicks, FloorTicks),+ R.PendingTicks >= FloorTicks);+ TestTrue(FString::Printf(TEXT("%s seed %llu: no button or state change before the reaction"), Names[k], Seed), R.bIdenticalWhilePending);+ TestTrue(FString::Printf(TEXT("%s seed %llu: the bot answers after the reaction"), Names[k], Seed), R.bReactedAfter);+ }+ }+ Tier->RemoveFromRoot();+ return true;+}++// 8.4 / 7.2: the prefire mode occurs (PrefireChance per approach) at the peek edge a fresh heard+// percept is near, and never without the roll.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotPrefireTest, "Verse.Bot.Brain.Prefire", VERSE_BOT_TEST_FLAGS)++bool FVerseBotPrefireTest::RunTest(const FString& Parameters)+{+ using namespace VerseBotReactionTest;+ UVerseBotTier* Tier = NewObject<UVerseBotTier>();+ Tier->AddToRoot();+ UVerseBotTier::ApplyStartValues(TEXT("elite"), *Tier);+ int32 Prefires[2] = {0, 0};+ for (int32 Pass = 0; Pass < 2; ++Pass)+ {+ Tier->PrefireChance = Pass == 0 ? 1.f : 0.f;+ FFakeVerseBotWorldQueries World;+ FFakeVerseBotWorldQueries::BuildStandardArena(World);+ const FVerseBotCoverPoint* Edge = World.Cover.FindByPredicate([](const FVerseBotCoverPoint& P) { return P.EdgeId != INDEX_NONE; });+ if (!TestNotNull(TEXT("arena has a peek edge"), Edge))+ {+ break;+ }+ const FVector EdgeAt = Edge->Location;+ const FVector At = EdgeAt - Edge->Facing.GetSafeNormal2D() * 800.f;+ FRotator View = (EdgeAt + FVector(0, 0, 120.f) - (At + FVector(0, 0, 165.f))).Rotation();+ FVerseBotBrainCore Brain;+ FVerseBotBrainCore::FConfig Config;+ Config.Seed = 77;+ Config.SelfId = 1;+ Brain.Init(*Tier, Config);+ Brain.GetFireAudit().SetCaptureAll(true);+ uint32 Id = 1;+ for (int32 t = 0; t < 120; ++t)+ {+ const uint32 Ms = TickMs * uint32(t + 1);+ FVersePerceptFrame F = BaseFrame(Ms, At, View, 100.f);+ if (t % 30 == 0)+ {+ FVerseHeardPercept H;+ H.PerceptId = Id++;+ H.Noise = VerseTags::Noise_Footstep_Run;+ H.Location = EdgeAt;+ H.ErrorSdM = 0.3f;+ H.ServerTimeMs = Ms;+ F.Heard.Add(H);+ }+ const FVerseInputFrame Out = Brain.Think(F, World);+ View.Pitch = FMath::Clamp(float(View.Pitch) + Out.LookDeltaDeg.X, -89.f, 89.f);+ View.Yaw = FRotator::NormalizeAxis(float(View.Yaw) + Out.LookDeltaDeg.Y);+ }+ Prefires[Pass] = Brain.GetFireAudit().Count(EVerseBotFireMode::Prefire);+ }+ TestTrue(FString::Printf(TEXT("prefire shots with the roll passing (%d)"), Prefires[0]), Prefires[0] > 0);+ TestEqual(TEXT("no prefire without the roll"), Prefires[1], 0);+ Tier->RemoveFromRoot();+ return true;+}++// The engine stand-in's believed-intact piece rule: a segment through a piece's intact bounds is+// blocked whatever the live proxy shows.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotEngineQueriesPieceTest, "Verse.Bot.Controller.PieceBelief", VERSE_BOT_TEST_FLAGS)++bool FVerseBotEngineQueriesPieceTest::RunTest(const FString& Parameters)+{+ const FBox Wall(FVector(-50.f, -200.f, 0.f), FVector(50.f, 200.f, 300.f));+ TestTrue(TEXT("a line through the wall is blocked"), FVerseBotEngineQueries::SegmentHitsBox(Wall, FVector(-500.f, 0.f, 150.f), FVector(500.f, 0.f, 150.f)));+ TestFalse(TEXT("a line past the wall is clear"), FVerseBotEngineQueries::SegmentHitsBox(Wall, FVector(-500.f, 400.f, 150.f), FVector(500.f, 400.f, 150.f)));+ TestFalse(TEXT("a line over the wall is clear"), FVerseBotEngineQueries::SegmentHitsBox(Wall, FVector(-500.f, 0.f, 400.f), FVector(500.f, 0.f, 400.f)));+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseBot/Private/Tests/Brain/VerseBotReplayTest.cpp b/unreal/Verse/Source/VerseBot/Private/Tests/Brain/VerseBotReplayTest.cppnew file mode 100644index 0000000000..9078ab6ef7--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tests/Brain/VerseBotReplayTest.cpp@@ -0,0 +1,149 @@+#include "Brain/VerseBotReplay.h"+#include "Misc/AutomationTest.h"+#include "Tests/Brain/Fakes/FakeVerseDuelSim.h"+#include "Tests/Brain/VerseBotTestProof.h"++#if WITH_DEV_AUTOMATION_TESTS++#define VERSE_BOT_TEST_FLAGS (EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++namespace VerseBotReplayTest+{+ /** Replays a tape on a fresh brain with the same seed and tier; returns the output bytes. */+ bool Replay(const FVerseBotTape& Tape, UVerseBotTier& Tier, TArray<uint8>& OutOutputs, bool& bOutDiverged, bool& bOutAtEnd)+ {+ FVerseBotBrainCore Brain;+ FVerseBotBrainCore::FConfig C;+ C.Seed = Tape.Seed;+ C.SelfId = FFakeVerseDuelSim::BotId;+ Brain.Init(Tier, C);+ FVerseBotReplayQueries Queries(Tape.Queries);+ OutOutputs.Reset();+ for (const FVersePerceptFrame& F : Tape.Frames)+ {+ FVerseBotTape::AppendOutput(OutOutputs, Brain.Think(F, Queries));+ }+ bOutDiverged = Queries.HasDiverged();+ bOutAtEnd = Queries.IsAtEnd();+ return !bOutDiverged;+ }+}++// A8.1 / BR1: 10 recorded 5-minute streams replay bit-identical, and the brain cost per tick.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotReplayTest, "Verse.Bot.Brain.Replay", VERSE_BOT_TEST_FLAGS)++bool FVerseBotReplayTest::RunTest(const FString& Parameters)+{+ constexpr int32 Streams = 10;+ constexpr int32 TicksPerStream = 5 * 60 * 60;+ const FName Tiers[3] = {TEXT("normal"), TEXT("hard"), TEXT("elite")};+ TArray<double> AllUs;+ FString Rows;+ int32 Identical = 0;+ for (int32 s = 0; s < Streams; ++s)+ {+ FFakeVerseDuelSim::FConfig Cfg;+ Cfg.Seed = 1000 + s;+ Cfg.Model = (s % 3 == 2) ? FFakeVerseDuelSim::EModel::Hider : FFakeVerseDuelSim::EModel::Patrol;+ const FName TierId = Tiers[s % 3];++ // Live run: the sim world, its percept frames and the brain's outputs.+ FFakeVerseDuelSim Sim(TierId, Cfg);+ FVerseBotTape Tape;+ Tape.Seed = Cfg.Seed;+ Tape.TierId = TierId;+ Sim.bRecordFrames = true;+ Sim.bRecordOutputs = true;+ Sim.bMeasure = true;+ FVerseBotRecordingQueries Recorder(Sim.World, Tape.Queries);+ Sim.Run(TicksPerStream);+ Tape.Frames = Sim.RecordedFrames;+ Tape.Outputs = Sim.Outputs;++ // Record: a second brain sees the same frames through the recording proxy over the same world+ // and must give the live run's outputs.+ FVerseBotBrainCore Second;+ FVerseBotBrainCore::FConfig C;+ C.Seed = Cfg.Seed;+ C.SelfId = FFakeVerseDuelSim::BotId;+ Second.Init(*Sim.Tier, C);+ TArray<uint8> SecondOut;+ for (const FVersePerceptFrame& F : Tape.Frames)+ {+ FVerseBotTape::AppendOutput(SecondOut, Second.Think(F, Recorder));+ }+ TestTrue(FString::Printf(TEXT("stream %d: recording run equals live run"), s), SecondOut == Tape.Outputs);++ TArray<uint8> Out1, Out2;+ bool bDiv1 = false, bDiv2 = false, bEnd1 = false, bEnd2 = false;+ VerseBotReplayTest::Replay(Tape, *Sim.Tier, Out1, bDiv1, bEnd1);+ VerseBotReplayTest::Replay(Tape, *Sim.Tier, Out2, bDiv2, bEnd2);+ TestFalse(FString::Printf(TEXT("stream %d: replay 1 did not diverge"), s), bDiv1);+ TestFalse(FString::Printf(TEXT("stream %d: replay 2 did not diverge"), s), bDiv2);+ TestTrue(FString::Printf(TEXT("stream %d: replay consumed every recorded query"), s), bEnd1 && bEnd2);+ const bool bSame = Out1 == Tape.Outputs && Out2 == Tape.Outputs;+ TestTrue(FString::Printf(TEXT("stream %d: replays bit-identical"), s), bSame);+ Identical += bSame ? 1 : 0;+ AllUs.Append(Sim.ThinkUs);+ Rows += FString::Printf(TEXT("%s {\"stream\": %d, \"tier\": \"%s\", \"ticks\": %d, \"queryBytes\": %d, \"kills\": %d, \"identical\": %s}"),+ s == 0 ? TEXT("") : TEXT(",\n"), s, *TierId.ToString(), Tape.Frames.Num(), Tape.Queries.Num(), Sim.Kills(), bSame ? TEXT("true") : TEXT("false"));+ }+ const double P50 = VerseBotTestProof::Percentile(AllUs, 50.0);+ const double P99 = VerseBotTestProof::Percentile(AllUs, 99.0);+ const FString Json = FString::Printf(TEXT("{\n \"test\": \"BR1\",\n \"streams\": %d,\n \"identical\": %d,\n \"ticksPerStream\": %d,\n \"thinkUsP50\": %.2f,\n \"thinkUsP99\": %.2f,\n \"budgetUs\": 500,\n \"rows\": [\n%s\n ]\n}\n"),+ Streams, Identical, TicksPerStream, P50, P99, *Rows);+ VerseBotTestProof::Write(TEXT("8.1"), TEXT("br1_replay.json"), Json);+ AddInfo(FString::Printf(TEXT("BR1: %d/%d identical; Think p50 %.1f us, p99 %.1f us"), Identical, Streams, P50, P99));+ // A8.4 cost: bot total at most 0.5 ms p99 per tick (here without perception and engine nav).+ TestTrue(TEXT("Think p99 under 500 us"), P99 <= 500.0);+ return true;+}++// F3 (counterfactual invariance, world-free part): a silent, still opponent hidden at A vs B gives+// bit-identical input frames up to the first tick at which the percept streams differ.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotCounterfactualTest, "Verse.Bot.Brain.Counterfactual", VERSE_BOT_TEST_FLAGS)++bool FVerseBotCounterfactualTest::RunTest(const FString& Parameters)+{+ int32 Passed = 0;+ for (int32 Seed = 1; Seed <= 20; ++Seed)+ {+ FFakeVerseDuelSim::FConfig A;+ A.Seed = Seed;+ A.Model = FFakeVerseDuelSim::EModel::Still;+ A.StillSpot = FVector(0.f, 900.f, 0.f); // behind the north panel+ FFakeVerseDuelSim::FConfig B = A;+ B.StillSpot = FVector(-1800.f, -1450.f, 0.f); // behind the south-west wall+ FFakeVerseDuelSim SimA(TEXT("hard"), A);+ FFakeVerseDuelSim SimB(TEXT("hard"), B);+ SimA.bRecordFrames = SimB.bRecordFrames = true;+ SimA.bRecordOutputs = SimB.bRecordOutputs = true;+ constexpr int32 Ticks = 60 * 60;+ int32 FirstDiffPercept = Ticks;+ for (int32 t = 0; t < Ticks; ++t)+ {+ SimA.Tick();+ SimB.Tick();+ const FVersePerceptFrame& FA = SimA.RecordedFrames.Last();+ const FVersePerceptFrame& FB = SimB.RecordedFrames.Last();+ const bool bSame = FA.Sightings.Num() == FB.Sightings.Num() && FA.Heard.Num() == FB.Heard.Num()+ && FA.bHasHurt == FB.bHasHurt && FA.Hud.Num() == FB.Hud.Num() && FA.Self.Location.Equals(FB.Self.Location, 0.0)+ && FA.Self.ViewRotation.Equals(FB.Self.ViewRotation, 0.0);+ if (!bSame)+ {+ FirstDiffPercept = t;+ break;+ }+ }+ constexpr int32 FrameBytes = 4 * 4 + 4 * 3;+ const int32 Compare = FMath::Min(FirstDiffPercept, SimA.Outputs.Num() / FrameBytes);+ const bool bIdentical = FMemory::Memcmp(SimA.Outputs.GetData(), SimB.Outputs.GetData(), Compare * FrameBytes) == 0;+ TestTrue(FString::Printf(TEXT("seed %d: input frames identical for %d ticks before the first differing percept"), Seed, Compare), bIdentical);+ Passed += bIdentical ? 1 : 0;+ }+ VerseBotTestProof::Write(TEXT("8.1"), TEXT("f3_counterfactual.json"),+ FString::Printf(TEXT("{\n \"test\": \"F3\",\n \"seeds\": 20,\n \"passed\": %d\n}\n"), Passed));+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseBot/Private/Tests/Brain/VerseBotTestProof.h b/unreal/Verse/Source/VerseBot/Private/Tests/Brain/VerseBotTestProof.hnew file mode 100644index 0000000000..770274a191--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tests/Brain/VerseBotTestProof.h@@ -0,0 +1,52 @@+#pragma once++#if WITH_DEV_AUTOMATION_TESTS++#include "CoreMinimal.h"+#include "HAL/PlatformFileManager.h"+#include "Misc/FileHelper.h"+#include "Misc/Paths.h"++/**+ * Writes WP08 evidence (work-packages.md 0.4) to Saved/Harness/proof/WP08/<SubTask>/. Metrics and+ * reports only; never match-memory content (L1).+ */+namespace VerseBotTestProof+{+ inline FString Dir(const TCHAR* SubTask)+ {+ return FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("Harness"), TEXT("proof"), TEXT("WP08"), SubTask);+ }++ inline bool Write(const TCHAR* SubTask, const TCHAR* FileName, const FString& Text)+ {+ const FString Folder = Dir(SubTask);+ IPlatformFile& PF = FPlatformFileManager::Get().GetPlatformFile();+ PF.CreateDirectoryTree(*Folder);+ return FFileHelper::SaveStringToFile(Text, *FPaths::Combine(Folder, FileName), FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM);+ }++ /** p-th percentile (0..100) of a copy of Values. */+ inline double Percentile(TArray<double> Values, double P)+ {+ if (Values.Num() == 0)+ {+ return 0.0;+ }+ Values.Sort();+ const int32 Index = FMath::Clamp(int32(FMath::CeilToDouble(P / 100.0 * Values.Num())) - 1, 0, Values.Num() - 1);+ return Values[Index];+ }++ inline float Median(TArray<float> Values)+ {+ if (Values.Num() == 0)+ {+ return 0.f;+ }+ Values.Sort();+ return Values[Values.Num() / 2];+ }+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseBot/Private/Tests/Brain/VerseBotUtilityTest.cpp b/unreal/Verse/Source/VerseBot/Private/Tests/Brain/VerseBotUtilityTest.cppnew file mode 100644index 0000000000..cfd3692a11--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tests/Brain/VerseBotUtilityTest.cpp@@ -0,0 +1,110 @@+#include "Brain/VerseBotUtility.h"+#include "Misc/AutomationTest.h"++#if WITH_DEV_AUTOMATION_TESTS++#define VERSE_BOT_TEST_FLAGS (EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++// 8.2: utility selection, +0.18 hysteresis, U(0, UtilityNoise) noise, 0.4 s dwell, interrupts.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotUtilityTest, "Verse.Bot.Brain.Utility", VERSE_BOT_TEST_FLAGS)++bool FVerseBotUtilityTest::RunTest(const FString& Parameters)+{+ using EState = EVerseBotState;+ float NoBonus[VerseBot::NumStates] = {};+ auto Utils = [](float Attack, float Hold, float Search)+ {+ TArray<float> U;+ U.Init(-1.f, VerseBot::NumStates);+ U[int32(EState::Attack)] = Attack;+ U[int32(EState::Hold)] = Hold;+ U[int32(EState::Search)] = Search;+ return U;+ };+ auto Run = [&](FVerseBotUtilitySelector& Sel, const TArray<float>& U, float Noise, bool bInterrupt, float Now, FVerseRng& Rng, const float (&Bonus)[VerseBot::NumStates])+ {+ float A[VerseBot::NumStates];+ for (int32 i = 0; i < VerseBot::NumStates; ++i)+ {+ A[i] = U[i];+ }+ return Sel.Decide(A, Bonus, Noise, bInterrupt, Now, Rng);+ };++ // Hysteresis: a challenger needs more than +0.18 to take over (no noise).+ {+ FVerseBotUtilitySelector Sel;+ Sel.Reset(EState::Search, 0.f);+ FVerseRng Rng(1);+ TestEqual(TEXT("0.17 better does not switch"), Run(Sel, Utils(0.67f, -1.f, 0.5f), 0.f, false, 1.f, Rng, NoBonus).State, EState::Search);+ TestEqual(TEXT("0.19 better switches"), Run(Sel, Utils(0.69f, -1.f, 0.5f), 0.f, false, 2.f, Rng, NoBonus).State, EState::Attack);+ TestEqual(TEXT("hysteresis constant"), FVerseBotUtilitySelector::Hysteresis, 0.18f);+ }+ // Dwell: inside 0.4 s no switch without an interrupt; an interrupt switches at once.+ {+ FVerseBotUtilitySelector Sel;+ Sel.Reset(EState::Search, 10.f);+ FVerseRng Rng(2);+ TestEqual(TEXT("dwell holds at 0.3 s"), Run(Sel, Utils(2.f, -1.f, 0.1f), 0.f, false, 10.3f, Rng, NoBonus).State, EState::Search);+ TestEqual(TEXT("interrupt lifts the dwell"), Run(Sel, Utils(2.f, -1.f, 0.1f), 0.f, true, 10.3f, Rng, NoBonus).State, EState::Attack);+ Sel.Reset(EState::Search, 20.f);+ TestEqual(TEXT("dwell over at 0.41 s"), Run(Sel, Utils(2.f, -1.f, 0.1f), 0.f, false, 20.41f, Rng, NoBonus).State, EState::Attack);+ }+ // A state that cannot run is left even inside the dwell.+ {+ FVerseBotUtilitySelector Sel;+ Sel.Reset(EState::Attack, 0.f);+ FVerseRng Rng(3);+ TestEqual(TEXT("unrunnable current state is left"), Run(Sel, Utils(-1.f, 0.3f, 0.2f), 0.f, false, 0.1f, Rng, NoBonus).State, EState::Hold);+ }+ // Noise: scores stay within [utility, utility + noise] and the draw stream is one per state.+ {+ FVerseBotUtilitySelector Sel;+ Sel.Reset(EState::Search, 0.f);+ FVerseRng Rng(4);+ bool bBounded = true;+ int32 Wins[3] = {};+ for (int32 i = 0; i < 10000; ++i)+ {+ Sel.Reset(EState::Flank, 0.f);+ const FVerseBotUtilitySelector::FDecision D = Run(Sel, Utils(0.5f, 0.5f, 0.5f), 0.08f, true, 1.f, Rng, NoBonus);+ for (const EState S : {EState::Attack, EState::Hold, EState::Search})+ {+ const float Sc = D.Scores[int32(S)];+ bBounded &= Sc >= 0.5f && Sc < 0.58f;+ }+ Wins[D.State == EState::Attack ? 0 : D.State == EState::Hold ? 1 : 2]++;+ }+ TestTrue(TEXT("noise within U(0, 0.08)"), bBounded);+ for (int32 w = 0; w < 3; ++w)+ {+ TestTrue(FString::Printf(TEXT("equal utilities split evenly (%d)"), Wins[w]), Wins[w] > 2900 && Wins[w] < 3800);+ }+ }+ // Bonus (forced triggers, 5.2): Attack +0.4 on acquired sight.+ {+ FVerseBotUtilitySelector Sel;+ Sel.Reset(EState::Hold, 0.f);+ FVerseRng Rng(5);+ float Bonus[VerseBot::NumStates] = {};+ Bonus[int32(EState::Attack)] = 0.4f;+ TestEqual(TEXT("acquire bonus wins over hysteresis"), Run(Sel, Utils(0.5f, 0.6f, -1.f), 0.f, true, 1.f, Rng, Bonus).State, EState::Attack);+ }+ // Determinism: same seed, same decisions.+ {+ FVerseBotUtilitySelector S1, S2;+ S1.Reset(EState::Search, 0.f);+ S2.Reset(EState::Search, 0.f);+ FVerseRng R1(99), R2(99);+ bool bSame = true;+ for (int32 i = 0; i < 1000; ++i)+ {+ const TArray<float> U = Utils(0.4f + 0.001f * float(i % 50), 0.45f, 0.42f);+ bSame &= Run(S1, U, 0.08f, false, float(i) * 0.3f, R1, NoBonus).State == Run(S2, U, 0.08f, false, float(i) * 0.3f, R2, NoBonus).State;+ }+ TestTrue(TEXT("deterministic per seed"), bSame);+ }+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseBot/Private/Tests/Controller/Fakes/FakeVersePlayerState.h b/unreal/Verse/Source/VerseBot/Private/Tests/Controller/Fakes/FakeVersePlayerState.hnew file mode 100644index 0000000000..56f2c00eea--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tests/Controller/Fakes/FakeVersePlayerState.h@@ -0,0 +1,21 @@+#pragma once++#include "CoreMinimal.h"++#include "FakeVersePlayerState.generated.h"++/**+ * The two AVersePlayerState fields VerseBot writes (combat-state.md 2.1), as a reflected struct for+ * Verse.Bot.Controller.Identity until AVersePlayerState lands in VerseCombat. Test-only data shape.+ */+USTRUCT()+struct FFakeVersePlayerStateFields+{+ GENERATED_BODY()++ UPROPERTY()+ FName BotTier;++ UPROPERTY()+ float BotEffectiveSkill = -1.f;+};diff --git a/unreal/Verse/Source/VerseBot/Private/Tests/Controller/VerseBotControllerTest.cpp b/unreal/Verse/Source/VerseBot/Private/Tests/Controller/VerseBotControllerTest.cppnew file mode 100644index 0000000000..5d6a1b79df--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tests/Controller/VerseBotControllerTest.cpp@@ -0,0 +1,42 @@+#include "Bot/VerseBotTier.h"+#include "Controller/VerseBotController.h"+#include "Misc/AutomationTest.h"+#include "Tests/Controller/Fakes/FakeVersePlayerState.h"++#if WITH_DEV_AUTOMATION_TESTS++#define VERSE_BOT_TEST_FLAGS (EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++// 8.1: the controller's frozen surface: match option, player state identity, tier and adaptive.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotControllerIdentityTest, "Verse.Bot.Controller.Identity", VERSE_BOT_TEST_FLAGS)++bool FVerseBotControllerIdentityTest::RunTest(const FString& Parameters)+{+ TestEqual(TEXT("?BotTier=elite"), AVerseBotController::ParseBotTierOption(TEXT("?Listen?BotTier=elite")), FName(TEXT("elite")));+ TestEqual(TEXT("?BotTier=Adaptive (case)"), AVerseBotController::ParseBotTierOption(TEXT("?BotTier=Adaptive")), FName(TEXT("adaptive")));+ TestEqual(TEXT("unknown tier"), AVerseBotController::ParseBotTierOption(TEXT("?BotTier=nightmare")), FName(NAME_None));+ TestEqual(TEXT("no option"), AVerseBotController::ParseBotTierOption(TEXT("?Listen")), FName(NAME_None));++ FFakeVersePlayerStateFields Fields;+ TestTrue(TEXT("identity written"), AVerseBotController::WriteBotIdentity(FFakeVersePlayerStateFields::StaticStruct(), &Fields, TEXT("adaptive"), 0.62f));+ TestEqual(TEXT("BotTier"), Fields.BotTier, FName(TEXT("adaptive")));+ TestEqual(TEXT("BotEffectiveSkill"), Fields.BotEffectiveSkill, 0.62f);+ TestFalse(TEXT("a type without the fields is refused"), AVerseBotController::WriteBotIdentity(TBaseStructure<FVector>::Get(), &Fields, TEXT("hard"), 0.5f));++ // Tier and adaptive mode on a controller object (no world: no tick).+ AVerseBotController* Bot = NewObject<AVerseBotController>();+ UVerseBotTier* Elite = NewObject<UVerseBotTier>();+ UVerseBotTier::ApplyStartValues(TEXT("elite"), *Elite);+ Bot->SetTier(Elite);+ TestEqual(TEXT("elite skill is 1"), Bot->GetEffectiveSkill(), 1.f);+ TestFalse(TEXT("not adaptive"), Bot->IsAdaptive());+ Bot->SetAdaptive(true);+ TestTrue(TEXT("adaptive on"), Bot->IsAdaptive());+ TestEqual(TEXT("adaptive starts at StartSkill"), Bot->GetEffectiveSkill(), 0.5f);+ TestTrue(TEXT("brain ready"), Bot->GetBrain() != nullptr);+ TestEqual(TEXT("presentation starts in Search"), Bot->GetPresentation().State, EVerseBotState::Search);+ TestTrue(TEXT("presentation carries the Bot.State tag"), Bot->GetPresentation().StateTag.IsValid());+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseBot/Private/Tests/Eqs/VerseBotEqsTest.cpp b/unreal/Verse/Source/VerseBot/Private/Tests/Eqs/VerseBotEqsTest.cppnew file mode 100644index 0000000000..685bde55c3--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tests/Eqs/VerseBotEqsTest.cpp@@ -0,0 +1,325 @@+#include "Audit/VerseBotFireAudit.h"+#include "Bot/VerseBotTier.h"+#include "Eqs/VerseBeliefNavFilter.h"+#include "Eqs/VerseBotEqs.h"+#include "Learning/VerseBotMatchMemory.h"+#include "Misc/AutomationTest.h"+#include "Tactics/VerseBotTactics.h"+#include "Tests/Brain/Fakes/FakeVerseBotWorld.h"+#include "Tests/Brain/VerseBotTestProof.h"++#if WITH_DEV_AUTOMATION_TESTS++#define VERSE_BOT_TEST_FLAGS (EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++namespace VerseBotEqsTest+{+ struct FEqsScene+ {+ FFakeVerseBotWorldQueries World;+ FFakeVerseBotBelief Belief;+ FVerseBotBeliefSummary Summary;+ FVerseSelfPercept Self;+ FVerseBotMatchMemory Memory;+ UVerseBotTier* Tier = nullptr;+ FVerseBotQueryContext Ctx;++ explicit FEqsScene(FName TierId, const FVector& BotAt, const FVector& TopAt)+ {+ FFakeVerseBotWorldQueries::BuildStandardArena(World);+ Tier = NewObject<UVerseBotTier>();+ Tier->AddToRoot();+ UVerseBotTier::ApplyStartValues(TierId, *Tier);+ Memory.Configure(*Tier);+ Self.Location = BotAt;+ Self.EyeLocation = BotAt + FVector(0, 0, 165.f);+ Self.ViewRotation = (TopAt - BotAt).Rotation();+ Summary.State = EVerseBeliefState::Tracked;+ Summary.TopCenter = TopAt;+ Summary.Confidence = 0.9f;+ Summary.SupportAgeS = 1.f;+ Summary.bPriorOnly = false;+ Summary.SpreadCm = 150.f;+ Summary.FacingYawDeg = 90.f;+ Belief.Mass = 0.7f;+ Belief.SupportedMass = 0.7f;+ }+ ~FEqsScene() { Tier->RemoveFromRoot(); }++ const FVerseBotQueryContext& Build()+ {+ Belief.S = Summary;+ Ctx = FVerseBotQueryContext();+ Ctx.Self = &Self;+ Ctx.Belief = &Summary;+ Ctx.BeliefMap = &Belief;+ Ctx.World = &World;+ Ctx.Memory = &Memory;+ Ctx.Tier = Tier;+ Ctx.PreferredRangeCm = Tier->PreferredRangeM * 100.f;+ return Ctx;+ }+ };+}++// 8.6: belief contexts, EQS_Cover, EQS_PeekCorner.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotEqsCoverTest, "Verse.Bot.Eqs.Cover", VERSE_BOT_TEST_FLAGS)++bool FVerseBotEqsCoverTest::RunTest(const FString& Parameters)+{+ using namespace VerseBotEqsTest;+ {+ FEqsScene S(TEXT("hard"), FVector(0.f, -300.f, 0.f), FVector(-500.f, 1500.f, 0.f));+ const FVerseBotQueryContext& Ctx = S.Build();+ TestTrue(TEXT("BeliefTop is the TopCluster centre"), VerseBotEqs::BeliefTop(Ctx).Equals(S.Summary.TopCenter));+ TestTrue(TEXT("BeliefFacing is the facing estimate"), VerseBotEqs::BeliefFacing(Ctx).Equals(FVector(0, 1, 0), 1e-4));+ const FVerseBotCoverResult Near = VerseBotEqs::Cover(Ctx, EVerseBotCoverMode::Near);+ TestTrue(TEXT("near cover found"), Near.bFound);+ TArray<FVector> Cells;+ VerseBotEqs::BeliefCells(Ctx, Cells);+ TestTrue(TEXT("the chosen cover is hidden from every BeliefCells item"), VerseBotEqs::HiddenFromBelief(Ctx, Near.Point.Location, Cells, !Near.Point.bHigh));+ const FVerseBotCoverResult Far = VerseBotEqs::Cover(Ctx, EVerseBotCoverMode::Far);+ TestTrue(TEXT("far cover found"), Far.bFound);+ TestTrue(TEXT("far cover is farther from the belief than near cover"),+ FVector::Dist2D(Far.Point.Location, S.Summary.TopCenter) >= FVector::Dist2D(Near.Point.Location, S.Summary.TopCenter));++ // A cover point depending on a piece believed holed is filtered.+ S.Belief.PieceStates.Add(2, EVersePieceState::Holed);+ const FVerseBotCoverResult NoHoled = VerseBotEqs::Cover(S.Build(), EVerseBotCoverMode::Near);+ TestFalse(TEXT("no cover behind a believed-holed piece"), NoHoled.bFound && NoHoled.Point.DependsOnPieces.Contains(2));+ }+ {+ // Learned danger heat (7.2) pushes cover away from where the person shoots from.+ FEqsScene S(TEXT("elite"), FVector(0.f, -300.f, 0.f), FVector(-500.f, 1500.f, 0.f));+ const FVerseBotCoverResult Before = VerseBotEqs::Cover(S.Build(), EVerseBotCoverMode::Near);+ for (int32 i = 0; i < 60; ++i)+ {+ S.Memory.RecordShotFrom(Before.Point.Location, 1.f, true);+ }+ const FVerseBotCoverResult After = VerseBotEqs::Cover(S.Build(), EVerseBotCoverMode::Near);+ TestTrue(TEXT("learned danger lowers the old spot's score"), !After.bFound || After.Point.Id != Before.Point.Id || After.Score < Before.Score);+ FVerseBotQueryContext Explore = S.Build();+ Explore.bIgnoreLearned = true;+ const FVerseBotCoverResult Explored = VerseBotEqs::Cover(Explore, EVerseBotCoverMode::Near);+ TestEqual(TEXT("exploration ignores the learned term"), Explored.Point.Id, Before.Point.Id);+ }+ {+ // PeekCorner: a peek that sees BeliefTop; the repeat penalty lowers a thrice-used edge.+ FEqsScene S(TEXT("elite"), FVector(-500.f, 440.f, 0.f), FVector(-500.f, 1500.f, 0.f));+ FVerseBotCoverPoint From;+ From.Location = FVector(-460.f, 520.f, 0.f);+ From.Facing = FVector(0, 1, 0);+ From.bHigh = true;+ From.EdgeId = 11;+ const FVerseBotPeekResult Fresh = VerseBotEqs::PeekCorner(S.Build(), From);+ TestTrue(TEXT("a peek corner is found"), Fresh.bFound);+ TestTrue(TEXT("the peek eye sees BeliefTop"), S.World.TestSight(Fresh.Eye, S.Summary.TopCenter + FVector(0, 0, 120.f)));+ FVerseBotQueryContext Repeat = S.Build();+ Repeat.RecentPeekEdges = {11, 11, 11};+ const FVerseBotPeekResult Repeated = VerseBotEqs::PeekCorner(Repeat, From);+ TestTrue(TEXT("repeat penalty lowers the score"), Repeated.Score < Fresh.Score - 0.5f);+ }+ return true;+}++// 8.7: EQS_WallbangSpot, EQS_BreachSpot, EQS_FinisherApproach; and the wall-shot authority of 4.5.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotEqsTacticalTest, "Verse.Bot.Eqs.Tactical", VERSE_BOT_TEST_FLAGS)++bool FVerseBotEqsTacticalTest::RunTest(const FString& Parameters)+{+ using namespace VerseBotEqsTest;+ // The north panel (piece 1) is a penetrable, breachable wall at y 6.0-6.4 m.+ {+ FEqsScene S(TEXT("elite"), FVector(0.f, 300.f, 0.f), FVector(0.f, 900.f, 0.f));+ const FVerseBotWallbangResult W = VerseBotEqs::WallbangSpot(S.Build());+ TestTrue(TEXT("wallbang spot through the panel"), W.bFound);+ TestEqual(TEXT("one piece on the path"), W.Pieces, 1);+ S.Summary.bPriorOnly = true;+ TestFalse(TEXT("prior-only mass never authorises"), VerseBotEqs::WallbangSpot(S.Build()).bFound);+ S.Summary.bPriorOnly = false;+ S.Belief.SupportedMass = 0.2f;+ TestFalse(TEXT("mass below the 0.25 floor never authorises"), VerseBotEqs::WallbangSpot(S.Build()).bFound);+ S.Belief.SupportedMass = 0.7f;+ S.Summary.SupportAgeS = 4.5f;+ TestFalse(TEXT("support older than the 4 s cap never authorises"), VerseBotEqs::WallbangSpot(S.Build()).bFound);+ }+ {+ UVerseBotTier* Loose = NewObject<UVerseBotTier>();+ Loose->WallbangMinBelief = 0.05f;+ Loose->WallbangMaxSourceAgeS = 12.f;+ TestEqual(TEXT("floor 0.25 applies"), FVerseBotFireClassifier::MinBelief(*Loose), 0.25f);+ TestEqual(TEXT("cap 4 s applies"), FVerseBotFireClassifier::MaxSourceAgeS(*Loose), 4.f);+ FVerseBotFireEvidence E;+ E.bAimInTopCluster = true;+ E.bPriorOnly = false;+ E.SupportedMassAtAim = 0.24f;+ E.SupportAgeS = 1.f;+ E.TraceDamageFrac = 0.8f;+ E.TracePieces = 1;+ TestFalse(TEXT("0.24 below the floor"), FVerseBotFireClassifier::HasWallShotAuthority(E, *Loose));+ E.SupportedMassAtAim = 0.26f;+ TestTrue(TEXT("0.26 above the floor"), FVerseBotFireClassifier::HasWallShotAuthority(E, *Loose));+ E.TracePieces = 4;+ TestFalse(TEXT("more than 3 pieces"), FVerseBotFireClassifier::HasWallShotAuthority(E, *Loose));+ E.TracePieces = 1;+ E.TraceDamageFrac = 0.1f;+ TestFalse(TEXT("too little damage left"), FVerseBotFireClassifier::HasWallShotAuthority(E, *Loose));+ }+ {+ FEqsScene S(TEXT("elite"), FVector(0.f, 200.f, 0.f), FVector(0.f, 1200.f, 0.f));+ S.Self.GadgetCharges[1] = 2;+ const FVerseBotBreachResult B = VerseBotEqs::BreachSpot(S.Build());+ TestTrue(TEXT("breach spot found"), B.bFound);+ TestEqual(TEXT("the panel between bot and belief"), int32(B.PieceIndex), 1);+ TestTrue(TEXT("plant on the bot's side"), B.PlantPoint.Y < 600.f);+ TestTrue(TEXT("wait outside the self-damage radius"), FVector::Dist2D(B.WaitPoint, FVector(0.f, 620.f, 0.f)) > 300.f);+ S.Belief.PieceStates.Add(1, EVersePieceState::Breached);+ const FVerseBotBreachResult Open = VerseBotEqs::BreachSpot(S.Build());+ TestFalse(TEXT("a piece believed breached is not a breach target"), Open.bFound && Open.PieceIndex == 1);+ }+ {+ FEqsScene S(TEXT("elite"), FVector(400.f, 1000.f, 0.f), FVector(0.f, 1200.f, 0.f));+ const FVerseBotFinisherResult F = VerseBotEqs::FinisherApproach(S.Build());+ TestTrue(TEXT("finisher approach found"), F.bFound);+ TestTrue(TEXT("approach more than 100 deg off the believed facing"), VerseBotEqs::OffFacingDeg(S.Ctx, F.Approach) > 100.f);+ TestTrue(TEXT("approach within 1.5 m"), FVector::Dist2D(F.Approach, S.Summary.TopCenter) <= 150.f);+ TestTrue(TEXT("arrival within MaxStalkS"), F.ArrivalS <= S.Tier->MaxStalkS);+ S.Summary.Confidence = 0.5f;+ TestFalse(TEXT("no approach below FinisherCommitConfidence"), VerseBotEqs::FinisherApproach(S.Build()).bFound);+ }+ return true;+}++// 8.8: UVerseBeliefNavFilter rule on the piece belief.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotNavFilterTest, "Verse.Bot.Eqs.NavFilter", VERSE_BOT_TEST_FLAGS)++bool FVerseBotNavFilterTest::RunTest(const FString& Parameters)+{+ using R = EVerseNavPieceRelation;+ using P = EVersePieceState;+ struct FRow { R Rel; P State; bool bUsable; };+ const FRow Rows[] = {+ {R::None, P::Intact, true},+ {R::OpenedBy, P::Intact, false}, {R::OpenedBy, P::Damaged, false}, {R::OpenedBy, P::Holed, false},+ {R::OpenedBy, P::Breached, true}, {R::OpenedBy, P::Destroyed, true}, {R::OpenedBy, P::Repairing, false},+ {R::StandsOn, P::Intact, true}, {R::StandsOn, P::Holed, true}, {R::StandsOn, P::Destroyed, false},+ };+ for (const FRow& Row : Rows)+ {+ TestEqual(FString::Printf(TEXT("relation %d state %d"), int32(Row.Rel), int32(Row.State)),+ FVerseBeliefNavFilter::IsUsableInState(Row.Rel, Row.State), Row.bUsable);+ }+ // Belief, not truth: a breach the bot has not perceived stays closed for it (F7).+ FFakeVerseBotBelief Belief;+ TestFalse(TEXT("unperceived breach opening excluded"), FVerseBeliefNavFilter::IsUsable(R::OpenedBy, 5, Belief));+ Belief.NoteOwnPieceChange(5, P::Breached);+ TestTrue(TEXT("own breach opens it"), FVerseBeliefNavFilter::IsUsable(R::OpenedBy, 5, Belief));+ UVerseBotTier* T = NewObject<UVerseBotTier>();+ UVerseBotTier::ApplyStartValues(TEXT("normal"), *T);+ TestEqual(TEXT("link cost x NavLinkCostMul"), FVerseBeliefNavFilter::LinkCost(10.f, *T), 20.f);+ return true;+}++// 7.2 biases on EQS: peek habits (PeekShare, RepeekShare, TopPeekEdges) steer EQS_PeekCorner and+// Hold; the person's most used route steers EQS_Cover flank; each changes the decision.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotEqsLearnedTest, "Verse.Bot.Eqs.Learned", VERSE_BOT_TEST_FLAGS)++bool FVerseBotEqsLearnedTest::RunTest(const FString& Parameters)+{+ using namespace VerseBotEqsTest;+ {+ // An open floor with one peek edge (id 7) where the believed person stands.+ FEqsScene S(TEXT("hard"), FVector::ZeroVector, FVector(1000.f, 1000.f, 0.f));+ S.World.Walls.Reset();+ S.World.Cover.Reset();+ FVerseBotCoverPoint Edge;+ Edge.Id = 7;+ Edge.EdgeId = 7;+ Edge.Location = FVector(1000.f, 1000.f, 0.f);+ Edge.Facing = FVector(-1.f, 0.f, 0.f);+ S.World.Cover.Add(Edge);+ FVerseBotCoverPoint From;+ From.Id = 3;+ From.EdgeId = 3;+ From.Location = FVector::ZeroVector;+ From.Facing = FVector(1.f, 1.f, 0.f).GetSafeNormal();+ // The person re-peeks edge 7 within 3 s every time.+ for (int32 i = 0; i < 10; ++i)+ {+ S.Memory.RecordPeek(7, EVerseBotPeekType::StepOut, float(i));+ }+ FVerseBotQueryContext Ctx = S.Build();+ Ctx.NowS = 10.f;+ const FVerseBotPeekResult Learned = VerseBotEqs::PeekCorner(Ctx, From);+ Ctx.Memory = nullptr;+ const FVerseBotPeekResult Plain = VerseBotEqs::PeekCorner(Ctx, From);+ TestTrue(TEXT("a peek is found"), Learned.bFound && Plain.bFound);+ TestTrue(TEXT("the learned peek watches the person's top peek edge"), Learned.bHasWatch && Learned.WatchEdge == 7);+ TestFalse(TEXT("no watch without learning"), Plain.bHasWatch);+ TestTrue(TEXT("PeekShare raises the peek's score"), Learned.Score > Plain.Score);+ const float Scale = VerseBotTactics::PeekHoldScale(Learned);+ TestTrue(FString::Printf(TEXT("RepeekShare holds the peek longer (x%.2f)"), Scale), Scale > 1.05f && Scale <= 1.f + 2.f * 0.35f);+ TestEqual(TEXT("no hold change without learning"), VerseBotTactics::PeekHoldScale(Plain), 1.f);+ }+ {+ // Two mirror flank points; the person's most used route runs through the east one.+ FEqsScene S(TEXT("hard"), FVector(0.f, -2000.f, 0.f), FVector::ZeroVector);+ S.World.Walls.Reset();+ S.World.Cover.Reset();+ // A wall hides both points from the only belief cell, far north.+ S.World.AddWall(-30.f, 19.6f, 30.f, 20.f, 3.f);+ S.Belief.Cells = {FVector(0.f, 3000.f, 0.f)};+ for (const float X : {-1000.f, 1000.f})+ {+ FVerseBotCoverPoint P;+ P.Id = X < 0.f ? 1 : 2;+ P.Location = FVector(X, -364.f, 0.f);+ P.Facing = FVector(0.f, 1.f, 0.f);+ P.bHigh = true;+ P.MaterialProtection = 1.f;+ S.World.Cover.Add(P);+ }+ // The same mirror pair, the person's route once through the east point, once through the west one.+ int32 Picked[2] = {INDEX_NONE, INDEX_NONE};+ for (int32 Side = 0; Side < 2; ++Side)+ {+ S.Memory.Reset();+ const float X = Side == 0 ? 1000.f : -1000.f;+ for (int32 i = 0; i < 6; ++i)+ {+ S.Memory.RecordZone(1, FVector(X, -1000.f, 0.f), float(2 * i));+ S.Memory.RecordZone(2, FVector(X, 500.f, 0.f), float(2 * i + 1));+ }+ const FVerseBotQueryContext& Ctx = S.Build();+ const FVerseBotCoverResult R = VerseBotEqs::Cover(Ctx, EVerseBotCoverMode::Flank);+ TestTrue(TEXT("flank point found"), R.bFound);+ Picked[Side] = R.bFound ? R.Point.Id : INDEX_NONE;+ }+ TestEqual(TEXT("route east: the flank cuts it at the east point"), Picked[0], 2);+ TestEqual(TEXT("route west: the flank cuts it at the west point"), Picked[1], 1);+ }+ {+ // Time slicing: a budgeted query resumes and ends with the same answer as the full run.+ FEqsScene S(TEXT("hard"), FVector(0.f, -300.f, 0.f), FVector(-500.f, 1500.f, 0.f));+ const FVerseBotQueryContext& Ctx = S.Build();+ const FVerseBotCoverResult Full = VerseBotEqs::Cover(Ctx, EVerseBotCoverMode::Near);+ FVerseBotEqsSlice Slice;+ FVerseBotCoverResult Sliced;+ int32 MaxUnits = 0;+ int32 Slices = 0;+ while (!Slice.bDone && Slices < 100)+ {+ Slice.BeginSlice(24);+ VerseBotEqs::CoverSlice(Ctx, EVerseBotCoverMode::Near, Slice, Sliced);+ MaxUnits = FMath::Max(MaxUnits, Slice.SpentUnits);+ ++Slices;+ }+ TestTrue(TEXT("the sliced query finishes"), Slice.bDone);+ TestTrue(FString::Printf(TEXT("the query spans several ticks (%d slices)"), Slices), Slices > 1);+ TestTrue(TEXT("same answer as the full run"), Sliced.bFound == Full.bFound && Sliced.Point.Id == Full.Point.Id && Sliced.Score == Full.Score);+ TestTrue(FString::Printf(TEXT("one slice stays near the budget (max %d units, one candidate at most over)"), MaxUnits), MaxUnits <= 24 + 40);+ }+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseBot/Private/Tests/Learning/VerseBotLearningTest.cpp b/unreal/Verse/Source/VerseBot/Private/Tests/Learning/VerseBotLearningTest.cppnew file mode 100644index 0000000000..30daa3db98--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tests/Learning/VerseBotLearningTest.cpp@@ -0,0 +1,236 @@+#include "Bot/VerseBotTier.h"+#include "Brain/VerseBotBelief.h"+#include "Learning/VerseBotMatchMemory.h"+#include "Misc/AutomationTest.h"+#include "Tests/Brain/Fakes/FakeVerseDuelSim.h"+#include "Tests/Brain/VerseBotTestProof.h"+#include "UObject/UnrealType.h"+#include "VerseGameplayTags.h"++#if WITH_DEV_AUTOMATION_TESTS++#define VERSE_BOT_TEST_FLAGS (EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++// 8.9: what the memory records, its weight bound, decay and the biases' inputs.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotLearningModelTest, "Verse.Bot.Learning.Model", VERSE_BOT_TEST_FLAGS)++bool FVerseBotLearningModelTest::RunTest(const FString& Parameters)+{+ using FLayer = FVerseBotMatchMemory::ELayer;+ for (const TCHAR* Id : {TEXT("normal"), TEXT("hard"), TEXT("elite")})+ {+ UVerseBotTier* T = NewObject<UVerseBotTier>();+ UVerseBotTier::ApplyStartValues(Id, *T);+ FVerseBotMatchMemory M;+ M.Configure(*T);+ // w = LearnWeightMax x n / (n + LearnSamplesHalf), never above 0.35.+ const float W = M.Weight(T->LearnSamplesHalf);+ TestTrue(FString::Printf(TEXT("%s: w at n = half is LearnWeightMax / 2"), Id), FMath::IsNearlyEqual(W, T->LearnWeightMax * 0.5f, 1e-5f));+ TestTrue(FString::Printf(TEXT("%s: w bounded"), Id), M.Weight(1.0e9f) <= FMath::Min(T->LearnWeightMax, 0.35f) + 1e-6f);+ TestEqual(FString::Printf(TEXT("%s: w = 0 with no samples"), Id), M.Weight(0.f), 0.f);+ }+ {+ // The contract cap holds even for a tier above it.+ UVerseBotTier* T = NewObject<UVerseBotTier>();+ T->LearnWeightMax = 0.9f;+ FVerseBotMatchMemory M;+ M.Configure(*T);+ TestTrue(TEXT("cap 0.35"), M.Weight(1.0e9f) <= 0.35f + 1e-6f);+ }+ {+ UVerseBotTier* T = NewObject<UVerseBotTier>();+ UVerseBotTier::ApplyStartValues(TEXT("hard"), *T);+ FVerseBotMatchMemory M;+ M.Configure(*T);+ const FVector P(300.f, 400.f, 0.f);+ M.RecordSighting(P, 0.f, true);+ M.RecordSighting(P, 0.f, false);+ M.RecordHeard(P, 0.f);+ TestTrue(TEXT("heat weights 2 + 1 + 0.3"), FMath::IsNearlyEqual(M.Heat(FLayer::Position, P, 0.f), 3.3f, 1e-4f));+ TestTrue(TEXT("half-life decay"), FMath::IsNearlyEqual(M.Heat(FLayer::Position, P, T->HabitHalfLifeS), 1.65f, 1e-3f));+ M.RecordShotFrom(P, 0.f, true);+ TestTrue(TEXT("shooting layer"), M.HeatShare(FLayer::Shooting, P, 200.f, 0.f) > 0.99f);+ // Peek habits.+ M.RecordPeek(4, EVerseBotPeekType::LeanLeft, 10.f);+ M.RecordPeek(4, EVerseBotPeekType::LeanLeft, 11.5f);+ M.RecordPeek(9, EVerseBotPeekType::JumpPeek, 30.f);+ float N = 0.f;+ TestTrue(TEXT("peek share"), FMath::IsNearlyEqual(M.PeekShare(4, N), 2.f / 3.f, 1e-5f) && N == 2.f);+ TestTrue(TEXT("fast re-peek share"), FMath::IsNearlyEqual(M.RepeekShare(4), 0.5f, 1e-5f));+ TArray<int32> Top;+ M.TopPeekEdges(2, Top);+ TestTrue(TEXT("top peek edges"), Top.Num() == 2 && Top[0] == 4 && Top[1] == 9);+ // Routes.+ M.RecordZone(1, 0.f);+ M.RecordZone(2, 1.f);+ M.RecordZone(1, 2.f);+ M.RecordZone(2, 3.f);+ M.RecordZone(3, 4.f);+ TestTrue(TEXT("route probability"), FMath::IsNearlyEqual(M.ZoneTransitionProb(1, 2), 1.f, 1e-5f));+ TestEqual(TEXT("most likely next zone"), M.MostLikelyNextZone(2), 1);+ // Ranges: the person loses most at 10-20 m, the preferred band (12 m) stays; at 5-10 m it shifts.+ for (int32 i = 0; i < 4; ++i)+ {+ M.RecordEngagementEnd(700.f, true);+ M.RecordEngagementEnd(1500.f, false);+ }+ TestEqual(TEXT("range band stays where the person loses"), M.RangeBinShift(1200.f), 0);+ TestEqual(TEXT("range band moves toward the person's weak bin"), M.RangeBinShift(700.f), 1);+ M.RecordHabit(TEXT("slide"));+ TestEqual(TEXT("habit counter"), M.HabitCount(TEXT("slide")), 1);+ // Learning off records nothing.+ FVerseBotMatchMemory Off;+ Off.Configure(*T);+ Off.SetEnabled(false);+ Off.RecordSighting(P, 0.f, true);+ Off.RecordPeek(1, EVerseBotPeekType::StepOut, 0.f);+ TestTrue(TEXT("learning off records nothing"), Off.IsEmpty() && Off.Weight(10.f) == 0.f);+ }+ return true;+}++// A8.6 (BG9 reset and L1, world-free part): nothing carried into match 2; no reflected or+// serialisable field holds learned data.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotLearningResetTest, "Verse.Bot.Learning.Reset", VERSE_BOT_TEST_FLAGS)++bool FVerseBotLearningResetTest::RunTest(const FString& Parameters)+{+ // Match 1 against a patrol opponent fills the memory; ResetMatch empties it.+ FFakeVerseDuelSim::FConfig Cfg;+ Cfg.Seed = 77;+ FFakeVerseDuelSim Sim(TEXT("hard"), Cfg);+ Sim.Run(3 * 60 * 60);+ TestFalse(TEXT("match 1 learned something"), Sim.Brain.GetMemory().IsEmpty());+ Sim.Brain.ResetMatch();+ TestTrue(TEXT("match end drops everything"), Sim.Brain.GetMemory().IsEmpty());+ TestEqual(TEXT("audit cleared with the match"), Sim.Brain.GetFireAudit().Num(), 0);++ // Match 2 from a reset brain equals a brand-new brain on the same frames (nothing carried over).+ FFakeVerseDuelSim A(TEXT("hard"), Cfg);+ A.bRecordFrames = true;+ A.bRecordOutputs = true;+ A.Run(60 * 60);+ FVerseBotBrainCore Reused;+ FVerseBotBrainCore::FConfig C;+ C.Seed = Cfg.Seed;+ C.SelfId = FFakeVerseDuelSim::BotId;+ Reused.Init(*A.Tier, C);+ for (const FVersePerceptFrame& F : A.RecordedFrames)+ {+ Reused.Think(F, A.World);+ }+ Reused.Init(*A.Tier, C); // match end and a new match+ TArray<uint8> Out;+ for (const FVersePerceptFrame& F : A.RecordedFrames)+ {+ FVerseBotTape::AppendOutput(Out, Reused.Think(F, A.World));+ }+ TestTrue(TEXT("match 2 equals match 1 bit for bit"), Out == A.Outputs);++ // L1: the memory object has no reflected property (nothing to save, cook, replicate or bridge).+ int32 Reflected = 0;+ for (TFieldIterator<FProperty> It(UVerseBotMatchMemory::StaticClass(), EFieldIteratorFlags::ExcludeSuper); It; ++It)+ {+ ++Reflected;+ }+ TestEqual(TEXT("UVerseBotMatchMemory has no reflected fields"), Reflected, 0);+ TestTrue(TEXT("UVerseBotMatchMemory is transient"), UVerseBotMatchMemory::StaticClass()->HasAnyClassFlags(CLASS_Transient));+ VerseBotTestProof::Write(TEXT("8.9"), TEXT("bg9_l1_reset.json"),+ FString::Printf(TEXT("{\n \"gate\": \"BG9/L1 (world-free part)\",\n \"resetEmpties\": %s,\n \"match2EqualsMatch1\": %s,\n \"reflectedFields\": %d\n}\n"),+ Sim.Brain.GetMemory().IsEmpty() ? TEXT("true") : TEXT("false"), Out == A.Outputs ? TEXT("true") : TEXT("false"), Reflected));+ return true;+}++// 8.9 / 7.2: the belief consumes the learned zone transitions and the 1 % heatmap prior, and a+// contact-lost engagement is no decision for the range bias.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotLearningBiasTest, "Verse.Bot.Learning.Bias", VERSE_BOT_TEST_FLAGS)++bool FVerseBotLearningBiasTest::RunTest(const FString& Parameters)+{+ UVerseBotTier* T = NewObject<UVerseBotTier>();+ T->AddToRoot();+ UVerseBotTier::ApplyStartValues(TEXT("hard"), *T);+ auto Frame = [](uint32 Ms)+ {+ FVersePerceptFrame F;+ F.ServerTimeMs = Ms;+ F.Self.Location = FVector(0.f, -5000.f, 0.f);+ F.Self.EyeLocation = FVector(0.f, -5000.f, 165.f);+ F.Self.ViewRotation = FRotator(0.f, -90.f, 0.f);+ return F;+ };+ {+ // Zone transitions: the person keeps moving from zone 1 (around the origin) to zone 2 (20 m east).+ FVerseBotMatchMemory M;+ M.Configure(*T);+ for (int32 i = 0; i < 6; ++i)+ {+ M.RecordZone(1, FVector(0.f, 0.f, 0.f), float(2 * i));+ M.RecordZone(2, FVector(2000.f, 0.f, 0.f), float(2 * i + 1));+ }+ FVerseBotCoarseBelief WithMemory, Without;+ for (FVerseBotCoarseBelief* B : {&WithMemory, &Without})+ {+ B->Reset();+ FVersePerceptFrame F = Frame(100);+ FVerseHeardPercept H;+ H.PerceptId = 1;+ H.Noise = VerseTags::Noise_Footstep_Run;+ H.Location = FVector::ZeroVector;+ H.ErrorSdM = 1.f;+ F.Heard.Add(H);+ const FVerseBotMatchMemory* Mem = B == &WithMemory ? &M : nullptr;+ B->Step(F, 0.1f, Mem, {});+ for (int32 i = 0; i < 10; ++i)+ {+ B->Step(Frame(200 + 100 * i), 0.1f, Mem, {});+ }+ }+ const float Lean = float(WithMemory.Summary().TopCenter.X - Without.Summary().TopCenter.X);+ TestTrue(FString::Printf(TEXT("belief leans toward the learned next zone (%.1f cm)"), Lean), Lean > 100.f);+ }+ {+ // Heatmap prior: a lost belief keeps 1 % of mass on the person's hottest spot, prior-only.+ FVerseBotMatchMemory M;+ M.Configure(*T);+ const FVector Hot(2000.f, 2000.f, 0.f);+ for (int32 i = 0; i < 5; ++i)+ {+ M.RecordSighting(Hot, 1.f, false);+ }+ FVerseBotCoarseBelief WithMemory, Without;+ WithMemory.Reset();+ Without.Reset();+ WithMemory.Step(Frame(1000), 0.1f, &M, {});+ Without.Step(Frame(1000), 0.1f, nullptr, {});+ const float Mass = WithMemory.MassWithin(Hot, 300.f);+ TestTrue(FString::Printf(TEXT("heatmap prior mixed in (%.4f)"), Mass), Mass > 0.005f && Mass < 0.02f);+ TestEqual(TEXT("no prior without learning"), Without.MassWithin(Hot, 300.f), 0.f);+ TestEqual(TEXT("the prior is never support"), WithMemory.SupportedMassWithin(Hot, 300.f), 0.f);+ }+ {+ // Contact lost is no decision: it does not count as a bot win in the range bin.+ FVerseBotMatchMemory M;+ M.Configure(*T);+ for (int32 i = 0; i < 4; ++i)+ {+ M.RecordEngagementEnd(700.f, true);+ M.RecordEngagementEnd(1500.f, true);+ M.RecordEngagementEnd(1500.f, false);+ // 20-35 m: the person wins only one in four, so the band moves out one bin.+ M.RecordEngagementEnd(2500.f, i == 0);+ }+ const int32 Before = M.RangeBinShift(1200.f);+ TestEqual(TEXT("range band moves toward the person's weakest bin"), Before, 1);+ for (int32 i = 0; i < 20; ++i)+ {+ M.RecordEngagementNoDecision(1500.f);+ }+ TestEqual(TEXT("no-decision engagements leave the range bias alone"), M.RangeBinShift(1200.f), Before);+ TestEqual(TEXT("no-decision engagements are counted apart"), M.NoDecisionCount(FVerseBotMatchMemory::RangeBin(1500.f)), 20);+ }+ T->RemoveFromRoot();+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseBot/Private/Tests/Tactics/VerseBotTacticsTest.cpp b/unreal/Verse/Source/VerseBot/Private/Tests/Tactics/VerseBotTacticsTest.cppnew file mode 100644index 0000000000..d9e8ac5b7d--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tests/Tactics/VerseBotTacticsTest.cpp@@ -0,0 +1,327 @@+#include "Bot/VerseBotTier.h"+#include "Misc/AutomationTest.h"+#include "Tactics/VerseBotTactics.h"+#include "Tests/Brain/Fakes/FakeVerseBotWorld.h"+#include "Tests/Brain/Fakes/FakeVerseDuelSim.h"+#include "Tests/Brain/VerseBotTestProof.h"++#if WITH_DEV_AUTOMATION_TESTS++#define VERSE_BOT_TEST_FLAGS (EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++namespace VerseBotTacticsTest+{+ using EState = EVerseBotState;++ /** A scripted context over the standard arena: the bot at the origin's south, belief north. */+ struct FTacticsScene+ {+ FFakeVerseBotWorldQueries World;+ FFakeVerseBotBelief Belief;+ FVerseBotBeliefSummary Summary;+ FVerseSelfPercept Self;+ FVersePerceptFrame Frame;+ FVerseBotQueryCache Cache;+ FVerseSightPercept Sight;+ UVerseBotTier* Tier = nullptr;+ FVerseBotTacticsContext Ctx;++ explicit FTacticsScene(FName TierId)+ {+ FFakeVerseBotWorldQueries::BuildStandardArena(World);+ Tier = NewObject<UVerseBotTier>();+ Tier->AddToRoot();+ UVerseBotTier::ApplyStartValues(TierId, *Tier);+ Self.Location = FVector(0.f, -1200.f, 0.f);+ Self.EyeLocation = Self.Location + FVector(0, 0, 165.f);+ Self.ViewRotation = FRotator(0.f, 90.f, 0.f);+ Self.Health = 100.f;+ Self.MaxHealth = 100.f;+ Self.Magazine = 30;+ Self.Reserve = 90;+ Summary.State = EVerseBeliefState::Tracked;+ Summary.TopCenter = FVector(0.f, 1200.f, 0.f);+ Summary.Confidence = 0.7f;+ Summary.SupportAgeS = 0.5f;+ Summary.bPriorOnly = false;+ Summary.SpreadCm = 300.f;+ Summary.FacingYawDeg = 90.f; // facing away from the bot (north)+ Summary.FacingAgeS = 1.f;+ Summary.SinceSightingS = 3.f;+ }+ ~FTacticsScene() { Tier->RemoveFromRoot(); }++ FVerseBotTacticsContext& Build()+ {+ Belief.S = Summary;+ Frame.Self = Self;+ Ctx = FVerseBotTacticsContext();+ Ctx.Query.Self = &Self;+ Ctx.Query.Belief = &Summary;+ Ctx.Query.BeliefMap = &Belief;+ Ctx.Query.World = &World;+ Ctx.Query.Tier = Tier;+ Ctx.Query.PreferredRangeCm = Tier->PreferredRangeM * 100.f;+ Ctx.Frame = &Frame;+ Ctx.Cache = &Cache;+ Ctx.SinceSightS = Summary.SinceSightingS;+ Ctx.HealthFrac = Self.Health / Self.MaxHealth;+ Ctx.MagazineFrac = float(Self.Magazine) / 30.f;+ return Ctx;+ }++ EState Best()+ {+ float U[VerseBot::NumStates];+ VerseBotTactics::Utilities(Build(), U);+ int32 B = 0;+ for (int32 i = 1; i < VerseBot::NumStates; ++i)+ {+ B = U[i] > U[B] ? i : B;+ }+ return EState(B);+ }+ };+}++// 8.3-8.5: each state wins its own scenario (bot.md 5.1 utility terms).+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotTacticsUtilityTest, "Verse.Bot.Tactics.Utility", VERSE_BOT_TEST_FLAGS)++bool FVerseBotTacticsUtilityTest::RunTest(const FString& Parameters)+{+ using namespace VerseBotTacticsTest;+ {+ FTacticsScene S(TEXT("hard"));+ S.Sight.PelvisLocation = FVector(0.f, 0.f, 95.f);+ S.Sight.VisibleMask = 0xff;+ S.Build();+ S.Ctx.Sighting = &S.Sight;+ S.Summary.State = EVerseBeliefState::Known;+ S.Summary.SinceSightingS = 0.f;+ float U[VerseBot::NumStates];+ S.Ctx.SinceSightS = 0.f;+ VerseBotTactics::Utilities(S.Ctx, U);+ int32 B = 0;+ for (int32 i = 1; i < VerseBot::NumStates; ++i) B = U[i] > U[B] ? i : B;+ TestEqual(TEXT("Attack on a sighting"), EState(B), EState::Attack);+ }+ {+ FTacticsScene S(TEXT("hard"));+ S.Self.Health = 20.f;+ TestEqual(TEXT("Retreat when low against a healthy estimate"), S.Best(), EState::Retreat);+ }+ {+ FTacticsScene S(TEXT("hard"));+ S.Self.Magazine = 3;+ S.Summary.State = EVerseBeliefState::Lost;+ S.Summary.Confidence = 0.1f;+ TestEqual(TEXT("Reload with a low magazine and no threat"), S.Best(), EState::Reload);+ }+ {+ FTacticsScene S(TEXT("hard"));+ S.Summary.State = EVerseBeliefState::Lost;+ S.Summary.Confidence = 0.1f;+ TestEqual(TEXT("Search when the belief is lost"), S.Best(), EState::Search);+ }+ {+ FTacticsScene S(TEXT("hard"));+ S.Summary.SinceSightingS = 0.8f;+ S.Summary.Velocity = FVector(0.f, -400.f, 0.f); // toward the bot+ S.Cache.Cover[int32(EVerseBotCoverMode::Near)].bFound = true;+ S.Cache.Cover[int32(EVerseBotCoverMode::Near)].Point.Location = FVector(0.f, -700.f, 0.f);+ TestEqual(TEXT("Hold with cover and an approaching belief"), S.Best(), EState::Hold);+ }+ {+ FTacticsScene S(TEXT("elite"));+ S.Summary.SinceSightingS = 3.f;+ TestEqual(TEXT("Flank a still belief after 1.5-8 s without sight"), S.Best(), EState::Flank);+ }+ {+ FTacticsScene S(TEXT("elite"));+ S.Summary.SinceSightingS = 9.f;+ S.Summary.SpreadCm = 150.f;+ S.Cache.Finisher.bFound = true;+ TestEqual(TEXT("Stalk a static, facing-away belief with Spread < 2 m"), S.Best(), EState::StalkForFinisher);+ }+ {+ FTacticsScene S(TEXT("elite"));+ S.Summary.SinceSightingS = 9.f;+ S.Build();+ S.Ctx.bBulwarkReady = true;+ float U[VerseBot::NumStates];+ VerseBotTactics::Utilities(S.Ctx, U);+ int32 B = 0;+ for (int32 i = 1; i < VerseBot::NumStates; ++i) B = U[i] > U[B] ? i : B;+ TestEqual(TEXT("DeployBulwark with no cover within 6 m"), EState(B), EState::DeployBulwark);+ }+ {+ FTacticsScene S(TEXT("elite"));+ S.Summary.SinceSightingS = 9.f;+ S.Cache.Breach.bFound = true;+ S.Cache.Breach.Score = 0.5f;+ S.Build();+ S.Ctx.bBreachReady = true;+ float U[VerseBot::NumStates];+ VerseBotTactics::Utilities(S.Ctx, U);+ int32 B = 0;+ for (int32 i = 1; i < VerseBot::NumStates; ++i) B = U[i] > U[B] ? i : B;+ TestEqual(TEXT("Breach a believed-intact piece on the way"), EState(B), EState::Breach);+ }+ {+ FTacticsScene S(TEXT("elite"));+ S.Summary.SinceSightingS = 9.f;+ S.Build();+ S.Ctx.bWallbangAuthorised = true;+ float U[VerseBot::NumStates];+ VerseBotTactics::Utilities(S.Ctx, U);+ int32 B = 0;+ for (int32 i = 1; i < VerseBot::NumStates; ++i) B = U[i] > U[B] ? i : B;+ TestEqual(TEXT("Wallbang with authority"), EState(B), EState::Wallbang);+ S.Ctx.bWallbangAuthorised = false;+ VerseBotTactics::Utilities(S.Ctx, U);+ TestTrue(TEXT("no Wallbang without authority"), U[int32(EState::Wallbang)] < 0.f);+ }+ return true;+}++// 8.3-8.5: what the states do (intents).+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotTacticsTickTest, "Verse.Bot.Tactics.Tick", VERSE_BOT_TEST_FLAGS)++bool FVerseBotTacticsTickTest::RunTest(const FString& Parameters)+{+ using namespace VerseBotTacticsTest;+ // Hold: Go -> Hide -> Peek -> Hide with the contract times.+ {+ FTacticsScene S(TEXT("hard"));+ FVerseBotCoverPoint Cover;+ Cover.Location = S.Self.Location;+ Cover.bHigh = false;+ Cover.EdgeId = 7;+ S.Cache.Cover[int32(EVerseBotCoverMode::Near)].bFound = true;+ S.Cache.Cover[int32(EVerseBotCoverMode::Near)].Point = Cover;+ S.Cache.Peek.bFound = true;+ S.Cache.Peek.Type = EVerseBotPeekType::LeanRight;+ S.Cache.Peek.StandPoint = Cover.Location;+ FVerseBotTacticsMemory Mem;+ FVerseRng Rng(3);+ FVerseBotTacticsContext& Ctx = S.Build();+ VerseBotTactics::Enter(EState::Hold, Ctx, Mem, Rng);+ Ctx.Query.NowS = 0.f;+ VerseBotTactics::Tick(EState::Hold, Ctx, Mem, Rng);+ TestEqual(TEXT("arrived: Hide"), Mem.HoldPhase, EVerseBotHoldPhase::Hide);+ const float HideFor = Mem.PhaseUntilS;+ TestTrue(TEXT("hide U(0.5, 1.1) s"), HideFor >= 0.5f && HideFor <= 1.1f);+ const FVerseBotIntent Hidden = VerseBotTactics::Tick(EState::Hold, Ctx, Mem, Rng);+ TestEqual(TEXT("low cover: crouch while hiding"), Hidden.Stance, EVerseStance::Crouch);+ Ctx.Query.NowS = HideFor + 0.01f;+ VerseBotTactics::Tick(EState::Hold, Ctx, Mem, Rng);+ TestEqual(TEXT("then Peek"), Mem.HoldPhase, EVerseBotHoldPhase::Peek);+ const float PeekFor = Mem.PhaseUntilS - Ctx.Query.NowS;+ TestTrue(TEXT("peek U(0.7, 1.5) s"), PeekFor >= 0.7f && PeekFor <= 1.5f);+ const FVerseBotIntent Peek = VerseBotTactics::Tick(EState::Hold, Ctx, Mem, Rng);+ TestEqual(TEXT("lean peek leans right"), int32(Peek.Lean), 1);+ TestEqual(TEXT("recent peek edge recorded"), Mem.RecentPeekEdges.Num() > 0 ? Mem.RecentPeekEdges.Last() : -1, 7);+ Ctx.Query.NowS += 1.6f;+ VerseBotTactics::Tick(EState::Hold, Ctx, Mem, Rng);+ TestEqual(TEXT("back to Hide"), Mem.HoldPhase, EVerseBotHoldPhase::Hide);+ // No peek with a low magazine.+ S.Self.Magazine = 2;+ FVerseBotTacticsContext& Low = S.Build();+ Low.Query.NowS = Mem.PhaseUntilS + 0.01f;+ VerseBotTactics::Tick(EState::Hold, Low, Mem, Rng);+ TestEqual(TEXT("no peek below the reload threshold"), Mem.HoldPhase, EVerseBotHoldPhase::Hide);+ }+ // StalkForFinisher: silent crouch-walk, melee press inside 1.5 m when the finisher can activate.+ {+ FTacticsScene S(TEXT("elite"));+ S.Summary.TopCenter = S.Self.Location + FVector(0.f, 120.f, 0.f);+ FVerseBotTacticsMemory Mem;+ FVerseRng Rng(4);+ FVerseBotTacticsContext& Ctx = S.Build();+ const FVerseBotIntent I = VerseBotTactics::Tick(EState::StalkForFinisher, Ctx, Mem, Rng);+ TestEqual(TEXT("stalk crouches"), I.Stance, EVerseStance::Crouch);+ TestTrue(TEXT("stalk walks"), I.bWalk);+ TestTrue(TEXT("finisher press in range"), I.bMelee);+ S.World.bFinisherReady = false;+ TestFalse(TEXT("no press when the ability cannot activate"), VerseBotTactics::Tick(EState::StalkForFinisher, S.Build(), Mem, Rng).bMelee);+ }+ // DeployBulwark: one GadgetA press at the spot; Breach: GadgetB at the plant point, then wait.+ {+ FTacticsScene S(TEXT("elite"));+ S.Self.GadgetCharges[0] = 1;+ FVerseBotTacticsMemory Mem;+ FVerseRng Rng(5);+ FVerseBotTacticsContext& Ctx = S.Build();+ Ctx.bBulwarkReady = true;+ const FVerseBotIntent First = VerseBotTactics::Tick(EState::DeployBulwark, Ctx, Mem, Rng);+ const FVerseBotIntent Second = VerseBotTactics::Tick(EState::DeployBulwark, Ctx, Mem, Rng);+ TestTrue(TEXT("Bulwark deployed once"), First.bGadgetA && !Second.bGadgetA);+ }+ {+ FTacticsScene S(TEXT("elite"));+ S.Cache.Breach.bFound = true;+ S.Cache.Breach.PieceIndex = 2;+ S.Cache.Breach.PlantPoint = S.Self.Location;+ S.Cache.Breach.WaitPoint = S.Self.Location + FVector(0.f, -400.f, 0.f);+ FVerseBotTacticsMemory Mem;+ FVerseRng Rng(6);+ FVerseBotTacticsContext& Ctx = S.Build();+ VerseBotTactics::Enter(EState::Breach, Ctx, Mem, Rng);+ const FVerseBotIntent Plant = VerseBotTactics::Tick(EState::Breach, Ctx, Mem, Rng);+ TestTrue(TEXT("plants at the plant point"), Plant.bGadgetB && Mem.bBreachPlanted);+ Ctx.Query.NowS = 1.f;+ const FVerseBotIntent Wait = VerseBotTactics::Tick(EState::Breach, Ctx, Mem, Rng);+ TestTrue(TEXT("steps back to the wait point"), Wait.bHasMoveTarget && Wait.MoveTarget.Equals(S.Cache.Breach.WaitPoint));+ }+ return true;+}++// A8.4 (world-free part, BG12 health): time to contact against a hider, stuck events.+IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBotHealthTest, "Verse.Bot.Tactics.Health", VERSE_BOT_TEST_FLAGS)++bool FVerseBotHealthTest::RunTest(const FString& Parameters)+{+ TArray<float> Contacts;+ int32 Stuck = 0;+ float Minutes = 0.f;+ TArray<double> Us;+ int32 ByState[VerseBot::NumStates] = {};+ int32 Decisions[VerseBot::NumStates] = {};+ for (int32 Seed = 1; Seed <= 6; ++Seed)+ {+ FFakeVerseDuelSim::FConfig Cfg;+ Cfg.Seed = 500 + Seed;+ Cfg.Model = FFakeVerseDuelSim::EModel::Hider;+ FFakeVerseDuelSim Sim(TEXT("hard"), Cfg);+ Sim.bMeasure = true;+ Sim.Run(10 * 60 * 60);+ Contacts.Append(Sim.TimeToContactS);+ Stuck += Sim.Brain.GetStuckEvents();+ Minutes += 10.f;+ Us.Append(Sim.ThinkUs);+ for (int32 i = 0; i < VerseBot::NumStates; ++i)+ {+ ByState[i] += Sim.Brain.GetStuckByState()[i];+ Decisions[i] += Sim.Brain.GetStateCounts()[i];+ }+ }+ FString PerState;+ for (int32 i = 0; i < VerseBot::NumStates; ++i)+ {+ PerState += FString::Printf(TEXT("%s\"%s\": {\"decisions\": %d, \"stuck\": %d}"), i == 0 ? TEXT("") : TEXT(", "),+ VerseBot::StateName(EVerseBotState(i)), Decisions[i], ByState[i]);+ }+ const float Median = VerseBotTestProof::Median(Contacts);+ const float StuckPer10 = float(Stuck) / (Minutes / 10.f);+ const double P99 = VerseBotTestProof::Percentile(Us, 99.0);+ VerseBotTestProof::Write(TEXT("8.3"), TEXT("bg12_health.json"),+ FString::Printf(TEXT("{\n \"gate\": \"BG12\",\n \"opponent\": \"hider\",\n \"tier\": \"hard\",\n \"contacts\": %d,\n \"timeToContactS_median\": %.2f,\n \"stuckEventsPer10Min\": %.2f,\n \"thinkUsP99\": %.2f,\n \"states\": {%s}\n}\n"),+ Contacts.Num(), Median, StuckPer10, P99, *PerState));+ AddInfo(FString::Printf(TEXT("hider: %d contacts, median %.1f s, stuck %.2f per 10 min, p99 %.1f us; states %s"), Contacts.Num(), Median, StuckPer10, P99, *PerState));+ TestTrue(TEXT("the hider is found"), Contacts.Num() >= 6);+ TestTrue(TEXT("timeToContactS median <= 25 s"), Median <= 25.f);+ TestTrue(TEXT("stuck events <= 1 per 10 min"), StuckPer10 <= 1.f);+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseBot/Public/Audit/VerseBotFireAudit.h b/unreal/Verse/Source/VerseBot/Public/Audit/VerseBotFireAudit.hnew file mode 100644index 0000000000..2bad7e5582--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Audit/VerseBotFireAudit.h@@ -0,0 +1,161 @@+#pragma once++#include "CoreMinimal.h"++#include "VerseBotFireAudit.generated.h"++class UVerseBotTier;+struct FVerseBotBeliefSummary;++/** How a bot shot is justified (bot.md 8.4, F4). Unclassified is a contract violation. */+UENUM(BlueprintType)+enum class EVerseBotFireMode : uint8+{+ Unclassified,+ Visible,+ Suppression,+ Prefire,+ WallShot+};++/** One logged bot shot (bot.md frozen interface). */+USTRUCT(BlueprintType)+struct VERSEBOT_API FVerseBotFireAudit+{+ GENERATED_BODY()++ UPROPERTY()+ uint32 ServerTimeMs = 0;++ UPROPERTY()+ EVerseBotFireMode Mode = EVerseBotFireMode::Unclassified;++ UPROPERTY()+ bool bTargetVisible = false;++ /** The percepts that back the shot (sighting, heard). */+ UPROPERTY()+ TArray<uint32> PerceptIds;++ /** Belief mass within 1.5 m of the aim point. */+ UPROPERTY()+ float BeliefMassAtAim = 0.f;++ UPROPERTY()+ float SupportAgeS = 0.f;++ /** One log line: "VerseBotFire t=<ms> mode=<mode> visible=<0|1> percepts=<id,id> mass=<f> age=<f>". */+ FString ToLogLine() const;+};++/** Everything the classifier needs about one shot. World cm. */+struct VERSEBOT_API FVerseBotFireEvidence+{+ uint32 ServerTimeMs = 0;+ FVector AimPoint = FVector::ZeroVector;+ /** A sighting this frame of a target that is not spawn-protected, and the aim is on it. */+ bool bTargetVisible = false;+ uint32 SightPerceptId = 0;+ /** Seconds since sight of the target was lost; large when never seen. */+ float SinceSightLostS = 1.0e6f;+ FVector LastSeenLocation = FVector::ZeroVector;+ /** Newest heard percept: age, location, sd, id. */+ float HeardAgeS = 1.0e6f;+ FVector HeardLocation = FVector::ZeroVector;+ float HeardSdCm = 0.f;+ uint32 HeardPerceptId = 0;+ /** The aim point is a peek edge (cover edge of arena data) near which the heard percept lies. */+ bool bAimAtPeekEdge = false;+ /** A prefire roll (PrefireChance) passed for this approach. */+ bool bPrefireRolled = false;+ /** Believed bolt trace from the eye to the aim point. */+ float TraceDamageFrac = 0.f;+ int32 TracePieces = 0;+ /** Belief values (4.3, 4.5). */+ float MassAtAim = 0.f;+ float SupportedMassAtAim = 0.f;+ float SupportAgeS = 1.0e6f;+ bool bPriorOnly = true;+ bool bAimInTopCluster = false;+ /** The target is visibly spawn-protected (5.2: hold fire). */+ bool bTargetSpawnProtected = false;+};++/** The F4 classifier and the wall-shot authority of bot.md 4.5. */+struct VERSEBOT_API FVerseBotFireClassifier+{+ /** Suppression window after losing sight (8.4). */+ static constexpr float SuppressionS = 0.35f;+ /** Suppression radius around the last seen position (8.4). */+ static constexpr float SuppressionRadiusCm = 200.f;+ /** Prefire: heard within 2 s within 6 m of a peek edge (8.4). */+ static constexpr float PrefireHeardMaxAgeS = 2.f;+ static constexpr float PrefireEdgeRadiusCm = 600.f;+ /** Mass is measured within 1.5 m of the aim point (4.5). */+ static constexpr float MassRadiusCm = 150.f;+ /** Contract cap on penetrated pieces (destruction 2). */+ static constexpr int32 MaxPieces = 3;++ /** Effective tier values after the contract floors and caps (4.5). */+ static float MinBelief(const UVerseBotTier& Tier);+ static float MaxSourceAgeS(const UVerseBotTier& Tier);++ /** Wall-shot authority (4.5): all four conditions; learned or prior-only mass never authorises. */+ static bool HasWallShotAuthority(const FVerseBotFireEvidence& E, const UVerseBotTier& Tier);++ /** The mode of a shot, Unclassified when none of 8.4 applies. Order: Visible, Suppression, Prefire, WallShot. */+ static EVerseBotFireMode Classify(const FVerseBotFireEvidence& E, const UVerseBotTier& Tier);++ /** The audit record of a classified shot. */+ static FVerseBotFireAudit MakeAudit(const FVerseBotFireEvidence& E, EVerseBotFireMode Mode);+ /** The same, written into an existing record (keeps its PerceptIds allocation). */+ static void MakeAuditInto(const FVerseBotFireEvidence& E, EVerseBotFireMode Mode, FVerseBotFireAudit& Out);+};++/**+ * The per-bot audit log (F4). Counts every record per mode for the whole match and keeps the+ * newest records in a fixed ring (no growth, no per-tick allocation once warm); the harness sets+ * capture-all to keep every record of a bout and writes them next to its report. Fire intents the+ * gate blocked because no mode of 8.4 applied are counted apart: they never reach the trigger.+ */+class VERSEBOT_API FVerseBotFireAuditLog+{+public:+ /** Records kept outside capture-all. */+ static constexpr int32 RingCapacity = 1024;++ FVerseBotFireAuditLog();+ void Add(const FVerseBotFireAudit& Audit);+ /** Classify-and-log in place: the record is built in its ring slot. */+ void Add(const FVerseBotFireEvidence& E, EVerseBotFireMode Mode);+ /** A fire intent the gate dropped as unclassified (never a trigger press). */+ void AddBlocked() { ++Blocked; }+ void Reset();+ /** Keep every record (harness bouts and tests) instead of the newest RingCapacity. */+ void SetCaptureAll(bool bInCaptureAll) { bCaptureAll = bInCaptureAll; }+ /** The kept records, oldest first. */+ TArray<FVerseBotFireAudit> GetEntries() const;+ /** Records of a mode over the whole match (not only the kept ones). */+ int32 Count(EVerseBotFireMode Mode) const { return ByMode[int32(Mode)]; }+ /** All records over the whole match. */+ int32 Num() const { return Total; }+ int32 NumKept() const { return Entries.Num(); }+ int32 BlockedCount() const { return Blocked; }+ /** The kept lines joined with '\n'. */+ FString ToText() const;++private:+ FVerseBotFireAudit& NextSlot();++ TArray<FVerseBotFireAudit> Entries;+ int32 Head = 0;+ int32 Total = 0;+ int32 Blocked = 0;+ int32 ByMode[5] = {};+ bool bCaptureAll = false;+};++namespace VerseBot+{+ VERSEBOT_API const TCHAR* FireModeName(EVerseBotFireMode Mode);+}diff --git a/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotAimDriver.h b/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotAimDriver.hnew file mode 100644index 0000000000..f2e4f5f67b--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotAimDriver.h@@ -0,0 +1,62 @@+#pragma once++#include "Bot/VersePerceptTypes.h"+#include "CoreMinimal.h"++class UVerseBotTier;++/** What the brain asks of the aim layer this tick. World cm. */+struct VERSEBOT_API FVerseBotAimRequest+{+ bool bHasTarget = false;+ FVector TargetPoint = FVector::ZeroVector;+ /** The target was just acquired (a sighting after none): reaction starts now. */+ bool bNewTarget = false;+ /**+ * With bNewTarget: the reaction still left, s. The brain samples the stimulus reaction of 8.1+ * once and holds the sighting back from the decision layer for it, so it hands the aim 0 (the+ * reaction is already spent). Negative: the aim layer samples its own.+ */+ float ReactionRemainingS = -1.f;+ /** Target angular half-width, deg (fire tolerance, bot.md 8.1). */+ float TargetHalfWidthDeg = 1.f;+};++struct VERSEBOT_API FVerseBotAimResult+{+ /** Pitch, yaw for FVerseInputFrame::LookDeltaDeg. */+ FVector2f LookDeltaDeg = FVector2f::ZeroVector;+ /** Angle between the view axis after this step and the target, deg. */+ float ErrorDeg = 180.f;+ /** Reaction elapsed and error within FireTolerance x half-width. */+ bool bOnTarget = false;+};++/**+ * The aim and reaction layer (bot.md 8.1). WP09 ships the human-limited model in the Aim folder;+ * the brain codes against this surface. Deterministic per seed (B5).+ */+class VERSEBOT_API IVerseBotAimDriver+{+public:+ virtual ~IVerseBotAimDriver() = default;+ virtual void Reset(uint64 Seed, const UVerseBotTier& Tier) = 0;+ virtual FVerseBotAimResult Step(const FVerseSelfPercept& Self, const FVerseBotAimRequest& Request, float DtS) = 0;+};++/**+ * Fixed reaction (the tier's mean ReactionMs), then a follow capped at TurnRateDegS with no noise.+ * The controller's default until WP09 lands, and the "perfect follow" fake of WP08's tests.+ */+class VERSEBOT_API FVerseBotFollowAim final : public IVerseBotAimDriver+{+public:+ virtual void Reset(uint64 Seed, const UVerseBotTier& Tier) override;+ virtual FVerseBotAimResult Step(const FVerseSelfPercept& Self, const FVerseBotAimRequest& Request, float DtS) override;++private:+ float ReactionS = 0.32f;+ float TurnRateDegS = 450.f;+ float FireTolerance = 2.f;+ float SinceAcquireS = 0.f;+};diff --git a/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotBelief.h b/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotBelief.hnew file mode 100644index 0000000000..a549bfa051--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotBelief.h@@ -0,0 +1,134 @@+#pragma once++#include "Bot/VersePerceptTypes.h"+#include "Brain/VerseBotTypes.h"+#include "CoreMinimal.h"+#include "Destruction/VerseDestructionTypes.h"++class FVerseBotMatchMemory;++/** The derived values the decision layer reads (bot.md 4.3). World cm, seconds. */+struct VERSEBOT_API FVerseBotBeliefSummary+{+ EVerseBeliefState State = EVerseBeliefState::Lost;+ /** TopCluster: the 3 m disc with the highest mass. */+ FVector TopCenter = FVector::ZeroVector;+ EVerseArenaLevel TopLevel = EVerseArenaLevel::Floor;+ /** Mass of TopCluster, 0..1. */+ float Confidence = 0.f;+ /** Seconds since the newest seen or heard support inside TopCluster; large when none. */+ float SupportAgeS = 1.0e6f;+ /** True when TopCluster has no seen or heard support at all (prior or inference only). */+ bool bPriorOnly = true;+ /** Weighted sd of the top 90 % of mass, cm. */+ float SpreadCm = 1.0e5f;+ /** Opponent facing estimate (4.1): last seen yaw and its age. */+ float FacingYawDeg = 0.f;+ float FacingAgeS = 1.0e6f;+ /** A reload was heard or seen and not yet followed by a shot. */+ bool bReloadNoticed = false;+ /** Believed velocity of TopCluster, cm/s (from consecutive supports). */+ FVector Velocity = FVector::ZeroVector;+ /** Seconds since the last sighting. */+ float SinceSightingS = 1.0e6f;+ /** Last sighted pelvis location. */+ FVector LastSeenLocation = FVector::ZeroVector;+ /** Estimated opponent health from own confirmed hits (3.3), 0..1 of max. */+ float OpponentHealthFrac = 1.f;+ /** Estimated rounds the opponent fired since the last noticed reload (3.3). */+ int32 OpponentShotsSinceReload = 0;+};++/**+ * The belief map the brain reads (bot.md 4). WP07 ships the grid implementation in+ * the Belief folders of VerseBot; the brain codes against this read and step surface only. Step is+ * deterministic (B5): same frames in, same summary out.+ */+class VERSEBOT_API IVerseBotBelief+{+public:+ virtual ~IVerseBotBelief() = default;++ /** Drop everything (own death, match end). */+ virtual void Reset() = 0;++ /**+ * One belief step on one percept frame. Memory may be null (learning off); it biases+ * predict and the 1 % prior mix (7.2). Spawns are the public spawn points (kill feed prior).+ */+ virtual void Step(const FVersePerceptFrame& Frame, float DtS, const FVerseBotMatchMemory* Memory, TConstArrayView<FVector> Spawns) = 0;++ /** Record an own action that changed a piece (destruction 6.2 "Own action"). */+ virtual void NoteOwnPieceChange(uint16 PieceIndex, EVersePieceState NewState) = 0;++ virtual FVerseBotBeliefSummary Summary() const = 0;++ /** Mass within RadiusCm of Location (4.5). */+ virtual float MassWithin(const FVector& Location, float RadiusCm) const = 0;++ /** Mass within RadiusCm of Location that has seen or heard support (prior-only mass excluded, 4.5). */+ virtual float SupportedMassWithin(const FVector& Location, float RadiusCm) const = 0;++ /** Top N cells by mass (BeliefCells context: N = 8). */+ virtual void TopCells(int32 N, TArray<FVector>& Out) const = 0;++ /** The believed state of a piece; Intact for one never perceived (DR6). */+ virtual EVersePieceState GetPieceBelief(uint16 PieceIndex) const = 0;+};++/**+ * A small deterministic belief: a mixture of up to eight Gaussian hypotheses fed by the same rules+ * as bot.md 4.2 (sighting replaces, heard multiplies, hurt and bolt add a wedge, kill feed clears+ * and seeds the spawn prior, predict diffuses at 4.5 m/s). The controller uses it until WP07's+ * grid lands; tests use it as the scripted-belief baseline.+ */+class VERSEBOT_API FVerseBotCoarseBelief final : public IVerseBotBelief+{+public:+ static constexpr int32 MaxHypotheses = 8;++ virtual void Reset() override;+ virtual void Step(const FVersePerceptFrame& Frame, float DtS, const FVerseBotMatchMemory* Memory, TConstArrayView<FVector> Spawns) override;+ virtual void NoteOwnPieceChange(uint16 PieceIndex, EVersePieceState NewState) override;+ virtual FVerseBotBeliefSummary Summary() const override { return Cached; }+ virtual float MassWithin(const FVector& Location, float RadiusCm) const override;+ virtual float SupportedMassWithin(const FVector& Location, float RadiusCm) const override;+ virtual void TopCells(int32 N, TArray<FVector>& Out) const override;+ virtual EVersePieceState GetPieceBelief(uint16 PieceIndex) const override;++ /** Own player id, so kill feed entries can be read (set by the brain). */+ void SetSelfId(int32 InSelfId) { SelfId = InSelfId; }++private:+ enum class ESupport : uint8 { Prior, Inferred, Heard, Seen };++ struct FHypothesis+ {+ FVector Center = FVector::ZeroVector;+ float SdCm = 50.f;+ float Weight = 0.f;+ EVerseArenaLevel Level = EVerseArenaLevel::Floor;+ ESupport Support = ESupport::Prior;+ float SupportTimeS = -1.0e6f;+ FVector Velocity = FVector::ZeroVector;+ };++ void Normalise();+ void AddHypothesis(const FHypothesis& H);+ void Refresh(float NowS);+ static float DiscMass(const FHypothesis& H, const FVector& Location, float RadiusCm);++ TArray<FHypothesis, TInlineAllocator<MaxHypotheses>> Hyps;+ TMap<uint16, EVersePieceState> Pieces;+ FVerseBotBeliefSummary Cached;+ bool bDead = false;+ bool bReload = false;+ float NowS = 0.f;+ float LastSeenS = -1.0e6f;+ FVector LastSeen = FVector::ZeroVector;+ float FacingYaw = 0.f;+ float FacingTimeS = -1.0e6f;+ float OpponentHealth = 1.f;+ int32 ShotsSinceReload = 0;+ int32 SelfId = 0;+};diff --git a/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotBrainCore.h b/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotBrainCore.hnew file mode 100644index 0000000000..fa05615442--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotBrainCore.h@@ -0,0 +1,230 @@+#pragma once++#include "Audit/VerseBotFireAudit.h"+#include "Bot/VersePerceptTypes.h"+#include "Brain/VerseBotAimDriver.h"+#include "Brain/VerseBotBelief.h"+#include "Brain/VerseBotTypes.h"+#include "Brain/VerseBotUtility.h"+#include "Brain/VerseBotWorldQueries.h"+#include "Combat/VerseCombatTypes.h"+#include "CoreMinimal.h"+#include "Learning/VerseBotMatchMemory.h"+#include "Tactics/VerseBotTactics.h"+#include "VerseRng.h"++class UVerseBotTier;++/**+ * The deterministic bot brain (bot.md B5, frozen interface): percept frame and world-query answers+ * in, one FVerseInputFrame out. No engine state is read: given the seed, the tier, the percept+ * stream and the query answers, the output is bit-identical (BR1). Runs on the server.+ *+ * Per tick: belief step (10 Hz, at once on a positive percept), learning update, reflexes, a+ * decision every DecisionMs x U(0.8, 1.2) or on a forced trigger (5.2), at most one scheduled EQS+ * query, the current state's tick, aim, the fire gate with the F4 audit, and the input frame.+ */+class VERSEBOT_API FVerseBotBrainCore+{+public:+ struct FConfig+ {+ uint64 Seed = 0;+ /** The bot's player id (kill feed). */+ int32 SelfId = 0;+ /** Learning on (7); the harness turns it off for the BG8 control run. */+ bool bLearning = true;+ };++ FVerseBotBrainCore();+ ~FVerseBotBrainCore();++ /** Starts a match: tier copied by reference (must outlive the brain), RNG streams seeded, memory empty. */+ void Init(const UVerseBotTier& InTier, const FConfig& InConfig);++ /** Swap the tier (adaptive applies at respawn, 9.2). Memory is kept. */+ void SetTier(const UVerseBotTier& InTier);++ /** Replace the belief (WP07's grid) or aim (WP09's model); the brain owns them. */+ void SetBelief(TUniquePtr<IVerseBotBelief> InBelief);+ void SetAimDriver(TUniquePtr<IVerseBotAimDriver> InAim);++ /** One server tick. */+ FVerseInputFrame Think(const FVersePerceptFrame& Frame, IVerseBotWorldQueries& World);++ /** Match end (7.3): memory, belief, plan, audit dropped. */+ void ResetMatch();++ EVerseBotState GetState() const { return Selector.Current(); }+ FVerseBotPresentation GetPresentation() const;+ const FVerseBotFireAuditLog& GetFireAudit() const { return Audit; }+ FVerseBotFireAuditLog& GetFireAudit() { return Audit; }+ const FVerseBotMatchMemory& GetMemory() const { return *Memory; }+ FVerseBotMatchMemory& GetMemory() { return *Memory; }+ /** Use an external memory (UVerseBotMatchMemory of the controller); it must outlive the brain. */+ void UseMemory(FVerseBotMatchMemory& InMemory);+ const IVerseBotBelief& GetBelief() const { return *Belief; }+ int32 GetDecisionCount() const { return DecisionIndex; }+ /** Number of decisions per state since Init (presentation, harness). */+ const int32* GetStateCounts() const { return StateCounts; }+ /** Ticks the bot wanted to move but made no progress for 3 s (BG12 stuck events). */+ int32 GetStuckEvents() const { return StuckEvents; }+ /** Paths the belief nav could not build (BG12 navFailures). */+ int32 GetNavFailures() const { return NavFailures; }+ /** Stuck events by the state the bot was in. */+ const int32* GetStuckByState() const { return StuckByState; }+ /** A sighting or hurt stimulus is still inside its sampled reaction (8.1): not yet acted on. */+ bool IsReactionPending() const { return bSightHeld || bHurtPending; }+ /** Ticks a query slice ran on, and query slices that stopped on the per-tick budget. */+ int32 GetQuerySlices() const { return QuerySlices; }+ int32 GetQueryBudgetStops() const { return QueryBudgetStops; }++ /** EQS cost units (FVerseBotEqsSlice) a query may spend per tick: bot.md 2, EQS 0.2 ms amortised. */+ static constexpr int32 QueryUnitsPerTick = 24;++private:+ void BuildContext(const FVersePerceptFrame& Frame, IVerseBotWorldQueries& World);+ void UpdateLearning(const FVersePerceptFrame& Frame);+ bool ForcedTriggers(const FVersePerceptFrame& Frame, float (&Bonus)[VerseBot::NumStates]);+ void RunScheduledQuery();+ void StartQuery(EVerseBotQuery Query);+ /** Holds new sighting and hurt stimuli back for their sampled reaction (8.1, 5.2). */+ const FVersePerceptFrame& GateStimuli(const FVersePerceptFrame& Raw);+ /** N(ReactionMs), floor 0.6 x mean, times Mul (peripheral, partial exposure). Seconds. */+ float SampleReactionS(float Mul);+ /** Prefire (8.4, 7.2): pre-aim and fire at the peek edge a fresh heard percept is near. */+ void UpdatePrefire(FVerseBotIntent& Intent);+ void Decide(bool bInterrupt, const float (&Bonus)[VerseBot::NumStates]);+ void Reflexes(FVerseBotIntent& Intent);+ void ApplyFireGate(FVerseBotIntent& Intent, const FVerseBotAimResult& Aim);+ FVerseInputFrame ToInput(const FVerseBotIntent& Intent, const FVerseBotAimResult& Aim, uint32 ServerTimeMs);+ void OnOwnDeath();+ void OnOwnRespawn();+ void TacticsVisibleReset();+ FVector NextWaypoint(const FVector& Target, bool bCrouch);++ const UVerseBotTier* Tier = nullptr;+ FConfig Config;+ TUniquePtr<IVerseBotBelief> Belief;+ TUniquePtr<IVerseBotAimDriver> Aim;+ FVerseBotMatchMemory OwnedMemory;+ FVerseBotMatchMemory* Memory = &OwnedMemory;+ FVerseBotFireAuditLog Audit;+ FVerseBotUtilitySelector Selector;+ FVerseBotTacticsMemory TacticsMem;+ FVerseBotQueryCache Cache;+ FVerseRng DecisionRng;+ FVerseRng TacticsRng;+ FVerseRng ReflexRng;+ FVerseRng ReactRng;++ // Reaction gate (8.1, 5.2)+ FVersePerceptFrame GatedFrame;+ bool bRawHadSighting = false;+ bool bSightHeld = false;+ float SightReactUntilS = -1.f;+ bool bHurtPending = false;+ float HurtReactUntilS = -1.f;+ FVerseHurtPercept PendingHurt;+ float HealthBeforeHurt = 0.f;+ float LastRawHealth = 0.f;++ // The running time-sliced query (at most one; Pending holds the next).+ struct FQueryJob+ {+ bool bActive = false;+ EVerseBotQuery Query = EVerseBotQuery::Count;+ /** Snapshot of the context at start: the generator sees the same inputs on every slice. */+ FVerseSelfPercept Self;+ FVerseBotBeliefSummary Belief;+ FVerseBotCoverPoint From;+ FVerseBotQueryContext Ctx;+ FVerseBotEqsSlice Slice;+ FVerseBotCoverResult Cover;+ FVerseBotPeekResult Peek;+ FVerseBotWallbangResult Wallbang;+ FVerseBotBreachResult Breach;+ FVerseBotFinisherResult Finisher;+ };+ FQueryJob Job;+ int32 QuerySlices = 0;+ int32 QueryBudgetStops = 0;++ // Per-tick context (valid inside Think).+ FVerseBotTacticsContext Ctx;+ FVerseBotBeliefSummary BeliefSummary;+ TArray<FVector> BeliefCellsScratch;+ TArray<FVector> Spawns;+ IVerseBotWorldQueries* WorldThisTick = nullptr;+ const FVersePerceptFrame* FrameThisTick = nullptr;+ FVerseSightPercept SightingThisTick;+ bool bSightingThisTick = false;+ FVerseHeardPercept LastHeard;+ float LastHeardS = -1.0e6f;++ // Timing+ float NowS = 0.f;+ float LastThinkS = -1.f;+ float NextDecisionS = 0.f;+ float NextBeliefStepS = 0.f;+ float LastBeliefStepS = 0.f;+ int32 DecisionIndex = 0;+ int32 StateCounts[VerseBot::NumStates] = {};+ int32 StuckByState[VerseBot::NumStates] = {};++ // Triggers (5.2)+ bool bHadSighting = false;+ float LastSightingS = -1.0e6f;+ FVector LastSeenLocation = FVector::ZeroVector;+ uint32 LastSightPerceptId = 0;+ bool bWasAlive = false;+ int32 LastMagazine = -1;+ float LastHurtS = -1.0e6f;+ float AttackBonusUntilS = -1.f;+ bool bAcquiredPending = false;++ // EQS scheduler+ TArray<EVerseBotQuery, TInlineAllocator<2>> Pending;+ int32 QueryCursor = 0;++ // Path cache+ FVerseBotPath Path;+ FVector PathTarget = FVector(1.0e9);+ int32 PathIndex = 0;+ int32 PathDecision = -1;++ // Learning bookkeeping+ bool bInEngagement = false;+ float EngagementRangeCm = 0.f;+ float EngagementLastS = -1.0e6f;+ int32 LastPersonZone = INDEX_NONE;+ bool bFirstContactDone = false;++ // Health+ FVector StuckRef = FVector::ZeroVector;+ float StuckSinceS = 0.f;+ bool bStuckCounted = false;+ bool bStuckReplanned = false;+ bool bNavFailCounted = false;+ int32 NavFailures = 0;++ // Reflex state+ bool bAdsHeld = false;+ bool bFireHeld = false;+ uint32 PrevButtons = 0;+ int32 VisibleBurst = 0;+ float BurstRestUntilS = 0.f;+ bool bNewTargetForAim = false;+ FVector AimTarget = FVector::ZeroVector;+ bool bHasAimTarget = false;+ bool bChooseHead = false;+ bool bPistolRolled = false;+ bool bPistolChosen = false;+ bool bKnifeRolled = false;+ bool bKnifeChosen = false;+ bool bCoarseBelief = true;+ bool bSpawnsFetched = false;+ int32 StuckEvents = 0;+ float LastSightRecordS = -1.0e6f;+ float LastOpponentKillS = -1.0e6f;+};diff --git a/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotReplay.h b/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotReplay.hnew file mode 100644index 0000000000..83f717dd1f--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotReplay.h@@ -0,0 +1,80 @@+#pragma once++#include "Bot/VersePerceptTypes.h"+#include "Brain/VerseBotWorldQueries.h"+#include "Combat/VerseCombatTypes.h"+#include "CoreMinimal.h"++// Record and replay harness of BR1 (bot.md 10): a recorded percept stream plus the recorded+// world-query answers plus the seed, fed to FVerseBotBrainCore twice, must give identical outputs.+// The tape is an in-memory byte stream; it is never written to disk by the game (L1).++/** A recorded run: frames, query answers, and the brain's outputs. */+struct VERSEBOT_API FVerseBotTape+{+ uint64 Seed = 0;+ FName TierId;+ TArray<FVersePerceptFrame> Frames;+ /** Serialised query calls and answers, in call order. */+ TArray<uint8> Queries;+ /** Serialised FVerseInputFrame outputs, one per frame. */+ TArray<uint8> Outputs;++ /** Bytes of one input frame as the tape stores it. */+ static void AppendOutput(TArray<uint8>& Out, const FVerseInputFrame& Frame);+};++/** Wraps a live world: forwards every call and appends call id, arguments and answer to a tape. */+class VERSEBOT_API FVerseBotRecordingQueries final : public IVerseBotWorldQueries+{+public:+ FVerseBotRecordingQueries(IVerseBotWorldQueries& InInner, TArray<uint8>& InTape) : Inner(InInner), Tape(InTape) {}++ virtual bool TestSight(const FVector& Eye, const FVector& Target) override;+ virtual FVerseBotBoltTrace TraceBolt(const FVector& Origin, const FVector& Target, const FVerseBotWeaponInfo& Weapon) override;+ virtual FVerseBotPath FindPath(const FVector& From, const FVector& To, bool bCrouch) override;+ virtual void GetCoverPoints(const FVector& Center, float RadiusCm, TArray<FVerseBotCoverPoint>& Out) override;+ virtual void GetPieces(const FVector& Center, float RadiusCm, TArray<FVerseBotPieceInfo>& Out) override;+ virtual void GetSpawnPoints(TArray<FVector>& Out) override;+ virtual int32 GetZoneId(const FVector& Location) override;+ virtual FVerseBotWeaponInfo GetOwnWeapon() override;+ virtual bool CanActivateFinisher() override;++private:+ IVerseBotWorldQueries& Inner;+ TArray<uint8>& Tape;+};++/**+ * Answers from a tape. Every call checks its call id and arguments against the recording; the+ * first mismatch sets Diverged and the call answers a neutral default from then on.+ */+class VERSEBOT_API FVerseBotReplayQueries final : public IVerseBotWorldQueries+{+public:+ explicit FVerseBotReplayQueries(const TArray<uint8>& InTape) : Tape(InTape) {}++ virtual bool TestSight(const FVector& Eye, const FVector& Target) override;+ virtual FVerseBotBoltTrace TraceBolt(const FVector& Origin, const FVector& Target, const FVerseBotWeaponInfo& Weapon) override;+ virtual FVerseBotPath FindPath(const FVector& From, const FVector& To, bool bCrouch) override;+ virtual void GetCoverPoints(const FVector& Center, float RadiusCm, TArray<FVerseBotCoverPoint>& Out) override;+ virtual void GetPieces(const FVector& Center, float RadiusCm, TArray<FVerseBotPieceInfo>& Out) override;+ virtual void GetSpawnPoints(TArray<FVector>& Out) override;+ virtual int32 GetZoneId(const FVector& Location) override;+ virtual FVerseBotWeaponInfo GetOwnWeapon() override;+ virtual bool CanActivateFinisher() override;++ bool HasDiverged() const { return bDiverged; }+ /** All recorded calls were consumed. */+ bool IsAtEnd() const { return Offset == Tape.Num(); }+ int32 GetCallCount() const { return Calls; }++private:+ bool Begin(uint8 CallId, uint32 ArgHash);+ template <typename T> T Read();++ const TArray<uint8>& Tape;+ int32 Offset = 0;+ int32 Calls = 0;+ bool bDiverged = false;+};diff --git a/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotTypes.h b/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotTypes.hnew file mode 100644index 0000000000..9ae50010d7--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotTypes.h@@ -0,0 +1,141 @@+#pragma once++#include "Combat/VerseCombatTypes.h"+#include "CoreMinimal.h"+#include "GameplayTagContainer.h"++#include "VerseBotTypes.generated.h"++// Shared types of the bot brain (bot.md 5, 6). Units: Unreal cm, seconds, degrees.++/** The decision states of bot.md 5.1, in table order (Bot.State.* tags, same order). */+UENUM(BlueprintType)+enum class EVerseBotState : uint8+{+ Attack,+ Hold,+ Flank,+ StalkForFinisher,+ Retreat,+ Reload,+ DeployBulwark,+ Breach,+ Wallbang,+ Search+};++/** Hold substates (bot.md 5.2): Go -> Hide -> Peek -> Hide. */+UENUM(BlueprintType)+enum class EVerseBotHoldPhase : uint8+{+ Go,+ Hide,+ Peek+};++/** Peek types EQS_PeekCorner generates (bot.md 6.2). */+UENUM(BlueprintType)+enum class EVerseBotPeekType : uint8+{+ LeanLeft,+ LeanRight,+ CrouchRise,+ StepOut,+ JumpPeek+};++/** Belief states of bot.md 4.3 plus Dead (kill feed). */+UENUM(BlueprintType)+enum class EVerseBeliefState : uint8+{+ Known,+ Tracked,+ Rough,+ Lost,+ Dead+};++/** What AVerseBotController::GetPresentation returns: presentation and screenshots only. */+USTRUCT(BlueprintType)+struct VERSEBOT_API FVerseBotPresentation+{+ GENERATED_BODY()++ UPROPERTY(BlueprintReadOnly, Category = "Bot")+ EVerseBotState State = EVerseBotState::Search;++ /** The Bot.State.* tag of State (not reflected: VerseBot links no GameplayTags module of its own). */+ FGameplayTag StateTag;++ UPROPERTY(BlueprintReadOnly, Category = "Bot")+ EVerseBotHoldPhase HoldPhase = EVerseBotHoldPhase::Go;++ UPROPERTY(BlueprintReadOnly, Category = "Bot")+ bool bHasCoverSpot = false;++ /** World cm. */+ UPROPERTY(BlueprintReadOnly, Category = "Bot")+ FVector CoverSpot = FVector::ZeroVector;++ UPROPERTY(BlueprintReadOnly, Category = "Bot")+ bool bHasPeekPoint = false;++ /** World cm. */+ UPROPERTY(BlueprintReadOnly, Category = "Bot")+ FVector PeekPoint = FVector::ZeroVector;++ /** Believed opponent position (TopCluster centre), world cm. */+ UPROPERTY(BlueprintReadOnly, Category = "Bot")+ FVector BeliefTop = FVector::ZeroVector;++ UPROPERTY(BlueprintReadOnly, Category = "Bot")+ float Confidence = 0.f;+};++/** What a state wants this tick; the brain turns it into one FVerseInputFrame. */+struct VERSEBOT_API FVerseBotIntent+{+ bool bHasMoveTarget = false;+ /** World cm; the brain paths there through IVerseBotWorldQueries::FindPath. */+ FVector MoveTarget = FVector::ZeroVector;+ bool bHasLookTarget = false;+ /** World cm. */+ FVector LookTarget = FVector::ZeroVector;+ EVerseStance Stance = EVerseStance::Stand;+ /** -1 left, 0 none, 1 right. */+ int8 Lean = 0;+ bool bSprint = false;+ /** Walk instead of run (sound discipline, 8.3); crouch-walk is Stance Crouch plus bWalk. */+ bool bWalk = false;+ bool bSlide = false;+ bool bJump = false;+ bool bAds = false;+ /** The state wants to shoot at LookTarget; the fire gate decides (audit 8.10). */+ bool bWantFire = false;+ bool bReload = false;+ bool bMelee = false;+ /** GadgetA = Bulwark, GadgetB = breach charge (combat-state.md 2.2). */+ bool bGadgetA = false;+ bool bGadgetB = false;+ bool bSwitchSecondary = false;+ bool bSwitchPrimary = false;+ /** Strafe sign while attacking: -1, 0, 1 (pawn right). */+ int8 Strafe = 0;+};++struct FVerseRng;++namespace VerseBot+{+ /** The decision period jitter U(Min, Max) of bot.md 5.2, one draw from Rng. */+ VERSEBOT_API double Jitter(FVerseRng& Rng, double Min, double Max);++ inline constexpr float CmPerM = 100.f;+ inline constexpr int32 NumStates = 10;++ /** The Bot.State.* tag of a state. */+ VERSEBOT_API FGameplayTag StateTag(EVerseBotState State);++ /** Stable lower-case name for logs and reports. */+ VERSEBOT_API const TCHAR* StateName(EVerseBotState State);+}diff --git a/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotUtility.h b/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotUtility.hnew file mode 100644index 0000000000..b567ba7000--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotUtility.h@@ -0,0 +1,46 @@+#pragma once++#include "Brain/VerseBotTypes.h"+#include "CoreMinimal.h"+#include "VerseRng.h"++/**+ * Utility selection with hysteresis (bot.md 5): the current state gets +0.18, every state gets+ * U(0, UtilityNoise) per decision, a state is kept at least 0.4 s unless the decision is an+ * interrupt. Deterministic per RNG stream. The StateTree root (ST_VerseDuelBot) evaluates its+ * children's utility through this selector, so the rule lives in one place.+ */+class VERSEBOT_API FVerseBotUtilitySelector+{+public:+ static constexpr float Hysteresis = 0.18f;+ static constexpr float MinDwellS = 0.4f;++ struct FDecision+ {+ EVerseBotState State = EVerseBotState::Search;+ bool bChanged = false;+ /** Final scores (utility + hysteresis + noise + bonus), state order. */+ float Scores[VerseBot::NumStates] = {};+ };++ void Reset(EVerseBotState Start, float NowS);++ /**+ * Picks a state. Utilities: base utility per state, state order; a negative value means the+ * state cannot run. Bonus: per-state forced bonus for this decision (5.2). bInterrupt lifts the+ * dwell. Noise draws come from Rng in state order, one per state, every decision.+ */+ FDecision Decide(const float (&Utilities)[VerseBot::NumStates], const float (&Bonus)[VerseBot::NumStates],+ float UtilityNoise, bool bInterrupt, float NowS, FVerseRng& Rng);++ /** Force a state (own respawn: Search), restarting its dwell. */+ void Force(EVerseBotState State, float NowS);++ EVerseBotState Current() const { return CurrentState; }+ float EnteredS() const { return EnteredAtS; }++private:+ EVerseBotState CurrentState = EVerseBotState::Search;+ float EnteredAtS = 0.f;+};diff --git a/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotWorldQueries.h b/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotWorldQueries.hnew file mode 100644index 0000000000..eab1fd4893--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Brain/VerseBotWorldQueries.h@@ -0,0 +1,100 @@+#pragma once++#include "CoreMinimal.h"++// Everything the brain may ask the world (bot.md B5: "the world-query answers" of the BR1 replay).+// Every answer is either static arena data a person learns from the map (cover points, pieces,+// spawn points, zones; bot.md 3.3), the bot's own state (its weapon, its finisher ability), or a+// query evaluated against the bot's piece belief, never against piece truth (bot.md 6, DR6). No+// query takes or returns an opponent actor (F1). All positions are world cm.++/** A cover point from arena data or the auto generator (bot.md 6.2 EQS_Cover). */+struct VERSEBOT_API FVerseBotCoverPoint+{+ int32 Id = INDEX_NONE;+ FVector Location = FVector::ZeroVector;+ /** High cover hides a standing eye (1.7 m); low cover only a crouched one (1.0 m). */+ bool bHigh = true;+ /** A spot where a Bulwark can be deployed. */+ bool bBulwarkSpot = false;+ /** Arena data id of the cover edge (peek habits, 7.1); INDEX_NONE when none. */+ int32 EdgeId = INDEX_NONE;+ /** Unit vector from the cover toward the side it protects against. */+ FVector Facing = FVector::ForwardVector;+ /** 0..1, how much the covering piece costs a bolt (thin sheet low, concrete high). */+ float MaterialProtection = 1.f;+ /** Pieces whose state the cover depends on (destruction 6.2). */+ TArray<uint16, TInlineAllocator<2>> DependsOnPieces;+};++/** A destructible piece as static arena data (material, place); its state comes from belief. */+struct VERSEBOT_API FVerseBotPieceInfo+{+ uint16 PieceIndex = 0;+ FVector Center = FVector::ZeroVector;+ /** Unit normal of the face toward the bot's side is not known; this is the authored +X face. */+ FVector Normal = FVector::ForwardVector;+ /** Breach charge can open it (destruction 2). */+ bool bBreachable = false;+ /** A rifle bolt can pass it (destruction 2). */+ bool bPenetrable = false;+};++/** A path through the belief nav filter (6.1). */+struct VERSEBOT_API FVerseBotPath+{+ bool bValid = false;+ float LengthCm = 0.f;+ TArray<FVector, TInlineAllocator<8>> Waypoints;+};++/** The bot's own held weapon (it is on its HUD, 3.3). */+struct VERSEBOT_API FVerseBotWeaponInfo+{+ float Damage = 30.f;+ float PenetrationPower = 100.f;+ int32 MagazineSize = 30;+ uint8 HoleRadiusMm = 6;+};++/** Result of a believed bolt trace (4.5 Path). */+struct VERSEBOT_API FVerseBotBoltTrace+{+ /** Damage fraction left at the target, 0..1. */+ float DamageFrac = 0.f;+ /** Pieces entered. */+ int32 Pieces = 0;+};++class VERSEBOT_API IVerseBotWorldQueries+{+public:+ virtual ~IVerseBotWorldQueries() = default;++ /** Sight from Eye to Target through the believed pieces (holes the bot has seen honoured). */+ virtual bool TestSight(const FVector& Eye, const FVector& Target) = 0;++ /** The own weapon's bolt from Origin to Target through the believed pieces (at most 3). */+ virtual FVerseBotBoltTrace TraceBolt(const FVector& Origin, const FVector& Target, const FVerseBotWeaponInfo& Weapon) = 0;++ /** Nav path through UVerseBeliefNavFilter; bCrouch uses the Crouch agent. */+ virtual FVerseBotPath FindPath(const FVector& From, const FVector& To, bool bCrouch) = 0;++ /** Cover points within RadiusCm of Center. */+ virtual void GetCoverPoints(const FVector& Center, float RadiusCm, TArray<FVerseBotCoverPoint>& Out) = 0;++ /** Destructible pieces within RadiusCm of Center. */+ virtual void GetPieces(const FVector& Center, float RadiusCm, TArray<FVerseBotPieceInfo>& Out) = 0;++ /** Spawn points of the arena (public rule, 3.3). */+ virtual void GetSpawnPoints(TArray<FVector>& Out) = 0;++ /** Arena zone id (about 20 zones, 7.1); INDEX_NONE outside the arena. */+ virtual int32 GetZoneId(const FVector& Location) = 0;++ /** The own weapon in the active slot. */+ virtual FVerseBotWeaponInfo GetOwnWeapon() = 0;++ /** The own finisher ability could activate now (it gates on the rules, not on the opponent). */+ virtual bool CanActivateFinisher() = 0;+};diff --git a/unreal/Verse/Source/VerseBot/Public/Controller/VerseBotController.h b/unreal/Verse/Source/VerseBot/Public/Controller/VerseBotController.hnew file mode 100644index 0000000000..9f3821cdb0--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Controller/VerseBotController.h@@ -0,0 +1,116 @@+#pragma once++#include "Bot/VersePerceptTypes.h"+#include "Brain/VerseBotBrainCore.h"+#include "Brain/VerseBotTypes.h"+#include "Brain/VerseBotWorldQueries.h"+#include "Combat/VerseCombatTypes.h"+#include "CoreMinimal.h"+#include "GameFramework/Controller.h"++#include "VerseBotController.generated.h"++class UVerseBotMatchMemory;+class UVerseBotTier;++DECLARE_MULTICAST_DELEGATE_OneParam(FOnVerseBotInputFrame, const FVerseInputFrame&);++/**+ * The duel bot (bot.md B1, frozen interface). Possesses an ordinary AVerseCharacter on the server+ * and acts only through FVerseInputFrame, the input a person produces: the frame drives the pawn's+ * movement input and control rotation, and OnInputFrame hands the buttons to the pawn's input+ * consumer (the "virtual input device", architecture 3.4). It reads the world only through the+ * percept frames the perception service delivers (ReceivePerceptFrame) and the world queries.+ *+ * Writes BotTier and BotEffectiveSkill into its own player state (combat-state.md 2.1).+ */+UCLASS()+class VERSEBOT_API AVerseBotController : public AController+{+ GENERATED_BODY()++public:+ AVerseBotController();+ virtual ~AVerseBotController() override;++ /** Tier for the next life; resets the match memory when the tier changes (7.3). */+ void SetTier(const UVerseBotTier* InTier);+ /** Adaptive mode (9.2); resets the match memory when it changes. */+ void SetAdaptive(bool bInAdaptive);+ bool IsAdaptive() const { return bAdaptive; }+ /** Adaptive s in [0, 1]; for a fixed tier 0 (normal), 0.5 (hard) or 1 (elite). */+ float GetEffectiveSkill() const { return EffectiveSkill; }+ /** WP09's adaptive controller sets the next s; it is applied at the next own respawn. */+ void SetPendingSkill(float S);+ /** Presentation only: state, cover spot, peek point. */+ FVerseBotPresentation GetPresentation() const;++ /** The perception service's OnPerceptFrame for this observer lands here. */+ void ReceivePerceptFrame(const FVersePerceptFrame& Frame);++ /** Match end (7.3): duel exit, arena off, tier or mode change, Verse.exe exit. */+ void ResetMatch();++ /** The input frame of the last tick. */+ const FVerseInputFrame& GetLastInputFrame() const { return LastInput; }+ FOnVerseBotInputFrame OnInputFrame;++ FVerseBotBrainCore* GetBrain() const { return Brain.Get(); }+ /** Override the world queries (harness, tests). The controller does not own them. */+ void SetWorldQueries(IVerseBotWorldQueries* InQueries) { QueriesOverride = InQueries; }++ /** Seed of the next match's brain RNG streams (harness: seeded runs). 0 picks one. */+ void SetSeed(uint64 InSeed) { FixedSeed = InSeed; }++ /** Match option ?BotTier=normal|hard|elite|adaptive; None when absent or unknown. */+ static FName ParseBotTierOption(const FString& Options);++ /**+ * Writes FName BotTier and float BotEffectiveSkill into any reflected container that has them+ * (the player state). False when a field is missing.+ */+ static bool WriteBotIdentity(const UStruct* Type, void* Container, FName InTier, float InSkill);++ virtual void Tick(float DeltaSeconds) override;+ virtual void PostInitializeComponents() override;+ virtual void OnPossess(APawn* InPawn) override;+ virtual void OnUnPossess() override;+ virtual void EndPlay(const EEndPlayReason::Type Reason) override;++private:+ void EnsureBrain();+ void ApplyInput(const FVerseInputFrame& Frame);+ void WriteIdentity();+ /** The last service frame with only the own pose refreshed from the own pawn (no new percepts). */+ FVersePerceptFrame SelfRefreshedFrame(uint32 ServerTimeMs) const;+ /** The world's server clock, ms: one clock for service frames and refreshed frames. */+ uint32 WorldServerTimeMs() const;+ const UVerseBotTier* EffectiveTier();++ TUniquePtr<FVerseBotBrainCore> Brain;+ TUniquePtr<IVerseBotWorldQueries> DefaultQueries;+ IVerseBotWorldQueries* QueriesOverride = nullptr;++ UPROPERTY(Transient)+ TObjectPtr<const UVerseBotTier> Tier;++ UPROPERTY(Transient)+ TObjectPtr<UVerseBotTier> InterpolatedTier;++ UPROPERTY(Transient)+ TObjectPtr<UVerseBotMatchMemory> MatchMemory;++ bool bAdaptive = false;+ float EffectiveSkill = 0.f;+ float PendingSkill = -1.f;+ bool bHasFrame = false;+ FVersePerceptFrame PendingFrame;+ /** The newest service frame: its own HUD (health, magazine, gadgets) stays valid between frames. */+ FVersePerceptFrame LastRealFrame;+ bool bHasRealFrame = false;+ uint32 LastThinkMs = 0;+ FVerseInputFrame LastInput;+ uint64 Seed = 0;+ uint64 FixedSeed = 0;+ bool bBrainReady = false;+};diff --git a/unreal/Verse/Source/VerseBot/Public/Eqs/VerseBeliefNavFilter.h b/unreal/Verse/Source/VerseBot/Public/Eqs/VerseBeliefNavFilter.hnew file mode 100644index 0000000000..e3e439a4ae--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Eqs/VerseBeliefNavFilter.h@@ -0,0 +1,38 @@+#pragma once++#include "CoreMinimal.h"+#include "Destruction/VerseDestructionTypes.h"++class IVerseBotBelief;+class UVerseBotTier;++/** How a nav poly or link depends on a destructible piece (destruction 6.1). */+enum class EVerseNavPieceRelation : uint8+{+ /** Not tied to a piece. */+ None,+ /** Exists only because the piece is open: breach openings, mantle links over low breaches, drop-downs. */+ OpenedBy,+ /** Exists while the piece stands: catwalk decks and their links. */+ StandsOn+};++/**+ * The rule of UVerseBeliefNavFilter (bot.md 6.1) on the piece belief, never on truth: polys a+ * breach or destruction created are excluded while the piece is believed closed; polys of a piece+ * believed standing are used until the bot sees it gone (the path then fails and it re-plans).+ * The engine filter class answers every poly through this function.+ */+struct VERSEBOT_API FVerseBeliefNavFilter+{+ /** True for Breached and Destroyed: an opening a bot or person can pass. */+ static bool IsOpen(EVersePieceState State);++ static bool IsUsable(EVerseNavPieceRelation Relation, uint16 PieceIndex, const IVerseBotBelief& Belief);++ /** Same, on a known believed state. */+ static bool IsUsableInState(EVerseNavPieceRelation Relation, EVersePieceState BelievedState);++ /** Nav link cost x NavLinkCostMul (stairs, ladders, mantles, jumps, drops). */+ static float LinkCost(float BaseCost, const UVerseBotTier& Tier);+};diff --git a/unreal/Verse/Source/VerseBot/Public/Eqs/VerseBotEqs.h b/unreal/Verse/Source/VerseBot/Public/Eqs/VerseBotEqs.hnew file mode 100644index 0000000000..0415d49ac8--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Eqs/VerseBotEqs.h@@ -0,0 +1,225 @@+#pragma once++#include "Bot/VersePerceptTypes.h"+#include "Brain/VerseBotBelief.h"+#include "Brain/VerseBotTypes.h"+#include "Brain/VerseBotWorldQueries.h"+#include "CoreMinimal.h"++class FVerseBotMatchMemory;+class UVerseBotTier;++// The EQS queries of bot.md 6.2 as deterministic generator / filter / score passes over belief+// contexts only. The contexts (BeliefTop, BeliefCells, BeliefFacing) resolve to belief values,+// never to an actor (F1); sight tests go through IVerseBotWorldQueries::TestSight against the+// piece belief. Every item score is (1 - w) x base + w x learned with w from 7.3.++/** Everything a query reads. */+struct VERSEBOT_API FVerseBotQueryContext+{+ const FVerseSelfPercept* Self = nullptr;+ const FVerseBotBeliefSummary* Belief = nullptr;+ const IVerseBotBelief* BeliefMap = nullptr;+ IVerseBotWorldQueries* World = nullptr;+ const FVerseBotMatchMemory* Memory = nullptr;+ const UVerseBotTier* Tier = nullptr;+ float NowS = 0.f;+ /** Exploration (7.3): this decision ignores the learned term. */+ bool bIgnoreLearned = false;+ /** Preferred engagement range after the learned shift, cm. */+ float PreferredRangeCm = 1400.f;+ FVerseBotWeaponInfo Weapon;+ /** The bot's last three peek edges (PeekRepeatPenalty). */+ TArray<int32, TInlineAllocator<3>> RecentPeekEdges;+ /** Peek edge ids already spent this decision; not used by the queries themselves. */+ int32 CurrentCoverEdge = INDEX_NONE;+};++enum class EVerseBotCoverMode : uint8+{+ Near,+ Far,+ Flank,+ Bulwark+};++struct VERSEBOT_API FVerseBotCoverResult+{+ bool bFound = false;+ FVerseBotCoverPoint Point;+ float Score = 0.f;+ int32 Candidates = 0;+};++struct VERSEBOT_API FVerseBotPeekResult+{+ bool bFound = false;+ EVerseBotPeekType Type = EVerseBotPeekType::LeanRight;+ /** Where the bot stands while peeking. */+ FVector StandPoint = FVector::ZeroVector;+ /** The peek eye. */+ FVector Eye = FVector::ZeroVector;+ float Score = 0.f;+ /**+ * Learned (7.2): the person's most used peek edge near TopCluster that this peek sees. Hold+ * pre-aims it and stays out longer the more the person re-peeks it fast.+ */+ bool bHasWatch = false;+ FVector WatchPoint = FVector::ZeroVector;+ int32 WatchEdge = INDEX_NONE;+ /** The person's fast re-peek share at the watched edge and the learned weight behind it. */+ float WatchRepeekShare = 0.f;+ float WatchWeight = 0.f;+};++struct VERSEBOT_API FVerseBotWallbangResult+{+ bool bFound = false;+ FVector FireFrom = FVector::ZeroVector;+ FVector AimPoint = FVector::ZeroVector;+ float DamageFrac = 0.f;+ int32 Pieces = 0;+ float Score = 0.f;+};++struct VERSEBOT_API FVerseBotBreachResult+{+ bool bFound = false;+ uint16 PieceIndex = 0;+ FVector PlantPoint = FVector::ZeroVector;+ FVector WaitPoint = FVector::ZeroVector;+ float Score = 0.f;+};++struct VERSEBOT_API FVerseBotFinisherResult+{+ bool bFound = false;+ FVector Approach = FVector::ZeroVector;+ float PathLengthCm = 0.f;+ float ArrivalS = 0.f;+ float Score = 0.f;+};++/**+ * Resumable state of one time-sliced query (bot.md 2: EQS 0.2 ms amortised). A query evaluates+ * candidates until its cost budget for this tick is spent (at least one candidate per slice) and+ * resumes with the next candidate on the next tick. The generator runs on the context snapshot the+ * brain took when the query started, so candidate order is stable across slices.+ */+struct VERSEBOT_API FVerseBotEqsSlice+{+ /** Cost units of the world calls (TestSight 1, TraceBolt 2, FindPath 6). */+ static constexpr int32 SightCost = 1;+ static constexpr int32 BoltCost = 2;+ static constexpr int32 PathCost = 6;++ int32 BudgetUnits = MAX_int32;+ int32 SpentUnits = 0;+ int32 TotalUnits = 0;+ int32 Next = 0;+ int32 SliceStart = 0;+ int32 Tested = 0;+ int32 Slices = 0;+ float BestScore = -1.0e9f;+ /** Generator value cached on the first slice (BreachSpot: the direct path length). */+ float Scratch = 0.f;+ bool bScratchSet = false;+ bool bDone = false;++ void BeginSlice(int32 Units)+ {+ BudgetUnits = Units;+ SpentUnits = 0;+ SliceStart = Next;+ ++Slices;+ }+ /** True when this slice should stop before candidate Index (never before the first one). */+ bool OutOfBudget(int32 Index) const { return Index > SliceStart && SpentUnits >= BudgetUnits; }+ void Spend(int32 Units)+ {+ SpentUnits += Units;+ TotalUnits += Units;+ }+};++/** Forwards to the real world queries and charges each call to a slice. */+class VERSEBOT_API FVerseBotMeteredWorld final : public IVerseBotWorldQueries+{+public:+ FVerseBotMeteredWorld(IVerseBotWorldQueries& InInner, FVerseBotEqsSlice& InSlice) : Inner(InInner), Slice(InSlice) {}++ virtual bool TestSight(const FVector& Eye, const FVector& Target) override { Slice.Spend(FVerseBotEqsSlice::SightCost); return Inner.TestSight(Eye, Target); }+ virtual FVerseBotBoltTrace TraceBolt(const FVector& Origin, const FVector& Target, const FVerseBotWeaponInfo& Weapon) override+ {+ Slice.Spend(FVerseBotEqsSlice::BoltCost);+ return Inner.TraceBolt(Origin, Target, Weapon);+ }+ virtual FVerseBotPath FindPath(const FVector& From, const FVector& To, bool bCrouch) override { Slice.Spend(FVerseBotEqsSlice::PathCost); return Inner.FindPath(From, To, bCrouch); }+ virtual void GetCoverPoints(const FVector& Center, float RadiusCm, TArray<FVerseBotCoverPoint>& Out) override { Inner.GetCoverPoints(Center, RadiusCm, Out); }+ virtual void GetPieces(const FVector& Center, float RadiusCm, TArray<FVerseBotPieceInfo>& Out) override { Inner.GetPieces(Center, RadiusCm, Out); }+ virtual void GetSpawnPoints(TArray<FVector>& Out) override { Inner.GetSpawnPoints(Out); }+ virtual int32 GetZoneId(const FVector& Location) override { return Inner.GetZoneId(Location); }+ virtual FVerseBotWeaponInfo GetOwnWeapon() override { return Inner.GetOwnWeapon(); }+ virtual bool CanActivateFinisher() override { return Inner.CanActivateFinisher(); }++private:+ IVerseBotWorldQueries& Inner;+ FVerseBotEqsSlice& Slice;+};++namespace VerseBotEqs+{+ /** Eye heights of the cover hidden-filter (6.2): standing 1.65 m, crouched 1.1 m. */+ inline constexpr float StandEyeCm = 165.f;+ inline constexpr float CrouchEyeCm = 110.f;+ inline constexpr float CoverRadiusCm = 2500.f;+ inline constexpr float BreachRadiusCm = 3000.f;+ inline constexpr float FinisherRangeCm = 150.f;+ inline constexpr float FinisherArcDeg = 100.f;+ inline constexpr float BelievedViewHalfAngleDeg = 55.f;+ /** Crouch-walk speed used for the stalk arrival time, cm/s. */+ inline constexpr float CrouchSpeedCmS = 200.f;+ /** Breach charge pawn radius (combat-state 2.3), cm. */+ inline constexpr float BreachSelfDamageRadiusCm = 300.f;+ inline constexpr float BreachFuseS = 2.5f;++ // Contexts+ VERSEBOT_API FVector BeliefTop(const FVerseBotQueryContext& Ctx);+ VERSEBOT_API void BeliefCells(const FVerseBotQueryContext& Ctx, TArray<FVector>& Out);+ /** Unit facing of the believed opponent (yaw only). */+ VERSEBOT_API FVector BeliefFacing(const FVerseBotQueryContext& Ctx);++ /** (1 - w) x base + w x learned. */+ VERSEBOT_API float Blend(float Base, float Learned, float W);++ /** EQS_Cover (6.2). */+ VERSEBOT_API FVerseBotCoverResult Cover(const FVerseBotQueryContext& Ctx, EVerseBotCoverMode Mode);++ /** EQS_PeekCorner (6.2) from a cover point. */+ VERSEBOT_API FVerseBotPeekResult PeekCorner(const FVerseBotQueryContext& Ctx, const FVerseBotCoverPoint& From);++ /** EQS_WallbangSpot (6.2): only spots that pass wall-shot authority (4.5). */+ VERSEBOT_API FVerseBotWallbangResult WallbangSpot(const FVerseBotQueryContext& Ctx);++ /** EQS_BreachSpot (6.2). */+ VERSEBOT_API FVerseBotBreachResult BreachSpot(const FVerseBotQueryContext& Ctx);++ /** EQS_FinisherApproach (6.2). */+ VERSEBOT_API FVerseBotFinisherResult FinisherApproach(const FVerseBotQueryContext& Ctx);++ // Time-sliced forms: run one slice; Slice.bDone says when InOut holds the final result.+ VERSEBOT_API void CoverSlice(const FVerseBotQueryContext& Ctx, EVerseBotCoverMode Mode, FVerseBotEqsSlice& Slice, FVerseBotCoverResult& InOut);+ VERSEBOT_API void PeekCornerSlice(const FVerseBotQueryContext& Ctx, const FVerseBotCoverPoint& From, FVerseBotEqsSlice& Slice, FVerseBotPeekResult& InOut);+ VERSEBOT_API void WallbangSpotSlice(const FVerseBotQueryContext& Ctx, FVerseBotEqsSlice& Slice, FVerseBotWallbangResult& InOut);+ VERSEBOT_API void BreachSpotSlice(const FVerseBotQueryContext& Ctx, FVerseBotEqsSlice& Slice, FVerseBotBreachResult& InOut);+ VERSEBOT_API void FinisherApproachSlice(const FVerseBotQueryContext& Ctx, FVerseBotEqsSlice& Slice, FVerseBotFinisherResult& InOut);++ /** Distance in 2D from Point to the segment A-B, cm. */+ VERSEBOT_API float DistToSegment2D(const FVector& Point, const FVector& A, const FVector& B);++ /** True when no BeliefCells item sees Point at either eye height (the cover hidden filter). */+ VERSEBOT_API bool HiddenFromBelief(const FVerseBotQueryContext& Ctx, const FVector& Point, TConstArrayView<FVector> Cells, bool bLowCover);++ /** Angle in degrees between the believed facing and the direction from BeliefTop to Point. */+ VERSEBOT_API float OffFacingDeg(const FVerseBotQueryContext& Ctx, const FVector& Point);+}diff --git a/unreal/Verse/Source/VerseBot/Public/Learning/VerseBotMatchMemory.h b/unreal/Verse/Source/VerseBot/Public/Learning/VerseBotMatchMemory.hnew file mode 100644index 0000000000..9a74741b5c--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Learning/VerseBotMatchMemory.h@@ -0,0 +1,154 @@+#pragma once++#include "Brain/VerseBotTypes.h"+#include "CoreMinimal.h"+#include "UObject/Object.h"++#include "VerseBotMatchMemory.generated.h"++class UVerseBotTier;++/**+ * What the bot learned about the person in this match (bot.md 7). Inputs are percepts only. Plain+ * native data with no reflection, no serialisation and no network path: it cannot be saved, cooked+ * or replicated (B8, L1). Times are match seconds; positions world cm.+ */+class VERSEBOT_API FVerseBotMatchMemory+{+public:+ /** Engagement range bins of 7.1: 0-5, 5-10, 10-20, 20-35, 35+ m. */+ static constexpr int32 NumRangeBins = 5;+ static int32 RangeBin(float RangeCm);+ /** The lower bound of a range bin, cm. */+ static float RangeBinCentreCm(int32 Bin);++ /** Heatmap layers (7.1). */+ enum class ELayer : uint8 { Position, Shooting };++ /** Tier fields the bounds of 7.3 read. */+ void Configure(const UVerseBotTier& Tier);+ void SetEnabled(bool bInEnabled) { bEnabled = bInEnabled; }+ bool IsEnabled() const { return bEnabled; }++ /** Match end (7.3 Reset): everything learned is dropped. */+ void Reset();+ bool IsEmpty() const;++ // Updates (7.1)+ void RecordSighting(const FVector& Location, float NowS, bool bFirstContact);+ void RecordHeard(const FVector& Location, float NowS);+ void RecordShotFrom(const FVector& Location, float NowS, bool bSeen);+ void RecordPeek(int32 EdgeId, EVerseBotPeekType Type, float NowS);+ /** An engagement decided by a kill or the bot's death. */+ void RecordEngagementEnd(float RangeCm, bool bPersonWon);+ /** An engagement that ended without a decision (contact lost): not part of the win share. */+ void RecordEngagementNoDecision(float RangeCm);+ void RecordZone(int32 ZoneId, float NowS);+ /** Zone entry with the percept position: also keeps the zone's centroid of the person's positions. */+ void RecordZone(int32 ZoneId, const FVector& Location, float NowS);+ void RecordHabit(FName Habit);++ // Reads (7.2, 7.3)+ /** Decayed heat of a 1 m column cell at Location. */+ float Heat(ELayer Layer, const FVector& Location, float NowS) const;+ /** Heat summed over a disc, normalised by the layer total (0..1). */+ float HeatShare(ELayer Layer, const FVector& Location, float RadiusCm, float NowS) const;+ /** Decayed sample count behind a disc (n of 7.3). */+ float SamplesNear(ELayer Layer, const FVector& Location, float RadiusCm, float NowS) const;+ /** w = LearnWeightMax x n / (n + LearnSamplesHalf); 0 when learning is off; never above 0.35. */+ float Weight(float Samples) const;+ /** Probability of a move From -> To among moves out of From (0 when unseen). */+ float ZoneTransitionProb(int32 FromZone, int32 ToZone) const;+ /** The zone most often entered from FromZone, INDEX_NONE when none. */+ int32 MostLikelyNextZone(int32 FromZone) const;+ /** The person's most used zone-to-zone route (from, to), or (INDEX_NONE, INDEX_NONE). */+ TPair<int32, int32> MostUsedRoute() const;+ /** Share of the person's appearances at an edge (0..1) and its sample count. */+ float PeekShare(int32 EdgeId, float& OutSamples) const;+ /** Share of the person's fast re-peeks (< 3 s) at an edge. */+ float RepeekShare(int32 EdgeId) const;+ /** The person's top N peek edges. */+ void TopPeekEdges(int32 N, TArray<int32>& Out) const;+ /** Preferred range shift in bins (-1, 0, 1) toward the bin where the person wins least (7.2). */+ int32 RangeBinShift(float PreferredRangeCm) const;+ int32 HabitCount(FName Habit) const;+ /** Engagements of a range bin without a decision (contact lost). */+ int32 NoDecisionCount(int32 Bin) const { return Ranges[FMath::Clamp(Bin, 0, NumRangeBins - 1)].NoDecision; }+ /** The mean position the person was perceived at inside a zone; false when never seen there. */+ bool ZoneCentroid(int32 ZoneId, FVector& Out) const;+ /**+ * Belief predict bias (7.2): the zone whose centroid is nearest From (within 10 m), the zone the+ * person most often entered from it, that zone's centroid and the transition probability.+ */+ bool PredictNextZone(const FVector& From, FVector& OutTarget, float& OutProb) const;+ /** The most used route as the two zone centroids and its move count (7.2 breach / flank). */+ bool MostUsedRouteSegment(FVector& OutFrom, FVector& OutTo, float& OutSamples) const;+ /** The hottest 1 m cell of a layer and its share of the layer (heatmap prior of 4.2). */+ bool HottestCell(ELayer Layer, float NowS, FVector& OutLocation, float& OutShare) const;+ float HalfLifeS() const { return HabitHalfLifeS; }++private:+ struct FCell+ {+ float Value = 0.f;+ float TimeS = 0.f;+ };+ struct FPeekHabit+ {+ float Appearances = 0.f;+ float FastRepeeks = 0.f;+ float JumpPeeks = 0.f;+ float LeanPeeks = 0.f;+ float LastS = -1.0e6f;+ };+ struct FRangeBin+ {+ int32 Engagements = 0;+ int32 PersonWins = 0;+ int32 NoDecision = 0;+ };+ struct FZoneCentroid+ {+ FVector Sum = FVector::ZeroVector;+ float Count = 0.f;+ };++ static FIntVector CellOf(const FVector& Location);+ float Decay(float DtS) const;+ void AddHeat(ELayer Layer, const FVector& Location, float Amount, float NowS);+ float Decayed(const FCell& Cell, float NowS) const;++ TMap<FIntVector, FCell> Layers[2];+ FCell LayerTotal[2];+ TMap<int32, FPeekHabit> Peeks;+ float PeekTotal = 0.f;+ FRangeBin Ranges[NumRangeBins];+ TMap<int64, float> Routes;+ TMap<int32, float> RouteOut;+ int32 LastZone = INDEX_NONE;+ TMap<FName, int32> Habits;+ TMap<int32, FZoneCentroid> Centroids;++ bool bEnabled = true;+ float LearnWeightMax = 0.1f;+ float LearnSamplesHalf = 12.f;+ float HabitHalfLifeS = 180.f;+};++/**+ * One per bot per match (bot.md 7). Owns the native memory; the object itself carries no+ * reflected state, so nothing of it reaches disk or the bridge. Reset on match end.+ */+UCLASS(Transient)+class VERSEBOT_API UVerseBotMatchMemory : public UObject+{+ GENERATED_BODY()++public:+ FVerseBotMatchMemory& Get() { return Memory; }+ const FVerseBotMatchMemory& Get() const { return Memory; }+ void ResetMatch() { Memory.Reset(); }++private:+ FVerseBotMatchMemory Memory;+};diff --git a/unreal/Verse/Source/VerseBot/Public/Tactics/VerseBotTactics.h b/unreal/Verse/Source/VerseBot/Public/Tactics/VerseBotTactics.hnew file mode 100644index 0000000000..71bd0d6e0c--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Tactics/VerseBotTactics.h@@ -0,0 +1,143 @@+#pragma once++#include "Audit/VerseBotFireAudit.h"+#include "Brain/VerseBotTypes.h"+#include "CoreMinimal.h"+#include "Eqs/VerseBotEqs.h"+#include "VerseRng.h"++// The decision states of bot.md 5.1: utility terms and what each state does per tick. The states+// read belief, own HUD, static arena data and the EQS cache; never truth.++/** The EQS queries the brain schedules (at most 2 in flight, results used on the next decision). */+enum class EVerseBotQuery : uint8+{+ CoverNear,+ CoverFar,+ CoverFlank,+ CoverBulwark,+ PeekCorner,+ WallbangSpot,+ BreachSpot,+ FinisherApproach,+ Count+};++/** Latest result of every query and the decision index it was produced for. */+struct VERSEBOT_API FVerseBotQueryCache+{+ FVerseBotCoverResult Cover[4];+ FVerseBotPeekResult Peek;+ FVerseBotWallbangResult Wallbang;+ FVerseBotBreachResult Breach;+ FVerseBotFinisherResult Finisher;+ int32 ProducedAt[int32(EVerseBotQuery::Count)] = {-1, -1, -1, -1, -1, -1, -1, -1};++ const FVerseBotCoverResult& GetCover(EVerseBotCoverMode Mode) const { return Cover[int32(Mode)]; }+ void Reset() { *this = FVerseBotQueryCache(); }+};++/** Per-life working memory of the states. */+struct VERSEBOT_API FVerseBotTacticsMemory+{+ EVerseBotHoldPhase HoldPhase = EVerseBotHoldPhase::Go;+ float PhaseUntilS = 0.f;+ bool bHasCover = false;+ FVerseBotCoverPoint Cover;+ bool bHasPeek = false;+ FVerseBotPeekResult Peek;+ TArray<int32, TInlineAllocator<3>> RecentPeekEdges;+ int8 StrafeSign = 1;+ float StrafeUntilS = 0.f;+ /** Stalk: when it started; aborted this life. */+ float StalkStartS = -1.f;+ /** Breach: plant pressed, waiting for the detonation. */+ bool bBreachPlanted = false;+ float BreachPlantedS = -1.f;+ uint16 BreachPiece = 0;+ /** Bulwark deployed this life. */+ bool bBulwarkDeployed = false;+ float BulwarkDeployedS = -1.f;+ /** Wallbang burst counter. */+ int32 BurstShots = 0;+ float BurstPauseUntilS = 0.f;+ /** Search: chosen target and when it was chosen. */+ FVector SearchTarget = FVector::ZeroVector;+ bool bHasSearchTarget = false;+ float SearchSweepPhase = 0.f;+ float SearchUntilS = 0.f;+ /** Search: ranked arena points still to check for a path, one per tick (path budget). */+ TArray<FVector, TInlineAllocator<5>> SearchQueue;+ int32 SearchQueueIndex = 0;+ bool bSearchVerifying = false;+ /** Search: when each arena cover point was last visited this life (information gain). */+ TMap<int32, float> Visited;+ /** Flank: chosen point. */+ FVector FlankPoint = FVector::ZeroVector;+ bool bHasFlankPoint = false;+ /** Prefire roll for the current approach (8.4: one roll per approach). */+ bool bPrefireRolled = false;+ bool bPrefireRollDone = false;+ /** The approach the roll belongs to: the peek edge the heard percept is near. */+ int32 PrefireEdge = INDEX_NONE;+ FVector PrefirePoint = FVector::ZeroVector;+ bool bPrefireActive = false;++ void Reset() { *this = FVerseBotTacticsMemory(); }+};++/** Everything a state reads this tick. */+struct VERSEBOT_API FVerseBotTacticsContext+{+ FVerseBotQueryContext Query;+ const FVersePerceptFrame* Frame = nullptr;+ const FVerseBotQueryCache* Cache = nullptr;+ /** The visible, not spawn-protected sighting of this frame, if any. */+ const FVerseSightPercept* Sighting = nullptr;+ /** The newest heard percept of the last 2 s, if any. */+ const FVerseHeardPercept* RecentHeard = nullptr;+ float RecentHeardAgeS = 1.0e6f;+ /** Own health 0..1, own magazine 0..1. */+ float HealthFrac = 1.f;+ float MagazineFrac = 1.f;+ bool bPistolLow = false;+ /** Seconds since the bot last had a sighting; large when none. */+ float SinceSightS = 1.0e6f;+ /** Seconds since the last own hit taken. */+ float SinceHurtS = 1.0e6f;+ /** Bulwark and breach charges and cooldowns from the HUD. */+ bool bBulwarkReady = false;+ bool bBreachReady = false;+ /** The bot is unseen as far as it can tell: no hurt in 1.5 s and in cover. */+ bool bInCover = false;+ /** Wall-shot authority holds for the cached wallbang spot. */+ bool bWallbangAuthorised = false;+ FVerseBotFireEvidence WallbangEvidence;+};++namespace VerseBotTactics+{+ /** Utility per state (5.1); negative means the state cannot run. */+ VERSEBOT_API void Utilities(const FVerseBotTacticsContext& Ctx, float (&Out)[VerseBot::NumStates]);++ /** Called when the selector switches to State. */+ VERSEBOT_API void Enter(EVerseBotState State, const FVerseBotTacticsContext& Ctx, FVerseBotTacticsMemory& Mem, FVerseRng& Rng);++ /** One tick of State. */+ VERSEBOT_API FVerseBotIntent Tick(EVerseBotState State, const FVerseBotTacticsContext& Ctx, FVerseBotTacticsMemory& Mem, FVerseRng& Rng);++ /** Which queries the states want refreshed, in priority order. */+ VERSEBOT_API void WantedQueries(EVerseBotState Current, const FVerseBotTacticsContext& Ctx, TArray<EVerseBotQuery, TInlineAllocator<8>>& Out);++ /** Hold substate times (5.2): hide U(0.5, 1.1) s, peek U(0.7, 1.5) s. */+ inline constexpr float HideMinS = 0.5f, HideMaxS = 1.1f, PeekMinS = 0.7f, PeekMaxS = 1.5f;++ /**+ * Learned peek habit (7.2) on a peek result: the person re-peeks the watched edge fast, so the+ * bot holds the pre-aimed angle longer. 1 without a watched edge; at most 1 + 2 x 0.35.+ */+ VERSEBOT_API float PeekHoldScale(const FVerseBotPeekResult& Peek);++ /** The tier's preferred engagement distance after the learned bin shift (7.2), cm. Memory may be null. */+ VERSEBOT_API float PreferredBandCm(const UVerseBotTier& Tier, const FVerseBotMatchMemory* Memory);+}