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 perception service and belief map (#1170)
Ruben Lütkeed50b18ea1ab
diff --git a/unreal/Verse/Source/VerseBot/Private/Belief/VerseBeliefDebugDraw.cpp b/unreal/Verse/Source/VerseBot/Private/Belief/VerseBeliefDebugDraw.cppnew file mode 100644index 0000000000..27691fd6b2--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Belief/VerseBeliefDebugDraw.cpp@@ -0,0 +1,166 @@+#include "Belief/VerseBeliefDebugDraw.h"++#include "DrawDebugHelpers.h"+#include "Engine/World.h"+#include "ImageUtils.h"+#include "Misc/FileHelper.h"+#include "Misc/Paths.h"+#include "HAL/FileManager.h"++namespace+{+ float MaxMass(const FVerseBeliefGrid& Grid)+ {+ float Max = 0.f;+ for (int32 Cell = 0; Cell < Grid.NumCells(); ++Cell)+ {+ Max = FMath::Max(Max, Grid.GetMass(Cell));+ }+ return Max;+ }++ void Put(TArray<FColor>& Pixels, int32 Width, int32 Height, int32 X, int32 Y, const FColor& Color)+ {+ if (X >= 0 && Y >= 0 && X < Width && Y < Height)+ {+ Pixels[Y * Width + X] = Color;+ }+ }+}++FColor FVerseBeliefDebugDraw::HeatColor(float Relative)+{+ const float T = FMath::Clamp(Relative, 0.f, 1.f);+ // Steel (40, 42, 46) -> amber (232, 150, 40) -> red (210, 40, 30).+ const FLinearColor Steel(40.f / 255.f, 42.f / 255.f, 46.f / 255.f);+ const FLinearColor Amber(232.f / 255.f, 150.f / 255.f, 40.f / 255.f);+ const FLinearColor Red(210.f / 255.f, 40.f / 255.f, 30.f / 255.f);+ const FLinearColor Color = T < 0.5f ? FMath::Lerp(Steel, Amber, T * 2.f) : FMath::Lerp(Amber, Red, (T - 0.5f) * 2.f);+ return Color.ToFColor(false);+}++void FVerseBeliefDebugDraw::DrawWorld(const UWorld* World, const FVerseBeliefGrid& Grid, const FVerseBeliefDerived& Derived,+ float LifetimeS, float MinRelative)+{+#if ENABLE_DRAW_DEBUG+ if (!World)+ {+ return;+ }+ const float Max = MaxMass(Grid);+ if (Max <= 0.f)+ {+ return;+ }+ const float Half = 0.45f * Grid.GetCellSizeCm();+ for (int32 Cell = 0; Cell < Grid.NumCells(); ++Cell)+ {+ if (!Grid.IsActive(Cell))+ {+ continue;+ }+ const float Relative = Grid.GetMass(Cell) / Max;+ if (Relative < MinRelative)+ {+ continue;+ }+ const FVector Centre = Grid.GetCellCentre(Cell) + FVector(0.0, 0.0, 5.0);+ DrawDebugSolidBox(World, Centre, FVector(Half, Half, 2.0 + 30.0 * Relative), HeatColor(Relative).WithAlpha(160), false, LifetimeS);+ }+ if (Derived.TopCluster.CentreCell != INDEX_NONE)+ {+ DrawDebugCircle(World, Derived.TopCluster.Centre + FVector(0.0, 0.0, 10.0), Grid.GetTuning().ClusterRadiusCm, 48,+ FColor(212, 175, 55), false, LifetimeS, 0, 4.f, FVector(1, 0, 0), FVector(0, 1, 0), false);+ }+#endif+}++void FVerseBeliefDebugDraw::RenderTopDown(const FVerseBeliefGrid& Grid, const FVerseBeliefDerived& Derived, EVerseArenaLevel Level,+ int32 PixelsPerCell, TArray<FColor>& OutPixels, int32& OutWidth, int32& OutHeight, TConstArrayView<FVector> Marks)+{+ const int32 Scale = FMath::Max(1, PixelsPerCell);+ FIntPoint Min(TNumericLimits<int32>::Max(), TNumericLimits<int32>::Max());+ FIntPoint Max(TNumericLimits<int32>::Lowest(), TNumericLimits<int32>::Lowest());+ for (int32 Cell = 0; Cell < Grid.NumCells(); ++Cell)+ {+ const FIntPoint Column = Grid.GetCell(Cell).Column;+ Min.X = FMath::Min(Min.X, Column.X);+ Min.Y = FMath::Min(Min.Y, Column.Y);+ Max.X = FMath::Max(Max.X, Column.X);+ Max.Y = FMath::Max(Max.Y, Column.Y);+ }+ if (Grid.NumCells() == 0)+ {+ OutWidth = OutHeight = 0;+ OutPixels.Reset();+ return;+ }+ const int32 Columns = Max.X - Min.X + 1;+ const int32 Rows = Max.Y - Min.Y + 1;+ OutWidth = Columns * Scale;+ OutHeight = Rows * Scale;+ OutPixels.Init(FColor(8, 8, 9), OutWidth * OutHeight);+ const float MaxP = FMath::Max(MaxMass(Grid), 1e-12f);+ for (int32 Cell = 0; Cell < Grid.NumCells(); ++Cell)+ {+ const FVerseBeliefCellDesc& Desc = Grid.GetCell(Cell);+ if (Desc.Level != Level)+ {+ continue;+ }+ const FColor Color = Grid.IsActive(Cell) ? HeatColor(FMath::Sqrt(Grid.GetMass(Cell) / MaxP)) : FColor(20, 20, 22);+ const int32 Px = (Desc.Column.X - Min.X) * Scale;+ const int32 Py = (Max.Y - Desc.Column.Y) * Scale;+ for (int32 Dy = 0; Dy < Scale - (Scale > 3 ? 1 : 0); ++Dy)+ {+ for (int32 Dx = 0; Dx < Scale - (Scale > 3 ? 1 : 0); ++Dx)+ {+ Put(OutPixels, OutWidth, OutHeight, Px + Dx, Py + Dy, Color);+ }+ }+ }+ auto ToPixel = [&](const FVector& World) {+ const double Fx = (World.X - Grid.GetCellCentre(0).X) / Grid.GetCellSizeCm() + Grid.GetCell(0).Column.X;+ const double Fy = (World.Y - Grid.GetCellCentre(0).Y) / Grid.GetCellSizeCm() + Grid.GetCell(0).Column.Y;+ return FVector2D((Fx - Min.X + 0.5) * Scale, (Max.Y - Fy + 0.5) * Scale);+ };+ if (Derived.TopCluster.CentreCell != INDEX_NONE && Derived.TopCluster.Level == Level)+ {+ const FVector2D Centre = ToPixel(Derived.TopCluster.Centre);+ const double Radius = Grid.GetTuning().ClusterRadiusCm / Grid.GetCellSizeCm() * Scale;+ for (int32 Step = 0; Step < 720; ++Step)+ {+ const double A = Step * UE_DOUBLE_PI / 360.0;+ Put(OutPixels, OutWidth, OutHeight, FMath::RoundToInt(Centre.X + Radius * FMath::Cos(A)),+ FMath::RoundToInt(Centre.Y + Radius * FMath::Sin(A)), FColor(212, 175, 55));+ }+ }+ for (const FVector& Mark : Marks)+ {+ const FVector2D Pixel = ToPixel(Mark);+ const int32 Cx = FMath::RoundToInt(Pixel.X);+ const int32 Cy = FMath::RoundToInt(Pixel.Y);+ for (int32 D = -Scale; D <= Scale; ++D)+ {+ Put(OutPixels, OutWidth, OutHeight, Cx + D, Cy + D, FColor::White);+ Put(OutPixels, OutWidth, OutHeight, Cx + D, Cy - D, FColor::White);+ }+ }+}++bool FVerseBeliefDebugDraw::SavePng(const FString& Path, const FVerseBeliefGrid& Grid, const FVerseBeliefDerived& Derived,+ EVerseArenaLevel Level, int32 PixelsPerCell, TConstArrayView<FVector> Marks)+{+ TArray<FColor> Pixels;+ int32 Width = 0;+ int32 Height = 0;+ RenderTopDown(Grid, Derived, Level, PixelsPerCell, Pixels, Width, Height, Marks);+ if (Width == 0 || Height == 0)+ {+ return false;+ }+ TArray64<uint8> Png;+ FImageUtils::PNGCompressImageArray(Width, Height, TArrayView64<const FColor>(Pixels.GetData(), Pixels.Num()), Png);+ IFileManager::Get().MakeDirectory(*FPaths::GetPath(Path), true);+ return FFileHelper::SaveArrayToFile(TArrayView64<const uint8>(Png.GetData(), Png.Num()), *Path);+}diff --git a/unreal/Verse/Source/VerseBot/Private/Belief/VerseBeliefGrid.cpp b/unreal/Verse/Source/VerseBot/Private/Belief/VerseBeliefGrid.cppnew file mode 100644index 0000000000..1f92b989d8--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Belief/VerseBeliefGrid.cpp@@ -0,0 +1,1242 @@+#include "Belief/VerseBeliefGrid.h"++#include "Algo/Reverse.h"+#include "Math/VectorRegister.h"+#include "Misc/Crc.h"++namespace+{+ constexpr int32 LevelCount = 3;++ const FIntPoint EightOffsets[8] = {+ {1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}};++ bool GateOpen(EVerseBeliefGate Gate, int32 Piece, TFunctionRef<bool(int32)> IsOpen, TFunctionRef<bool(int32)> IsStanding)+ {+ switch (Gate)+ {+ case EVerseBeliefGate::WhenOpen:+ return Piece != INDEX_NONE && IsOpen(Piece);+ case EVerseBeliefGate::WhenStanding:+ return Piece == INDEX_NONE || IsStanding(Piece);+ default:+ return true;+ }+ }++ float FastPowCos(float Cos, float Exponent)+ {+ if (Cos <= 0.f)+ {+ return 0.f;+ }+ if (Exponent == 4.f)+ {+ const float Sq = Cos * Cos;+ return Sq * Sq;+ }+ return FMath::Pow(Cos, Exponent);+ }+}++void FVerseBeliefGrid::Build(const FVerseBeliefGridSource& Source, const FVerseBeliefTuning& InTuning)+{+ Tuning = InTuning;+ Origin = Source.Origin;+ CellSizeCm = FMath::Max(1.f, Source.CellSizeCm);++ Cells.Reset();+ TArray<int32> SourceToCell;+ SourceToCell.Init(INDEX_NONE, Source.Cells.Num());+ TArray<int32> CellToSource;++ FIntPoint Min(TNumericLimits<int32>::Max(), TNumericLimits<int32>::Max());+ FIntPoint Max(TNumericLimits<int32>::Lowest(), TNumericLimits<int32>::Lowest());+ for (const FVerseBeliefCellDesc& Desc : Source.Cells)+ {+ Min.X = FMath::Min(Min.X, Desc.Column.X);+ Min.Y = FMath::Min(Min.Y, Desc.Column.Y);+ Max.X = FMath::Max(Max.X, Desc.Column.X);+ Max.Y = FMath::Max(Max.Y, Desc.Column.Y);+ }+ if (Source.Cells.Num() == 0)+ {+ Min = Max = FIntPoint::ZeroValue;+ }+ MinColumn = Min;+ ColumnSpan = FIntPoint(Max.X - Min.X + 1, Max.Y - Min.Y + 1);+ ColumnLookup.Init(INDEX_NONE, ColumnSpan.X * ColumnSpan.Y * LevelCount);++ for (int32 SourceIndex = 0; SourceIndex < Source.Cells.Num(); ++SourceIndex)+ {+ const FVerseBeliefCellDesc& Desc = Source.Cells[SourceIndex];+ const int32 Key = Level3(Desc.Column, Desc.Level);+ if (Key == INDEX_NONE || ColumnLookup[Key] != INDEX_NONE)+ {+ continue;+ }+ ColumnLookup[Key] = Cells.Num();+ SourceToCell[SourceIndex] = Cells.Num();+ CellToSource.Add(SourceIndex);+ Cells.Add(Desc);+ }++ const int32 Num = Cells.Num();+ Centres.SetNumUninitialized(Num);+ for (int32 Cell = 0; Cell < Num; ++Cell)+ {+ const FVerseBeliefCellDesc& Desc = Cells[Cell];+ Centres[Cell] = FVector(Origin.X + double(Desc.Column.X) * CellSizeCm, Origin.Y + double(Desc.Column.Y) * CellSizeCm, Desc.FloorZ);+ }+ FBox CentreBox(ForceInit);+ for (int32 Cell = 0; Cell < Num; ++Cell)+ {+ CentreBox += Centres[Cell];+ }+ MomentOrigin = Num > 0 ? CentreBox.GetCenter() : FVector::ZeroVector;+ CellMoment.SetNumUninitialized(4 * Num);+ for (int32 Cell = 0; Cell < Num; ++Cell)+ {+ const FVector C = (Centres[Cell] - MomentOrigin) / 100.0;+ CellMoment[4 * Cell + 0] = float(C.X);+ CellMoment[4 * Cell + 1] = float(C.Y);+ CellMoment[4 * Cell + 2] = float(C.Z);+ CellMoment[4 * Cell + 3] = float(C.X * C.X + C.Y * C.Y + C.Z * C.Z);+ }+ TArray<TArray<FNeighbour>> PerCell;+ PerCell.SetNum(Num);+ for (int32 SourceIndex = 0; SourceIndex < Source.Cells.Num(); ++SourceIndex)+ {+ const int32 Cell = SourceToCell[SourceIndex];+ if (Cell == INDEX_NONE)+ {+ continue;+ }+ const FVerseBeliefCellDesc& Desc = Cells[Cell];+ for (int32 DirIndex = 0; DirIndex < 8; ++DirIndex)+ {+ const FIntPoint& Offset = EightOffsets[DirIndex];+ const int32 Key = Level3(Desc.Column + Offset, Desc.Level);+ const int32 Other = Key == INDEX_NONE ? INDEX_NONE : ColumnLookup[Key];+ if (Other == INDEX_NONE)+ {+ continue;+ }+ if (Source.AreNeighboursConnected)+ {+ if (!Source.AreNeighboursConnected(SourceIndex, CellToSource[Other]))+ {+ continue;+ }+ }+ const float DistCm = CellSizeCm * FMath::Sqrt(float(Offset.X * Offset.X + Offset.Y * Offset.Y));+ FNeighbour& Edge = PerCell[Cell].AddDefaulted_GetRef();+ Edge.Cell = Other;+ Edge.Rate = Tuning.TypicalSpeedCmS / DistCm;+ Edge.Dir = FVector2f(float(Offset.X), float(Offset.Y)).GetSafeNormal();+ Edge.DirIndex = uint8(DirIndex);+ }+ }+ for (const FVerseBeliefLinkDesc& Link : Source.Links)+ {+ const int32 A = Source.Cells.IsValidIndex(Link.From) ? SourceToCell[Link.From] : INDEX_NONE;+ const int32 B = Source.Cells.IsValidIndex(Link.To) ? SourceToCell[Link.To] : INDEX_NONE;+ if (A == INDEX_NONE || B == INDEX_NONE || A == B)+ {+ continue;+ }+ const FVector Delta = GetCellCentre(B) - GetCellCentre(A);+ const FVector2f Horizontal = FVector2f(float(Delta.X), float(Delta.Y));+ const float Rate = 1.f / FMath::Max(0.05f, Link.TraversalS);+ auto Add = [&](int32 From, int32 To, const FVector2f& Dir) {+ FNeighbour& Edge = PerCell[From].AddDefaulted_GetRef();+ Edge.Cell = To;+ Edge.Rate = Rate;+ Edge.Dir = Horizontal.SizeSquared() > 1.f ? Dir : FVector2f::ZeroVector;+ Edge.Gate = Link.Gate;+ Edge.GatePiece = Link.GatePiece;+ };+ Add(A, B, Horizontal.GetSafeNormal());+ if (Link.bBidirectional)+ {+ Add(B, A, -Horizontal.GetSafeNormal());+ }+ }++ NeighbourStart.SetNumUninitialized(Num + 1);+ Neighbours.Reset();+ for (int32 Cell = 0; Cell < Num; ++Cell)+ {+ NeighbourStart[Cell] = Neighbours.Num();+ Neighbours.Append(PerCell[Cell]);+ }+ NeighbourStart[Num] = Neighbours.Num();++ DiscOffsets.Reset();+ const int32 Reach = FMath::CeilToInt(Tuning.ClusterRadiusCm / CellSizeCm);+ DiscHalfWidth.Init(-1, 2 * Reach + 1);+ for (int32 Dx = -Reach; Dx <= Reach; ++Dx)+ {+ for (int32 Dy = -Reach; Dy <= Reach; ++Dy)+ {+ if (FMath::Square(float(Dx) * CellSizeCm) + FMath::Square(float(Dy) * CellSizeCm) <=+ FMath::Square(Tuning.ClusterRadiusCm) + 1.f)+ {+ DiscOffsets.Add(FIntPoint(Dx, Dy));+ DiscHalfWidth[Dy + Reach] = FMath::Max(DiscHalfWidth[Dy + Reach], FMath::Abs(Dx));+ }+ }+ }+ // Padded disc layout: Reach zero columns and rows around every level, so no disc reaches past it.+ DiscPadWidth = ColumnSpan.X + 2 * Reach;+ const int32 DiscPadHeight = ColumnSpan.Y + 2 * Reach;+ DiscPadSize = Num > 0 ? LevelCount * DiscPadWidth * DiscPadHeight : 0;+ CellDiscPad.SetNumUninitialized(Num);+ DiscPadCell.Init(INDEX_NONE, DiscPadSize);+ for (int32 Cell = 0; Cell < Num; ++Cell)+ {+ const FVerseBeliefCellDesc& Desc = Cells[Cell];+ const int32 Index = (int32(Desc.Level) * DiscPadHeight + (Desc.Column.Y - MinColumn.Y + Reach)) * DiscPadWidth ++ (Desc.Column.X - MinColumn.X + Reach);+ CellDiscPad[Cell] = Index;+ DiscPadCell[Index] = Cell;+ }+ DiscPadMass.Init(0.f, DiscPadSize);+ DiscPadSum.Init(0.f, DiscPadSize);+ DiscPadMask.Init(0.f, DiscPadSize);+ for (TArray<float>& Rows : DiscPadRows)+ {+ Rows.Init(0.f, DiscPadSize);+ }++ bCellActive.Init(1, Num);+ RateSum.Init(0.f, Num);+ P.Init(0.f, Num);+ Scratch.Init(0.f, Num);+ Prior.Reset();+ LastClearedS.Init(-1.f, Num);+ LastSupportS.Init(-1.f, Num);+ LastSupportKind.Init(EVerseBeliefSupport::None, Num);+ bMomentum = false;+ bOpponentDead = false;++ // The match starts with every piece intact (destruction full reset).+ ApplyGates([](int32) { return false; }, [](int32) { return true; });+ ResetUniform();+}++int32 FVerseBeliefGrid::Level3(const FIntPoint& Column, EVerseArenaLevel Level) const+{+ const FIntPoint Local = Column - MinColumn;+ if (Local.X < 0 || Local.Y < 0 || Local.X >= ColumnSpan.X || Local.Y >= ColumnSpan.Y)+ {+ return INDEX_NONE;+ }+ return (int32(Level) * ColumnSpan.Y + Local.Y) * ColumnSpan.X + Local.X;+}++FIntPoint FVerseBeliefGrid::ColumnOf(const FVector& WorldLocation) const+{+ return FIntPoint(FMath::RoundToInt((WorldLocation.X - Origin.X) / CellSizeCm),+ FMath::RoundToInt((WorldLocation.Y - Origin.Y) / CellSizeCm));+}++int32 FVerseBeliefGrid::FindCell(const FIntPoint& Column, EVerseArenaLevel Level) const+{+ const int32 Key = Level3(Column, Level);+ const int32 Cell = Key == INDEX_NONE ? INDEX_NONE : ColumnLookup[Key];+ return Cell != INDEX_NONE && bCellActive[Cell] ? Cell : INDEX_NONE;+}++int32 FVerseBeliefGrid::FindCellAnyState(const FIntPoint& Column, EVerseArenaLevel Level) const+{+ const int32 Key = Level3(Column, Level);+ return Key == INDEX_NONE ? INDEX_NONE : ColumnLookup[Key];+}++void FVerseBeliefGrid::RecomputeRateSums()+{+ // Dense, padded per-level layout for the predict stencil: one weight array per adjacency+ // direction (0 where the edge does not exist or is inactive), plus a short list of links.+ const int32 Num = Cells.Num();+ const int32 PadX = ColumnSpan.X + 2;+ const int32 PadY = ColumnSpan.Y + 2;+ DenseSize = 3 * PadX * PadY;+ CellDense.SetNumUninitialized(Num);+ for (int32 Cell = 0; Cell < Num; ++Cell)+ {+ const FVerseBeliefCellDesc& Desc = Cells[Cell];+ CellDense[Cell] = (int32(Desc.Level) * PadY + (Desc.Column.Y - MinColumn.Y + 1)) * PadX + (Desc.Column.X - MinColumn.X + 1);+ }+ for (int32 DirIndex = 0; DirIndex < 8; ++DirIndex)+ {+ DirOffset[DirIndex] = EightOffsets[DirIndex].Y * PadX + EightOffsets[DirIndex].X;+ DenseRateBias[DirIndex].Init(0.f, DenseSize);+ DenseRate[DirIndex].Init(0.f, DenseSize);+ }+ LinkFrom.Reset();+ LinkTo.Reset();+ LinkRateBias.Reset();+ LinkRate.Reset();+ LinkDirs.Reset();+ for (int32 Cell = 0; Cell < Num; ++Cell)+ {+ float Sum = 0.f;+ for (int32 Edge = NeighbourStart[Cell]; Edge < NeighbourStart[Cell + 1]; ++Edge)+ {+ const FNeighbour& Neighbour = Neighbours[Edge];+ if (!Neighbour.bActive)+ {+ continue;+ }+ Sum += Neighbour.Rate * Neighbour.Bias;+ if (Neighbour.DirIndex < 8)+ {+ DenseRateBias[Neighbour.DirIndex][CellDense[Cell]] = Neighbour.Rate * Neighbour.Bias;+ DenseRate[Neighbour.DirIndex][CellDense[Cell]] = Neighbour.Rate;+ }+ else+ {+ LinkFrom.Add(Cell);+ LinkTo.Add(Neighbour.Cell);+ LinkRateBias.Add(Neighbour.Rate * Neighbour.Bias);+ LinkRate.Add(Neighbour.Rate);+ LinkDirs.Add(Neighbour.Dir);+ }+ }+ RateSum[Cell] = Sum;+ }+ DenseOut.Init(0.f, DenseSize);+ DenseDiffuse.Init(0.f, DenseSize);+ DenseAdvect.Init(0.f, DenseSize);+ bMomentumWeightsValid = false;+ ActiveMaskF.SetNumUninitialized(Num);+ ActiveCount = 0;+ for (int32 Cell = 0; Cell < Num; ++Cell)+ {+ DiscPadMask[CellDiscPad[Cell]] = bCellActive[Cell] ? 1.f : 0.f;+ ActiveMaskF[Cell] = bCellActive[Cell] ? 1.f : 0.f;+ ActiveCount += bCellActive[Cell] ? 1 : 0;+ }+}++int32 FVerseBeliefGrid::FindCell(const FVector& WorldLocation) const+{+ // The floor under the point: the highest cell of the column at most 60 cm above it.+ const FIntPoint Column = ColumnOf(WorldLocation);+ int32 Best = INDEX_NONE;+ float BestZ = TNumericLimits<float>::Lowest();+ for (int32 Level = 0; Level < LevelCount; ++Level)+ {+ const int32 Cell = FindCell(Column, EVerseArenaLevel(Level));+ if (Cell != INDEX_NONE && Cells[Cell].FloorZ <= WorldLocation.Z + 60.f && Cells[Cell].FloorZ > BestZ)+ {+ Best = Cell;+ BestZ = Cells[Cell].FloorZ;+ }+ }+ if (Best != INDEX_NONE)+ {+ return Best;+ }+ double BestDist = TNumericLimits<double>::Max();+ for (int32 Cell = 0; Cell < Cells.Num(); ++Cell)+ {+ if (!bCellActive[Cell])+ {+ continue;+ }+ const double Dist = FVector::DistSquared(GetCellCentre(Cell), WorldLocation);+ if (Dist < BestDist)+ {+ BestDist = Dist;+ Best = Cell;+ }+ }+ return Best;+}++int32 FVerseBeliefGrid::NumNeighbours(int32 Cell) const+{+ int32 Count = 0;+ for (int32 Edge = NeighbourStart[Cell]; Edge < NeighbourStart[Cell + 1]; ++Edge)+ {+ Count += Neighbours[Edge].bActive ? 1 : 0;+ }+ return Count;+}++void FVerseBeliefGrid::GetNeighbours(int32 Cell, TArray<int32>& Out) const+{+ Out.Reset();+ for (int32 Edge = NeighbourStart[Cell]; Edge < NeighbourStart[Cell + 1]; ++Edge)+ {+ if (Neighbours[Edge].bActive)+ {+ Out.Add(Neighbours[Edge].Cell);+ }+ }+}++bool FVerseBeliefGrid::ApplyGates(TFunctionRef<bool(int32 Piece)> IsOpen, TFunctionRef<bool(int32 Piece)> IsStanding)+{+ bool bChanged = false;+ bool bDropped = false;+ for (int32 Cell = 0; Cell < Cells.Num(); ++Cell)+ {+ const FVerseBeliefCellDesc& Desc = Cells[Cell];+ if (Desc.Gate == EVerseBeliefGate::Always)+ {+ continue;+ }+ const uint8 Active = GateOpen(Desc.Gate, Desc.GatePiece, IsOpen, IsStanding) ? 1 : 0;+ if (Active != bCellActive[Cell])+ {+ bCellActive[Cell] = Active;+ bChanged = true;+ if (!Active && P.IsValidIndex(Cell) && P[Cell] > 0.f)+ {+ P[Cell] = 0.f;+ bDropped = true;+ }+ }+ }+ for (int32 Cell = 0; Cell < Cells.Num(); ++Cell)+ {+ for (int32 Edge = NeighbourStart[Cell]; Edge < NeighbourStart[Cell + 1]; ++Edge)+ {+ FNeighbour& Neighbour = Neighbours[Edge];+ const bool bActive = bCellActive[Cell] && bCellActive[Neighbour.Cell] &&+ GateOpen(Neighbour.Gate, Neighbour.GatePiece, IsOpen, IsStanding);+ bChanged |= bActive != Neighbour.bActive;+ Neighbour.bActive = bActive;+ }+ }+ RecomputeRateSums();+ if (bDropped)+ {+ Normalise();+ }+ return bChanged;+}++void FVerseBeliefGrid::ResetUniform()+{+ bOpponentDead = false;+ int32 Active = 0;+ for (int32 Cell = 0; Cell < Cells.Num(); ++Cell)+ {+ Active += bCellActive[Cell];+ }+ const float Mass = Active > 0 ? float(1.0 / double(Active)) : 0.f;+ for (int32 Cell = 0; Cell < Cells.Num(); ++Cell)+ {+ P[Cell] = bCellActive[Cell] ? Mass : 0.f;+ }+}++void FVerseBeliefGrid::SetPositionPrior(TConstArrayView<float> PerCell)+{+ Prior.Reset();+ if (PerCell.Num() == Cells.Num())+ {+ Prior.Append(PerCell.GetData(), PerCell.Num());+ }+}++void FVerseBeliefGrid::SetZoneTransitionPrior(int32 Zones, TConstArrayView<float> Matrix)+{+ const bool bValid = Zones > 0 && Matrix.Num() == Zones * Zones;+ for (int32 Cell = 0; Cell < Cells.Num(); ++Cell)+ {+ for (int32 Edge = NeighbourStart[Cell]; Edge < NeighbourStart[Cell + 1]; ++Edge)+ {+ FNeighbour& Neighbour = Neighbours[Edge];+ const int32 From = Cells[Cell].Zone;+ const int32 To = Cells[Neighbour.Cell].Zone;+ Neighbour.Bias = 1.f;+ if (bValid && From < Zones && To < Zones)+ {+ Neighbour.Bias = 1.f + Tuning.ZoneBiasGain * FMath::Clamp(Matrix[From * Zones + To], 0.f, 1.f);+ }+ }+ }+ RecomputeRateSums();+}++void FVerseBeliefGrid::SetMomentum(const FVector& Velocity, float AtS)+{+ MomentumVelocity = FVector2f(float(Velocity.X), float(Velocity.Y));+ MomentumAtS = AtS;+ bMomentum = MomentumVelocity.SizeSquared() > 1.f;+}++void FVerseBeliefGrid::ClearMomentum()+{+ bMomentum = false;+}++void FVerseBeliefGrid::RefreshMomentumWeights(const FVector2f& Dir)+{+ // The momentum split depends only on the direction and the edges: computed once per sighting+ // direction, not per step. Weight per edge: cos^Exponent x rate, normalised per source cell.+ bMomentumWeightsValid = true;+ MomentumWeightsDir = Dir;+ const int32 Size = DenseSize;+ TArray<float> Sum;+ Sum.Init(0.f, Size);+ for (int32 DirIndex = 0; DirIndex < 8; ++DirIndex)+ {+ const FVector2f Axis = FVector2f(float(EightOffsets[DirIndex].X), float(EightOffsets[DirIndex].Y)).GetSafeNormal();+ const float C = FastPowCos(FVector2f::DotProduct(Axis, Dir), Tuning.MomentumExponent);+ MomentumCos[DirIndex] = C;+ if (C <= 0.f)+ {+ continue;+ }+ const float* Rate = DenseRate[DirIndex].GetData();+ for (int32 Index = 0; Index < Size; ++Index)+ {+ Sum[Index] += C * Rate[Index];+ }+ }+ const int32 Links = LinkFrom.Num();+ TArray<float> LinkCos;+ LinkCos.SetNumUninitialized(Links);+ for (int32 Link = 0; Link < Links; ++Link)+ {+ LinkCos[Link] = FastPowCos(FVector2f::DotProduct(LinkDirs[Link], Dir), Tuning.MomentumExponent);+ Sum[CellDense[LinkFrom[Link]]] += LinkCos[Link] * LinkRate[Link];+ }+ DenseHasAdvect.SetNumUninitialized(Size);+ for (int32 Index = 0; Index < Size; ++Index)+ {+ DenseHasAdvect[Index] = Sum[Index] > 0.f ? 1 : 0;+ Sum[Index] = Sum[Index] > 0.f ? 1.f / Sum[Index] : 0.f;+ }+ for (int32 DirIndex = 0; DirIndex < 8; ++DirIndex)+ {+ const float C = MomentumCos[DirIndex];+ if (C <= 0.f)+ {+ DenseAdvectWeight[DirIndex].Reset();+ continue;+ }+ DenseAdvectWeight[DirIndex].SetNumUninitialized(Size);+ const float* Rate = DenseRate[DirIndex].GetData();+ float* Weight = DenseAdvectWeight[DirIndex].GetData();+ for (int32 Index = 0; Index < Size; ++Index)+ {+ Weight[Index] = C * Rate[Index] * Sum[Index];+ }+ }+ LinkAdvectWeight.SetNumUninitialized(Links);+ for (int32 Link = 0; Link < Links; ++Link)+ {+ LinkAdvectWeight[Link] = LinkCos[Link] * LinkRate[Link] * Sum[CellDense[LinkFrom[Link]]];+ }+}++void FVerseBeliefGrid::Predict(float DeltaS, float NowS)+{+ if (bOpponentDead || DeltaS <= 0.f)+ {+ return;+ }+ float MomentumCellFraction = 0.f;+ FVector2f MomentumDir = FVector2f::ZeroVector;+ const float MomentumAge = FMath::Max(0.f, NowS - MomentumAtS);+ if (bMomentum && MomentumAge <= Tuning.MomentumMaxAgeS)+ {+ const float Speed = MomentumVelocity.Size() * FMath::Exp(-MomentumAge / FMath::Max(0.01f, Tuning.MomentumDecayS));+ MomentumCellFraction = FMath::Min(Tuning.MomentumMaxFraction, Speed * DeltaS / CellSizeCm);+ MomentumDir = MomentumVelocity.GetSafeNormal();+ }+ const bool bAdvect = MomentumCellFraction > 0.f;+ if (bAdvect && (!bMomentumWeightsValid || MomentumDir != MomentumWeightsDir))+ {+ RefreshMomentumWeights(MomentumDir);+ }++ const int32 Num = Cells.Num();+ const int32 Size = DenseSize;+ float* Out = DenseOut.GetData();+ float* Diffuse = DenseDiffuse.GetData();+ float* Advect = DenseAdvect.GetData();+ FMemory::Memzero(Out, sizeof(float) * Size);+ FMemory::Memzero(Diffuse, sizeof(float) * Size);+ if (bAdvect)+ {+ FMemory::Memzero(Advect, sizeof(float) * Size);+ }++ // Per cell: what stays, the diffusion scale and the advected mass.+ const float MaxDiffusion = Tuning.MaxDiffusionFraction;+ const uint8* HasAdvect = bAdvect ? DenseHasAdvect.GetData() : nullptr;+ for (int32 Cell = 0; Cell < Num; ++Cell)+ {+ const float M = P[Cell];+ if (M <= 0.f)+ {+ continue;+ }+ const int32 Dense = CellDense[Cell];+ const float SumW = RateSum[Cell] * DeltaS;+ if (SumW <= 0.f)+ {+ Out[Dense] += M;+ continue;+ }+ const float DiffusionScale = FMath::Min(1.f, MaxDiffusion / SumW);+ float Kept = M * (1.f - SumW * DiffusionScale);+ Diffuse[Dense] = M * DeltaS * DiffusionScale;+ if (HasAdvect && HasAdvect[Dense])+ {+ const float Moved = M * MomentumCellFraction;+ Kept -= Moved;+ Advect[Dense] = Moved;+ }+ Out[Dense] += Kept;+ }++ // The stencil: each direction is one contiguous pass (padding keeps every target in range).+ for (int32 DirIndex = 0; DirIndex < 8; ++DirIndex)+ {+ const int32 Offset = DirOffset[DirIndex];+ const float* RateBias = DenseRateBias[DirIndex].GetData();+ const int32 Begin = FMath::Max(0, -Offset);+ const int32 End = FMath::Min(Size, Size - Offset);+ float* Target = Out + Offset;+ int32 Index = Begin;+ if (bAdvect && MomentumCos[DirIndex] > 0.f)+ {+ const float* Weight = DenseAdvectWeight[DirIndex].GetData();+ for (; Index + 4 <= End; Index += 4)+ {+ const VectorRegister4Float Flow = VectorAdd(VectorMultiply(VectorLoad(Diffuse + Index), VectorLoad(RateBias + Index)),+ VectorMultiply(VectorLoad(Advect + Index), VectorLoad(Weight + Index)));+ VectorStore(VectorAdd(VectorLoad(Target + Index), Flow), Target + Index);+ }+ for (; Index < End; ++Index)+ {+ Target[Index] += Diffuse[Index] * RateBias[Index] + Advect[Index] * Weight[Index];+ }+ }+ else+ {+ for (; Index + 4 <= End; Index += 4)+ {+ const VectorRegister4Float Flow = VectorMultiply(VectorLoad(Diffuse + Index), VectorLoad(RateBias + Index));+ VectorStore(VectorAdd(VectorLoad(Target + Index), Flow), Target + Index);+ }+ for (; Index < End; ++Index)+ {+ Target[Index] += Diffuse[Index] * RateBias[Index];+ }+ }+ }+ const int32 Links = LinkFrom.Num();+ for (int32 Link = 0; Link < Links; ++Link)+ {+ const int32 From = CellDense[LinkFrom[Link]];+ float Flow = Diffuse[From] * LinkRateBias[Link];+ if (bAdvect)+ {+ Flow += Advect[From] * LinkAdvectWeight[Link];+ }+ Out[CellDense[LinkTo[Link]]] += Flow;+ }++ for (int32 Cell = 0; Cell < Num; ++Cell)+ {+ P[Cell] = Out[CellDense[Cell]];+ }+}++float FVerseBeliefGrid::ClearPd(int32 Cell, const FVector& Eye) const+{+ const float DistM = float(FVector::Dist(Eye, GetCellCentre(Cell)) / 100.0);+ float Pd = Tuning.ClearNearPd;+ if (DistM > Tuning.ClearNearM)+ {+ const float Alpha = FMath::Clamp((DistM - Tuning.ClearNearM) / FMath::Max(1.f, Tuning.ClearFarM - Tuning.ClearNearM), 0.f, 1.f);+ Pd = FMath::Lerp(Tuning.ClearNearPd, Tuning.ClearFarPd, Alpha);+ }+ return Pd * FMath::Clamp(Cells[Cell].Visibility, 0.f, 1.f);+}++void FVerseBeliefGrid::Clear(const FVector& Eye, TFunctionRef<bool(int32 Cell)> IsVisible, float NowS)+{+ if (bOpponentDead)+ {+ return;+ }+ for (int32 Cell = 0; Cell < Cells.Num(); ++Cell)+ {+ if (!bCellActive[Cell] || !IsVisible(Cell))+ {+ continue;+ }+ P[Cell] *= 1.f - ClearPd(Cell, Eye);+ LastClearedS[Cell] = NowS;+ }+}++void FVerseBeliefGrid::Clear(const FVector& Eye, TConstArrayView<int32> VisibleCells, float NowS)+{+ if (bOpponentDead)+ {+ return;+ }+ for (const int32 Cell : VisibleCells)+ {+ if (!bCellActive.IsValidIndex(Cell) || !bCellActive[Cell])+ {+ continue;+ }+ P[Cell] *= 1.f - ClearPd(Cell, Eye);+ LastClearedS[Cell] = NowS;+ }+}++void FVerseBeliefGrid::ApplySighting(const FVector& PelvisLocation, float NowS)+{+ bOpponentDead = false;+ const int32 Centre = FindCell(PelvisLocation - FVector(0.0, 0.0, 95.0));+ if (Centre == INDEX_NONE)+ {+ return;+ }+ const EVerseArenaLevel Level = Cells[Centre].Level;+ const FIntPoint Column = Cells[Centre].Column;+ const float Sd = FMath::Max(1.f, Tuning.SightingSdCm);+ FMemory::Memzero(P.GetData(), sizeof(float) * P.Num());+ const int32 Reach = FMath::Max(1, FMath::CeilToInt(3.f * Sd / CellSizeCm));+ for (int32 Dx = -Reach; Dx <= Reach; ++Dx)+ {+ for (int32 Dy = -Reach; Dy <= Reach; ++Dy)+ {+ const int32 Cell = FindCell(Column + FIntPoint(Dx, Dy), Level);+ if (Cell == INDEX_NONE)+ {+ continue;+ }+ const FVector C = GetCellCentre(Cell);+ const double D2 = FMath::Square(C.X - PelvisLocation.X) + FMath::Square(C.Y - PelvisLocation.Y);+ P[Cell] = float(FMath::Exp(-D2 / (2.0 * Sd * Sd)));+ if (D2 <= FMath::Square(double(CellSizeCm)))+ {+ LastSupportS[Cell] = NowS;+ LastSupportKind[Cell] = EVerseBeliefSupport::Seen;+ }+ }+ }+ if (P[Centre] <= 0.f)+ {+ P[Centre] = 1.f;+ }+ LastSupportS[Centre] = NowS;+ LastSupportKind[Centre] = EVerseBeliefSupport::Seen;+}++void FVerseBeliefGrid::ApplyHeard(const FVerseHeardPercept& Heard, float NowS)+{+ if (bOpponentDead)+ {+ return;+ }+ const double Sd = FMath::Max(25.0, double(Heard.ErrorSdM) * 100.0);+ const double Inv2Var = 1.0 / (2.0 * Sd * Sd);+ const double Support2 = FMath::Square(2.0 * Sd);+ for (int32 Cell = 0; Cell < Cells.Num(); ++Cell)+ {+ if (!bCellActive[Cell])+ {+ continue;+ }+ const FVector C = GetCellCentre(Cell);+ const double D2 = FMath::Square(C.X - Heard.Location.X) + FMath::Square(C.Y - Heard.Location.Y);+ const double LevelWeight =+ Cells[Cell].Level == Heard.LevelGuess ? Tuning.HeardLevelWeight : 1.0 - Tuning.HeardLevelWeight;+ P[Cell] *= float(Tuning.HeardEps + LevelWeight * FMath::Exp(-D2 * Inv2Var));+ if (D2 <= Support2 && Cells[Cell].Level == Heard.LevelGuess)+ {+ LastSupportS[Cell] = NowS;+ LastSupportKind[Cell] = EVerseBeliefSupport::Heard;+ }+ }+}++void FVerseBeliefGrid::ApplyWedge(const FVector& Point, const FVector& BackDirection, float MaxDistCm, float NowS)+{+ if (bOpponentDead)+ {+ return;+ }+ const FVector2D Back = FVector2D(BackDirection.X, BackDirection.Y).GetSafeNormal();+ if (Back.IsNearlyZero())+ {+ return;+ }+ const double Half = FMath::DegreesToRadians(double(Tuning.WedgeHalfAngleDeg));+ for (int32 Cell = 0; Cell < Cells.Num(); ++Cell)+ {+ if (!bCellActive[Cell])+ {+ continue;+ }+ const FVector C = GetCellCentre(Cell);+ const FVector2D V(C.X - Point.X, C.Y - Point.Y);+ const double Dist = V.Size();+ double Like = 0.0;+ if (Dist <= MaxDistCm)+ {+ if (Dist < CellSizeCm)+ {+ Like = 1.0;+ }+ else+ {+ const double Angle = FMath::Acos(FMath::Clamp(FVector2D::DotProduct(V / Dist, Back), -1.0, 1.0));+ Like = Angle <= Half ? 1.0 : (Angle <= 2.0 * Half ? 1.0 - (Angle - Half) / Half : 0.0);+ }+ }+ P[Cell] *= float(Tuning.WedgeEps + (1.0 - Tuning.WedgeEps) * Like);+ if (Like >= 0.5)+ {+ LastSupportS[Cell] = NowS;+ LastSupportKind[Cell] = EVerseBeliefSupport::Inferred;+ }+ }+}++void FVerseBeliefGrid::ApplyOpponentDead()+{+ bOpponentDead = true;+ bMomentum = false;+ FMemory::Memzero(P.GetData(), sizeof(float) * P.Num());+}++void FVerseBeliefGrid::ApplySpawnPrior(TConstArrayView<FVector> RankedSpawnPoints, float NowS)+{+ bOpponentDead = false;+ bMomentum = false;+ const int32 Count = FMath::Min(3, RankedSpawnPoints.Num());+ if (Count == 0)+ {+ ResetUniform();+ return;+ }+ double WeightSum = 0.0;+ for (int32 Index = 0; Index < Count; ++Index)+ {+ WeightSum += Tuning.SpawnWeights[Index];+ }+ FMemory::Memzero(P.GetData(), sizeof(float) * P.Num());+ const double Sd = FMath::Max(1.0, double(Tuning.SpawnSdCm));+ const int32 Reach = FMath::Max(1, FMath::CeilToInt(3.0 * Sd / CellSizeCm));+ for (int32 Index = 0; Index < Count; ++Index)+ {+ const FVector& Spawn = RankedSpawnPoints[Index];+ const int32 Centre = FindCell(Spawn);+ if (Centre == INDEX_NONE)+ {+ continue;+ }+ const EVerseArenaLevel Level = Cells[Centre].Level;+ TArray<TPair<int32, double>, TInlineAllocator<64>> Disc;+ double DiscSum = 0.0;+ for (int32 Dx = -Reach; Dx <= Reach; ++Dx)+ {+ for (int32 Dy = -Reach; Dy <= Reach; ++Dy)+ {+ const int32 Cell = FindCell(Cells[Centre].Column + FIntPoint(Dx, Dy), Level);+ if (Cell == INDEX_NONE)+ {+ continue;+ }+ const FVector C = GetCellCentre(Cell);+ const double D2 = FMath::Square(C.X - Spawn.X) + FMath::Square(C.Y - Spawn.Y);+ const double W = FMath::Exp(-D2 / (2.0 * Sd * Sd));+ Disc.Add({Cell, W});+ DiscSum += W;+ }+ }+ const double Share = Tuning.SpawnWeights[Index] / WeightSum;+ for (const TPair<int32, double>& Item : Disc)+ {+ P[Item.Key] += float(Share * Item.Value / FMath::Max(DiscSum, 1e-12));+ LastSupportS[Item.Key] = NowS;+ LastSupportKind[Item.Key] = EVerseBeliefSupport::Inferred;+ }+ }+}++void FVerseBeliefGrid::Normalise()+{+ if (bOpponentDead)+ {+ return;+ }+ const int32 Num = Cells.Num();+ const int32 Active = ActiveCount;+ if (Active == 0)+ {+ return;+ }+ // Sum of active mass: four double accumulators, branch-free on the active mask.+ float* Mass = P.GetData();+ const float* MaskF = ActiveMaskF.GetData();+ double Sums[4] = {0.0, 0.0, 0.0, 0.0};+ int32 Cell = 0;+ for (; Cell + 4 <= Num; Cell += 4)+ {+ Sums[0] += double(Mass[Cell] * MaskF[Cell]);+ Sums[1] += double(Mass[Cell + 1] * MaskF[Cell + 1]);+ Sums[2] += double(Mass[Cell + 2] * MaskF[Cell + 2]);+ Sums[3] += double(Mass[Cell + 3] * MaskF[Cell + 3]);+ }+ for (; Cell < Num; ++Cell)+ {+ Sums[0] += double(Mass[Cell] * MaskF[Cell]);+ }+ const double Sum = (Sums[0] + Sums[1]) + (Sums[2] + Sums[3]);+ if (!(Sum > 0.0) || !FMath::IsFinite(Sum))+ {+ ResetUniform();+ return;+ }+ // Prior: 90 % learned heatmap (when there is one) plus 10 % uniform, so it is never 0.+ double PriorSum = 0.0;+ if (Prior.Num() == Num)+ {+ for (int32 Index = 0; Index < Num; ++Index)+ {+ PriorSum += bCellActive[Index] ? FMath::Max(0.f, Prior[Index]) : 0.f;+ }+ }+ const bool bHeat = PriorSum > 0.0;+ const double Mix = FMath::Clamp(double(Tuning.PriorMix), 1e-6, 1.0);+ const float Keep = float((1.0 - Mix) / Sum);+ const float Uniform = float(Mix * (bHeat ? 0.1 : 1.0) / double(Active));+ if (bHeat)+ {+ const double HeatScale = Mix * 0.9 / PriorSum;+ for (int32 Index = 0; Index < Num; ++Index)+ {+ P[Index] = bCellActive[Index] ? P[Index] * Keep + Uniform + float(HeatScale * FMath::Max(0.f, Prior[Index])) : 0.f;+ }+ return;+ }+ // (m x Keep + Uniform) x mask: exact for the 0 / 1 mask, inactive cells stay 0.+ const VectorRegister4Float KeepV = VectorSetFloat1(Keep);+ const VectorRegister4Float UniformV = VectorSetFloat1(Uniform);+ Cell = 0;+ for (; Cell + 4 <= Num; Cell += 4)+ {+ const VectorRegister4Float Value = VectorAdd(VectorMultiply(VectorLoad(Mass + Cell), KeepV), UniformV);+ VectorStore(VectorMultiply(Value, VectorLoad(MaskF + Cell)), Mass + Cell);+ }+ for (; Cell < Num; ++Cell)+ {+ Mass[Cell] = (Mass[Cell] * Keep + Uniform) * MaskF[Cell];+ }+}++double FVerseBeliefGrid::TotalMass() const+{+ double Sum = 0.0;+ for (int32 Cell = 0; Cell < Cells.Num(); ++Cell)+ {+ Sum += bCellActive[Cell] ? P[Cell] : 0.f;+ }+ return Sum;+}++FVerseBeliefDerived FVerseBeliefGrid::ComputeDerived(float NowS, bool bKnown) const+{+ FVerseBeliefDerived Out;+ if (bOpponentDead)+ {+ Out.State = EVerseBeliefState::Dead;+ return Out;+ }+ const int32 Num = Cells.Num();+ if (Num == 0 || DiscPadSize == 0)+ {+ return Out;+ }++ // Pass 1 over the cells: scatter the mass into the padded disc layout, and a histogram by float+ // exponent (one bucket per factor of 2) holding the mass and the moment sums (x, y, z, x^2+y^2+z^2+ // in metres from the grid middle, one vector) of each bucket. Four interleaved banks keep+ // consecutive cells (usually the same bucket) off one dependency chain.+ constexpr int32 Banks = 4;+ constexpr int32 Buckets = 64;+ constexpr int32 ExpBase = 127 - Buckets + 1;+ alignas(16) float HistMoments[Banks * Buckets * 4];+ float HistMass[Banks * Buckets];+ FMemory::Memzero(HistMoments, sizeof(HistMoments));+ FMemory::Memzero(HistMass, sizeof(HistMass));+ {+ const float* Mass = P.GetData();+ const float* Moment = CellMoment.GetData();+ float* PadOut = DiscPadMass.GetData();+ const int32* PadIndex = CellDiscPad.GetData();+ for (int32 Cell = 0; Cell < Num; ++Cell)+ {+ const float Value = Mass[Cell];+ PadOut[PadIndex[Cell]] = Value;+ if (!(Value > 0.f))+ {+ continue;+ }+ uint32 Bits;+ FMemory::Memcpy(&Bits, &Value, sizeof(Bits));+ const int32 Bucket = FMath::Clamp(int32((Bits >> 23) & 0xFFu) - ExpBase, 0, Buckets - 1);+ const int32 Slot = (Cell & (Banks - 1)) * Buckets + Bucket;+ HistMass[Slot] += Value;+ float* Acc = HistMoments + 4 * Slot;+ VectorStoreAligned(VectorAdd(VectorLoadAligned(Acc), VectorMultiply(VectorSetFloat1(Value), VectorLoad(Moment + 4 * Cell))), Acc);+ }+ }+ double BucketMass[Buckets] = {};+ double Total = 0.0;+ for (int32 Bucket = 0; Bucket < Buckets; ++Bucket)+ {+ for (int32 Bank = 0; Bank < Banks; ++Bank)+ {+ BucketMass[Bucket] += HistMass[Bank * Buckets + Bucket];+ }+ Total += BucketMass[Bucket];+ }+ if (!(Total > 0.0))+ {+ return Out;+ }++ // Spread: the buckets (from the top) that hold 90 % of the mass.+ {+ double W = 0.0;+ double Sx = 0.0;+ double Sy = 0.0;+ double Sz = 0.0;+ double Sq = 0.0;+ for (int32 Bucket = Buckets - 1; Bucket >= 0 && W < 0.9 * Total; --Bucket)+ {+ for (int32 Bank = 0; Bank < Banks; ++Bank)+ {+ const int32 Slot = Bank * Buckets + Bucket;+ W += HistMass[Slot];+ Sx += HistMoments[4 * Slot + 0];+ Sy += HistMoments[4 * Slot + 1];+ Sz += HistMoments[4 * Slot + 2];+ Sq += HistMoments[4 * Slot + 3];+ }+ }+ if (W > 0.0)+ {+ const double Mx = Sx / W;+ const double My = Sy / W;+ const double Mz = Sz / W;+ const double Var = FMath::Max(0.0, Sq / W - (Mx * Mx + My * My + Mz * Mz));+ Out.SpreadM = float(FMath::Sqrt(Var));+ }+ }++ // TopCluster (bot.md 4.3): the disc sum of every cell, from horizontal box sums of the disc's row+ // half-widths, then the active cell with the largest sum (ties: the lowest padded index).+ const int32 Reach = DiscHalfWidth.Num() / 2;+ const int32 Width = DiscPadWidth;+ const int32 Size = DiscPadSize;+ const float* Pad = DiscPadMass.GetData();+ int32 MaxHalf = 0;+ for (const int32 Half : DiscHalfWidth)+ {+ MaxHalf = FMath::Max(MaxHalf, Half);+ }+ MaxHalf = FMath::Min(MaxHalf, 7);+ const float* Rows[8] = {Pad, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr};+ for (int32 Half = 1; Half <= MaxHalf; ++Half)+ {+ const float* Prev = Rows[Half - 1];+ float* Cur = DiscPadRows[Half].GetData();+ const int32 End = Size - Reach;+ int32 Index = Reach;+ for (; Index + 4 <= End; Index += 4)+ {+ const VectorRegister4Float Sides = VectorAdd(VectorLoad(Pad + Index - Half), VectorLoad(Pad + Index + Half));+ VectorStore(VectorAdd(VectorLoad(Prev + Index), Sides), Cur + Index);+ }+ for (; Index < End; ++Index)+ {+ Cur[Index] = Prev[Index] + (Pad[Index - Half] + Pad[Index + Half]);+ }+ Rows[Half] = Cur;+ }+ const float* TermRows[17];+ int32 TermOffsets[17];+ int32 NumTerms = 0;+ for (int32 Dy = -Reach; Dy <= Reach && NumTerms < 17; ++Dy)+ {+ const int32 Half = DiscHalfWidth[Dy + Reach];+ if (Half >= 0 && Half <= MaxHalf)+ {+ TermRows[NumTerms] = Rows[Half];+ TermOffsets[NumTerms] = Dy * Width;+ ++NumTerms;+ }+ }+ if (NumTerms == 0)+ {+ return Out;+ }+ float* Score = DiscPadSum.GetData();+ const float* Mask = DiscPadMask.GetData();+ const int32 Begin = Reach * Width;+ const int32 End = Size - Reach * Width;+ const VectorRegister4Float One = VectorSetFloat1(1.f);+ VectorRegister4Float BestLanes = VectorSetFloat1(-2.f);+ int32 Index = Begin;+ for (; Index + 4 <= End; Index += 4)+ {+ VectorRegister4Float Acc = VectorLoad(TermRows[0] + Index + TermOffsets[0]);+ for (int32 Term = 1; Term < NumTerms; ++Term)+ {+ Acc = VectorAdd(Acc, VectorLoad(TermRows[Term] + Index + TermOffsets[Term]));+ }+ const VectorRegister4Float M = VectorLoad(Mask + Index);+ // Inactive or no cell: -1, below every real disc sum.+ const VectorRegister4Float Value = VectorAdd(VectorMultiply(Acc, M), VectorSubtract(M, One));+ VectorStore(Value, Score + Index);+ BestLanes = VectorMax(BestLanes, Value);+ }+ float Best = -2.f;+ for (; Index < End; ++Index)+ {+ float Acc = TermRows[0][Index + TermOffsets[0]];+ for (int32 Term = 1; Term < NumTerms; ++Term)+ {+ Acc += TermRows[Term][Index + TermOffsets[Term]];+ }+ const float Value = Acc * Mask[Index] + (Mask[Index] - 1.f);+ Score[Index] = Value;+ Best = FMath::Max(Best, Value);+ }+ float Lanes[4];+ VectorStore(BestLanes, Lanes);+ Best = FMath::Max(FMath::Max(Best, FMath::Max(Lanes[0], Lanes[1])), FMath::Max(Lanes[2], Lanes[3]));+ if (Best < 0.f)+ {+ return Out;+ }+ int32 BestCell = INDEX_NONE;+ for (Index = Begin; Index < End; ++Index)+ {+ if (Score[Index] == Best)+ {+ BestCell = DiscPadCell[Index];+ break;+ }+ }+ if (BestCell == INDEX_NONE)+ {+ return Out;+ }++ FVector Weighted = FVector::ZeroVector;+ double DiscMass = 0.0;+ float NewestSupport = -1.f;+ EVerseBeliefSupport NewestKind = EVerseBeliefSupport::None;+ for (const FIntPoint& Offset : DiscOffsets)+ {+ const int32 Cell = FindCell(Cells[BestCell].Column + Offset, Cells[BestCell].Level);+ if (Cell == INDEX_NONE)+ {+ continue;+ }+ Weighted += Centres[Cell] * double(P[Cell]);+ DiscMass += P[Cell];+ const EVerseBeliefSupport Kind = LastSupportKind[Cell];+ if ((Kind == EVerseBeliefSupport::Seen || Kind == EVerseBeliefSupport::Heard) && LastSupportS[Cell] > NewestSupport)+ {+ NewestSupport = LastSupportS[Cell];+ NewestKind = Kind;+ }+ }+ Out.TopCluster.CentreCell = BestCell;+ Out.TopCluster.Level = Cells[BestCell].Level;+ Out.TopCluster.Mass = float(DiscMass);+ Out.TopCluster.Centre = DiscMass > 0.0 ? Weighted / DiscMass : Centres[BestCell];+ Out.Confidence = float(FMath::Clamp(DiscMass, 0.0, 1.0));+ if (NewestSupport >= 0.f)+ {+ Out.SupportAgeS = FMath::Max(0.f, NowS - NewestSupport);+ Out.SupportKind = NewestKind;+ }++ if (bKnown)+ {+ Out.State = EVerseBeliefState::Known;+ }+ else if (Out.Confidence >= Tuning.TrackedConfidence)+ {+ Out.State = EVerseBeliefState::Tracked;+ }+ else if (Out.Confidence >= Tuning.RoughConfidence)+ {+ Out.State = EVerseBeliefState::Rough;+ }+ else+ {+ Out.State = EVerseBeliefState::Lost;+ }+ return Out;+}++TArray<int32> FVerseBeliefGrid::FindPath(int32 From, int32 To) const+{+ TArray<int32> Path;+ if (!Cells.IsValidIndex(From) || !Cells.IsValidIndex(To) || !bCellActive[From] || !bCellActive[To])+ {+ return Path;+ }+ TArray<int32> Parent;+ Parent.Init(INDEX_NONE, Cells.Num());+ TArray<int32> Queue;+ Queue.Add(From);+ Parent[From] = From;+ for (int32 Head = 0; Head < Queue.Num(); ++Head)+ {+ const int32 Cell = Queue[Head];+ if (Cell == To)+ {+ break;+ }+ for (int32 Edge = NeighbourStart[Cell]; Edge < NeighbourStart[Cell + 1]; ++Edge)+ {+ const FNeighbour& Neighbour = Neighbours[Edge];+ if (Neighbour.bActive && Parent[Neighbour.Cell] == INDEX_NONE)+ {+ Parent[Neighbour.Cell] = Cell;+ Queue.Add(Neighbour.Cell);+ }+ }+ }+ if (Parent[To] == INDEX_NONE)+ {+ return Path;+ }+ for (int32 Cell = To; Cell != From; Cell = Parent[Cell])+ {+ Path.Add(Cell);+ }+ Path.Add(From);+ Algo::Reverse(Path);+ return Path;+}++uint32 FVerseBeliefGrid::HashMass() const+{+ return FCrc::MemCrc32(P.GetData(), P.Num() * sizeof(float));+}diff --git a/unreal/Verse/Source/VerseBot/Private/Belief/VerseBeliefMap.cpp b/unreal/Verse/Source/VerseBot/Private/Belief/VerseBeliefMap.cppnew file mode 100644index 0000000000..e70b16c329--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Belief/VerseBeliefMap.cpp@@ -0,0 +1,376 @@+#include "Belief/VerseBeliefMap.h"++#include "Destruction/VerseDestructionInterfaces.h"+#include "Perception/VersePerceptionModel.h"+#include "VerseGameplayTags.h"++namespace+{+ /** Sample heights of a cell test, in rotation order: 1.6 m, 1.0 m, then 0.4 m where prone is possible. */+ constexpr float CellSightHeightsCm[3] = {160.f, 100.f, 40.f};+ /** Bound on the hurt and bolt wedges, cm. */+ constexpr float WedgeMaxRangeCm = 8000.f;++ /** The view cone of bot.md 3.1 as cheap comparisons (no trigonometry per point). */+ struct FClearCone+ {+ double Fx = 1.0;+ double Fy = 0.0;+ double CosHalf = 0.0;+ double TanLo = 0.0;+ double TanHi = 0.0;+ bool bLoOpen = false;+ bool bHiOpen = false;++ explicit FClearCone(const FRotator& View)+ {+ const double Yaw = FMath::DegreesToRadians(double(View.Yaw));+ Fx = FMath::Cos(Yaw);+ Fy = FMath::Sin(Yaw);+ CosHalf = FMath::Cos(FMath::DegreesToRadians(double(VersePerception::ViewHalfAngleDeg)));+ const double Pitch = double(FRotator::NormalizeAxis(View.Pitch));+ const double Lo = Pitch - double(VersePerception::VerticalHalfAngleDeg);+ const double Hi = Pitch + double(VersePerception::VerticalHalfAngleDeg);+ bLoOpen = Lo <= -89.999;+ bHiOpen = Hi >= 89.999;+ TanLo = bLoOpen ? 0.0 : FMath::Tan(FMath::DegreesToRadians(Lo));+ TanHi = bHiOpen ? 0.0 : FMath::Tan(FMath::DegreesToRadians(Hi));+ }++ /** Horizontal half-angle against the view yaw, elevation within the vertical half-angle of the pitch. */+ bool Contains(const FVector& Eye, const FVector& Point) const+ {+ const double Vx = Point.X - Eye.X;+ const double Vy = Point.Y - Eye.Y;+ const double Vz = Point.Z - Eye.Z;+ const double H = FMath::Sqrt(Vx * Vx + Vy * Vy);+ if (H < 1.0)+ {+ return true;+ }+ if (Vx * Fx + Vy * Fy < CosHalf * H)+ {+ return false;+ }+ if (!bLoOpen && Vz < H * TanLo)+ {+ return false;+ }+ return bHiOpen || Vz <= H * TanHi;+ }+ };+}++void FVerseBeliefMap::Initialize(const FVerseBeliefGridSource& Source, const FVerseBeliefMapConfig& InConfig,+ const FVerseBeliefWorld& World, const FVerseBeliefTuning& Tuning)+{+ Config = InConfig;+ Grid.Build(Source, Tuning);+ Opponent = FVerseOpponentEstimate();+ Pieces = FVersePieceBelief();+ if (Config.PieceLayout.Num() > 0)+ {+ Pieces.Initialize(Config.PieceLayout);+ }+ else if (World.Pieces)+ {+ Pieces.Initialize(*World.Pieces, Config.ArenaBox);+ }+ RefreshGates();+ Grid.ResetUniform();+ const int32 Num = Grid.NumCells();+ CachedVisible.Init(0, Num);+ CachedEye.Init(FVector(TNumericLimits<float>::Max()), Num);+ CachedAtS.Init(-1000.f, Num);+ CachedHeight.Init(0, Num);+ VisibleScratch.Reset();+ ClearCursor = 0;+ LastClearSightTests = 0;+ LastStepS = -1.f;+ StepCount = 0;+ bHasFrame = false;+ Derived = Grid.ComputeDerived(0.f, false);+}++void FVerseBeliefMap::RefreshGates()+{+ Pieces.ConsumeChangedPieces();+ Grid.ApplyGates([this](int32 Piece) { return Pieces.IsBelievedOpen(Piece); },+ [this](int32 Piece) { return Pieces.IsBelievedStanding(Piece); });+}++bool FVerseBeliefMap::TestCellVisible(int32 Cell, const FVector& Eye, const FRotator& View, const IVersePenetrationQuery& Sight) const+{+ const FVector Centre = Grid.GetCellCentre(Cell);+ const FClearCone Cone(View);+ const int32 Heights = Grid.GetCell(Cell).bProneCapable ? 3 : 2;+ for (int32 Height = 0; Height < Heights; ++Height)+ {+ const FVector Point = Centre + FVector(0.0, 0.0, CellSightHeightsCm[Height]);+ if (Cone.Contains(Eye, Point) && Sight.TestSight(Eye, Point))+ {+ return true;+ }+ }+ return false;+}++void FVerseBeliefMap::RunClear(const FVerseSelfPercept& Self, const FVerseBeliefWorld& World, float NowS)+{+ LastClearSightTests = 0;+ if (!World.Sight || Self.Phase == EVerseCombatPhase::Dead)+ {+ return;+ }+ const FVector Eye = Self.EyeLocation;+ const FClearCone Cone(Self.ViewRotation);+ const int32 Num = Grid.NumCells();+ if (Num == 0)+ {+ return;+ }+ const double RangeSq = FMath::Square(double(Config.ClearRangeCm));+ const double MoveSq = FMath::Square(double(Config.VisibilityCacheMoveCm));+ const float MaxAgeS = Config.VisibilityCacheMaxAgeS;++ // Every in-cone cell with a valid cache is cleared from the cache; stale ones are retested, one+ // trace each, in a rotating order until the budget is spent. The rest wait for the next step.+ VisibleScratch.Reset();+ int32 Budget = Config.MaxCellSightTestsPerStep;+ int32 StoppedAt = INDEX_NONE;+ for (int32 Step = 0; Step < Num; ++Step)+ {+ int32 Cell = ClearCursor + Step;+ Cell -= Cell >= Num ? Num : 0;+ if (!Grid.IsActive(Cell))+ {+ continue;+ }+ const FVector Centre = Grid.GetCellCentre(Cell);+ const FVector Mid = Centre + FVector(0.0, 0.0, 130.0);+ if (FVector::DistSquared(Eye, Mid) > RangeSq || !Cone.Contains(Eye, Mid))+ {+ continue;+ }+ const bool bCacheValid = FVector::DistSquared(CachedEye[Cell], Eye) <= MoveSq && NowS - CachedAtS[Cell] <= MaxAgeS;+ if (!bCacheValid)+ {+ if (Budget <= 0)+ {+ if (StoppedAt == INDEX_NONE)+ {+ StoppedAt = Cell;+ }+ continue;+ }+ --Budget;+ const int32 Heights = Grid.GetCell(Cell).bProneCapable ? 3 : 2;+ const int32 Height = CachedHeight[Cell] % Heights;+ CachedHeight[Cell] = uint8((Height + 1) % Heights);+ const FVector Point = Centre + FVector(0.0, 0.0, CellSightHeightsCm[Height]);+ CachedVisible[Cell] = Cone.Contains(Eye, Point) && World.Sight->TestSight(Eye, Point) ? 1 : 0;+ CachedEye[Cell] = Eye;+ CachedAtS[Cell] = NowS;+ }+ if (CachedVisible[Cell])+ {+ VisibleScratch.Add(Cell);+ }+ }+ LastClearSightTests = Config.MaxCellSightTestsPerStep - Budget;+ if (StoppedAt != INDEX_NONE)+ {+ ClearCursor = StoppedAt;+ }+ Grid.Clear(Eye, VisibleScratch, NowS);+}++TArray<FVector> FVerseBeliefMap::RankSpawnPoints(const FVector& Eye, const IVersePenetrationQuery* Sight) const+{+ struct FRanked+ {+ FVector Point;+ bool bHidden;+ double Dist;+ int32 Index;+ };+ TArray<FRanked> Ranked;+ for (int32 Index = 0; Index < Config.SpawnPoints.Num(); ++Index)+ {+ const FVector& Point = Config.SpawnPoints[Index];+ const bool bHidden = Sight ? !Sight->TestSight(Eye, Point + FVector(0.0, 0.0, 150.0)) : true;+ Ranked.Add({Point, bHidden, FVector::Dist(Eye, Point), Index});+ }+ Ranked.Sort([](const FRanked& A, const FRanked& B) {+ if (A.bHidden != B.bHidden)+ {+ return A.bHidden;+ }+ if (A.Dist != B.Dist)+ {+ return A.Dist > B.Dist;+ }+ return A.Index < B.Index;+ });+ TArray<FVector> Out;+ for (const FRanked& Item : Ranked)+ {+ Out.Add(Item.Point);+ }+ return Out;+}++bool FVerseBeliefMap::ApplyFrame(const FVersePerceptFrame& Frame, const FVerseBeliefWorld& World)+{+ const float NowS = float(double(Frame.ServerTimeMs) / 1000.0);++ bool bPositive = Frame.Sightings.Num() > 0 || Frame.Bolts.Num() > 0 || Frame.bHasHurt;+ for (const FVerseHeardPercept& Heard : Frame.Heard)+ {+ bPositive |= Heard.Noise != VerseTags::Noise_Impact && Heard.Noise != VerseTags::Noise_Drone;+ }+ bPositive |= Frame.Hud.Num() > 0;+ const bool bDue = !bHasFrame || NowS - LastStepS >= Config.StepIntervalS - 1e-4f;+ if (!bDue && !bPositive)+ {+ return false;+ }+ const float DeltaS = bHasFrame ? FMath::Clamp(NowS - LastStepS, 0.f, 1.f) : 0.f;++ // Own death first: the belief is cleared before this step's evidence lands.+ for (const FVerseHudEvent& Hud : Frame.Hud)+ {+ if (Hud.Kind == EVerseHudEventKind::Kill && Hud.VictimId == Config.SelfPlayerId)+ {+ Grid.ResetUniform();+ Grid.ClearMomentum();+ }+ }++ // bot.md 4.2 order: predict, clear, sighting, heard, hurt / bolt, kill feed, normalise. Clearing+ // and looking at pieces trace sight, so they run on the 10 Hz steps only; a step that runs at+ // once for a positive percept between them skips the traces (bot.md 2 budget).+ Grid.Predict(DeltaS, NowS);+ if (bDue)+ {+ RunClear(Frame.Self, World, NowS);+ }+ else+ {+ LastClearSightTests = 0;+ }++ const bool bSighted = Frame.Sightings.Num() > 0;+ if (bSighted)+ {+ // One opponent in a duel: the first sighting is the opponent.+ const FVerseSightPercept& Sight = Frame.Sightings[0];+ Grid.ApplySighting(Sight.PelvisLocation, NowS);+ Grid.SetMomentum(Sight.Velocity, NowS);+ Opponent.OnSighting(Sight, NowS);+ }++ for (const FVerseHeardPercept& Heard : Frame.Heard)+ {+ Opponent.OnHeard(Heard, NowS);+ if (Heard.Noise == VerseTags::Noise_Fracture)+ {+ // A fracture says a piece changed, not where the opponent is.+ Pieces.OnHeardFracture(Heard, NowS);+ continue;+ }+ if (Heard.Noise == VerseTags::Noise_Impact || Heard.Noise == VerseTags::Noise_Drone || bSighted)+ {+ continue;+ }+ Grid.ApplyHeard(Heard, NowS);+ }++ if (!bSighted)+ {+ if (Frame.bHasHurt)+ {+ const FVector Eye = Frame.Self.EyeLocation;+ const FVector Back = Frame.Hurt.IncomingDirection.GetSafeNormal();+ Grid.ApplyWedge(Eye, Back, Pieces.OpaqueDistance(Eye, Back, WedgeMaxRangeCm), NowS);+ }+ for (const FVerseBoltPercept& Bolt : Frame.Bolts)+ {+ Opponent.OnSeenShot(NowS);+ const FVector Back = -Bolt.Direction.GetSafeNormal();+ Grid.ApplyWedge(Bolt.Position, Back, Pieces.OpaqueDistance(Bolt.Position, Back, WedgeMaxRangeCm), NowS);+ }+ }++ for (const FVerseHudEvent& Hud : Frame.Hud)+ {+ switch (Hud.Kind)+ {+ case EVerseHudEventKind::Kill:+ if (Hud.VictimId != Config.SelfPlayerId)+ {+ Grid.ApplyOpponentDead();+ Opponent.OnOpponentDead();+ }+ else if (Hud.bKillerPositionShown)+ {+ // The kill cam showed where the killer stood.+ Grid.ApplySighting(Hud.KillerPosition, NowS);+ }+ break;+ case EVerseHudEventKind::OpponentRespawned:+ if (Hud.VictimId != Config.SelfPlayerId)+ {+ Grid.ApplySpawnPrior(RankSpawnPoints(Frame.Self.EyeLocation, World.Sight), NowS);+ Opponent.OnOpponentRespawned();+ }+ break;+ case EVerseHudEventKind::HitMarker:+ Opponent.OnOwnHit(Config.OwnHitDamage, NowS);+ break;+ case EVerseHudEventKind::HeadshotMarker:+ Opponent.OnOwnHit(Config.OwnHeadshotDamage, NowS);+ break;+ default:+ break;+ }+ }++ Grid.Normalise();++ if (bDue && World.Pieces && World.Sight && Frame.Self.Phase != EVerseCombatPhase::Dead)+ {+ Pieces.ObserveSight(Frame.Self.EyeLocation, Frame.Self.ViewRotation, *World.Pieces, *World.Sight, NowS,+ Config.MaxPieceSightTestsPerStep);+ }+ if (Pieces.ConsumeChangedPieces().Num() > 0)+ {+ Grid.ApplyGates([this](int32 Piece) { return Pieces.IsBelievedOpen(Piece); },+ [this](int32 Piece) { return Pieces.IsBelievedStanding(Piece); });+ }++ Derived = Grid.ComputeDerived(NowS, bSighted);+ LastStepS = NowS;+ ++StepCount;+ bHasFrame = true;+ return true;+}++void FVerseBeliefMap::OnOwnDeath(float NowS)+{+ Grid.ResetUniform();+ Grid.ClearMomentum();+ Derived = Grid.ComputeDerived(NowS, false);+}++void FVerseBeliefMap::OnOwnPieceAction(uint16 Piece, EVersePieceState NewState, float NowS)+{+ Pieces.OnOwnAction(Piece, NewState, NowS);+ RefreshGates();+}++void FVerseBeliefMap::OnDestructionReset()+{+ Pieces.ResetAll();+ RefreshGates();+}diff --git a/unreal/Verse/Source/VerseBot/Private/Belief/VerseBeliefNavSampler.cpp b/unreal/Verse/Source/VerseBot/Private/Belief/VerseBeliefNavSampler.cppnew file mode 100644index 0000000000..b117c2599a--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Belief/VerseBeliefNavSampler.cpp@@ -0,0 +1,161 @@+#include "Belief/VerseBeliefNavSampler.h"++#include "AI/Navigation/NavigationDataInterface.h"+#include "AI/Navigation/NavigationTypes.h"+#include "AI/NavigationSystemBase.h"+#include "Engine/World.h"++bool FVerseBeliefNavSampler::Build(const UWorld& World, const FVerseBeliefNavSettings& Settings, FVerseBeliefGridSource& OutSource)+{+ OutSource = FVerseBeliefGridSource();+ const UNavigationSystemBase* NavSys = World.GetNavigationSystem();+ const INavigationDataInterface* Nav = NavSys ? NavSys->GetMainNavData() : nullptr;+ return Nav ? Build(*Nav, Settings, OutSource) : false;+}++bool FVerseBeliefNavSampler::Build(const INavigationDataInterface& Nav, const FVerseBeliefNavSettings& Settings, FVerseBeliefGridSource& OutSource)+{+ OutSource = FVerseBeliefGridSource();+ if (!Settings.ArenaBox.IsValid)+ {+ return false;+ }+ const float Cell = FMath::Max(10.f, Settings.CellSizeCm);+ OutSource.CellSizeCm = Cell;+ OutSource.Origin = FVector2D(Settings.ArenaBox.Min.X + 0.5 * Cell, Settings.ArenaBox.Min.Y + 0.5 * Cell);+ const int32 Nx = FMath::Max(1, FMath::FloorToInt((Settings.ArenaBox.Max.X - Settings.ArenaBox.Min.X) / Cell));+ const int32 Ny = FMath::Max(1, FMath::FloorToInt((Settings.ArenaBox.Max.Y - Settings.ArenaBox.Min.Y) / Cell));+ const FVector Extent(Settings.ProjectHalfXYCm, Settings.ProjectHalfXYCm, Settings.ProjectHalfZCm);++ TArray<FNavLocation> Locations;+ TMap<FIntVector, int32> Lookup;+ for (int32 X = 0; X < Nx; ++X)+ {+ for (int32 Y = 0; Y < Ny; ++Y)+ {+ TArray<float, TInlineAllocator<3>> Floors;+ for (int32 Level = 0; Level < 3; ++Level)+ {+ const FVector Probe(OutSource.Origin.X + X * Cell, OutSource.Origin.Y + Y * Cell, Settings.LevelProbeZCm[Level]);+ FNavLocation Hit;+ if (!Nav.ProjectPoint(Probe, Hit, Extent))+ {+ continue;+ }+ if (Floors.ContainsByPredicate([&](float Z) { return FMath::Abs(Z - Hit.Location.Z) < Settings.SameFloorCm; }))+ {+ continue;+ }+ Floors.Add(float(Hit.Location.Z));+ FVerseBeliefCellDesc& Desc = OutSource.Cells.AddDefaulted_GetRef();+ Desc.Column = FIntPoint(X, Y);+ Desc.FloorZ = float(Hit.Location.Z);+ Desc.Level = EVerseArenaLevel(Level);+ Desc.Visibility = Settings.VisibilityAt ? Settings.VisibilityAt(Hit.Location) : 1.f;+ Desc.Zone = Settings.ZoneAt ? Settings.ZoneAt(Hit.Location) : 255;+ Lookup.Add(FIntVector(X, Y, Level), OutSource.Cells.Num() - 1);+ Locations.Add(Hit);+ }+ }+ }++ // Piece gates: catwalk cells go with their piece, breach openings appear when it opens.+ TArray<uint8> Unsampled;+ Unsampled.Init(0, OutSource.Cells.Num());+ for (const FVerseBeliefNavSettings::FPieceFootprint& Footprint : Settings.PieceFootprints)+ {+ if (!Footprint.Bounds.IsValid || Footprint.Piece == INDEX_NONE || Footprint.Gate == EVerseBeliefGate::Always)+ {+ continue;+ }+ const int32 X0 = FMath::Max(0, FMath::CeilToInt((Footprint.Bounds.Min.X - OutSource.Origin.X) / Cell));+ const int32 X1 = FMath::Min(Nx - 1, FMath::FloorToInt((Footprint.Bounds.Max.X - OutSource.Origin.X) / Cell));+ const int32 Y0 = FMath::Max(0, FMath::CeilToInt((Footprint.Bounds.Min.Y - OutSource.Origin.Y) / Cell));+ const int32 Y1 = FMath::Min(Ny - 1, FMath::FloorToInt((Footprint.Bounds.Max.Y - OutSource.Origin.Y) / Cell));+ for (int32 X = X0; X <= X1; ++X)+ {+ for (int32 Y = Y0; Y <= Y1; ++Y)+ {+ if (Footprint.Gate == EVerseBeliefGate::WhenStanding)+ {+ for (int32 Level = 0; Level < 3; ++Level)+ {+ const int32* Found = Lookup.Find(FIntVector(X, Y, Level));+ if (!Found)+ {+ continue;+ }+ FVerseBeliefCellDesc& Desc = OutSource.Cells[*Found];+ if (Desc.FloorZ >= Footprint.Bounds.Min.Z - Settings.SameFloorCm &&+ Desc.FloorZ <= Footprint.Bounds.Max.Z + Settings.SameFloorCm)+ {+ Desc.Gate = EVerseBeliefGate::WhenStanding;+ Desc.GatePiece = Footprint.Piece;+ }+ }+ continue;+ }+ const FIntVector Key(X, Y, int32(Footprint.Level));+ if (const int32* Found = Lookup.Find(Key))+ {+ OutSource.Cells[*Found].Gate = EVerseBeliefGate::WhenOpen;+ OutSource.Cells[*Found].GatePiece = Footprint.Piece;+ continue;+ }+ const FVector Floor(OutSource.Origin.X + X * Cell, OutSource.Origin.Y + Y * Cell, Footprint.Bounds.Min.Z);+ FVerseBeliefCellDesc& Desc = OutSource.Cells.AddDefaulted_GetRef();+ Desc.Column = FIntPoint(X, Y);+ Desc.FloorZ = float(Floor.Z);+ Desc.Level = Footprint.Level;+ Desc.Visibility = Settings.VisibilityAt ? Settings.VisibilityAt(Floor) : 1.f;+ Desc.Zone = Settings.ZoneAt ? Settings.ZoneAt(Floor) : 255;+ Desc.Gate = EVerseBeliefGate::WhenOpen;+ Desc.GatePiece = Footprint.Piece;+ Lookup.Add(Key, OutSource.Cells.Num() - 1);+ Locations.Add(FNavLocation(Floor));+ Unsampled.Add(1);+ }+ }+ }++ for (const FVerseBeliefNavSettings::FLink& Link : Settings.Links)+ {+ const int32* From = Lookup.Find(FIntVector(Link.FromColumn.X, Link.FromColumn.Y, int32(Link.FromLevel)));+ const int32* To = Lookup.Find(FIntVector(Link.ToColumn.X, Link.ToColumn.Y, int32(Link.ToLevel)));+ if (!From || !To)+ {+ continue;+ }+ FVerseBeliefLinkDesc& Desc = OutSource.Links.AddDefaulted_GetRef();+ Desc.From = *From;+ Desc.To = *To;+ Desc.TraversalS = Link.TraversalS;+ Desc.bBidirectional = Link.bBidirectional;+ Desc.Kind = Link.Kind;+ Desc.Gate = Link.Gate;+ Desc.GatePiece = Link.GatePiece;+ }++ // Connectivity of same-level neighbours: a move along the surface must arrive.+ const INavigationDataInterface* NavPtr = &Nav;+ TArray<FNavLocation> Captured = Locations;+ OutSource.AreNeighboursConnected = [NavPtr, Captured, Unsampled, Cell](int32 A, int32 B) {+ if (!Captured.IsValidIndex(A) || !Captured.IsValidIndex(B))+ {+ return false;+ }+ if (Unsampled[A] || Unsampled[B])+ {+ // An opening has no navmesh while the piece stands: a step of at most 60 cm joins it.+ return FMath::Abs(Captured[A].Location.Z - Captured[B].Location.Z) <= 60.f;+ }+ FNavLocation Reached;+ if (!NavPtr->FindMoveAlongSurface(Captured[A], Captured[B].Location, Reached))+ {+ return false;+ }+ return FVector::Dist2D(Reached.Location, Captured[B].Location) <= 0.25f * Cell &&+ FMath::Abs(Reached.Location.Z - Captured[B].Location.Z) <= 60.f;+ };+ return OutSource.Cells.Num() > 0;+}diff --git a/unreal/Verse/Source/VerseBot/Private/Belief/VerseOpponentEstimate.cpp b/unreal/Verse/Source/VerseBot/Private/Belief/VerseOpponentEstimate.cppnew file mode 100644index 0000000000..0b2725e99a--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Belief/VerseOpponentEstimate.cpp@@ -0,0 +1,92 @@+#include "Belief/VerseOpponentEstimate.h"++#include "VerseGameplayTags.h"++void FVerseOpponentEstimate::OnSighting(const FVerseSightPercept& Sight, float NowS)+{+ bDead = false;+ LastSeenYawDeg = Sight.FacingYawDeg;+ LastSeenYawAtS = NowS;+ LastSeenLocation = Sight.PelvisLocation;+ LastSeenVelocity = Sight.Velocity;+ if (Sight.bReloading)+ {+ // The reload animation is visible: the magazine is refilled.+ ShotsSinceReload = 0;+ bHeardReload = true;+ HeardReloadAtS = NowS;+ }+ if (Sight.HeldWeaponId != LastSeenWeapon)+ {+ LastSeenWeapon = Sight.HeldWeaponId;+ ShotsSinceReload = 0;+ }+}++void FVerseOpponentEstimate::OnHeard(const FVerseHeardPercept& Heard, float NowS)+{+ if (Heard.Noise == VerseTags::Noise_Shot)+ {+ ++ShotsSinceReload;+ // A shot after the reload: the fresh magazine is being used up.+ bHeardReload = false;+ }+ else if (Heard.Noise == VerseTags::Noise_Reload)+ {+ ShotsSinceReload = 0;+ bHeardReload = true;+ HeardReloadAtS = NowS;+ }+}++void FVerseOpponentEstimate::OnSeenShot(float NowS)+{+ // A seen bolt is a shot after the reload. Ammo counts only heard shots (every shot is heard).+ bHeardReload = false;+}++void FVerseOpponentEstimate::OnOwnHit(float Damage, float NowS)+{+ DamageSinceFull = FMath::Clamp(DamageSinceFull + FMath::Max(0.f, Damage), 0.f, MaxHealth);+ LastOwnHitAtS = NowS;+}++void FVerseOpponentEstimate::OnOpponentDead()+{+ bDead = true;+}++void FVerseOpponentEstimate::OnOpponentRespawned()+{+ bDead = false;+ DamageSinceFull = 0.f;+ ShotsSinceReload = 0;+ bHeardReload = false;+ LastSeenYawAtS = -1.f;+ LastOwnHitAtS = -1.f;+}++float FVerseOpponentEstimate::EstimatedHealth(float NowS) const+{+ if (bDead)+ {+ return 0.f;+ }+ float Damage = DamageSinceFull;+ if (RegenPerS > 0.f && LastOwnHitAtS >= 0.f)+ {+ const float Regen = FMath::Max(0.f, NowS - LastOwnHitAtS - RegenDelayS) * RegenPerS;+ Damage = FMath::Max(0.f, Damage - Regen);+ }+ return FMath::Max(0.f, MaxHealth - Damage);+}++int32 FVerseOpponentEstimate::EstimatedAmmo() const+{+ return FMath::Max(0, MagazineSize - ShotsSinceReload);+}++float FVerseOpponentEstimate::FacingAgeS(float NowS) const+{+ return LastSeenYawAtS < 0.f ? TNumericLimits<float>::Max() : FMath::Max(0.f, NowS - LastSeenYawAtS);+}diff --git a/unreal/Verse/Source/VerseBot/Private/Belief/VersePieceBelief.cpp b/unreal/Verse/Source/VerseBot/Private/Belief/VersePieceBelief.cppnew file mode 100644index 0000000000..16a2e62bc6--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Belief/VersePieceBelief.cpp@@ -0,0 +1,300 @@+#include "Belief/VersePieceBelief.h"++#include "Bot/VersePerceptTypes.h"+#include "Destruction/VerseDestructionInterfaces.h"+#include "Perception/VersePerceptionModel.h"++namespace+{+ /** Sight is tested to a point this far in front of the piece, so the piece itself does not block it. */+ constexpr double SurfaceStandOffCm = 15.0;+}++void FVersePieceBelief::Initialize(const IVersePieceQuery& Query, const FBox& ArenaBox)+{+ Pieces.Reset();+ SlotOf.Reset();+ Changed.Reset();+ DirtyCover.Reset();+ Cursor = 0;+ TArray<uint16> Indices = Query.GetPiecesInBox(ArenaBox);+ Indices.Sort();+ for (const uint16 Index : Indices)+ {+ if (SlotOf.Contains(Index))+ {+ continue;+ }+ FVerseBelievedPiece& Piece = Pieces.AddDefaulted_GetRef();+ Piece.Index = Index;+ Piece.Material = Query.GetPieceMaterial(Index);+ Piece.Bounds = Query.GetPieceBounds(Index);+ Piece.State = EVersePieceState::Intact;+ SlotOf.Add(Index, Pieces.Num() - 1);+ }+}++void FVersePieceBelief::Initialize(TConstArrayView<FVersePieceLayoutEntry> Layout)+{+ Pieces.Reset();+ SlotOf.Reset();+ Changed.Reset();+ DirtyCover.Reset();+ Cursor = 0;+ TArray<FVersePieceLayoutEntry> Sorted(Layout.GetData(), Layout.Num());+ Sorted.Sort([](const FVersePieceLayoutEntry& A, const FVersePieceLayoutEntry& B) { return A.Index < B.Index; });+ for (const FVersePieceLayoutEntry& Entry : Sorted)+ {+ if (SlotOf.Contains(Entry.Index))+ {+ continue;+ }+ FVerseBelievedPiece& Piece = Pieces.AddDefaulted_GetRef();+ Piece.Index = Entry.Index;+ Piece.Material = Entry.Material;+ Piece.Bounds = Entry.Bounds;+ Piece.State = EVersePieceState::Intact;+ SlotOf.Add(Entry.Index, Pieces.Num() - 1);+ }+}++void FVersePieceBelief::ResetAll()+{+ for (int32 Slot = 0; Slot < Pieces.Num(); ++Slot)+ {+ FVerseBelievedPiece& Piece = Pieces[Slot];+ const bool bWasChanged = Piece.State != EVersePieceState::Intact || Piece.bChangedUnknown;+ Piece.State = EVersePieceState::Intact;+ Piece.bChangedUnknown = false;+ if (bWasChanged)+ {+ MarkChanged(Slot);+ }+ }+}++void FVersePieceBelief::SightPoints(const FBox& Bounds, FVector OutPoints[9])+{+ const FVector Centre = Bounds.GetCenter();+ const FVector Extent = Bounds.GetExtent() * 0.9;+ OutPoints[0] = Centre;+ int32 Out = 1;+ for (int32 Sx = -1; Sx <= 1; Sx += 2)+ {+ for (int32 Sy = -1; Sy <= 1; Sy += 2)+ {+ for (int32 Sz = -1; Sz <= 1; Sz += 2)+ {+ OutPoints[Out++] = Centre + FVector(Extent.X * Sx, Extent.Y * Sy, Extent.Z * Sz);+ }+ }+ }+}++int32 FVersePieceBelief::ObserveSight(const FVector& Eye, const FRotator& View, const IVersePieceQuery& Query,+ const IVersePenetrationQuery& Sight, float NowS, int32 MaxSightTests)+{+ const FVersePerceptionModel::FCone Cone = FVersePerceptionModel::ConeFor(false, VersePerception::DefaultAdsFovDeg);+ int32 Tests = 0;+ int32 Updates = 0;+ const int32 Count = Pieces.Num();+ for (int32 Step = 0; Step < Count && Tests < MaxSightTests; ++Step)+ {+ const int32 Slot = (Cursor + Step) % Count;+ FVerseBelievedPiece& Piece = Pieces[Slot];+ if (!Piece.Bounds.IsValid)+ {+ continue;+ }+ FVector Points[9];+ SightPoints(Piece.Bounds, Points);+ bool bSeen = false;+ for (const FVector& Point : Points)+ {+ if (FVersePerceptionModel::Classify(Eye, View, Cone, Point) != FVersePerceptionModel::EConeZone::Inside)+ {+ continue;+ }+ const FVector ToEye = (Eye - Point).GetSafeNormal();+ const FVector Target = Point + ToEye * SurfaceStandOffCm;+ ++Tests;+ if (Sight.TestSight(Eye, Target))+ {+ bSeen = true;+ break;+ }+ if (Tests >= MaxSightTests)+ {+ break;+ }+ }+ if (Tests >= MaxSightTests && !bSeen)+ {+ Cursor = Slot;+ break;+ }+ if (!bSeen)+ {+ continue;+ }+ // Seen: the bot sees what is there (destruction.md 6.2, no error on state).+ const EVersePieceState Truth = Query.GetPieceState(Piece.Index);+ const FBox Bounds = Query.GetPieceBounds(Piece.Index);+ Piece.LastSeenS = NowS;+ if (Bounds.IsValid)+ {+ Piece.Bounds = Bounds;+ }+ if (Truth != Piece.State || Piece.bChangedUnknown)+ {+ const bool bStateChanged = Truth != Piece.State;+ Piece.State = Truth;+ Piece.bChangedUnknown = false;+ MarkChanged(Slot);+ Updates += bStateChanged ? 1 : 0;+ }+ Cursor = (Slot + 1) % FMath::Max(1, Count);+ }+ return Updates;+}++void FVersePieceBelief::OnHeardFracture(const FVerseHeardPercept& Heard, float NowS)+{+ const double MarkReachCm = FMath::Max(100.0, 2.0 * double(Heard.ErrorSdM) * 100.0);+ for (int32 Slot = 0; Slot < Pieces.Num(); ++Slot)+ {+ FVerseBelievedPiece& Piece = Pieces[Slot];+ if (!Piece.Bounds.IsValid)+ {+ continue;+ }+ const FVector Closest = Piece.Bounds.GetClosestPointTo(Heard.Location);+ const double Horizontal = FVector2D(Closest.X - Heard.Location.X, Closest.Y - Heard.Location.Y).Size();+ if (Horizontal <= MarkReachCm && !Piece.bChangedUnknown)+ {+ Piece.bChangedUnknown = true;+ MarkChanged(Slot);+ }+ }+}++void FVersePieceBelief::OnOwnAction(uint16 PieceIndex, EVersePieceState NewState, float NowS)+{+ const int32 Slot = FindIndex(PieceIndex);+ if (Slot == INDEX_NONE)+ {+ return;+ }+ FVerseBelievedPiece& Piece = Pieces[Slot];+ if (Piece.State != NewState || Piece.bChangedUnknown)+ {+ Piece.State = NewState;+ Piece.bChangedUnknown = false;+ MarkChanged(Slot);+ }+}++int32 FVersePieceBelief::FindIndex(uint16 Piece) const+{+ const int32* Slot = SlotOf.Find(Piece);+ return Slot ? *Slot : INDEX_NONE;+}++void FVersePieceBelief::MarkChanged(int32 Slot)+{+ const uint16 Index = Pieces[Slot].Index;+ Changed.AddUnique(Index);+ for (const TPair<int32, TArray<uint16>>& Cover : CoverDeps)+ {+ if (Cover.Value.Contains(Index))+ {+ DirtyCover.Add(Cover.Key);+ }+ }+}++const FVerseBelievedPiece* FVersePieceBelief::Find(uint16 Piece) const+{+ const int32 Slot = FindIndex(Piece);+ return Slot == INDEX_NONE ? nullptr : &Pieces[Slot];+}++EVersePieceState FVersePieceBelief::GetBelievedState(uint16 Piece) const+{+ const FVerseBelievedPiece* Found = Find(Piece);+ return Found ? Found->State : EVersePieceState::Intact;+}++bool FVersePieceBelief::IsBelievedOpen(int32 Piece) const+{+ if (Piece < 0 || Piece > MAX_uint16)+ {+ return false;+ }+ const EVersePieceState State = GetBelievedState(uint16(Piece));+ return State == EVersePieceState::Breached || State == EVersePieceState::Destroyed;+}++bool FVersePieceBelief::IsBelievedStanding(int32 Piece) const+{+ if (Piece < 0 || Piece > MAX_uint16)+ {+ return true;+ }+ return GetBelievedState(uint16(Piece)) != EVersePieceState::Destroyed;+}++void FVersePieceBelief::RegisterCover(int32 CoverId, TConstArrayView<uint16> DependsOn)+{+ CoverDeps.FindOrAdd(CoverId) = TArray<uint16>(DependsOn.GetData(), DependsOn.Num());+}++void FVersePieceBelief::UnregisterCover(int32 CoverId)+{+ CoverDeps.Remove(CoverId);+ DirtyCover.Remove(CoverId);+}++TArray<int32> FVersePieceBelief::ConsumeDirtyCover()+{+ TArray<int32> Out = DirtyCover.Array();+ Out.Sort();+ DirtyCover.Reset();+ return Out;+}++TArray<uint16> FVersePieceBelief::ConsumeChangedPieces()+{+ TArray<uint16> Out = MoveTemp(Changed);+ Changed.Reset();+ return Out;+}++float FVersePieceBelief::OpaqueDistance(const FVector& Origin, const FVector& Direction, float MaxDistCm) const+{+ const FVector Dir = Direction.GetSafeNormal();+ if (Dir.IsNearlyZero())+ {+ return MaxDistCm;+ }+ const FVector End = Origin + Dir * MaxDistCm;+ float Best = MaxDistCm;+ for (const FVerseBelievedPiece& Piece : Pieces)+ {+ const bool bStops = Piece.Material == EVersePenetrationMaterial::Concrete ||+ Piece.Material == EVersePenetrationMaterial::ArmorSteel;+ if (!bStops || !Piece.Bounds.IsValid || Piece.State == EVersePieceState::Breached ||+ Piece.State == EVersePieceState::Destroyed)+ {+ continue;+ }+ FVector HitLocation;+ FVector HitNormal;+ float HitTime = 0.f;+ if (FMath::LineExtentBoxIntersection(Piece.Bounds, Origin, End, FVector::ZeroVector, HitLocation, HitNormal, HitTime))+ {+ Best = FMath::Min(Best, HitTime * MaxDistCm);+ }+ }+ return Best;+}diff --git a/unreal/Verse/Source/VerseBot/Private/Tests/Belief/Fakes/FakeVerseBeliefWorld.h b/unreal/Verse/Source/VerseBot/Private/Tests/Belief/Fakes/FakeVerseBeliefWorld.hnew file mode 100644index 0000000000..5e558224fc--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tests/Belief/Fakes/FakeVerseBeliefWorld.h@@ -0,0 +1,132 @@+#pragma once++#if WITH_DEV_AUTOMATION_TESTS++#include "CoreMinimal.h"+#include "Destruction/VerseDestructionInterfaces.h"++namespace VerseBotBeliefTests+{+ /** One fake piece: truth state, material, bounds; blocks sight unless Breached or Destroyed. */+ struct FFakePiece+ {+ uint16 Index = 0;+ EVersePieceState State = EVersePieceState::Intact;+ EVersePenetrationMaterial Material = EVersePenetrationMaterial::SheetMetal;+ FBox Bounds = FBox(ForceInit);+ };++ /** An opaque static box (non-destructible architecture). */+ struct FFakeWall+ {+ FBox Box = FBox(ForceInit);+ };++ /**+ * Fake of WP03's IVersePenetrationQuery (sight) and WP06's IVersePieceQuery (piece truth)+ * for the belief tests (work-packages 0.3). Sight is blocked by walls and by pieces that are+ * not Breached or Destroyed. GetPieceState calls are logged so tests can prove the belief reads+ * a piece's truth only when it perceives it (bot.md F1, destruction.md DR6).+ */+ class FFakeVerseBeliefWorld : public IVersePenetrationQuery, public IVersePieceQuery+ {+ public:+ TArray<FFakeWall> Walls;+ TArray<FFakePiece> Pieces;+ mutable int32 SightCalls = 0;+ mutable TArray<uint16> StateReads;++ void AddWall(const FVector& Min, const FVector& Max) { Walls.Add({FBox(Min, Max)}); }++ FFakePiece& AddPiece(uint16 Index, const FVector& Min, const FVector& Max, EVersePenetrationMaterial Material)+ {+ FFakePiece& Piece = Pieces.AddDefaulted_GetRef();+ Piece.Index = Index;+ Piece.Bounds = FBox(Min, Max);+ Piece.Material = Material;+ return Piece;+ }++ const FFakePiece* FindPiece(uint16 Index) const+ {+ return Pieces.FindByPredicate([Index](const FFakePiece& Piece) { return Piece.Index == Index; });+ }++ static bool SegmentHits(const FBox& Box, const FVector& A, const FVector& B)+ {+ FVector HitLocation;+ FVector HitNormal;+ float HitTime = 0.f;+ return FMath::LineExtentBoxIntersection(Box, A, B, FVector::ZeroVector, HitLocation, HitNormal, HitTime);+ }++ /** Geometry only (no call counting): used for neighbour connectivity at build. */+ bool Clear(const FVector& A, const FVector& B) const+ {+ for (const FFakeWall& Wall : Walls)+ {+ if (SegmentHits(Wall.Box, A, B))+ {+ return false;+ }+ }+ for (const FFakePiece& Piece : Pieces)+ {+ if (Piece.State != EVersePieceState::Breached && Piece.State != EVersePieceState::Destroyed &&+ SegmentHits(Piece.Bounds, A, B))+ {+ return false;+ }+ }+ return true;+ }++ // IVersePenetrationQuery+ virtual TArray<FVersePenetrationHit> TraceBolt(const FVector& Origin, const FVector& Dir, float MaxDist, float Power,+ float Damage, uint8 RadiusMm, int32 MaxPieces) const override+ {+ return {};+ }++ virtual bool TestSight(const FVector& Eye, const FVector& Target) const override+ {+ ++SightCalls;+ return Clear(Eye, Target);+ }++ // IVersePieceQuery+ virtual EVersePieceState GetPieceState(uint16 PieceIndex) const override+ {+ StateReads.Add(PieceIndex);+ const FFakePiece* Piece = FindPiece(PieceIndex);+ return Piece ? Piece->State : EVersePieceState::Intact;+ }++ virtual EVersePenetrationMaterial GetPieceMaterial(uint16 PieceIndex) const override+ {+ const FFakePiece* Piece = FindPiece(PieceIndex);+ return Piece ? Piece->Material : EVersePenetrationMaterial::Concrete;+ }++ virtual FBox GetPieceBounds(uint16 PieceIndex) const override+ {+ const FFakePiece* Piece = FindPiece(PieceIndex);+ return Piece ? Piece->Bounds : FBox(ForceInit);+ }++ virtual TArray<uint16> GetPiecesInBox(const FBox& WorldBox) const override+ {+ TArray<uint16> Out;+ for (const FFakePiece& Piece : Pieces)+ {+ if (WorldBox.Intersect(Piece.Bounds))+ {+ Out.Add(Piece.Index);+ }+ }+ return Out;+ }+ };+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseBot/Private/Tests/Belief/VerseBeliefTest.cpp b/unreal/Verse/Source/VerseBot/Private/Tests/Belief/VerseBeliefTest.cppnew file mode 100644index 0000000000..7a7b5e0269--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tests/Belief/VerseBeliefTest.cpp@@ -0,0 +1,1073 @@+#include "Belief/VerseBeliefDebugDraw.h"+#include "Belief/VerseBeliefGrid.h"+#include "Belief/VerseBeliefMap.h"+#include "Belief/VerseBeliefNavSampler.h"+#include "HAL/PlatformTime.h"+#include "Misc/AutomationTest.h"+#include "Noise/VerseAudibilityTable.h"+#include "Perception/VersePerceptionModel.h"+#include "Serialization/MemoryWriter.h"+#include "Tests/Belief/VerseBeliefTestFixture.h"+#include "VerseGameplayTags.h"+#include "VerseRng.h"++#if WITH_DEV_AUTOMATION_TESTS++// Verse.Bot.Belief.*: the belief grid, opponent estimates and piece belief of contracts/bot.md 4+// (WP07.5-7.10) and the acceptance tests A7.3 (F3), A7.4 (tracking), A7.5 (mass), A7.6 (cost) and+// A7.7 (F7 wall_opened_unseen).++#define VERSE_BELIEF_TEST_FLAGS (EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++using namespace VerseBotBeliefTests;++namespace VerseBotBeliefTests+{+ const FVector ObserverFeet = ColumnCentre(25, 5);+ constexpr float ObserverYaw = 90.f;++ double MinActiveMass(const FVerseBeliefGrid& Grid)+ {+ double Min = TNumericLimits<double>::Max();+ for (int32 Cell = 0; Cell < Grid.NumCells(); ++Cell)+ {+ if (Grid.IsActive(Cell))+ {+ Min = FMath::Min(Min, double(Grid.GetMass(Cell)));+ }+ }+ return Min;+ }++ /** A stand-in for WP08's brain: a pure function of the belief and the frame (bot.md B5). */+ FVerseInputFrame NullBrain(const FVerseBeliefMap& Map, const FVersePerceptFrame& Frame)+ {+ FVerseInputFrame Input;+ Input.ServerTimeMs = Frame.ServerTimeMs;+ const FVerseBeliefDerived& Derived = Map.GetDerived();+ const FVector To = Derived.TopCluster.Centre - Frame.Self.Location;+ Input.LookDeltaDeg = FVector2f(float(FRotator::NormalizeAxis(To.Rotation().Yaw - Frame.Self.ViewRotation.Yaw)) * 0.1f,+ Derived.SpreadM * 0.01f);+ Input.Move = FVector2f(float(To.X), float(To.Y)).GetSafeNormal() * Derived.Confidence;+ Input.Buttons = uint32(Derived.State);+ return Input;+ }++ TArray<uint8> InputBytes(const FVerseInputFrame& Input)+ {+ TArray<uint8> Bytes;+ Bytes.Append(reinterpret_cast<const uint8*>(&Input.Move), sizeof(Input.Move));+ Bytes.Append(reinterpret_cast<const uint8*>(&Input.LookDeltaDeg), sizeof(Input.LookDeltaDeg));+ Bytes.Append(reinterpret_cast<const uint8*>(&Input.Buttons), sizeof(Input.Buttons));+ Bytes.Append(reinterpret_cast<const uint8*>(&Input.Pressed), sizeof(Input.Pressed));+ Bytes.Append(reinterpret_cast<const uint8*>(&Input.ServerTimeMs), sizeof(Input.ServerTimeMs));+ return Bytes;+ }++ TArray<uint8> FrameBytes(const FVersePerceptFrame& Frame)+ {+ TArray<uint8> Bytes;+ FMemoryWriter Writer(Bytes);+ FVersePerceptFrame Copy = Frame;+ FVersePerceptFrame::StaticStruct()->SerializeItem(Writer, &Copy, nullptr);+ return Bytes;+ }++ FVerseSightPercept Sighting(const FVector& Pelvis, const FVector& Velocity)+ {+ FVerseSightPercept Sight;+ Sight.PerceptId = 1;+ Sight.PelvisLocation = Pelvis;+ Sight.Velocity = Velocity;+ Sight.VisibleMask = 0xFF;+ return Sight;+ }+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBeliefGridBuildTest, "Verse.Bot.Belief.Grid", VERSE_BELIEF_TEST_FLAGS)++bool FVerseBeliefGridBuildTest::RunTest(const FString& Parameters)+{+ // WP07.5: 1 m columns, 8-neighbour adjacency that respects walls, links, gates.+ FLaneFixture Fixture;+ FVerseBeliefGrid Grid;+ Grid.Build(Fixture.Source);+ TestEqual(TEXT("one cell per column"), Grid.NumCells(), 50 * 40);+ const int32 Open = Grid.FindCell(FIntPoint(10, 10), EVerseArenaLevel::Floor);+ TestEqual(TEXT("open floor: 8 neighbours"), Grid.NumNeighbours(Open), 8);+ const int32 BelowWall = Grid.FindCell(FIntPoint(10, 19), EVerseArenaLevel::Floor);+ const int32 AboveWall = Grid.FindCell(FIntPoint(10, 20), EVerseArenaLevel::Floor);+ TArray<int32> Neighbours;+ Grid.GetNeighbours(BelowWall, Neighbours);+ TestFalse(TEXT("no step through wall A"), Neighbours.Contains(AboveWall));+ const int32 DoorBelow = Grid.FindCell(FIntPoint(24, 19), EVerseArenaLevel::Floor);+ const int32 DoorAbove = Grid.FindCell(FIntPoint(24, 20), EVerseArenaLevel::Floor);+ Grid.GetNeighbours(DoorBelow, Neighbours);+ TestTrue(TEXT("the door connects"), Neighbours.Contains(DoorAbove));+ const TArray<int32> Path = Grid.FindPath(Grid.FindCell(ObserverFeet), Grid.FindCell(ColumnCentre(10, 23)));+ TestTrue(TEXT("a path into the lane exists"), Path.Num() > 0);+ bool bThroughDoor = false;+ for (const int32 Cell : Path)+ {+ const FIntPoint C = Grid.GetCell(Cell).Column;+ bThroughDoor |= C.Y == 20 && (C.X == 24 || C.X == 25);+ }+ TestTrue(TEXT("the path goes through the door"), bThroughDoor);+ TestTrue(TEXT("uniform start sums to 1"), FMath::Abs(Grid.TotalMass() - 1.0) < 1e-6);++ // Links, levels and gates on a small two-level source.+ FVerseBeliefGridSource Small;+ for (int32 Level = 0; Level < 2; ++Level)+ {+ for (int32 X = 0; X < 4; ++X)+ {+ FVerseBeliefCellDesc& Cell = Small.Cells.AddDefaulted_GetRef();+ Cell.Column = FIntPoint(X, 0);+ Cell.Level = EVerseArenaLevel(Level);+ Cell.FloorZ = 400.f * Level;+ if (Level == 1 && X == 3)+ {+ Cell.Gate = EVerseBeliefGate::WhenStanding;+ Cell.GatePiece = 4;+ }+ }+ }+ FVerseBeliefLinkDesc& Stair = Small.Links.AddDefaulted_GetRef();+ Stair.From = 0;+ Stair.To = 4;+ Stair.TraversalS = 2.f;+ FVerseBeliefLinkDesc& Breach = Small.Links.AddDefaulted_GetRef();+ Breach.From = 3;+ Breach.To = 7;+ Breach.Gate = EVerseBeliefGate::WhenOpen;+ Breach.GatePiece = 9;+ FVerseBeliefGrid Two;+ Two.Build(Small);+ TestEqual(TEXT("8 cells on two levels"), Two.NumCells(), 8);+ Two.GetNeighbours(0, Neighbours);+ TestTrue(TEXT("stair link up"), Neighbours.Contains(4));+ Two.GetNeighbours(4, Neighbours);+ TestTrue(TEXT("stair link down"), Neighbours.Contains(0));+ Two.GetNeighbours(3, Neighbours);+ TestFalse(TEXT("closed breach link inactive"), Neighbours.Contains(7));+ TestTrue(TEXT("standing catwalk cell active"), Two.IsActive(7));+ Two.ApplyGates([](int32 Piece) { return Piece == 9; }, [](int32 Piece) { return true; });+ Two.GetNeighbours(3, Neighbours);+ TestTrue(TEXT("opened breach link active"), Neighbours.Contains(7));+ Two.ApplyGates([](int32 Piece) { return Piece == 9; }, [](int32 Piece) { return Piece != 4; });+ TestFalse(TEXT("destroyed catwalk cell inactive"), Two.IsActive(7));+ TestEqual(TEXT("inactive cell holds no mass"), Two.GetMass(7), 0.f);+ TestTrue(TEXT("mass renormalised"), FMath::Abs(Two.TotalMass() - 1.0) < 1e-6);+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBeliefMassTest, "Verse.Bot.Belief.Mass", VERSE_BELIEF_TEST_FLAGS)++bool FVerseBeliefMassTest::RunTest(const FString& Parameters)+{+ // A7.5: after every step the mass sums to 1 within 1e-6 and no cell is exactly 0.+ FLaneFixture Fixture;+ FVerseBeliefGrid Grid;+ Grid.Build(Fixture.Source);+ FVerseRng Rng(2024);+ double WorstSum = 0.0;+ double SmallestMass = TNumericLimits<double>::Max();+ int32 Checked = 0;+ int32 Failures = 0;+ TArray<float> Prior;+ Prior.Init(0.f, Grid.NumCells());+ for (int32 Cell = 0; Cell < Prior.Num(); ++Cell)+ {+ Prior[Cell] = Cell % 7 == 0 ? 3.f : 0.f;+ }+ for (int32 Step = 0; Step < 3000; ++Step)+ {+ const float NowS = Step * 0.1f;+ const int32 Op = Rng.RangeInt(0, 9);+ if (Step == 1500)+ {+ Grid.SetPositionPrior(Prior);+ const TArray<float> Matrix = {0.8f, 0.2f, 0.4f, 0.6f};+ Grid.SetZoneTransitionPrior(2, Matrix);+ }+ Grid.Predict(0.1f, NowS);+ const FVector Eye = ColumnCentre(Rng.RangeInt(0, 49), Rng.RangeInt(0, 39), 165.f);+ Grid.Clear(Eye, [&](int32 Cell) { return Fixture.World.Clear(Eye, Grid.GetCellCentre(Cell) + FVector(0.0, 0.0, 100.0)); }, NowS);+ switch (Op)+ {+ case 0:+ Grid.ApplySighting(ColumnCentre(Rng.RangeInt(0, 49), Rng.RangeInt(0, 39), 95.f), NowS);+ Grid.SetMomentum(FVector(Rng.Range(-450.0, 450.0), Rng.Range(-450.0, 450.0), 0.0), NowS);+ break;+ case 1:+ case 2:+ {+ FVerseHeardPercept Heard;+ Heard.Location = ColumnCentre(Rng.RangeInt(0, 49), Rng.RangeInt(0, 39));+ Heard.ErrorSdM = float(Rng.Range(0.5, 6.0));+ Heard.LevelGuess = EVerseArenaLevel::Floor;+ Grid.ApplyHeard(Heard, NowS);+ break;+ }+ case 3:+ Grid.ApplyWedge(Eye, FVector(Rng.Range(-1.0, 1.0), Rng.Range(-1.0, 1.0), 0.0), float(Rng.Range(500.0, 6000.0)), NowS);+ break;+ case 4:+ if (Rng.Chance(0.1))+ {+ Grid.ApplyOpponentDead();+ Grid.Normalise();+ TestEqual(TEXT("dead: no mass"), Grid.TotalMass(), 0.0);+ const TArray<FVector> Spawns = {ColumnCentre(5, 35), ColumnCentre(45, 35), ColumnCentre(5, 2)};+ Grid.ApplySpawnPrior(Spawns, NowS);+ }+ break;+ default:+ break;+ }+ Grid.Normalise();+ const double Sum = Grid.TotalMass();+ const double Min = MinActiveMass(Grid);+ WorstSum = FMath::Max(WorstSum, FMath::Abs(Sum - 1.0));+ SmallestMass = FMath::Min(SmallestMass, Min);+ Failures += (FMath::Abs(Sum - 1.0) > 1e-6 || !(Min > 0.0)) ? 1 : 0;+ ++Checked;+ }+ TestEqual(TEXT("A7.5 every step: sum 1 within 1e-6, no cell at 0"), Failures, 0);+ SaveProof(TEXT("7.6"), TEXT("mass.json"),+ FString::Printf(TEXT("{\n \"test\": \"A7.5 mass\",\n \"steps\": %d,\n \"worstAbsSumError\": %.3e,\n")+ TEXT(" \"smallestCellMass\": %.3e,\n \"failures\": %d,\n \"pass\": %s\n}\n"),+ Checked, WorstSum, SmallestMass, Failures, Failures == 0 ? TEXT("true") : TEXT("false")));+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBeliefRulesTest, "Verse.Bot.Belief.Rules", VERSE_BELIEF_TEST_FLAGS)++bool FVerseBeliefRulesTest::RunTest(const FString& Parameters)+{+ // WP07.6 / 7.7: each update rule and the derived values.+ FLaneFixture Fixture;+ FVerseBeliefGrid Grid;+ Grid.Build(Fixture.Source);++ FVerseBeliefDerived Derived = Grid.ComputeDerived(0.f, false);+ TestTrue(TEXT("uniform: Lost"), Derived.State == EVerseBeliefState::Lost);+ TestTrue(TEXT("uniform: wide spread"), Derived.SpreadM > 10.f);++ const FVector Seen = ColumnCentre(10, 10, 95.f);+ Grid.ApplySighting(Seen, 1.f);+ Grid.Normalise();+ Derived = Grid.ComputeDerived(1.f, true);+ TestTrue(TEXT("sighting: Known"), Derived.State == EVerseBeliefState::Known);+ TestTrue(TEXT("sighting: TopCluster at the sighting"), FVector::Dist2D(Derived.TopCluster.Centre, Seen) < 50.0);+ TestTrue(TEXT("sighting: confidence > 0.95"), Derived.Confidence > 0.95f);+ TestTrue(TEXT("sighting: support seen, age 0"), Derived.SupportKind == EVerseBeliefSupport::Seen && Derived.SupportAgeS < 1e-3f);+ TestTrue(TEXT("sighting: spread under 1 m"), Derived.SpreadM < 1.f);+ Derived = Grid.ComputeDerived(1.f, false);+ TestTrue(TEXT("sighting without sight now: Tracked"), Derived.State == EVerseBeliefState::Tracked);++ // Predict spreads mass but keeps the cluster; support ages.+ for (int32 Step = 0; Step < 10; ++Step)+ {+ Grid.Predict(0.1f, 1.f + 0.1f * Step);+ Grid.Normalise();+ }+ Derived = Grid.ComputeDerived(2.f, false);+ TestTrue(TEXT("predict: spread grows"), Derived.SpreadM > 1.f);+ TestTrue(TEXT("predict: support age 1 s"), FMath::Abs(Derived.SupportAgeS - 1.f) < 1e-3f);++ // Clear: a visible cell loses 95 % of its mass at short range.+ const int32 Centre = Grid.FindCell(Seen);+ const float Before = Grid.GetMass(Centre);+ Grid.Clear(ColumnCentre(10, 5, 165.f), [Centre](int32 Cell) { return Cell == Centre; }, 2.f);+ TestTrue(TEXT("clear multiplies by 1 - 0.95"), FMath::IsNearlyEqual(Grid.GetMass(Centre), Before * 0.05f, Before * 1e-4f));+ TestEqual(TEXT("clear sets LastCleared"), Grid.GetLastClearedS(Centre), 2.f);+ Grid.Normalise();++ // Heard: mass moves toward the heard point on the guessed level.+ Grid.ResetUniform();+ FVerseHeardPercept Heard;+ Heard.Location = ColumnCentre(40, 10);+ Heard.ErrorSdM = 2.f;+ Heard.LevelGuess = EVerseArenaLevel::Floor;+ Heard.Noise = VerseTags::Noise_Shot;+ Grid.ApplyHeard(Heard, 3.f);+ Grid.Normalise();+ Derived = Grid.ComputeDerived(3.f, false);+ TestTrue(TEXT("heard: cluster near the heard point"), FVector::Dist2D(Derived.TopCluster.Centre, Heard.Location) < 150.0);+ TestTrue(TEXT("heard: support heard"), Derived.SupportKind == EVerseBeliefSupport::Heard);++ // Wedge: mass along the back-traced bolt line, cut at the opaque distance.+ Grid.ResetUniform();+ Grid.ApplyWedge(ColumnCentre(5, 5), FVector(1.0, 0.0, 0.0), 1500.f, 4.f);+ Grid.Normalise();+ const float OnLine = Grid.GetMass(Grid.FindCell(FIntPoint(15, 5), EVerseArenaLevel::Floor));+ const float OffLine = Grid.GetMass(Grid.FindCell(FIntPoint(15, 15), EVerseArenaLevel::Floor));+ const float Beyond = Grid.GetMass(Grid.FindCell(FIntPoint(30, 5), EVerseArenaLevel::Floor));+ TestTrue(TEXT("wedge: on the line > off the line"), OnLine > 20.f * OffLine);+ TestTrue(TEXT("wedge: cut at the first opaque piece"), OnLine > 20.f * Beyond);++ // Kill feed: dead, then the spawn prior over the top 3 points 0.5 / 0.3 / 0.2.+ Grid.ApplyOpponentDead();+ Grid.Normalise();+ TestTrue(TEXT("dead state"), Grid.ComputeDerived(5.f, false).State == EVerseBeliefState::Dead);+ const TArray<FVector> Spawns = {ColumnCentre(5, 35), ColumnCentre(45, 35), ColumnCentre(5, 2), ColumnCentre(45, 2)};+ Grid.ApplySpawnPrior(Spawns, 6.f);+ Grid.Normalise();+ auto MassNear = [&Grid](const FVector& Point) {+ double Sum = 0.0;+ for (int32 Cell = 0; Cell < Grid.NumCells(); ++Cell)+ {+ Sum += FVector::Dist2D(Grid.GetCellCentre(Cell), Point) <= 500.0 ? Grid.GetMass(Cell) : 0.f;+ }+ return Sum;+ };+ TestTrue(TEXT("spawn 1 about 0.5"), FMath::Abs(MassNear(Spawns[0]) - 0.5) < 0.03);+ TestTrue(TEXT("spawn 2 about 0.3"), FMath::Abs(MassNear(Spawns[1]) - 0.3) < 0.03);+ TestTrue(TEXT("spawn 3 about 0.2"), FMath::Abs(MassNear(Spawns[2]) - 0.2) < 0.03);+ TestTrue(TEXT("spawn 4 gets only the prior"), MassNear(Spawns[3]) < 0.01);+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBeliefMapTest, "Verse.Bot.Belief.Map", VERSE_BELIEF_TEST_FLAGS)++bool FVerseBeliefMapTest::RunTest(const FString& Parameters)+{+ // The map: 10 Hz steps, at once on a positive percept; estimates; spawn ranking; own death.+ FLaneFixture Fixture;+ FVerseBeliefMap Map;+ Map.Initialize(Fixture.Source, Fixture.Config(), Fixture.BeliefWorld());+ const FVerseBeliefWorld World = Fixture.BeliefWorld();+ uint32 NowMs = 1000;+ int32 Steps = 0;+ for (int32 Tick = 0; Tick < 60; ++Tick)+ {+ NowMs += 17;+ Steps += Map.ApplyFrame(SelfFrame(NowMs, ObserverFeet, ObserverYaw), World) ? 1 : 0;+ }+ TestTrue(TEXT("about 10 steps per second"), Steps >= 9 && Steps <= 11);+ FVersePerceptFrame Frame = SelfFrame(NowMs + 1, ObserverFeet, ObserverYaw);+ Frame.Sightings.Add(Sighting(ColumnCentre(25, 15, 95.f), FVector::ZeroVector));+ TestTrue(TEXT("a sighting steps at once"), Map.ApplyFrame(Frame, World));+ TestTrue(TEXT("Known after a sighting"), Map.GetDerived().State == EVerseBeliefState::Known);++ // Cleared view: the visible hall in front of the observer holds almost nothing after a while.+ Map.OnOwnDeath(2.f);+ for (int32 Tick = 0; Tick < 120; ++Tick)+ {+ NowMs += 17;+ Map.ApplyFrame(SelfFrame(NowMs, ObserverFeet, ObserverYaw), World);+ }+ double Visible = 0.0;+ double Lane = 0.0;+ for (int32 Cell = 0; Cell < Map.GetGrid().NumCells(); ++Cell)+ {+ const FIntPoint C = Map.GetGrid().GetCell(Cell).Column;+ if (C.Y >= 8 && C.Y <= 18 && C.X >= 20 && C.X <= 30)+ {+ Visible += Map.GetGrid().GetMass(Cell);+ }+ if (C.Y >= 21 && C.Y <= 25 && (C.X < 20 || C.X > 30))+ {+ Lane += Map.GetGrid().GetMass(Cell);+ }+ }+ TestTrue(TEXT("visible area cleared"), Visible < 0.02);+ TestTrue(TEXT("hidden lane keeps mass"), Lane > 0.1);++ // Estimates: shots heard lower the ammo estimate; a heard reload refills; hit markers lower health.+ FVersePerceptFrame Shots = SelfFrame(NowMs += 200, ObserverFeet, ObserverYaw);+ for (int32 Shot = 0; Shot < 12; ++Shot)+ {+ FVerseHeardPercept& Heard = Shots.Heard.AddDefaulted_GetRef();+ Heard.Noise = VerseTags::Noise_Shot;+ Heard.Location = ColumnCentre(10, 23);+ Heard.ErrorSdM = 2.f;+ }+ FVerseHudEvent& Marker = Shots.Hud.AddDefaulted_GetRef();+ Marker.Kind = EVerseHudEventKind::HitMarker;+ Marker.KillerId = SelfId;+ Marker.VictimId = OpponentId;+ Map.ApplyFrame(Shots, World);+ TestEqual(TEXT("ammo estimate after 12 shots"), Map.GetOpponent().EstimatedAmmo(), 18);+ TestEqual(TEXT("health estimate after one hit"), Map.GetOpponent().EstimatedHealth(NowMs / 1000.f), 75.f);+ FVersePerceptFrame Reload = SelfFrame(NowMs += 200, ObserverFeet, ObserverYaw);+ FVerseHeardPercept& Heard = Reload.Heard.AddDefaulted_GetRef();+ Heard.Noise = VerseTags::Noise_Reload;+ Heard.Location = ColumnCentre(10, 23);+ Heard.ErrorSdM = 2.f;+ Map.ApplyFrame(Reload, World);+ TestEqual(TEXT("heard reload refills the estimate"), Map.GetOpponent().EstimatedAmmo(), 30);+ TestTrue(TEXT("heard reload flag for flank and finisher queries"), Map.GetOpponent().bHeardReload);++ // Spawn rule: out of sight first, then farthest.+ const TArray<FVector> Ranked = Map.RankSpawnPoints(ObserverFeet + FVector(0.0, 0.0, 165.0), &Fixture.World);+ TestEqual(TEXT("hidden far spawn first"), Ranked[0], ColumnCentre(47, 37));+ TestEqual(TEXT("hidden spawn second"), Ranked[1], ColumnCentre(5, 35));++ // Kill feed through the map: opponent dead, then respawned.+ FVersePerceptFrame Kill = SelfFrame(NowMs += 200, ObserverFeet, ObserverYaw);+ FVerseHudEvent& Dead = Kill.Hud.AddDefaulted_GetRef();+ Dead.Kind = EVerseHudEventKind::Kill;+ Dead.KillerId = SelfId;+ Dead.VictimId = OpponentId;+ Map.ApplyFrame(Kill, World);+ TestTrue(TEXT("opponent dead"), Map.GetDerived().State == EVerseBeliefState::Dead);+ FVersePerceptFrame Respawn = SelfFrame(NowMs += 3000, ObserverFeet, ObserverYaw);+ FVerseHudEvent& Back = Respawn.Hud.AddDefaulted_GetRef();+ Back.Kind = EVerseHudEventKind::OpponentRespawned;+ Back.VictimId = OpponentId;+ Map.ApplyFrame(Respawn, World);+ TestTrue(TEXT("respawn: belief at the best hidden spawn"),+ FVector::Dist2D(Map.GetDerived().TopCluster.Centre, ColumnCentre(47, 37)) < 300.0);+ TestEqual(TEXT("respawn resets the health estimate"), Map.GetOpponent().EstimatedHealth(NowMs / 1000.f), 100.f);+ return true;+}++namespace VerseBotBeliefTests+{+ /** How the hidden opponent moves after it leaves the observer's view (A7.4 and its variants). */+ enum class ETrackingMove : uint8+ {+ /** Runs into the lane and along it (the A7.4 case). */+ Straight,+ /** Stops 0.5 s after it was last seen. */+ Stop,+ /** Turns back 1 s after it was last seen. */+ TurnBack+ };++ struct FTrackingResult+ {+ double ContainRate = 0.0;+ double MeanErrorM = 0.0;+ double MedianErrorM = 0.0;+ };++ /**+ * Trials of a sighting at the lane door, then hidden movement at 4.5 m/s for 3 s: the share in+ * which the TopCluster (3 m disc) contains the true position. Whenever the truth is in the+ * observer's cone with line of sight it is sighted again, as the perception service would.+ */+ FTrackingResult RunTrackingTrials(const FLaneFixture& Fixture, ETrackingMove Move, const FVerseBeliefTuning& Tuning,+ int32 Trials, bool bSaveShots)+ {+ const FVerseBeliefWorld World = Fixture.BeliefWorld();+ const FVector Eye = ObserverFeet + FVector(0.0, 0.0, 165.0);+ const FVersePerceptionModel::FCone Cone = FVersePerceptionModel::ConeFor(false, 70.f);+ const FRotator View(0.f, ObserverYaw, 0.f);+ int32 Hits = 0;+ double SumError = 0.0;+ TArray<double> Errors;+ for (int32 Trial = 0; Trial < Trials; ++Trial)+ {+ FVerseRng Rng(uint64(Trial) + 1);+ FVerseBeliefMap Map;+ Map.Initialize(Fixture.Source, Fixture.Config(), World, Tuning);+ const double Side = Rng.Chance(0.5) ? 1.0 : -1.0;+ const double LaneY = 2300.0 + Rng.Range(-150.0, 250.0);+ FVector Truth(2500.0 + Rng.Range(-80.0, 80.0), 2060.0, 95.0);+ const FVector Waypoints[2] = {FVector(2500.0 + Side * 150.0, LaneY, 95.0), FVector(2500.0 + Side * 3000.0, LaneY, 95.0)};+ const FVector BackTarget(2500.0 - Side * 3000.0, LaneY, 95.0);+ int32 Waypoint = 0;+ uint32 NowMs = 1000;+ double HiddenS = 0.0;+ bool bTurned = false;+ bool bFirst = true;+ const bool bShots = bSaveShots && Trial == 0;+ double NextShotS = 0.0;+ for (int32 Tick = 0; Tick < 600 && HiddenS < 3.0; ++Tick)+ {+ FVector Velocity = FVector::ZeroVector;+ if (!bFirst)+ {+ if (Waypoint == 0 && FVector::Dist2D(Truth, Waypoints[0]) < 50.0)+ {+ Waypoint = 1;+ }+ bTurned |= Move == ETrackingMove::TurnBack && HiddenS > 1.0;+ const bool bStopped = Move == ETrackingMove::Stop && HiddenS > 0.5;+ const FVector Goal = bTurned ? BackTarget : Waypoints[Waypoint];+ Velocity = bStopped ? FVector::ZeroVector : (Goal - Truth).GetSafeNormal2D() * 450.0;+ Truth += Velocity * (1.0 / 60.0);+ NowMs += 17;+ }+ else+ {+ Velocity = (Waypoints[0] - Truth).GetSafeNormal2D() * 450.0;+ }+ FVersePerceptFrame Frame = SelfFrame(NowMs, ObserverFeet, ObserverYaw);+ bool bVisible = bFirst;+ for (const double Height : {75.0, 0.0})+ {+ const FVector Point = Truth + FVector(0.0, 0.0, Height);+ bVisible |= FVersePerceptionModel::Classify(Eye, View, Cone, Point) == FVersePerceptionModel::EConeZone::Inside &&+ Fixture.World.Clear(Eye, Point);+ }+ if (bVisible)+ {+ Frame.Sightings.Add(Sighting(Truth, Velocity));+ HiddenS = 0.0;+ }+ else+ {+ HiddenS += 1.0 / 60.0;+ }+ Map.ApplyFrame(Frame, World);+ if (bShots)+ {+ const double SinceSighting = (NowMs - 1000) / 1000.0;+ if (SinceSighting >= NextShotS)+ {+ const TCHAR* Shot = NextShotS == 0.0 ? TEXT("heatmap_sighting.png")+ : (NextShotS == 1.0 ? TEXT("heatmap_plus1s.png") : TEXT("heatmap_plus3s.png"));+ NextShotS = NextShotS == 0.0 ? 1.0 : (NextShotS == 1.0 ? 3.0 : 1e9);+ const FVector Marks[1] = {Truth};+ FVerseBeliefDebugDraw::SavePng(ProofDir(TEXT("7.10")) / Shot, Map.GetGrid(), Map.GetDerived(),+ EVerseArenaLevel::Floor, 12, Marks);+ }+ }+ bFirst = false;+ }+ if (bShots)+ {+ const FVector Marks[1] = {Truth};+ FVerseBeliefDebugDraw::SavePng(ProofDir(TEXT("7.10")) / TEXT("heatmap_hidden3s.png"), Map.GetGrid(), Map.GetDerived(),+ EVerseArenaLevel::Floor, 12, Marks);+ }+ const double Error = FVector::Dist2D(Map.GetDerived().TopCluster.Centre, Truth);+ Errors.Add(Error);+ SumError += Error;+ Hits += Error <= Map.GetGrid().GetTuning().ClusterRadiusCm ? 1 : 0;+ }+ Errors.Sort();+ FTrackingResult Result;+ Result.ContainRate = Trials > 0 ? double(Hits) / Trials : 0.0;+ Result.MeanErrorM = Trials > 0 ? SumError / Trials / 100.0 : 0.0;+ Result.MedianErrorM = Trials > 0 ? Errors[Trials / 2] / 100.0 : 0.0;+ return Result;+ }+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBeliefTrackingTest, "Verse.Bot.Belief.Tracking", VERSE_BELIEF_TEST_FLAGS)++bool FVerseBeliefTrackingTest::RunTest(const FString& Parameters)+{+ // A7.4: a sighting at the lane door, then 3 s hidden movement at 4.5 m/s: the TopCluster+ // contains the true position in at least 70 % of 200 trials. The variants (the opponent stops+ // or turns back after the last sighting) and the same trials under the bot.md 4.2 rules alone+ // (no momentum term) are reported for the contract-change review; they are not gated.+ FLaneFixture Fixture;+ const FVerseBeliefTuning WithMomentum = FVerseBeliefTuning();+ FVerseBeliefTuning ContractOnly;+ ContractOnly.MomentumMaxFraction = 0.f;++ const FTrackingResult Straight = RunTrackingTrials(Fixture, ETrackingMove::Straight, WithMomentum, 200, true);+ const FTrackingResult StraightContract = RunTrackingTrials(Fixture, ETrackingMove::Straight, ContractOnly, 200, false);+ const FTrackingResult Stop = RunTrackingTrials(Fixture, ETrackingMove::Stop, WithMomentum, 100, false);+ const FTrackingResult StopContract = RunTrackingTrials(Fixture, ETrackingMove::Stop, ContractOnly, 100, false);+ const FTrackingResult Turn = RunTrackingTrials(Fixture, ETrackingMove::TurnBack, WithMomentum, 100, false);+ const FTrackingResult TurnContract = RunTrackingTrials(Fixture, ETrackingMove::TurnBack, ContractOnly, 100, false);++ AddInfo(FString::Printf(TEXT("contain rate with momentum / contract rules only: straight %.1f / %.1f %%, stop %.1f / %.1f %%, turn back %.1f / %.1f %%"),+ Straight.ContainRate * 100.0, StraightContract.ContainRate * 100.0, Stop.ContainRate * 100.0, StopContract.ContainRate * 100.0,+ Turn.ContainRate * 100.0, TurnContract.ContainRate * 100.0));+ TestTrue(FString::Printf(TEXT("A7.4 TopCluster contains the truth in %.1f %% of trials (>= 70 %%)"), Straight.ContainRate * 100.0),+ Straight.ContainRate >= 0.70);+ SaveProof(TEXT("7.6"), TEXT("tracking.json"),+ FString::Printf(TEXT("{\n \"test\": \"A7.4 belief tracking\",\n \"trials\": 200,\n \"hidden_s\": 3.0,\n")+ TEXT(" \"speed_m_s\": 4.5,\n \"containRate\": %.4f,\n \"meanErrorM\": %.3f,\n \"medianErrorM\": %.3f,\n")+ TEXT(" \"momentumTermIsAContractChangeProposal\": true,\n")+ TEXT(" \"containRateContractRulesOnly\": %.4f,\n")+ TEXT(" \"variants\": {\"stopAfter0_5s\": {\"trials\": 100, \"withMomentum\": %.4f, \"contractRulesOnly\": %.4f},\n")+ TEXT(" \"turnBackAfter1s\": {\"trials\": 100, \"withMomentum\": %.4f, \"contractRulesOnly\": %.4f}},\n")+ TEXT(" \"pass\": %s\n}\n"),+ Straight.ContainRate, Straight.MeanErrorM, Straight.MedianErrorM, StraightContract.ContainRate, Stop.ContainRate,+ StopContract.ContainRate, Turn.ContainRate, TurnContract.ContainRate, Straight.ContainRate >= 0.70 ? TEXT("true") : TEXT("false")));+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBeliefPlateauTest, "Verse.Bot.Belief.Plateau", VERSE_BELIEF_TEST_FLAGS)++bool FVerseBeliefPlateauTest::RunTest(const FString& Parameters)+{+ // bot.md 4.3: TopCluster is the 3 m disc with the most mass anywhere. A broad heard percept+ // (sd 14 m) makes a plateau of far more than a few hundred cells within a factor of 2 of the+ // peak; the best disc lies in the high cell-index region and must still be found there.+ FLaneFixture Fixture;+ FVerseBeliefGrid Grid;+ Grid.Build(Fixture.Source);+ Grid.ResetUniform();+ FVerseHeardPercept Heard;+ Heard.Location = ColumnCentre(38, 14);+ Heard.ErrorSdM = 14.f;+ Heard.LevelGuess = EVerseArenaLevel::Floor;+ Heard.Noise = VerseTags::Noise_Shot;+ Grid.ApplyHeard(Heard, 1.f);+ Grid.Normalise();+ int32 Plateau = 0;+ float Peak = 0.f;+ for (int32 Cell = 0; Cell < Grid.NumCells(); ++Cell)+ {+ Peak = FMath::Max(Peak, Grid.GetMass(Cell));+ }+ for (int32 Cell = 0; Cell < Grid.NumCells(); ++Cell)+ {+ Plateau += Grid.GetMass(Cell) >= 0.5f * Peak ? 1 : 0;+ }+ TestTrue(FString::Printf(TEXT("plateau of %d cells within 2x of the peak (> 384)"), Plateau), Plateau > 384);+ const FVerseBeliefDerived Derived = Grid.ComputeDerived(1.f, false);+ // Brute force: the disc sum of every active cell.+ double BestMass = -1.0;+ int32 BestCell = INDEX_NONE;+ for (int32 Cell = 0; Cell < Grid.NumCells(); ++Cell)+ {+ if (!Grid.IsActive(Cell))+ {+ continue;+ }+ double Mass = 0.0;+ for (int32 Other = 0; Other < Grid.NumCells(); ++Other)+ {+ if (Grid.IsActive(Other) && FVector::DistSquared2D(Grid.GetCellCentre(Cell), Grid.GetCellCentre(Other)) <= 300.0 * 300.0 + 1.0)+ {+ Mass += Grid.GetMass(Other);+ }+ }+ if (Mass > BestMass + 1e-9)+ {+ BestMass = Mass;+ BestCell = Cell;+ }+ }+ TestTrue(TEXT("TopCluster disc holds the most mass (brute force)"), FMath::Abs(Derived.TopCluster.Mass - BestMass) <= 1e-5);+ TestTrue(TEXT("TopCluster in the high-index region near the heard point"),+ FVector::Dist2D(Derived.TopCluster.Centre, Heard.Location) < 200.0 && Grid.GetCell(Derived.TopCluster.CentreCell).Column.X >= 33);+ AddInfo(FString::Printf(TEXT("plateau %d cells, best disc mass %.5f (brute force cell %d, grid cell %d)"), Plateau, BestMass, BestCell,+ Derived.TopCluster.CentreCell));+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBeliefF3Test, "Verse.Bot.Belief.F3", VERSE_BELIEF_TEST_FLAGS)++bool FVerseBeliefF3Test::RunTest(const FString& Parameters)+{+ // A7.3 / F3 counterfactual invariance: a silent, still opponent at hidden spot A vs B. For 20+ // seeds the percept frames, the belief and the (null) brain's input frames are bit-identical up+ // to the first tick at which the percept streams differ (the opponent fires at tick 300).+ FLaneFixture Fixture;+ UVerseAudibilityTable* Audibility = NewObject<UVerseAudibilityTable>();+ Audibility->AddToRoot();+ const FVerseBeliefWorld BeliefWorld = Fixture.BeliefWorld();+ FVersePerceptionWorld PerceptionWorld;+ const FFakeVerseBeliefWorld* Geometry = &Fixture.World;+ PerceptionWorld.TestSight = [Geometry](const FVector& A, const FVector& B) { return Geometry->Clear(A, B); };+ PerceptionWorld.Audibility = Audibility;++ constexpr int32 Seeds = 20;+ constexpr int32 Ticks = 420;+ constexpr int32 FireTick = 300;+ int32 Passed = 0;+ FString Detail;+ for (int32 Seed = 0; Seed < Seeds; ++Seed)+ {+ struct FRun+ {+ TArray<TArray<uint8>> Frames;+ TArray<TArray<uint8>> Inputs;+ TArray<uint32> Mass;+ };+ auto Run = [&](const FVector& Spot) {+ FRun Out;+ FVersePerceptionModel Model;+ FVersePerceptionProfile Profile;+ Profile.Seed = 1000 + Seed;+ Model.AddObserver(SelfId, Profile);+ FVerseBeliefMap Map;+ Map.Initialize(Fixture.Source, Fixture.Config(), BeliefWorld);+ FVersePerceptionBody Target;+ Target.PlayerId = OpponentId;+ Target.Pelvis = Spot;+ Target.SetSamplePointsFromStance();+ const FVersePerceptionBody Bodies[1] = {Target};+ FVerseRng Sweep(uint64(Seed) * 7 + 3);+ const float StartYaw = float(Sweep.Range(0.0, 360.0));+ uint32 NowMs = 1000;+ for (int32 Tick = 0; Tick < Ticks; ++Tick)+ {+ NowMs += 17;+ if (Tick == FireTick)+ {+ FVerseNoiseEvent Shot;+ Shot.Noise = VerseTags::Noise_Shot;+ Shot.SourceId = OpponentId;+ Shot.Location = Spot;+ Shot.ServerTime = NowMs / 1000.f;+ Model.OnNoise(Shot);+ }+ FVersePerceptionObserverInput Input;+ Input.Self = SelfFrame(NowMs, ObserverFeet, StartYaw + Tick * 0.75f).Self;+ const FVersePerceptFrame Frame = Model.BuildFrame(SelfId, Input, Bodies, PerceptionWorld, NowMs, 1.f / 60.f);+ Map.ApplyFrame(Frame, BeliefWorld);+ Out.Frames.Add(FrameBytes(Frame));+ Out.Inputs.Add(InputBytes(NullBrain(Map, Frame)));+ Out.Mass.Add(Map.GetGrid().HashMass());+ }+ return Out;+ };+ const FRun A = Run(ColumnCentre(10, 23, 95.f));+ const FRun B = Run(ColumnCentre(40, 23, 95.f));+ int32 FirstPerceptDiff = Ticks;+ int32 FirstInputDiff = Ticks;+ int32 FirstMassDiff = Ticks;+ for (int32 Tick = 0; Tick < Ticks; ++Tick)+ {+ if (FirstPerceptDiff == Ticks && A.Frames[Tick] != B.Frames[Tick])+ {+ FirstPerceptDiff = Tick;+ }+ if (FirstInputDiff == Ticks && A.Inputs[Tick] != B.Inputs[Tick])+ {+ FirstInputDiff = Tick;+ }+ if (FirstMassDiff == Ticks && A.Mass[Tick] != B.Mass[Tick])+ {+ FirstMassDiff = Tick;+ }+ }+ const bool bOk = FirstPerceptDiff == FireTick && FirstInputDiff >= FirstPerceptDiff && FirstMassDiff >= FirstPerceptDiff;+ Passed += bOk ? 1 : 0;+ Detail += FString::Printf(TEXT("%s {\"seed\": %d, \"firstPerceptDiff\": %d, \"firstInputDiff\": %d, \"firstMassDiff\": %d}"),+ Seed == 0 ? TEXT("") : TEXT(",\n"), Seed, FirstPerceptDiff, FirstInputDiff, FirstMassDiff);+ if (!bOk)+ {+ AddError(FString::Printf(TEXT("seed %d: percept diff at %d, input diff at %d, mass diff at %d"), Seed,+ FirstPerceptDiff, FirstInputDiff, FirstMassDiff));+ }+ }+ Audibility->RemoveFromRoot();+ TestEqual(TEXT("A7.3 all 20 seeds invariant up to the first differing percept"), Passed, Seeds);+ SaveProof(TEXT("7.9"), TEXT("f3_counterfactual.json"),+ FString::Printf(TEXT("{\n \"test\": \"F3 counterfactual invariance (A7.3)\",\n \"seeds\": %d,\n \"ticks\": %d,\n")+ TEXT(" \"fireTick\": %d,\n \"passed\": %d,\n \"runs\": [\n%s\n ],\n \"pass\": %s\n}\n"),+ Seeds, Ticks, FireTick, Passed, *Detail, Passed == Seeds ? TEXT("true") : TEXT("false")));+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBeliefReplayTest, "Verse.Bot.Belief.Replay", VERSE_BELIEF_TEST_FLAGS)++bool FVerseBeliefReplayTest::RunTest(const FString& Parameters)+{+ // B5 for the belief layer: the same frame stream twice gives bit-identical mass every step.+ FLaneFixture Fixture;+ const FVerseBeliefWorld World = Fixture.BeliefWorld();+ TArray<FVersePerceptFrame> Stream;+ FVerseRng Rng(77);+ uint32 NowMs = 1000;+ for (int32 Tick = 0; Tick < 900; ++Tick)+ {+ NowMs += 17;+ FVersePerceptFrame Frame = SelfFrame(NowMs, ObserverFeet, float(Tick % 360));+ const int32 Roll = Rng.RangeInt(0, 99);+ if (Roll < 3)+ {+ Frame.Sightings.Add(Sighting(ColumnCentre(Rng.RangeInt(0, 49), Rng.RangeInt(0, 39), 95.f),+ FVector(Rng.Range(-400.0, 400.0), Rng.Range(-400.0, 400.0), 0.0)));+ }+ else if (Roll < 8)+ {+ FVerseHeardPercept& Heard = Frame.Heard.AddDefaulted_GetRef();+ Heard.Noise = VerseTags::Noise_Footstep_Run;+ Heard.Location = ColumnCentre(Rng.RangeInt(0, 49), Rng.RangeInt(0, 39));+ Heard.ErrorSdM = float(Rng.Range(1.0, 4.0));+ }+ Stream.Add(Frame);+ }+ auto Play = [&]() {+ TArray<uint32> Hashes;+ FVerseBeliefMap Map;+ Map.Initialize(Fixture.Source, Fixture.Config(), World);+ for (const FVersePerceptFrame& Frame : Stream)+ {+ Map.ApplyFrame(Frame, World);+ Hashes.Add(Map.GetGrid().HashMass());+ }+ return Hashes;+ };+ TestTrue(TEXT("replay: identical mass every step"), Play() == Play());+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBeliefPiecesTest, "Verse.Bot.Belief.Pieces", VERSE_BELIEF_TEST_FLAGS)++bool FVerseBeliefPiecesTest::RunTest(const FString& Parameters)+{+ // WP07.8: piece belief from sight, sound and own actions only; cover dependency sets.+ FFakeVerseBeliefWorld World;+ World.AddPiece(1, FVector(1000.0, -200.0, 0.0), FVector(1020.0, 200.0, 300.0), EVersePenetrationMaterial::SheetMetal);+ World.AddPiece(2, FVector(-1020.0, -200.0, 0.0), FVector(-1000.0, 200.0, 300.0), EVersePenetrationMaterial::ContainerWall);+ World.AddPiece(3, FVector(2000.0, -200.0, 0.0), FVector(2050.0, 200.0, 300.0), EVersePenetrationMaterial::Concrete);+ FVersePieceBelief Belief;+ Belief.Initialize(World, FBox(FVector(-5000.0), FVector(5000.0)));+ TestEqual(TEXT("layout of 3 pieces"), Belief.Num(), 3);+ TestEqual(TEXT("layout read no state"), World.StateReads.Num(), 0);++ // Truth changes everywhere; the bot looks at +X and sees piece 1 only (3 is behind 1).+ World.Pieces[0].State = EVersePieceState::Holed;+ World.Pieces[1].State = EVersePieceState::Breached;+ World.Pieces[2].State = EVersePieceState::Damaged;+ Belief.RegisterCover(10, TArray<uint16>{2});+ Belief.RegisterCover(11, TArray<uint16>{1});+ const FVector Eye(0.0, 0.0, 165.0);+ Belief.ObserveSight(Eye, FRotator(0.f, 0.f, 0.f), World, World, 1.f);+ TestTrue(TEXT("seen piece: true state"), Belief.GetBelievedState(1) == EVersePieceState::Holed);+ TestTrue(TEXT("unseen piece behind the bot: still intact"), Belief.GetBelievedState(2) == EVersePieceState::Intact);+ TestTrue(TEXT("occluded piece: still intact"), Belief.GetBelievedState(3) == EVersePieceState::Intact);+ bool bOnlySeen = World.StateReads.Num() > 0;+ for (const uint16 Read : World.StateReads)+ {+ bOnlySeen &= Read == 1;+ }+ TestTrue(TEXT("GetPieceState only for the seen piece (F1, DR6)"), bOnlySeen);+ TestTrue(TEXT("cover on piece 1 dirty"), Belief.ConsumeDirtyCover() == TArray<int32>{11});++ // A heard fracture near piece 2: changed, state unknown; its cover is rescored.+ FVerseHeardPercept Fracture;+ Fracture.Noise = VerseTags::Noise_Fracture;+ Fracture.Location = FVector(-1100.0, 50.0, 0.0);+ Fracture.ErrorSdM = 1.f;+ Belief.OnHeardFracture(Fracture, 2.f);+ TestTrue(TEXT("heard fracture: changed, state unknown"), Belief.Find(2)->bChangedUnknown);+ TestTrue(TEXT("heard fracture: believed state kept"), Belief.GetBelievedState(2) == EVersePieceState::Intact);+ TestFalse(TEXT("heard fracture: not an opening"), Belief.IsBelievedOpen(2));+ TestTrue(TEXT("cover on piece 2 dirty"), Belief.ConsumeDirtyCover() == TArray<int32>{10});++ // Turning around: piece 2 seen, Breached.+ World.StateReads.Reset();+ Belief.ObserveSight(Eye, FRotator(0.f, 180.f, 0.f), World, World, 3.f);+ TestTrue(TEXT("seen after turning: breached"), Belief.IsBelievedOpen(2));+ TestFalse(TEXT("flag cleared once seen"), Belief.Find(2)->bChangedUnknown);++ // Own action and the full reset.+ Belief.OnOwnAction(3, EVersePieceState::Destroyed, 4.f);+ TestFalse(TEXT("own action: destroyed"), Belief.IsBelievedStanding(3));+ Belief.ResetAll();+ TestTrue(TEXT("reset: all intact"), Belief.GetBelievedState(1) == EVersePieceState::Intact &&+ Belief.GetBelievedState(2) == EVersePieceState::Intact && Belief.GetBelievedState(3) == EVersePieceState::Intact);++ // Opaque distance for the hurt wedge: concrete stops at 20 m, sheet metal does not.+ const float Opaque = Belief.OpaqueDistance(FVector(0.0, 0.0, 100.0), FVector(1.0, 0.0, 0.0), 5000.f);+ TestTrue(TEXT("opaque at the concrete piece"), FMath::IsNearlyEqual(Opaque, 2000.f, 5.f));+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBeliefF7Test, "Verse.Bot.Belief.F7", VERSE_BELIEF_TEST_FLAGS)++bool FVerseBeliefF7Test::RunTest(const FString& Parameters)+{+ // A7.7 / F7 wall_opened_unseen: a wall between two rooms is breached out of sight and earshot.+ // No believed path uses the opening and no mass flows through it until the bot sees it.+ FFakeVerseBeliefWorld World;+ World.AddPiece(7, FVector(1000.0, 0.0, 0.0), FVector(1100.0, 1000.0, 300.0), EVersePenetrationMaterial::SheetMetal);+ FVerseBeliefGridSource Source;+ Source.Origin = FVector2D(50.0, 50.0);+ for (int32 X = 0; X < 20; ++X)+ {+ for (int32 Y = 0; Y < 10; ++Y)+ {+ FVerseBeliefCellDesc& Cell = Source.Cells.AddDefaulted_GetRef();+ Cell.Column = FIntPoint(X, Y);+ if (X == 10)+ {+ // The wall's column: walkable only through the opening of a breached wall.+ Cell.Gate = EVerseBeliefGate::WhenOpen;+ Cell.GatePiece = 7;+ }+ }+ }+ FVerseBeliefMapConfig Config;+ Config.SelfPlayerId = SelfId;+ Config.ArenaBox = FBox(FVector(-100.0, -100.0, -100.0), FVector(2100.0, 1100.0, 500.0));+ Config.MaxCellSightTestsPerStep = 100000;+ Config.MaxPieceSightTestsPerStep = 100000;+ FVerseBeliefWorld BeliefWorld;+ BeliefWorld.Sight = &World;+ BeliefWorld.Pieces = &World;+ FVerseBeliefMap Map;+ Map.Initialize(Source, Config, BeliefWorld);++ const FVector Feet = ColumnCentre(2, 5);+ const int32 RoomA = Map.GetGrid().FindCell(ColumnCentre(4, 5));+ const int32 RoomB = Map.GetGrid().FindCell(ColumnCentre(15, 5));+ TestTrue(TEXT("no path before the breach"), Map.GetGrid().FindPath(RoomA, RoomB).Num() == 0);++ // Breached out of sight (the bot looks away, -X) and out of earshot (no fracture percept).+ World.Pieces[0].State = EVersePieceState::Breached;+ uint32 NowMs = 1000;+ int32 PlansThroughOpening = 0;+ for (int32 Tick = 0; Tick < 600; ++Tick)+ {+ NowMs += 17;+ Map.ApplyFrame(SelfFrame(NowMs, Feet, 180.f), BeliefWorld);+ PlansThroughOpening += Map.GetGrid().FindPath(RoomA, RoomB).Num() > 0 ? 1 : 0;+ }+ TestEqual(TEXT("A7.7 no plan uses the breach before it is perceived"), PlansThroughOpening, 0);+ TestTrue(TEXT("belief still intact"), Map.GetPieces().GetBelievedState(7) == EVersePieceState::Intact);+ TestFalse(TEXT("opening cells inactive"), Map.GetGrid().IsActive(Map.GetGrid().FindCellAnyState(FIntPoint(10, 5), EVerseArenaLevel::Floor)));+ TestEqual(TEXT("piece truth never read while unseen"), World.StateReads.Num(), 0);++ // The bot turns toward the wall: it sees the breach and may now plan through it.+ NowMs += 17;+ Map.ApplyFrame(SelfFrame(NowMs, Feet, 0.f), BeliefWorld);+ TestTrue(TEXT("seen: breached"), Map.GetPieces().GetBelievedState(7) == EVersePieceState::Breached);+ const TArray<int32> Path = Map.GetGrid().FindPath(RoomA, RoomB);+ TestTrue(TEXT("seen: a path through the opening"), Path.Num() > 0);++ SaveProof(TEXT("7.9"), TEXT("f7_wall_opened_unseen.json"),+ FString::Printf(TEXT("{\n \"test\": \"F7 wall_opened_unseen (A7.7)\",\n \"ticksUnseen\": 600,\n")+ TEXT(" \"plansThroughOpeningWhileUnseen\": %d,\n \"pathAfterSeen\": %s,\n \"pass\": %s\n}\n"),+ PlansThroughOpening, Path.Num() > 0 ? TEXT("true") : TEXT("false"), HasAnyErrors() ? TEXT("false") : TEXT("true")));+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBeliefCostTest, "Verse.Perf.Bot.BeliefCost", VERSE_BELIEF_TEST_FLAGS)++bool FVerseBeliefCostTest::RunTest(const FString& Parameters)+{+ // A7.6: the belief step (predict with momentum, clear of the cached visible cells, normalise,+ // derived values) at most 0.05 ms with 6,000 cells. Sight traces are TestSight's (WP03) cost,+ // bounded by the map's per-step budget; Verse.Perf.Bot.BeliefTraceCost times them with real+ // line traces on a Recast-built arena.+ FVerseBeliefGrid Grid;+ Grid.Build(MakeThreeLevelSource());+ TestEqual(TEXT("6,000 cells"), Grid.NumCells(), 6000);+ const FVector Eye(2500.0, 500.0, 165.0);+ TArray<int32> Visible;+ for (int32 Cell = 0; Cell < Grid.NumCells(); ++Cell)+ {+ if (Grid.GetCell(Cell).Level == EVerseArenaLevel::Floor && Grid.GetCell(Cell).Column.Y < 15)+ {+ Visible.Add(Cell);+ }+ }+ // Spread the mass everywhere first (worst case: no empty cell to skip).+ Grid.ApplySighting(FVector(2500.0, 2000.0, 95.0), 0.f);+ Grid.SetMomentum(FVector(300.0, 200.0, 0.0), 0.f);+ for (int32 Step = 0; Step < 200; ++Step)+ {+ Grid.Predict(0.1f, Step * 0.1f);+ Grid.Normalise();+ }+ double Best = TNumericLimits<double>::Max();+ double Total = 0.0;+ int32 Steps = 0;+ FVerseBeliefDerived Derived;+ for (int32 Batch = 0; Batch < 5; ++Batch)+ {+ const double Start = FPlatformTime::Seconds();+ for (int32 Step = 0; Step < 100; ++Step)+ {+ const float NowS = 20.f + (Batch * 100 + Step) * 0.1f;+ Grid.Predict(0.1f, NowS);+ Grid.Clear(Eye, Visible, NowS);+ Grid.Normalise();+ Derived = Grid.ComputeDerived(NowS, false);+ }+ const double Elapsed = FPlatformTime::Seconds() - Start;+ Best = FMath::Min(Best, Elapsed / 100.0);+ Total += Elapsed;+ Steps += 100;+ }+ const double BestMs = Best * 1000.0;+ const double MeanMs = Total / Steps * 1000.0;++ // Per phase, best of 5 batches, for the report.+ double PhaseBest[4] = {1e9, 1e9, 1e9, 1e9};+ for (int32 Batch = 0; Batch < 5; ++Batch)+ {+ double Phase[4] = {0.0, 0.0, 0.0, 0.0};+ for (int32 Step = 0; Step < 100; ++Step)+ {+ const float NowS = 100.f + (Batch * 100 + Step) * 0.1f;+ double T0 = FPlatformTime::Seconds();+ Grid.Predict(0.1f, NowS);+ double T1 = FPlatformTime::Seconds();+ Grid.Clear(Eye, Visible, NowS);+ double T2 = FPlatformTime::Seconds();+ Grid.Normalise();+ double T3 = FPlatformTime::Seconds();+ Derived = Grid.ComputeDerived(NowS, false);+ double T4 = FPlatformTime::Seconds();+ Phase[0] += T1 - T0;+ Phase[1] += T2 - T1;+ Phase[2] += T3 - T2;+ Phase[3] += T4 - T3;+ }+ for (int32 Index = 0; Index < 4; ++Index)+ {+ PhaseBest[Index] = FMath::Min(PhaseBest[Index], Phase[Index] / 100.0 * 1000.0);+ }+ }+ AddInfo(FString::Printf(TEXT("phases ms: predict %.4f clear %.4f normalise %.4f derived %.4f"), PhaseBest[0], PhaseBest[1],+ PhaseBest[2], PhaseBest[3]));++ // The full map step on the lane fixture with the fake sight query and the default trace budget.+ FLaneFixture Fixture;+ FVerseBeliefMapConfig Config = Fixture.Config();+ Config.MaxCellSightTestsPerStep = FVerseBeliefMapConfig().MaxCellSightTestsPerStep;+ Config.MaxPieceSightTestsPerStep = FVerseBeliefMapConfig().MaxPieceSightTestsPerStep;+ FVerseBeliefMap Map;+ Map.Initialize(Fixture.Source, Config, Fixture.BeliefWorld());+ uint32 NowMs = 1000;+ const double MapStart = FPlatformTime::Seconds();+ int32 MapSteps = 0;+ for (int32 Tick = 0; Tick < 1200; ++Tick)+ {+ NowMs += 17;+ MapSteps += Map.ApplyFrame(SelfFrame(NowMs, ObserverFeet, float(Tick % 360)), Fixture.BeliefWorld()) ? 1 : 0;+ }+ const double MapMs = (FPlatformTime::Seconds() - MapStart) * 1000.0 / FMath::Max(1, MapSteps);++ TestTrue(FString::Printf(TEXT("A7.6 belief step %.4f ms with 6,000 cells <= 0.05"), BestMs), BestMs <= 0.05);+ SaveProof(TEXT("7.6"), TEXT("belief_cost.json"),+ FString::Printf(TEXT("{\n \"test\": \"A7.6 belief cost\",\n \"cells\": %d,\n \"msPerStepBestBatch\": %.5f,\n")+ TEXT(" \"msPerStepMean\": %.5f,\n \"budgetMs\": 0.05,\n \"mapStepWithFakeSightMs\": %.5f,\n")+ TEXT(" \"mapCellSightTestsPerStep\": %d,\n \"phaseMs\": {\"predict\": %.5f, \"clear\": %.5f, \"normalise\": %.5f, \"derived\": %.5f},\n")+ TEXT(" \"pass\": %s\n}\n"),+ Grid.NumCells(), BestMs, MeanMs, MapMs, Config.MaxCellSightTestsPerStep, PhaseBest[0], PhaseBest[1], PhaseBest[2], PhaseBest[3],+ BestMs <= 0.05 ? TEXT("true") : TEXT("false")));+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBeliefDebugDrawTest, "Verse.Bot.Belief.DebugDraw", VERSE_BELIEF_TEST_FLAGS)++bool FVerseBeliefDebugDrawTest::RunTest(const FString& Parameters)+{+ // WP07.10: the top-down render covers the grid, outlines the cluster and uses no cyan or violet.+ FLaneFixture Fixture;+ FVerseBeliefGrid Grid;+ Grid.Build(Fixture.Source);+ Grid.ApplySighting(ColumnCentre(25, 30, 95.f), 0.f);+ Grid.Normalise();+ const FVerseBeliefDerived Derived = Grid.ComputeDerived(0.f, true);+ TArray<FColor> Pixels;+ int32 Width = 0;+ int32 Height = 0;+ FVerseBeliefDebugDraw::RenderTopDown(Grid, Derived, EVerseArenaLevel::Floor, 8, Pixels, Width, Height);+ TestEqual(TEXT("width 50 columns x 8"), Width, 400);+ TestEqual(TEXT("height 40 rows x 8"), Height, 320);+ int32 Gold = 0;+ int32 CoolHue = 0;+ for (const FColor& Pixel : Pixels)+ {+ Gold += Pixel == FColor(212, 175, 55) ? 1 : 0;+ CoolHue += (Pixel.B > Pixel.R + 20 && Pixel.B > 60) ? 1 : 0;+ }+ TestTrue(TEXT("cluster outlined in gold"), Gold > 50);+ TestEqual(TEXT("no cyan or violet pixels"), CoolHue, 0);+ TestTrue(TEXT("png written"), FVerseBeliefDebugDraw::SavePng(ProofDir(TEXT("7.10")) / TEXT("heatmap_render_check.png"), Grid,+ Derived, EVerseArenaLevel::Floor, 8));+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseBot/Private/Tests/Belief/VerseBeliefTestFixture.h b/unreal/Verse/Source/VerseBot/Private/Tests/Belief/VerseBeliefTestFixture.hnew file mode 100644index 0000000000..34e79fb986--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tests/Belief/VerseBeliefTestFixture.h@@ -0,0 +1,158 @@+#pragma once++#if WITH_DEV_AUTOMATION_TESTS++#include "Belief/VerseBeliefGrid.h"+#include "Belief/VerseBeliefMap.h"+#include "CoreMinimal.h"+#include "HAL/FileManager.h"+#include "Misc/FileHelper.h"+#include "Misc/Paths.h"+#include "Tests/Belief/Fakes/FakeVerseBeliefWorld.h"++namespace VerseBotBeliefTests+{+ constexpr int32 SelfId = 1;+ constexpr int32 OpponentId = 2;++ inline FString ProofDir(const TCHAR* SubTask)+ {+ return FPaths::ProjectSavedDir() / TEXT("Harness/proof/WP07") / SubTask;+ }++ inline void SaveProof(const TCHAR* SubTask, const TCHAR* File, const FString& Json)+ {+ const FString Dir = ProofDir(SubTask);+ IFileManager::Get().MakeDirectory(*Dir, true);+ FFileHelper::SaveStringToFile(Json, *(Dir / File));+ }++ /** World cm of a cell column centre for a fixture whose column (0, 0) is at (50, 50) cm. */+ inline FVector ColumnCentre(int32 X, int32 Y, float Z = 0.f)+ {+ return FVector(50.0 + X * 100.0, 50.0 + Y * 100.0, Z);+ }++ /**+ * The lane fixture (Content/Verse/Test/WP07 graybox in code): a 50 x 40 m hall, one level.+ * Wall A along y = 20 m with a 2 m door at x 24-26 m; wall B along y = 26 m. Between them a+ * 6 m lane, hidden from the observer post at (25, 5) m except through the door.+ * Walls are 4 m tall, so sight at 1.0 and 1.6 m equals the 2D line of sight.+ */+ struct FLaneFixture+ {+ FFakeVerseBeliefWorld World;+ FVerseBeliefGridSource Source;++ static constexpr int32 Columns = 50;+ static constexpr int32 Rows = 40;++ FLaneFixture()+ {+ World.AddWall(FVector(200.0, 1990.0, 0.0), FVector(2400.0, 2010.0, 400.0));+ World.AddWall(FVector(2600.0, 1990.0, 0.0), FVector(4800.0, 2010.0, 400.0));+ World.AddWall(FVector(200.0, 2590.0, 0.0), FVector(4800.0, 2610.0, 400.0));+ BuildSource();+ }++ void BuildSource()+ {+ Source = FVerseBeliefGridSource();+ Source.Origin = FVector2D(50.0, 50.0);+ Source.CellSizeCm = 100.f;+ for (int32 X = 0; X < Columns; ++X)+ {+ for (int32 Y = 0; Y < Rows; ++Y)+ {+ FVerseBeliefCellDesc& Cell = Source.Cells.AddDefaulted_GetRef();+ Cell.Column = FIntPoint(X, Y);+ }+ }+ const FFakeVerseBeliefWorld* Geometry = &World;+ const TArray<FVerseBeliefCellDesc>* Cells = &Source.Cells;+ Source.AreNeighboursConnected = [Geometry, Cells](int32 A, int32 B) {+ const FIntPoint Ca = (*Cells)[A].Column;+ const FIntPoint Cb = (*Cells)[B].Column;+ const FVector Pa = ColumnCentre(Ca.X, Ca.Y, 50.f);+ const FVector Pb = ColumnCentre(Cb.X, Cb.Y, 50.f);+ for (const FFakeWall& Wall : Geometry->Walls)+ {+ if (FFakeVerseBeliefWorld::SegmentHits(Wall.Box, Pa, Pb))+ {+ return false;+ }+ }+ return true;+ };+ }++ FVerseBeliefMapConfig Config() const+ {+ FVerseBeliefMapConfig Out;+ Out.SelfPlayerId = SelfId;+ Out.ArenaBox = FBox(FVector(0.0, 0.0, -100.0), FVector(5000.0, 4000.0, 1200.0));+ Out.MaxCellSightTestsPerStep = 100000;+ Out.MaxPieceSightTestsPerStep = 100000;+ Out.SpawnPoints = {ColumnCentre(5, 35), ColumnCentre(47, 37), ColumnCentre(5, 2), ColumnCentre(45, 2)};+ return Out;+ }++ FVerseBeliefWorld BeliefWorld() const+ {+ FVerseBeliefWorld Out;+ Out.Sight = &World;+ Out.Pieces = &World;+ return Out;+ }+ };++ /** A frame with the observer's own HUD state only. */+ inline FVersePerceptFrame SelfFrame(uint32 NowMs, const FVector& Feet, float YawDeg)+ {+ FVersePerceptFrame Frame;+ Frame.ServerTimeMs = NowMs;+ Frame.Self.Location = Feet;+ Frame.Self.EyeLocation = Feet + FVector(0.0, 0.0, 165.0);+ Frame.Self.ViewRotation = FRotator(0.f, YawDeg, 0.f);+ Frame.Self.Phase = EVerseCombatPhase::Alive;+ return Frame;+ }++ /** Three-level 50 x 40 m grid (6,000 cells) with stair links, no walls: the A7.6 cost case. */+ inline FVerseBeliefGridSource MakeThreeLevelSource()+ {+ FVerseBeliefGridSource Source;+ Source.Origin = FVector2D(50.0, 50.0);+ Source.CellSizeCm = 100.f;+ for (int32 Level = 0; Level < 3; ++Level)+ {+ for (int32 X = 0; X < 50; ++X)+ {+ for (int32 Y = 0; Y < 40; ++Y)+ {+ FVerseBeliefCellDesc& Cell = Source.Cells.AddDefaulted_GetRef();+ Cell.Column = FIntPoint(X, Y);+ Cell.Level = EVerseArenaLevel(Level);+ Cell.FloorZ = 400.f * Level;+ Cell.Zone = uint8((X / 10) + 5 * (Y / 20));+ }+ }+ }+ auto IndexOf = [](int32 X, int32 Y, int32 Level) { return (Level * 50 + X) * 40 + Y; };+ for (int32 Stair = 0; Stair < 8; ++Stair)+ {+ const int32 X = 3 + Stair * 6;+ for (int32 Level = 0; Level < 2; ++Level)+ {+ FVerseBeliefLinkDesc& Link = Source.Links.AddDefaulted_GetRef();+ Link.From = IndexOf(X, 10 + Level * 10, Level);+ Link.To = IndexOf(X + 1, 10 + Level * 10, Level + 1);+ Link.TraversalS = 1.5f;+ Link.Kind = EVerseBeliefLinkKind::Stair;+ }+ }+ return Source;+ }+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseBot/Private/Tests/Belief/VerseBeliefWorldTest.cpp b/unreal/Verse/Source/VerseBot/Private/Tests/Belief/VerseBeliefWorldTest.cppnew file mode 100644index 0000000000..2266a465e1--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Private/Tests/Belief/VerseBeliefWorldTest.cpp@@ -0,0 +1,344 @@+#include "AI/NavigationSystemBase.h"+#include "AI/Navigation/NavigationDataInterface.h"+#include "AI/Navigation/NavigationTypes.h"+#include "Belief/VerseBeliefGrid.h"+#include "Belief/VerseBeliefMap.h"+#include "Belief/VerseBeliefNavSampler.h"+#include "CollisionQueryParams.h"+#include "Components/BrushComponent.h"+#include "Components/StaticMeshComponent.h"+#include "Engine/Brush.h"+#include "Engine/Engine.h"+#include "Engine/StaticMesh.h"+#include "Engine/StaticMeshActor.h"+#include "Engine/World.h"+#include "HAL/PlatformProcess.h"+#include "HAL/PlatformTime.h"+#include "Misc/AutomationTest.h"+#include "PhysicsEngine/BodySetup.h"+#include "Tests/Belief/VerseBeliefTestFixture.h"+#include "VerseCollision.h"++#if WITH_DEV_AUTOMATION_TESTS++// Verse.Bot.Belief.Recast and Verse.Perf.Bot.BeliefTraceCost: the WP07 fixture arena (the lane+// graybox of VerseBeliefTestFixture.h) built as real geometry in a transient editor world, with a+// Recast navmesh built from it. The belief grid is sampled from that navmesh (WP07.5) and the map+// step is timed with real VerseSight line traces (A7.6 with real TestSight cost).++#define VERSE_BELIEF_WORLD_TEST_FLAGS (EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++namespace VerseBotBeliefWorldTests+{+ using namespace VerseBotBeliefTests;++ /** Pieces of the fixture: a catwalk-like floor slab (piece 3) and a solid 3 x 3 m block (piece 9). */+ constexpr int32 SlabPiece = 3;+ constexpr int32 BlockPiece = 9;+ /** The observer post of the lane fixture, (25, 5) m. */+ const FVector PostFeet = ColumnCentre(25, 5);+ const FBox SlabFootprint(FVector(4000.0, 3000.0, -50.0), FVector(4500.0, 3500.0, 50.0));+ const FBox BlockBox(FVector(3500.0, 1000.0, 0.0), FVector(3800.0, 1300.0, 400.0));++ /** TestSight as a plain line trace on VerseSight (the WP03 stand-in), counting its calls. */+ class FTraceSight : public IVersePenetrationQuery+ {+ public:+ explicit FTraceSight(UWorld* InWorld) : World(InWorld) {}++ UWorld* World = nullptr;+ mutable int32 Calls = 0;++ virtual TArray<FVersePenetrationHit> TraceBolt(const FVector& Origin, const FVector& Dir, float MaxDist, float Power,+ float Damage, uint8 RadiusMm, int32 MaxPieces) const override+ {+ return {};+ }++ virtual bool TestSight(const FVector& Eye, const FVector& Target) const override+ {+ ++Calls;+ static const FName TraceTag(TEXT("VerseSight"));+ const FCollisionQueryParams Params(TraceTag, false);+ return !World->LineTraceTestByChannel(Eye, Target, VerseCollision::Sight, Params);+ }+ };++ /** The transient arena: floor, the fixture walls, the block; nav bounds; Recast built. */+ struct FArenaWorld+ {+ UWorld* World = nullptr;+ FString Error;++ FArenaWorld()+ {+ World = UWorld::CreateWorld(EWorldType::Editor, false, TEXT("VerseBeliefRecastFixture"));+ if (!World)+ {+ Error = TEXT("no world");+ return;+ }+ FWorldContext& Context = GEngine->CreateNewWorldContext(EWorldType::Editor);+ Context.SetCurrentWorld(World);+ FNavigationSystem::AddNavigationSystemToWorld(*World, FNavigationSystemRunMode::EditorMode);++ UStaticMesh* Cube = LoadObject<UStaticMesh>(nullptr, TEXT("/Engine/BasicShapes/Cube.Cube"));+ if (!Cube)+ {+ Error = TEXT("no cube mesh");+ return;+ }+ // The cube is 100 cm with its pivot at the centre.+ auto AddBox = [this, Cube](const FBox& Box) {+ FActorSpawnParameters Params;+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;+ AStaticMeshActor* Actor = World->SpawnActor<AStaticMeshActor>(Box.GetCenter(), FRotator::ZeroRotator, Params);+ UStaticMeshComponent* Mesh = Actor->GetStaticMeshComponent();+ Mesh->SetMobility(EComponentMobility::Static);+ Mesh->SetStaticMesh(Cube);+ Mesh->SetWorldScale3D(Box.GetSize() / 100.0);+ Mesh->SetCollisionProfileName(VerseCollision::Profile::Architecture);+ Mesh->SetCanEverAffectNavigation(true);+ };+ AddBox(FBox(FVector(-100.0, -100.0, -20.0), FVector(5100.0, 4100.0, 0.0)));+ FLaneFixture Fixture;+ for (const FFakeWall& Wall : Fixture.World.Walls)+ {+ AddBox(Wall.Box);+ }+ AddBox(BlockBox);++ // Nav bounds: a NavMeshBoundsVolume (found by class name; VerseBot does not link the+ // NavigationSystem module) whose brush is a box body.+ UClass* BoundsClass = FindObject<UClass>(nullptr, TEXT("/Script/NavigationSystem.NavMeshBoundsVolume"));+ if (!BoundsClass)+ {+ Error = TEXT("no NavMeshBoundsVolume class");+ return;+ }+ const FTransform BoundsAt(FVector(2500.0, 2000.0, 200.0));+ ABrush* Bounds = World->SpawnActorDeferred<ABrush>(BoundsClass, BoundsAt);+ if (!Bounds || !Bounds->GetBrushComponent())+ {+ Error = TEXT("no bounds volume");+ return;+ }+ UBodySetup* Body = NewObject<UBodySetup>(Bounds->GetBrushComponent());+ Body->AggGeom.BoxElems.Add(FKBoxElem(5400.f, 4400.f, 1000.f));+ Bounds->GetBrushComponent()->BrushBodySetup = Body;+ Bounds->FinishSpawning(BoundsAt);+ // Components register at spawn, before the body was set: register again so the+ // navigation system sees the volume's real bounds.+ Bounds->UnregisterAllComponents();+ Bounds->RegisterAllComponents();++ UNavigationSystemBase* NavSys = World->GetNavigationSystem();+ if (!NavSys)+ {+ Error = TEXT("no navigation system");+ return;+ }+ for (int32 Tick = 0; Tick < 4; ++Tick)+ {+ NavSys->Tick(0.1f);+ }+ GEngine->Exec(World, TEXT("RebuildNavigation"));+ const double Deadline = FPlatformTime::Seconds() + 60.0;+ while (FPlatformTime::Seconds() < Deadline)+ {+ NavSys->Tick(0.05f);+ const INavigationDataInterface* Nav = NavSys->GetMainNavData();+ FNavLocation Hit;+ if (Nav && Nav->ProjectPoint(FVector(2500.0, 500.0, 0.0), Hit, FVector(50.0, 50.0, 150.0)) &&+ Nav->ProjectPoint(FVector(1000.0, 2300.0, 0.0), Hit, FVector(50.0, 50.0, 150.0)))+ {+ return;+ }+ FPlatformProcess::Sleep(0.01f);+ }+ Error = TEXT("navmesh not built within 60 s");+ }++ ~FArenaWorld()+ {+ if (World)+ {+ GEngine->DestroyWorldContext(World);+ World->DestroyWorld(false);+ }+ }++ FVerseBeliefNavSettings Settings() const+ {+ FVerseBeliefNavSettings Out;+ Out.ArenaBox = FBox(FVector(0.0, 0.0, -100.0), FVector(5000.0, 4000.0, 1200.0));+ Out.CellSizeCm = 100.f;+ Out.PieceFootprints.Add({SlabPiece, SlabFootprint, EVerseBeliefGate::WhenStanding, EVerseArenaLevel::Floor});+ Out.PieceFootprints.Add({BlockPiece, BlockBox, EVerseBeliefGate::WhenOpen, EVerseArenaLevel::Floor});+ return Out;+ }+ };+}++using namespace VerseBotBeliefWorldTests;++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBeliefRecastTest, "Verse.Bot.Belief.Recast", VERSE_BELIEF_WORLD_TEST_FLAGS)++bool FVerseBeliefRecastTest::RunTest(const FString& Parameters)+{+ // WP07.5: the grid is sampled from a real Recast navmesh of the fixture arena: one cell per 1 m+ // column, none inside walls, the walls cut adjacency except at the door, and piece footprints+ // gate cells (a slab goes when destroyed, an opening appears when breached).+ FArenaWorld Arena;+ if (!Arena.Error.IsEmpty())+ {+ AddError(FString::Printf(TEXT("fixture arena: %s"), *Arena.Error));+ return false;+ }+ FVerseBeliefGridSource Source;+ const bool bBuilt = FVerseBeliefNavSampler::Build(*Arena.World, Arena.Settings(), Source);+ TestTrue(TEXT("sampled from Recast"), bBuilt);+ int32 Gated = 0;+ int32 Openings = 0;+ for (const FVerseBeliefCellDesc& Cell : Source.Cells)+ {+ Gated += Cell.Gate == EVerseBeliefGate::WhenStanding && Cell.GatePiece == SlabPiece ? 1 : 0;+ Openings += Cell.Gate == EVerseBeliefGate::WhenOpen && Cell.GatePiece == BlockPiece ? 1 : 0;+ }+ AddInfo(FString::Printf(TEXT("Recast sample: %d cells, %d slab-gated, %d opening cells"), Source.Cells.Num(), Gated, Openings));+ TestTrue(TEXT("about one cell per walkable column (1,500..2,100)"), Source.Cells.Num() >= 1500 && Source.Cells.Num() <= 2100);+ TestEqual(TEXT("slab footprint: 5 x 5 columns gated"), Gated, 25);+ TestEqual(TEXT("block footprint: 3 x 3 opening cells"), Openings, 9);++ FVerseBeliefGrid Grid;+ Grid.Build(Source);+ const int32 Post = Grid.FindCell(FIntPoint(25, 5), EVerseArenaLevel::Floor);+ const int32 Lane = Grid.FindCell(FIntPoint(10, 23), EVerseArenaLevel::Floor);+ const int32 SouthOfWall = Grid.FindCell(FIntPoint(10, 19), EVerseArenaLevel::Floor);+ const int32 NorthOfWall = Grid.FindCell(FIntPoint(10, 20), EVerseArenaLevel::Floor);+ TestTrue(TEXT("cells on both sides of wall A"), Post != INDEX_NONE && Lane != INDEX_NONE && SouthOfWall != INDEX_NONE &&+ NorthOfWall != INDEX_NONE);+ if (SouthOfWall != INDEX_NONE && NorthOfWall != INDEX_NONE)+ {+ TArray<int32> Neighbours;+ Grid.GetNeighbours(SouthOfWall, Neighbours);+ TestFalse(TEXT("wall A cuts adjacency"), Neighbours.Contains(NorthOfWall));+ }+ if (Post != INDEX_NONE && Lane != INDEX_NONE)+ {+ const TArray<int32> Path = Grid.FindPath(Post, Lane);+ TestTrue(TEXT("a path through the door"), Path.Num() > 0);+ bool bThroughDoor = false;+ for (const int32 Cell : Path)+ {+ const FIntPoint Column = Grid.GetCell(Cell).Column;+ bThroughDoor |= (Column.Y == 19 || Column.Y == 20) && Column.X >= 24 && Column.X <= 25;+ }+ TestTrue(TEXT("the path uses the door columns"), bThroughDoor);+ }++ // Gates: intact block, standing slab at match start.+ const int32 Slab = Grid.FindCellAnyState(FIntPoint(42, 32), EVerseArenaLevel::Floor);+ const int32 Opening = Grid.FindCellAnyState(FIntPoint(36, 11), EVerseArenaLevel::Floor);+ TestTrue(TEXT("slab standing: active"), Grid.IsActive(Slab));+ TestFalse(TEXT("block intact: no opening cell"), Grid.IsActive(Opening));+ Grid.ApplyGates([](int32 Piece) { return Piece == BlockPiece; }, [](int32 Piece) { return Piece != SlabPiece; });+ TestFalse(TEXT("slab destroyed: gone"), Grid.IsActive(Slab));+ TestTrue(TEXT("block breached: opening cell"), Grid.IsActive(Opening));+ TestTrue(TEXT("opening joins the floor around it"), Grid.NumNeighbours(Opening) >= 8);+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVerseBeliefTraceCostTest, "Verse.Perf.Bot.BeliefTraceCost", VERSE_BELIEF_WORLD_TEST_FLAGS)++bool FVerseBeliefTraceCostTest::RunTest(const FString& Parameters)+{+ // A7.6 with real sight: the map step on the Recast-sampled fixture arena with VerseSight line+ // traces, the default trace budget, the observer turning on the spot and then walking. Reports+ // the cost of a 10 Hz step (traces included) against the 0.05 ms belief budget, and the+ // amortised cost per 60 Hz tick against the 0.5 ms bot budget.+ FArenaWorld Arena;+ if (!Arena.Error.IsEmpty())+ {+ AddError(FString::Printf(TEXT("fixture arena: %s"), *Arena.Error));+ return false;+ }+ FVerseBeliefGridSource Source;+ if (!TestTrue(TEXT("sampled from Recast"), FVerseBeliefNavSampler::Build(*Arena.World, Arena.Settings(), Source)))+ {+ return false;+ }+ FTraceSight Sight(Arena.World);++ // One trace alone, for the report.+ {+ const FVector Eye(2500.0, 500.0, 165.0);+ const double Start = FPlatformTime::Seconds();+ for (int32 Index = 0; Index < 2000; ++Index)+ {+ Sight.TestSight(Eye, FVector(500.0 + (Index % 40) * 100.0, 2300.0, 160.0));+ }+ const double TraceUs = (FPlatformTime::Seconds() - Start) * 1e6 / 2000.0;+ AddInfo(FString::Printf(TEXT("one VerseSight trace: %.2f us"), TraceUs));+ Sight.Calls = 0;++ FVerseBeliefMapConfig Config;+ Config.SelfPlayerId = SelfId;+ Config.ArenaBox = FBox(FVector(0.0, 0.0, -100.0), FVector(5000.0, 4000.0, 1200.0));+ FVerseBeliefWorld World;+ World.Sight = &Sight;+ FVerseBeliefMap Map;+ Map.Initialize(Source, Config, World);++ uint32 NowMs = 1000;+ int32 Steps = 0;+ int32 MaxTraces = 0;+ double StepSeconds = 0.0;+ double WorstStep = 0.0;+ const int32 Ticks = 1800;+ const double TickStart = FPlatformTime::Seconds();+ for (int32 Tick = 0; Tick < Ticks; ++Tick)+ {+ NowMs += 17;+ // 15 s turning on the post, then 15 s walking along the hall at 4.5 m/s.+ FVector Feet = PostFeet;+ float Yaw = float(Tick % 720) * 0.5f;+ if (Tick >= 900)+ {+ Feet.X = 500.0 + FMath::Fmod((Tick - 900) * 7.5, 4000.0);+ Yaw = 0.f;+ }+ const int32 Before = Sight.Calls;+ const double T0 = FPlatformTime::Seconds();+ const bool bStep = Map.ApplyFrame(SelfFrame(NowMs, Feet, Yaw), World);+ const double Elapsed = FPlatformTime::Seconds() - T0;+ if (bStep)+ {+ ++Steps;+ StepSeconds += Elapsed;+ WorstStep = FMath::Max(WorstStep, Elapsed);+ MaxTraces = FMath::Max(MaxTraces, Sight.Calls - Before);+ }+ }+ const double TickMs = (FPlatformTime::Seconds() - TickStart) * 1000.0 / Ticks;+ const double StepMs = StepSeconds * 1000.0 / FMath::Max(1, Steps);+ const double TracesPerStep = double(Sight.Calls) / FMath::Max(1, Steps);+ const int32 Budget = Config.MaxCellSightTestsPerStep + Config.MaxPieceSightTestsPerStep;+ TestTrue(FString::Printf(TEXT("traces per step %d <= budget %d"), MaxTraces, Budget), MaxTraces <= Budget);+ TestTrue(FString::Printf(TEXT("amortised %.4f ms per tick within the 0.5 ms bot budget"), TickMs), TickMs <= 0.5);+ AddInfo(FString::Printf(TEXT("map step with real traces: %.4f ms mean, %.4f ms worst, %.1f traces per step (%d cells); %.4f ms per tick"),+ StepMs, WorstStep * 1000.0, TracesPerStep, Map.GetGrid().NumCells(), TickMs));+ SaveProof(TEXT("7.6"), TEXT("belief_trace_cost.json"),+ FString::Printf(TEXT("{\n \"test\": \"A7.6 belief step with real VerseSight traces (Recast fixture arena)\",\n")+ TEXT(" \"cells\": %d,\n \"traceUs\": %.3f,\n \"cellTraceBudgetPerStep\": %d,\n \"pieceTraceBudgetPerStep\": %d,\n")+ TEXT(" \"steps\": %d,\n \"tracesPerStepMean\": %.2f,\n \"tracesPerStepMax\": %d,\n")+ TEXT(" \"msPerStepMean\": %.5f,\n \"msPerStepWorst\": %.5f,\n \"beliefBudgetMs\": 0.05,\n")+ TEXT(" \"stepWithinBeliefBudget\": %s,\n \"msPerTickAmortised\": %.5f,\n \"botBudgetMs\": 0.5,\n \"pass\": %s\n}\n"),+ Map.GetGrid().NumCells(), TraceUs, Config.MaxCellSightTestsPerStep, Config.MaxPieceSightTestsPerStep, Steps, TracesPerStep,+ MaxTraces, StepMs, WorstStep * 1000.0, StepMs <= 0.05 ? TEXT("true") : TEXT("false"), TickMs,+ HasAnyErrors() ? TEXT("false") : TEXT("true")));+ }+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseBot/Public/Belief/VerseBeliefDebugDraw.h b/unreal/Verse/Source/VerseBot/Public/Belief/VerseBeliefDebugDraw.hnew file mode 100644index 0000000000..9c8f4600ee--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Belief/VerseBeliefDebugDraw.h@@ -0,0 +1,34 @@+#pragma once++#include "Belief/VerseBeliefGrid.h"+#include "CoreMinimal.h"++class UWorld;++/**+ * Dev-only belief heatmap (WP07.10): in-world debug boxes coloured by mass, and a top-down image+ * of one level for screenshots and test evidence. Presentation only; never read by the brain.+ * Colours follow the Verse palette: low mass dark steel, high mass amber to red (never cyan or violet).+ */+class VERSEBOT_API FVerseBeliefDebugDraw+{+public:+ /** Heat colour for a mass relative to the grid's maximum (0-1). */+ static FColor HeatColor(float Relative);++ /** Draw the grid into the world (no-op in Shipping or without debug drawing). */+ static void DrawWorld(const UWorld* World, const FVerseBeliefGrid& Grid, const FVerseBeliefDerived& Derived,+ float LifetimeS = 0.f, float MinRelative = 0.02f);++ /**+ * Render one level top-down, PixelsPerCell per cell, row 0 at the highest Y. Cells that do not+ * exist are black; the TopCluster disc is outlined in gold; Marks are drawn as white crosses.+ */+ static void RenderTopDown(const FVerseBeliefGrid& Grid, const FVerseBeliefDerived& Derived, EVerseArenaLevel Level,+ int32 PixelsPerCell, TArray<FColor>& OutPixels, int32& OutWidth, int32& OutHeight,+ TConstArrayView<FVector> Marks = {});++ /** RenderTopDown and save as PNG. Returns false when the file could not be written. */+ static bool SavePng(const FString& Path, const FVerseBeliefGrid& Grid, const FVerseBeliefDerived& Derived,+ EVerseArenaLevel Level, int32 PixelsPerCell, TConstArrayView<FVector> Marks = {});+};diff --git a/unreal/Verse/Source/VerseBot/Public/Belief/VerseBeliefGrid.h b/unreal/Verse/Source/VerseBot/Public/Belief/VerseBeliefGrid.hnew file mode 100644index 0000000000..f11515ec6a--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Belief/VerseBeliefGrid.h@@ -0,0 +1,370 @@+#pragma once++#include "Bot/VersePerceptTypes.h"+#include "CoreMinimal.h"+#include "Templates/Function.h"+#include "Destruction/VerseDestructionTypes.h"++// The belief grid (contracts/bot.md 4.1-4.3): where the opponent probably is, from percepts only.+// 1 x 1 m columns over the arena, one cell per walkable nav level in that column, 8-neighbour+// adjacency on a level plus authored links (stairs, ladders, mantles, jumps, drops). Mass P sums+// to 1 while the opponent is alive. Pure data and arithmetic: no UWorld, no pawn, no RNG, so a+// replay of the same percepts gives bit-identical mass (bot.md B5).++/** Kind of the newest positive percept that touched a cell (bot.md 4.1 LastSupport). */+enum class EVerseBeliefSupport : uint8+{+ None,+ Seen,+ Heard,+ Inferred+};++/** bot.md 4.3 states, plus Dead (the kill feed said so). */+enum class EVerseBeliefState : uint8+{+ Known,+ Tracked,+ Rough,+ Lost,+ Dead+};++/** When a cell or link exists, by the believed state of the piece that gates it (destruction.md 6.1). */+enum class EVerseBeliefGate : uint8+{+ /** Always there. */+ Always,+ /** Only while the piece is believed Breached or Destroyed (a breach opening). */+ WhenOpen,+ /** Only while the piece is not believed Destroyed (a catwalk segment). */+ WhenStanding+};++enum class EVerseBeliefLinkKind : uint8+{+ Stair,+ Ladder,+ Mantle,+ Jump,+ Drop,+ Breach+};++/** A cell as a source (nav sampler, fixture) describes it. */+struct VERSEBOT_API FVerseBeliefCellDesc+{+ /** Column index on the grid (X, Y), cell size apart. */+ FIntPoint Column = FIntPoint::ZeroValue;+ /** Floor height of the cell, world cm. */+ float FloorZ = 0.f;+ EVerseArenaLevel Level = EVerseArenaLevel::Floor;+ /** Arena VisibilityFactor at the cell (1 lit). */+ float Visibility = 1.f;+ /** Prone is possible here (clear also tests 0.4 m). */+ bool bProneCapable = false;+ /** Learning zone id (bot.md 7.1 routes), 0..254; 255 = none. */+ uint8 Zone = 255;+ EVerseBeliefGate Gate = EVerseBeliefGate::Always;+ int32 GatePiece = INDEX_NONE;+};++/** A link between two cells (indices into the source's cell list). */+struct VERSEBOT_API FVerseBeliefLinkDesc+{+ int32 From = INDEX_NONE;+ int32 To = INDEX_NONE;+ /** Seconds to traverse at a run. */+ float TraversalS = 1.f;+ bool bBidirectional = true;+ EVerseBeliefLinkKind Kind = EVerseBeliefLinkKind::Stair;+ EVerseBeliefGate Gate = EVerseBeliefGate::Always;+ int32 GatePiece = INDEX_NONE;+};++/** Everything a grid is built from. */+struct VERSEBOT_API FVerseBeliefGridSource+{+ /** World position of column (0, 0)'s centre, cm. */+ FVector2D Origin = FVector2D::ZeroVector;+ float CellSizeCm = 100.f;+ TArray<FVerseBeliefCellDesc> Cells;+ TArray<FVerseBeliefLinkDesc> Links;+ /**+ * Optional: may an 8-neighbour step go from cell A to cell B (a wall between them says no)?+ * Called once per neighbour pair at build. Null = every same-level neighbour is connected.+ */+ TFunction<bool(int32 A, int32 B)> AreNeighboursConnected;+};++/** bot.md 4.3 TopCluster. */+struct VERSEBOT_API FVerseBeliefCluster+{+ /** Mass-weighted centre of the disc, world cm (floor height). */+ FVector Centre = FVector::ZeroVector;+ EVerseArenaLevel Level = EVerseArenaLevel::Floor;+ float Mass = 0.f;+ /** The cell the disc is centred on. */+ int32 CentreCell = INDEX_NONE;+};++/** The read API of the decision layer (bot.md 4.3). */+struct VERSEBOT_API FVerseBeliefDerived+{+ FVerseBeliefCluster TopCluster;+ /** Mass of TopCluster, 0-1. */+ float Confidence = 0.f;+ /** Seconds since the newest seen or heard support inside TopCluster; large when none. */+ float SupportAgeS = TNumericLimits<float>::Max();+ EVerseBeliefSupport SupportKind = EVerseBeliefSupport::None;+ /** Weighted sd of the top 90 % of mass, metres. */+ float SpreadM = 0.f;+ EVerseBeliefState State = EVerseBeliefState::Lost;+};++/** Tuning of the update rules (bot.md 4.2; thresholds may be retuned, rules may not). */+struct VERSEBOT_API FVerseBeliefTuning+{+ /** Typical opponent speed, cm/s. */+ float TypicalSpeedCmS = 450.f;+ /** Most of a cell's mass that may diffuse in one step. */+ float MaxDiffusionFraction = 0.5f;+ /**+ * Momentum: after a sighting, part of the flow follows the seen velocity (a running person+ * keeps running). Neighbour weight cos^Exponent; the advected speed decays with this time.+ * Not a bot.md 4.2 rule yet: proposed to the integration owner as a contract change (A7.4 needs+ * it). MomentumMaxFraction = 0 gives the contract rules exactly.+ */+ float MomentumExponent = 4.f;+ float MomentumDecayS = 60.f;+ /** Momentum stops this long after the sighting that set it. */+ float MomentumMaxAgeS = 6.f;+ float MomentumMaxFraction = 0.45f;+ /** Clear: detection probability at up to NearM, falling linearly to FarPd at FarM. */+ float ClearNearPd = 0.95f;+ float ClearNearM = 30.f;+ float ClearFarPd = 0.7f;+ float ClearFarM = 50.f;+ /** Sighting Gaussian sd, cm. */+ float SightingSdCm = 50.f;+ /** Heard likelihood floor and level weights. */+ float HeardEps = 0.02f;+ float HeardLevelWeight = 0.9f;+ /** Hurt / bolt wedge half-angle, degrees, and its likelihood floor. */+ float WedgeHalfAngleDeg = 8.f;+ float WedgeEps = 0.02f;+ /** Spawn prior: top 3 spawn points weighted, sd cm. */+ float SpawnWeights[3] = {0.5f, 0.3f, 0.2f};+ float SpawnSdCm = 150.f;+ /** Normalise: share of the learned heatmap prior mixed in. */+ float PriorMix = 0.01f;+ /** Zone-transition bias gain (bot.md 7.2: x (1 + 0.5 x p)). */+ float ZoneBiasGain = 0.5f;+ /** TopCluster disc radius, cm. */+ float ClusterRadiusCm = 300.f;+ /** Unused: every active cell is a disc centre candidate; kept for tuning files. */+ int32 ClusterCandidates = 128;+ /** States: Tracked at or above, Rough at or above, else Lost. */+ float TrackedConfidence = 0.5f;+ float RoughConfidence = 0.2f;+};++/**+ * The grid. Build once from a source; ApplyGates when the piece belief changes; then the update+ * steps of bot.md 4.2 in order: Predict, Clear, Sighting / Heard / Wedge / KillFeed, Normalise.+ */+class VERSEBOT_API FVerseBeliefGrid+{+public:+ FVerseBeliefGrid() = default;++ void Build(const FVerseBeliefGridSource& Source, const FVerseBeliefTuning& InTuning = FVerseBeliefTuning());++ int32 NumCells() const { return Cells.Num(); }+ bool IsActive(int32 Cell) const { return bCellActive.IsValidIndex(Cell) && bCellActive[Cell] != 0; }+ const FVerseBeliefCellDesc& GetCell(int32 Cell) const { return Cells[Cell]; }+ FVector GetCellCentre(int32 Cell) const { return Centres[Cell]; }+ float GetMass(int32 Cell) const { return P[Cell]; }+ TConstArrayView<float> GetMassArray() const { return P; }+ float GetLastClearedS(int32 Cell) const { return LastClearedS[Cell]; }+ float GetLastSupportS(int32 Cell) const { return LastSupportS[Cell]; }+ EVerseBeliefSupport GetLastSupportKind(int32 Cell) const { return LastSupportKind[Cell]; }+ const FVerseBeliefTuning& GetTuning() const { return Tuning; }+ float GetCellSizeCm() const { return CellSizeCm; }++ /** Active cell nearest to a world point (same level preferred by height); INDEX_NONE if none. */+ int32 FindCell(const FVector& WorldLocation) const;+ /** Active cell of a column and level, or INDEX_NONE. */+ int32 FindCell(const FIntPoint& Column, EVerseArenaLevel Level) const;+ /** Cell of a column and level whether active or not (gated cells), or INDEX_NONE. */+ int32 FindCellAnyState(const FIntPoint& Column, EVerseArenaLevel Level) const;+ FIntPoint ColumnOf(const FVector& WorldLocation) const;++ /** Number of active neighbours (adjacency and links) of a cell. */+ int32 NumNeighbours(int32 Cell) const;+ /** Every active neighbour of a cell (for tests and plans). */+ void GetNeighbours(int32 Cell, TArray<int32>& Out) const;++ /**+ * Re-evaluate gated cells and links. IsOpen(piece): believed Breached or Destroyed;+ * IsStanding(piece): not believed Destroyed. Returns true when anything changed. Mass on a cell+ * that went inactive is dropped and the grid renormalised.+ */+ bool ApplyGates(TFunctionRef<bool(int32 Piece)> IsOpen, TFunctionRef<bool(int32 Piece)> IsStanding);++ /** Uniform mass over active cells (no information). */+ void ResetUniform();++ /** Learned position heatmap prior per cell (bot.md 7.2), any scale; empty = uniform. */+ void SetPositionPrior(TConstArrayView<float> PerCell);+ /** Zone-transition probabilities, Zones x Zones row-major (From * Zones + To); empty = none. */+ void SetZoneTransitionPrior(int32 Zones, TConstArrayView<float> Matrix);+ /** Last seen velocity of the opponent (cm/s) and its server time, for the momentum term. */+ void SetMomentum(const FVector& Velocity, float AtS);+ void ClearMomentum();++ // ---- update steps, bot.md 4.2 order ----++ /** Diffuse mass to reachable neighbours over DeltaS. */+ void Predict(float DeltaS, float NowS);+ /**+ * Multiply visible empty cells by 1 - Pd. IsVisible(cell) answers whether the cell is in the view+ * cone with line of sight at 1.0 m and 1.6 m (0.4 m when prone-capable); Eye for the range term.+ */+ void Clear(const FVector& Eye, TFunctionRef<bool(int32 Cell)> IsVisible, float NowS);+ /** The same for a list of cells already known visible (the map's cached visibility). */+ void Clear(const FVector& Eye, TConstArrayView<int32> VisibleCells, float NowS);+ /** Replace the grid by a Gaussian at the sighted pelvis (level known). */+ void ApplySighting(const FVector& PelvisLocation, float NowS);+ /** Multiply by eps + level weight x exp(-d^2 / 2 sd^2). */+ void ApplyHeard(const FVerseHeardPercept& Heard, float NowS);+ /**+ * Multiply by a wedge along a line traced back from Point toward the shooter (BackDirection),+ * up to MaxDistCm (the first opaque piece in the piece belief).+ */+ void ApplyWedge(const FVector& Point, const FVector& BackDirection, float MaxDistCm, float NowS);+ /** Opponent dead: no mass anywhere until a respawn. */+ void ApplyOpponentDead();+ /** Opponent respawned: prior over the 3 best spawn points (already ranked by the caller). */+ void ApplySpawnPrior(TConstArrayView<FVector> RankedSpawnPoints, float NowS);+ /** Renormalise to 1 and mix in the prior, so no active cell is ever exactly 0. */+ void Normalise();++ bool IsOpponentDead() const { return bOpponentDead; }++ /** bot.md 4.3 derived values. bKnown: a sighting in this step. */+ FVerseBeliefDerived ComputeDerived(float NowS, bool bKnown) const;++ /** Sum of active mass (tests: 1 within 1e-6 after Normalise). */+ double TotalMass() const;++ /**+ * Cells reachable from From to To over active adjacency and links, breadth first; empty if+ * none. A believed path: it never uses a link the piece belief has not opened.+ */+ TArray<int32> FindPath(int32 From, int32 To) const;++ /** Bit pattern hash of the mass (replay and counterfactual tests). */+ uint32 HashMass() const;++private:+ struct FNeighbour+ {+ int32 Cell = INDEX_NONE;+ /** dt-independent rate: 1 / traversal seconds. */+ float Rate = 0.f;+ /** Horizontal unit direction (momentum). */+ FVector2f Dir = FVector2f::ZeroVector;+ /** Gating of this edge (links); Always for plain adjacency. */+ EVerseBeliefGate Gate = EVerseBeliefGate::Always;+ int32 GatePiece = INDEX_NONE;+ bool bActive = true;+ /** Learned zone-transition multiplier. */+ float Bias = 1.f;+ /** Index into the 8 adjacency directions, 255 for a link. */+ uint8 DirIndex = 255;+ };++ void RecomputeRateSums();+ /** Momentum weights that depend only on the direction (cached until it or the edges change). */+ void RefreshMomentumWeights(const FVector2f& Dir);+ float ClearPd(int32 Cell, const FVector& Eye) const;++ int32 Level3(const FIntPoint& Column, EVerseArenaLevel Level) const;++ FVerseBeliefTuning Tuning;+ FVector2D Origin = FVector2D::ZeroVector;+ float CellSizeCm = 100.f;+ FIntPoint MinColumn = FIntPoint::ZeroValue;+ FIntPoint ColumnSpan = FIntPoint::ZeroValue;++ TArray<FVerseBeliefCellDesc> Cells;+ TArray<FVector> Centres;+ TArray<uint8> bCellActive;+ /** Per cell: sum of Rate x Bias over its active edges. */+ TArray<float> RateSum;+ /**+ * Derived values: a padded per-level layout (Reach zero columns and rows around each level) so+ * the disc sum of every cell is a few contiguous box-sum passes. DiscPadMask is 1 on active cells.+ */+ int32 DiscPadWidth = 0;+ int32 DiscPadSize = 0;+ TArray<int32> CellDiscPad;+ TArray<int32> DiscPadCell;+ TArray<float> DiscPadMask;+ mutable TArray<float> DiscPadMass;+ /** Horizontal box sums of half-width h, h = 1 .. Reach (h = 0 is the mass itself). */+ mutable TArray<float> DiscPadRows[8];+ mutable TArray<float> DiscPadSum;+ /** Per cell, 4 floats: centre X, Y, Z in metres from the grid middle, and their squared length (moment sums). */+ TArray<float> CellMoment;+ FVector MomentOrigin = FVector::ZeroVector;+ /** Per cell: 1 when active, else 0 (branch-free passes), and the active count. */+ TArray<float> ActiveMaskF;+ int32 ActiveCount = 0;+ /** Dense padded per-level layout for the predict stencil, rebuilt when gates or biases change. */+ int32 DenseSize = 0;+ TArray<int32> CellDense;+ int32 DirOffset[8] = {0, 0, 0, 0, 0, 0, 0, 0};+ TArray<float> DenseRateBias[8];+ TArray<float> DenseRate[8];+ TArray<float> DenseOut;+ TArray<float> DenseDiffuse;+ TArray<float> DenseAdvect;+ /** Momentum, per direction: Cos x Rate / (sum of Cos x Rate of the cell); empty when Cos <= 0. */+ TArray<float> DenseAdvectWeight[8];+ TArray<uint8> DenseHasAdvect;+ float MomentumCos[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};+ FVector2f MomentumWeightsDir = FVector2f::ZeroVector;+ bool bMomentumWeightsValid = false;+ /** Active link edges. */+ TArray<int32> LinkFrom;+ TArray<int32> LinkTo;+ TArray<float> LinkRateBias;+ TArray<float> LinkRate;+ TArray<FVector2f> LinkDirs;+ /** Per link: Cos x Rate / (the from cell's momentum weight sum). */+ TArray<float> LinkAdvectWeight;+ /** Disc row half-widths in columns, index dy + reach. */+ TArray<int32> DiscHalfWidth;+ /** Neighbours of cell i are Neighbours[NeighbourStart[i] .. NeighbourStart[i + 1]). */+ TArray<int32> NeighbourStart;+ TArray<FNeighbour> Neighbours;+ /** Column x level -> cell index or INDEX_NONE. */+ TArray<int32> ColumnLookup;++ TArray<float> P;+ TArray<float> Scratch;+ TArray<float> Prior;+ TArray<float> LastClearedS;+ TArray<float> LastSupportS;+ TArray<EVerseBeliefSupport> LastSupportKind;++ FVector2f MomentumVelocity = FVector2f::ZeroVector;+ float MomentumAtS = 0.f;+ bool bMomentum = false;+ bool bOpponentDead = false;++ /** Disc offsets (column deltas) within ClusterRadius. */+ TArray<FIntPoint> DiscOffsets;+};diff --git a/unreal/Verse/Source/VerseBot/Public/Belief/VerseBeliefMap.h b/unreal/Verse/Source/VerseBot/Public/Belief/VerseBeliefMap.hnew file mode 100644index 0000000000..6dc49b1e4b--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Belief/VerseBeliefMap.h@@ -0,0 +1,116 @@+#pragma once++#include "Belief/VerseBeliefGrid.h"+#include "Belief/VerseOpponentEstimate.h"+#include "Belief/VersePieceBelief.h"+#include "Bot/VersePerceptTypes.h"+#include "CoreMinimal.h"++class IVersePenetrationQuery;+class IVersePieceQuery;++/** World queries the belief layer may use: sight (the fair channel) and the gated piece query. */+struct VERSEBOT_API FVerseBeliefWorld+{+ /** TestSight for clearing cells and seeing pieces. Required. */+ const IVersePenetrationQuery* Sight = nullptr;+ /** Read only through FVersePieceBelief (bot.md F1). Optional (no pieces). */+ const IVersePieceQuery* Pieces = nullptr;+};++struct VERSEBOT_API FVerseBeliefMapConfig+{+ /** The bot's own player state id (kill feed: who died). */+ int32 SelfPlayerId = INDEX_NONE;+ /** Arena spawn points (public arena data), world cm. */+ TArray<FVector> SpawnPoints;+ /** Arena box for the piece layout. */+ FBox ArenaBox = FBox(ForceInit);+ /** Belief step period: 10 Hz (bot.md 2). */+ float StepIntervalS = 0.1f;+ /**+ * TestSight calls per 10 Hz step for clearing cells: one trace per cell test (the sample height+ * rotates through 1.6 m, 1.0 m and, where prone is possible, 0.4 m), the cells in a rotating+ * order. Cached visibility is reused while the eye moved less than VisibilityCacheMoveCm.+ */+ int32 MaxCellSightTestsPerStep = 32;+ /** TestSight calls per 10 Hz step for pieces. */+ int32 MaxPieceSightTestsPerStep = 16;+ /** Clear tests cells up to this range, cm. */+ float ClearRangeCm = 6000.f;+ /** A cached cell visibility is reused while the eye moved less than this, cm. */+ float VisibilityCacheMoveCm = 50.f;+ /** A cached cell visibility expires after this, seconds. */+ float VisibilityCacheMaxAgeS = 2.f;+ /** Static arena piece layout (original bounds). Empty: read from the piece query at Initialize. */+ TArray<FVersePieceLayoutEntry> PieceLayout;+ /** Damage of one own confirmed hit and headshot, for the health estimate, until weapons provide it. */+ float OwnHitDamage = 25.f;+ float OwnHeadshotDamage = 50.f;+};++/**+ * The belief map of one bot (work-packages WP07.5-7.8): the grid, the opponent estimates and the+ * piece belief, fed only by FVersePerceptFrame (bot.md B2). ApplyFrame runs the bot.md 4.2 step at+ * 10 Hz and at once on a positive percept. Deterministic for a given percept stream and world+ * answers (B5); holds nothing that outlives the match.+ */+class VERSEBOT_API FVerseBeliefMap+{+public:+ void Initialize(const FVerseBeliefGridSource& Source, const FVerseBeliefMapConfig& InConfig,+ const FVerseBeliefWorld& World, const FVerseBeliefTuning& Tuning = FVerseBeliefTuning());++ /** Feed one perception frame (every server tick). Returns true when a belief step ran. */+ bool ApplyFrame(const FVersePerceptFrame& Frame, const FVerseBeliefWorld& World);++ /** Own death: belief cleared (bot.md 5.2); the opponent is somewhere. */+ void OnOwnDeath(float NowS);+ /** The bot changed a piece itself (own breach). */+ void OnOwnPieceAction(uint16 Piece, EVersePieceState NewState, float NowS);+ /** Destruction full reset, which both players see. */+ void OnDestructionReset();++ const FVerseBeliefGrid& GetGrid() const { return Grid; }+ FVerseBeliefGrid& GetGridMutable() { return Grid; }+ const FVerseBeliefDerived& GetDerived() const { return Derived; }+ const FVerseOpponentEstimate& GetOpponent() const { return Opponent; }+ FVerseOpponentEstimate& GetOpponentMutable() { return Opponent; }+ const FVersePieceBelief& GetPieces() const { return Pieces; }+ FVersePieceBelief& GetPiecesMutable() { return Pieces; }+ const FVerseBeliefMapConfig& GetConfig() const { return Config; }+ int32 GetStepCount() const { return StepCount; }+ /** TestSight calls the last clear made (cost reports). */+ int32 GetLastClearSightTests() const { return LastClearSightTests; }+ float GetLastStepS() const { return LastStepS; }++ /** Cell visible from the eye in the view cone at 1.6 m or 1.0 m (0.4 m prone-capable). Uncached, all heights. */+ bool TestCellVisible(int32 Cell, const FVector& Eye, const FRotator& View, const IVersePenetrationQuery& Sight) const;++ /** The public spawn rule ranked from Eye: out of sight first, then farthest. */+ TArray<FVector> RankSpawnPoints(const FVector& Eye, const IVersePenetrationQuery* Sight) const;++private:+ void RunClear(const FVerseSelfPercept& Self, const FVerseBeliefWorld& World, float NowS);+ void RefreshGates();++ FVerseBeliefMapConfig Config;+ FVerseBeliefGrid Grid;+ FVerseBeliefDerived Derived;+ FVerseOpponentEstimate Opponent;+ FVersePieceBelief Pieces;++ /** Per cell: cached visibility and where the eye was. */+ TArray<uint8> CachedVisible;+ TArray<FVector> CachedEye;+ TArray<float> CachedAtS;+ /** Next sample height index per cell (one trace per test). */+ TArray<uint8> CachedHeight;+ TArray<int32> VisibleScratch;+ int32 ClearCursor = 0;+ int32 LastClearSightTests = 0;++ float LastStepS = -1.f;+ int32 StepCount = 0;+ bool bHasFrame = false;+};diff --git a/unreal/Verse/Source/VerseBot/Public/Belief/VerseBeliefNavSampler.h b/unreal/Verse/Source/VerseBot/Public/Belief/VerseBeliefNavSampler.hnew file mode 100644index 0000000000..e4debc4ac5--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Belief/VerseBeliefNavSampler.h@@ -0,0 +1,73 @@+#pragma once++#include "Belief/VerseBeliefGrid.h"+#include "CoreMinimal.h"+#include "Templates/Function.h"++class INavigationDataInterface;+class UWorld;++/** How to sample the arena's navmesh into belief cells (contracts/bot.md 4.1). */+struct VERSEBOT_API FVerseBeliefNavSettings+{+ /** The arena zone, world cm (about 50 x 40 m, three levels). */+ FBox ArenaBox = FBox(ForceInit);+ float CellSizeCm = 100.f;+ /** Floor height probed for each level, world cm (Floor, Mid, Upper). */+ float LevelProbeZCm[3] = {0.f, 400.f, 800.f};+ /** Projection extent: horizontal half-size and vertical reach, cm. */+ float ProjectHalfXYCm = 35.f;+ float ProjectHalfZCm = 150.f;+ /** Two cells of one column closer than this in height are the same floor. */+ float SameFloorCm = 80.f;+ /** Authored links in cell coordinates (column + level); resolved to cells after sampling. */+ struct FLink+ {+ FIntPoint FromColumn = FIntPoint::ZeroValue;+ EVerseArenaLevel FromLevel = EVerseArenaLevel::Floor;+ FIntPoint ToColumn = FIntPoint::ZeroValue;+ EVerseArenaLevel ToLevel = EVerseArenaLevel::Floor;+ float TraversalS = 1.f;+ bool bBidirectional = true;+ EVerseBeliefLinkKind Kind = EVerseBeliefLinkKind::Stair;+ EVerseBeliefGate Gate = EVerseBeliefGate::Always;+ int32 GatePiece = INDEX_NONE;+ };+ TArray<FLink> Links;+ /**+ * Piece gates (destruction.md 6.1): the footprint of a piece that carries or opens walkable+ * floor. WhenStanding (a catwalk segment): the sampled cells inside the footprint exist only+ * while the piece is not believed Destroyed. WhenOpen (a breach opening): cells at Level inside+ * the footprint, sampled or not (the intact piece blocks the navmesh), exist only while the piece+ * is believed Breached or Destroyed; their floor is the footprint's bottom.+ */+ struct FPieceFootprint+ {+ int32 Piece = INDEX_NONE;+ FBox Bounds = FBox(ForceInit);+ EVerseBeliefGate Gate = EVerseBeliefGate::WhenStanding;+ EVerseArenaLevel Level = EVerseArenaLevel::Floor;+ };+ TArray<FPieceFootprint> PieceFootprints;+ /** Optional per-cell arena data: VisibilityFactor and zone id at a world point. */+ TFunction<float(const FVector&)> VisibilityAt;+ TFunction<uint8(const FVector&)> ZoneAt;+};++/**+ * Builds a belief grid source from Recast nav (WP07.5): every 1 x 1 m column of the arena box is+ * projected onto the navmesh at each level's probe height; a hit within reach is a cell. Two+ * same-level neighbours are connected when a move along the nav surface from one reaches the other.+ * Piece footprints gate cells, so the grid follows the believed nav through FVerseBeliefGrid::ApplyGates+ * whenever the piece belief changes (WP07.5 "rebuild on believed nav change").+ * Uses only the engine's navigation interface (no NavigationSystem module dependency).+ */+class VERSEBOT_API FVerseBeliefNavSampler+{+public:+ /** Sample the world's main nav data. Returns false (empty source) when the world has no nav. */+ static bool Build(const UWorld& World, const FVerseBeliefNavSettings& Settings, FVerseBeliefGridSource& OutSource);++ /** Sample a given nav data interface (tests, harness). */+ static bool Build(const INavigationDataInterface& Nav, const FVerseBeliefNavSettings& Settings, FVerseBeliefGridSource& OutSource);+};diff --git a/unreal/Verse/Source/VerseBot/Public/Belief/VerseOpponentEstimate.h b/unreal/Verse/Source/VerseBot/Public/Belief/VerseOpponentEstimate.hnew file mode 100644index 0000000000..64f5fb1c91--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Belief/VerseOpponentEstimate.h@@ -0,0 +1,50 @@+#pragma once++#include "Bot/VersePerceptTypes.h"+#include "CoreMinimal.h"++/**+ * What the bot estimates about the opponent beyond position (contracts/bot.md 3.3, 4.1): facing,+ * health from its own confirmed hits, ammo from heard shots. Never read from the opponent's pawn.+ */+struct VERSEBOT_API FVerseOpponentEstimate+{+ // ---- facing (bot.md 4.1) ----+ float LastSeenYawDeg = 0.f;+ /** Server time of the last sighting, seconds; negative when never seen. */+ float LastSeenYawAtS = -1.f;+ /** A reload was heard or seen and no shot since (cleared by a heard or seen shot, or a respawn). */+ bool bHeardReload = false;+ float HeardReloadAtS = -1.f;+ FVector LastSeenLocation = FVector::ZeroVector;+ FVector LastSeenVelocity = FVector::ZeroVector;+ FName LastSeenWeapon;++ // ---- health (public rules: max health, regeneration) ----+ float MaxHealth = 100.f;+ /** Health per second after RegenDelayS without own hits; 0 = the ruleset has none. */+ float RegenPerS = 0.f;+ float RegenDelayS = 0.f;+ float DamageSinceFull = 0.f;+ float LastOwnHitAtS = -1.f;++ // ---- ammo ----+ int32 MagazineSize = 30;+ int32 ShotsSinceReload = 0;++ bool bDead = false;++ void OnSighting(const FVerseSightPercept& Sight, float NowS);+ void OnHeard(const FVerseHeardPercept& Heard, float NowS);+ /** An opponent bolt was seen (a shot): the heard-reload flag no longer holds. */+ void OnSeenShot(float NowS);+ /** A hit marker on the opponent; Damage from the bot's own weapon (public rules). */+ void OnOwnHit(float Damage, float NowS);+ void OnOpponentDead();+ void OnOpponentRespawned();++ float EstimatedHealth(float NowS) const;+ int32 EstimatedAmmo() const;+ /** Seconds since the facing estimate was last refreshed; large when never. */+ float FacingAgeS(float NowS) const;+};diff --git a/unreal/Verse/Source/VerseBot/Public/Belief/VersePieceBelief.h b/unreal/Verse/Source/VerseBot/Public/Belief/VersePieceBelief.hnew file mode 100644index 0000000000..36b70c6053--- /dev/null+++ b/unreal/Verse/Source/VerseBot/Public/Belief/VersePieceBelief.h@@ -0,0 +1,101 @@+#pragma once++#include "CoreMinimal.h"+#include "Destruction/VerseDestructionTypes.h"++class IVersePenetrationQuery;+class IVersePieceQuery;+struct FVerseHeardPercept;++/** What the bot believes about one destructible piece (contracts/bot.md 4.4, destruction.md 6.2). */+struct VERSEBOT_API FVerseBelievedPiece+{+ uint16 Index = 0;+ EVersePieceState State = EVersePieceState::Intact;+ EVersePenetrationMaterial Material = EVersePenetrationMaterial::Concrete;+ FBox Bounds = FBox(ForceInit);+ /** A heard fracture may have changed it; the state is the last one perceived. */+ bool bChangedUnknown = false;+ float LastSeenS = -1.f;+};++/** One piece of the static arena layout (public arena data: index, material, original bounds). */+struct VERSEBOT_API FVersePieceLayoutEntry+{+ uint16 Index = 0;+ EVersePenetrationMaterial Material = EVersePenetrationMaterial::Concrete;+ FBox Bounds = FBox(ForceInit);+};++/**+ * The bot's copy of piece states. The only place in VerseBot that may call+ * IVersePieceQuery::GetPieceState (bot.md F1), and only for a piece it sees this step+ * (destruction.md 6.2 Sight), or after a full reset both players see. Layout (index, material,+ * initial bounds) is public arena data, read at Initialize.+ */+class VERSEBOT_API FVersePieceBelief+{+public:+ /**+ * Learn the layout of every piece in the arena box from the piece query; every piece believed+ * Intact. The query answers with the current bounds, so this is only valid at match start or+ * right after a destruction full reset. A belief created mid-match uses the layout overload.+ */+ void Initialize(const IVersePieceQuery& Query, const FBox& ArenaBox);+ /** Learn the layout from static arena data (original bounds); every piece believed Intact. */+ void Initialize(TConstArrayView<FVersePieceLayoutEntry> Layout);++ /** Destruction full reset: every piece Intact again, flags cleared (both players see it). */+ void ResetAll();++ /**+ * Look at the pieces: a piece with part of its bounds in the view cone and in line of sight+ * enters the belief with its true state and bounds. MaxSightTests bounds the TestSight calls+ * per call (round robin). Returns the number of pieces whose believed state changed.+ */+ int32 ObserveSight(const FVector& Eye, const FRotator& View, const IVersePieceQuery& Query,+ const IVersePenetrationQuery& Sight, float NowS, int32 MaxSightTests = TNumericLimits<int32>::Max());++ /** A heard Noise.Fracture: pieces within 2 sd of the noisy location are "changed, state unknown". */+ void OnHeardFracture(const FVerseHeardPercept& Heard, float NowS);++ /** The bot caused the change itself (its own breach, its own bolts): no error. */+ void OnOwnAction(uint16 Piece, EVersePieceState NewState, float NowS);++ const FVerseBelievedPiece* Find(uint16 Piece) const;+ EVersePieceState GetBelievedState(uint16 Piece) const;+ /** Believed Breached or Destroyed: an opening the bot may plan through. */+ bool IsBelievedOpen(int32 Piece) const;+ /** Not believed Destroyed (a catwalk the bot may walk on). */+ bool IsBelievedStanding(int32 Piece) const;+ int32 Num() const { return Pieces.Num(); }+ TConstArrayView<FVerseBelievedPiece> GetPieces() const { return Pieces; }++ /** Cover dependency sets (bot.md 4.4): a belief change on one of these pieces dirties the cover point. */+ void RegisterCover(int32 CoverId, TConstArrayView<uint16> DependsOn);+ void UnregisterCover(int32 CoverId);+ /** Cover ids whose pieces changed in the belief since the last call. */+ TArray<int32> ConsumeDirtyCover();+ /** Pieces whose believed state changed since the last call (grid gates, nav filter). */+ TArray<uint16> ConsumeChangedPieces();++ /**+ * Distance along a ray to the first piece the belief says stops a bolt (an intact or damaged+ * concrete or armour-steel piece), or MaxDistCm. Used for the hurt wedge.+ */+ float OpaqueDistance(const FVector& Origin, const FVector& Direction, float MaxDistCm) const;++ /** Points of a piece the sight test aims at: centre and 8 corners pulled 10 % inward. */+ static void SightPoints(const FBox& Bounds, FVector OutPoints[9]);++private:+ int32 FindIndex(uint16 Piece) const;+ void MarkChanged(int32 Slot);++ TArray<FVerseBelievedPiece> Pieces;+ TMap<uint16, int32> SlotOf;+ TMap<int32, TArray<uint16>> CoverDeps;+ TSet<int32> DirtyCover;+ TArray<uint16> Changed;+ int32 Cursor = 0;+};diff --git a/unreal/Verse/Source/VerseCombat/Private/Perception/VersePerceptionModel.cpp b/unreal/Verse/Source/VerseCombat/Private/Perception/VersePerceptionModel.cppnew file mode 100644index 0000000000..b910be4b65--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Private/Perception/VersePerceptionModel.cpp@@ -0,0 +1,622 @@+#include "Perception/VersePerceptionModel.h"++#include "Bot/VerseBotTier.h"+#include "Noise/VerseAudibilityTable.h"++namespace+{+ /** Standing sample point heights above the pelvis, cm, in EVerseSightSample order, and lateral offsets. */+ struct FSampleOffset+ {+ float Forward;+ float Right;+ float Up;+ };++ // A 180 cm person with the pelvis at about 95 cm: head 170, neck 155, upper torso 135,+ // pelvis 95, shoulders 145 at +-20, knees 50 at +-12.+ constexpr FSampleOffset StandOffsets[8] = {+ {0.f, 0.f, 75.f},+ {0.f, 0.f, 60.f},+ {0.f, 0.f, 40.f},+ {0.f, 0.f, 0.f},+ {0.f, -20.f, 50.f},+ {0.f, 20.f, 50.f},+ {0.f, -12.f, -45.f},+ {0.f, 12.f, -45.f},+ };++ float StanceHeightScale(EVerseStance Stance)+ {+ switch (Stance)+ {+ case EVerseStance::Crouch:+ return 0.6f;+ case EVerseStance::Prone:+ case EVerseStance::Slide:+ return 0.25f;+ default:+ return 1.f;+ }+ }++ EVerseArenaLevel NeighbourLevel(EVerseArenaLevel Level, FVerseRng& Rng)+ {+ switch (Level)+ {+ case EVerseArenaLevel::Floor:+ return EVerseArenaLevel::Mid;+ case EVerseArenaLevel::Upper:+ return EVerseArenaLevel::Mid;+ default:+ return Rng.NextUnit() < 0.5 ? EVerseArenaLevel::Floor : EVerseArenaLevel::Upper;+ }+ }++ uint32 SecondsToMs(float Seconds)+ {+ return Seconds <= 0.f ? 0u : uint32(FMath::RoundToInt64(double(Seconds) * 1000.0));+ }+}++FVersePerceptionBody::FVersePerceptionBody()+{+ for (FVector& Point : SamplePoints)+ {+ Point = FVector::ZeroVector;+ }+}++void FVersePerceptionBody::SetSamplePointsFromStance()+{+ const float Scale = StanceHeightScale(Stance);+ const FRotator Yaw(0.f, FacingYawDeg, 0.f);+ for (int32 Index = 0; Index < 8; ++Index)+ {+ const FSampleOffset& Offset = StandOffsets[Index];+ const FVector Local(Offset.Forward, Offset.Right, Offset.Up * Scale);+ SamplePoints[Index] = Pelvis + Yaw.RotateVector(Local);+ }+}++EVerseArenaLevel FVersePerceptionWorld::ResolveLevel(const FVector& Location) const+{+ if (LevelOf)+ {+ return LevelOf(Location);+ }+ if (Location.Z >= UpperMinZCm)+ {+ return EVerseArenaLevel::Upper;+ }+ return Location.Z >= MidMinZCm ? EVerseArenaLevel::Mid : EVerseArenaLevel::Floor;+}++float FVersePerceptionWorld::ResolveLevelHeight(EVerseArenaLevel Level) const+{+ if (LevelHeightCm)+ {+ return LevelHeightCm(Level);+ }+ switch (Level)+ {+ case EVerseArenaLevel::Mid:+ return MidMinZCm;+ case EVerseArenaLevel::Upper:+ return UpperMinZCm;+ default:+ return 0.f;+ }+}++float FVersePerceptionWorld::ResolveVisibility(const FVector& Location) const+{+ return VisibilityFactor ? FMath::Clamp(VisibilityFactor(Location), 0.f, 1.f) : 1.f;+}++bool FVersePerceptionWorld::Sight(const FVector& Eye, const FVector& Target) const+{+ return TestSight ? TestSight(Eye, Target) : true;+}++FVersePerceptionProfile FVersePerceptionModel::MakeProfile(const UVerseBotTier& Tier, uint32 Seed)+{+ FVersePerceptionProfile Profile;+ Profile.HearingErrorBaseM = Tier.HearingErrorBaseM;+ Profile.HearingErrorPerM = Tier.HearingErrorPerM;+ Profile.ReactionMs = Tier.ReactionMs;+ Profile.PeripheralReactionMul = Tier.PeripheralReactionMul;+ Profile.PartialExposureAcquireMul = Tier.PartialExposureAcquireMul;+ Profile.TrackLatencyMs = Tier.TrackLatencyMs;+ Profile.Seed = Seed;+ return Profile;+}++void FVersePerceptionModel::AddObserver(int32 PlayerId, const FVersePerceptionProfile& Profile)+{+ RemoveObserver(PlayerId);+ FObserver& Observer = Observers.AddDefaulted_GetRef();+ Observer.PlayerId = PlayerId;+ Observer.Profile = Profile;+ Observer.Rng = FVerseRng(Profile.Seed, 0, EVerseRngSalt::Perception);+}++void FVersePerceptionModel::RemoveObserver(int32 PlayerId)+{+ Observers.RemoveAll([PlayerId](const FObserver& Observer) { return Observer.PlayerId == PlayerId; });+}++bool FVersePerceptionModel::HasObserver(int32 PlayerId) const+{+ return Observers.ContainsByPredicate([PlayerId](const FObserver& Observer) { return Observer.PlayerId == PlayerId; });+}++const FVersePerceptionProfile* FVersePerceptionModel::FindProfile(int32 PlayerId) const+{+ const FObserver* Found =+ Observers.FindByPredicate([PlayerId](const FObserver& Observer) { return Observer.PlayerId == PlayerId; });+ return Found ? &Found->Profile : nullptr;+}++TArray<int32> FVersePerceptionModel::GetObserverIds() const+{+ TArray<int32> Ids;+ for (const FObserver& Observer : Observers)+ {+ Ids.Add(Observer.PlayerId);+ }+ return Ids;+}++FVersePerceptionModel::FObserver* FVersePerceptionModel::Find(int32 PlayerId)+{+ return Observers.FindByPredicate([PlayerId](const FObserver& Observer) { return Observer.PlayerId == PlayerId; });+}++void FVersePerceptionModel::OnNoise(const FVerseNoiseEvent& Event)+{+ for (FObserver& Observer : Observers)+ {+ if (Event.SourceId != Observer.PlayerId)+ {+ Observer.PendingNoise.Add(Event);+ }+ }+}++void FVersePerceptionModel::OnFire(const FVerseFireEvent& Event)+{+ FLiveBolt& Bolt = Bolts.AddDefaulted_GetRef();+ Bolt.ShooterId = Event.ShooterId;+ Bolt.ShotCounter = Event.ShotCounter;+ Bolt.Origin = Event.Origin;+ Bolt.Direction = FVector(Event.Direction).GetSafeNormal();+ Bolt.StartS = Event.ServerTime;+ FBodyCues& Cue = Cues.FindOrAdd(Event.ShooterId);+ Cue.LastFireS = Event.ServerTime;+ if (!Event.WeaponId.IsNone())+ {+ Cue.Weapon = Event.WeaponId;+ }+}++void FVersePerceptionModel::OnReload(const FVerseReloadEvent& Event)+{+ FBodyCues& Cue = Cues.FindOrAdd(Event.PlayerId);+ if (!Event.WeaponId.IsNone())+ {+ Cue.Weapon = Event.WeaponId;+ }+ if (Event.bCancelled)+ {+ Cue.ReloadEndS = -1.f;+ return;+ }+ Cue.ReloadStartS = Event.StartServerTime;+ Cue.ReloadEndS = Event.EndServerTime;+}++FVersePerceptionBody FVersePerceptionModel::WithCues(const FVersePerceptionBody& Body, float NowS) const+{+ FVersePerceptionBody Out = Body;+ if (const FBodyCues* Cue = Cues.Find(Body.PlayerId))+ {+ Out.bFiring |= Cue->LastFireS >= 0.f && NowS >= Cue->LastFireS && NowS - Cue->LastFireS <= VersePerception::FiringVisibleS;+ if (Out.HeldWeaponId.IsNone())+ {+ Out.HeldWeaponId = Cue->Weapon;+ }+ Out.bReloading |= NowS >= Cue->ReloadStartS && NowS < Cue->ReloadEndS;+ }+ return Out;+}++void FVersePerceptionModel::OnHit(const FVerseHitEvent& Event)+{+ if (Event.Source == EVerseDamageSource::Bolt)+ {+ for (FLiveBolt& Bolt : Bolts)+ {+ if (Bolt.ShooterId == Event.InstigatorId && Bolt.ShotCounter == Event.ShotCounter)+ {+ Bolt.EndFlightS = float(FVector::Dist(Bolt.Origin, FVector(Event.ImpactWorld)) / VersePerception::BoltSpeedCmS);+ }+ }+ }+ if (Event.bBlockedBySpawnProtection)+ {+ return;+ }+ if (FObserver* Victim = Find(Event.VictimId))+ {+ Victim->PendingHurt.Add(Event);+ }+ if (Event.InstigatorId != Event.VictimId)+ {+ if (FObserver* Instigator = Find(Event.InstigatorId))+ {+ FVerseHudEvent& Hud = Instigator->PendingHud.AddDefaulted_GetRef();+ Hud.Kind = Event.bKillingBlow ? EVerseHudEventKind::KillMarker+ : Event.bHeadshot ? EVerseHudEventKind::HeadshotMarker+ : EVerseHudEventKind::HitMarker;+ Hud.KillerId = Event.InstigatorId;+ Hud.VictimId = Event.VictimId;+ Hud.Cause = Event.Source;+ Hud.WeaponId = Event.WeaponId;+ Hud.bWallShot = Event.PenetrationCount > 0;+ Hud.ServerTimeMs = SecondsToMs(Event.ServerTime);+ }+ }+}++void FVersePerceptionModel::OnDeath(const FVerseDeathEvent& Event, const FVersePerceptionBody* KillerBody)+{+ for (FObserver& Observer : Observers)+ {+ FVerseHudEvent& Hud = Observer.PendingHud.AddDefaulted_GetRef();+ Hud.Kind = EVerseHudEventKind::Kill;+ Hud.KillerId = Event.KillerId;+ Hud.VictimId = Event.VictimId;+ Hud.Cause = Event.Cause;+ Hud.WeaponId = Event.WeaponId;+ Hud.ServerTimeMs = SecondsToMs(Event.ServerTime);+ // The kill cam shows the victim where the killer stood (bot.md 3.3).+ if (Observer.PlayerId == Event.VictimId && KillerBody && Event.KillerId != Event.VictimId)+ {+ Hud.bKillerPositionShown = true;+ Hud.KillerPosition = KillerBody->Pelvis;+ }+ }+ if (Event.RespawnAt > 0.f)+ {+ Respawns.Add({Event.VictimId, SecondsToMs(Event.RespawnAt)});+ }+}++void FVersePerceptionModel::ResetEvents()+{+ Bolts.Reset();+ Respawns.Reset();+ Cues.Reset();+ for (FObserver& Observer : Observers)+ {+ Observer.PendingNoise.Reset();+ Observer.PendingHurt.Reset();+ Observer.PendingHud.Reset();+ Observer.Contacts.Reset();+ }+}++FVersePerceptionModel::FCone FVersePerceptionModel::ConeFor(bool bAds, float AdsFovDeg)+{+ FCone Cone;+ if (bAds)+ {+ Cone.HalfAngleDeg = 0.5f * AdsFovDeg + VersePerception::AdsMarginDeg;+ Cone.VerticalHalfAngleDeg = VersePerception::AdsVerticalHalfAngleDeg;+ }+ return Cone;+}++FVersePerceptionModel::EConeZone FVersePerceptionModel::Classify(+ const FVector& Eye, const FRotator& View, const FCone& Cone, const FVector& Point)+{+ const FVector Local = View.UnrotateVector(Point - Eye);+ const double Horizontal = FMath::Sqrt(Local.X * Local.X + Local.Y * Local.Y);+ if (Horizontal < KINDA_SMALL_NUMBER && FMath::Abs(Local.Z) < KINDA_SMALL_NUMBER)+ {+ return EConeZone::Inside;+ }+ const double HorizontalDeg = FMath::RadiansToDegrees(FMath::Atan2(FMath::Abs(Local.Y), Local.X));+ const double VerticalDeg = FMath::RadiansToDegrees(FMath::Atan2(FMath::Abs(Local.Z), Horizontal));+ if (VerticalDeg > Cone.VerticalHalfAngleDeg)+ {+ return EConeZone::Outside;+ }+ if (HorizontalDeg <= Cone.HalfAngleDeg)+ {+ return EConeZone::Inside;+ }+ return HorizontalDeg <= Cone.PeripheralHalfAngleDeg ? EConeZone::Peripheral : EConeZone::Outside;+}++FVersePerceptFrame FVersePerceptionModel::BuildFrame(int32 ObserverId, const FVersePerceptionObserverInput& Input,+ TConstArrayView<FVersePerceptionBody> Bodies, const FVersePerceptionWorld& World, uint32 NowMs, float DeltaS)+{+ FVersePerceptFrame Frame;+ Frame.ServerTimeMs = NowMs;+ Frame.Self = Input.Self;++ ClockS = float(double(NowMs) / 1000.0);+ // Respawns that are due reach every other observer's kill feed.+ for (int32 Index = Respawns.Num() - 1; Index >= 0; --Index)+ {+ if (Respawns[Index].AtMs <= NowMs)+ {+ for (FObserver& Other : Observers)+ {+ if (Other.PlayerId != Respawns[Index].PlayerId)+ {+ FVerseHudEvent& Hud = Other.PendingHud.AddDefaulted_GetRef();+ Hud.Kind = EVerseHudEventKind::OpponentRespawned;+ Hud.KillerId = INDEX_NONE;+ Hud.VictimId = Respawns[Index].PlayerId;+ Hud.ServerTimeMs = Respawns[Index].AtMs;+ }+ }+ Respawns.RemoveAt(Index);+ }+ }+ Bolts.RemoveAll([this](const FLiveBolt& Bolt) {+ return ClockS - Bolt.StartS > FMath::Min(Bolt.EndFlightS, VersePerception::BoltMaxLifeS) + 0.25f;+ });++ FObserver* Observer = Find(ObserverId);+ if (!Observer)+ {+ return Frame;+ }++ // Order is fixed (B5): sight, bolts, hearing, hurt, HUD. Only hearing and hurt draw from the RNG.+ BuildSightings(*Observer, Input, Bodies, World, NowMs, Frame);+ BuildBolts(*Observer, Input, World, NowMs, DeltaS, Frame);+ BuildHeard(*Observer, Input, World, NowMs, Frame);+ BuildHurt(*Observer, NowMs, Frame);+ BuildHud(*Observer, NowMs, Frame);+ Observer->LastFrameMs = NowMs;+ Observer->bHasFrame = true;+ return Frame;+}++void FVersePerceptionModel::BuildSightings(FObserver& Observer, const FVersePerceptionObserverInput& Input,+ TConstArrayView<FVersePerceptionBody> Bodies, const FVersePerceptionWorld& World, uint32 NowMs, FVersePerceptFrame& Out)+{+ const FVector Eye = Input.Self.EyeLocation;+ const FRotator View = Input.Self.ViewRotation;+ const FCone Cone = ConeFor(Input.bAds, Input.AdsFovDeg);++ const float NowS = float(double(NowMs) / 1000.0);+ for (const FVersePerceptionBody& Truth : Bodies)+ {+ if (Truth.PlayerId == Observer.PlayerId || !Truth.bAlive)+ {+ continue;+ }+ const FVersePerceptionBody Body = WithCues(Truth, NowS);+ uint8 Mask = 0;+ bool bAnyInside = false;+ bool bAnyPeripheral = false;+ for (int32 Index = 0; Index < 8; ++Index)+ {+ const EConeZone Zone = Classify(Eye, View, Cone, Body.SamplePoints[Index]);+ if (Zone == EConeZone::Outside)+ {+ continue;+ }+ if (World.Sight(Eye, Body.SamplePoints[Index]))+ {+ Mask |= uint8(1u << Index);+ bAnyInside |= Zone == EConeZone::Inside;+ bAnyPeripheral |= Zone == EConeZone::Peripheral;+ }+ }+ const bool bAware = FVector::DistSquared(Eye, Body.Pelvis) <= FMath::Square(VersePerception::AwarenessRadiusCm);+ const bool bPeripheralNotice =+ bAnyPeripheral && (Body.Velocity.Size() > VersePerception::PeripheralSpeedCmS || Body.bFiring);+ // Awareness alone (bot.md 3.1 "felt, heard"): only with a clear line to the body. Behind a+ // wall it is not noticed at all; its noises still reach the hearing path (F2, B2).+ const bool bFeltOnly = bAware && !bAnyInside && !bPeripheralNotice;+ bool bCandidate = bAnyInside || bPeripheralNotice || bAware;+ if (bFeltOnly)+ {+ bool bClearLine = false;+ for (int32 Index = 0; Index < 8 && !bClearLine; ++Index)+ {+ bClearLine = World.Sight(Eye, Body.SamplePoints[Index]);+ }+ bCandidate = bClearLine;+ }++ if (!bCandidate)+ {+ if (FContact* Contact = Observer.Contacts.Find(Body.PlayerId))+ {+ Contact->bVisibleLastTick = false;+ }+ continue;+ }++ FContact& Contact = Observer.Contacts.FindOrAdd(Body.PlayerId);+ if (!Contact.bVisibleLastTick)+ {+ Contact.VisibleSinceMs = NowMs;+ Contact.bVisibleLastTick = true;+ }+ // Dark zones lengthen the time to notice a target by 1 / VisibilityFactor (bot.md 3.1).+ // The base reaction, the peripheral and the partial-exposure multipliers are the aim+ // layer's (bot.md 8.1), so the service adds only the dark-zone part.+ if (!bAware)+ {+ const float Factor = World.ResolveVisibility(Body.Pelvis);+ if (Factor <= 0.f)+ {+ continue;+ }+ const double ExtraMs = double(Observer.Profile.ReactionMs.X) * (1.0 / double(Factor) - 1.0);+ if (double(NowMs - Contact.VisibleSinceMs) < ExtraMs)+ {+ continue;+ }+ }++ FVerseSightPercept& Sight = Out.Sightings.AddDefaulted_GetRef();+ Sight.PerceptId = Observer.NextPerceptId++;+ Sight.PelvisLocation = Body.Pelvis;+ if (bFeltOnly)+ {+ // Felt, not seen: where it is, nothing a look would show (no mask, no visual fields).+ Sight.VisibleMask = 0;+ Sight.bPeripheral = true;+ continue;+ }+ Sight.Velocity = Body.Velocity;+ Sight.FacingYawDeg = Body.FacingYawDeg;+ Sight.FacingPitchDeg = Body.FacingPitchDeg;+ Sight.Stance = Body.Stance;+ Sight.LeanQuantized = Body.LeanQuantized;+ Sight.bAds = Body.bAds;+ Sight.HeldWeaponId = Body.HeldWeaponId;+ Sight.bReloading = Body.bReloading;+ Sight.bSpawnProtected = Body.bSpawnProtected;+ Sight.VisibleMask = Mask;+ Sight.bPeripheral = !bAnyInside;+ }+}++void FVersePerceptionModel::BuildBolts(FObserver& Observer, const FVersePerceptionObserverInput& Input,+ const FVersePerceptionWorld& World, uint32 NowMs, float DeltaS, FVersePerceptFrame& Out)+{+ const FVector Eye = Input.Self.EyeLocation;+ const FRotator View = Input.Self.ViewRotation;+ const FCone Cone = ConeFor(Input.bAds, Input.AdsFovDeg);+ const float NowS = float(double(NowMs) / 1000.0);++ for (const FLiveBolt& Bolt : Bolts)+ {+ if (Bolt.ShooterId == Observer.PlayerId)+ {+ continue;+ }+ const float End = FMath::Min(Bolt.EndFlightS, VersePerception::BoltMaxLifeS);+ const float T1 = FMath::Min(NowS - Bolt.StartS, End);+ const float T0 = FMath::Max(0.f, NowS - FMath::Max(DeltaS, 0.f) - Bolt.StartS);+ if (T1 <= T0)+ {+ continue;+ }+ const float Times[3] = {T1, 0.5f * (T0 + T1), T0};+ for (const float T : Times)+ {+ const FVector Point = Bolt.Origin + Bolt.Direction * (VersePerception::BoltSpeedCmS * T);+ if (Classify(Eye, View, Cone, Point) == EConeZone::Inside && World.Sight(Eye, Point))+ {+ FVerseBoltPercept& Percept = Out.Bolts.AddDefaulted_GetRef();+ Percept.PerceptId = Observer.NextPerceptId++;+ Percept.Position = Point;+ Percept.Direction = Bolt.Direction;+ Percept.ServerTimeMs = NowMs;+ break;+ }+ }+ }+}++void FVersePerceptionModel::BuildHeard(FObserver& Observer, const FVersePerceptionObserverInput& Input,+ const FVersePerceptionWorld& World, uint32 NowMs, FVersePerceptFrame& Out)+{+ if (!World.Audibility)+ {+ Observer.PendingNoise.Reset();+ return;+ }+ const FVector Eye = Input.Self.EyeLocation;+ const EVerseArenaLevel ObserverLevel = World.ResolveLevel(Input.Self.Location);++ for (const FVerseNoiseEvent& Event : Observer.PendingNoise)+ {+ // Every audible range comes from the audibility table (DA_Audibility), never from code.+ const UVerseAudibilityTable& AudibilityTable = *World.Audibility;+ const FVerseAudibilityRow* Row = AudibilityTable.FindRow(Event.Noise);+ if (!Row)+ {+ // Crouch walk, prone crawl and standing still raise no event; an unknown tag is never heard.+ continue;+ }+ const float RangeM = AudibilityTable.GetAudibleRangeM(Event.Noise, Event.Loudness);+ const float DistanceM = float(FVector::Dist(Eye, Event.Location) / 100.0);+ if (DistanceM > RangeM)+ {+ continue;+ }+ const bool bLineOfSight = World.Sight(Eye, Event.Location);+ const float SdM = (Observer.Profile.HearingErrorBaseM + Observer.Profile.HearingErrorPerM * DistanceM) *+ Row->ErrorMultiplier * (bLineOfSight ? 1.f : VersePerception::NoLineOfSightErrorMul);++ const double Dx = Observer.Rng.Gaussian(0.0, double(SdM) * 100.0);+ const double Dy = Observer.Rng.Gaussian(0.0, double(SdM) * 100.0);++ const EVerseArenaLevel TrueLevel = World.ResolveLevel(Event.Location);+ const bool bNear = FMath::Abs(int32(TrueLevel) - int32(ObserverLevel)) <= 1;+ const double Correct = bNear ? VersePerception::LevelGuessNear : VersePerception::LevelGuessFar;+ const EVerseArenaLevel Guess = Observer.Rng.NextUnit() < Correct ? TrueLevel : NeighbourLevel(TrueLevel, Observer.Rng);++ FVerseHeardPercept& Heard = Out.Heard.AddDefaulted_GetRef();+ Heard.PerceptId = Observer.NextPerceptId++;+ Heard.Noise = Event.Noise;+ Heard.ErrorSdM = SdM;+ Heard.LevelGuess = Guess;+ Heard.ServerTimeMs = SecondsToMs(Event.ServerTime);+ if (SdM > 0.f)+ {+ // The height comes from the level guess only, never from the true source.+ Heard.Location = FVector(Event.Location.X + Dx, Event.Location.Y + Dy, World.ResolveLevelHeight(Guess));+ }+ else+ {+ // Noise.Impact: the impact point itself (bot.md 3.2), which is not the opponent's position.+ Heard.Location = Event.Location;+ }+ }+ Observer.PendingNoise.Reset();+}++void FVersePerceptionModel::BuildHurt(FObserver& Observer, uint32 NowMs, FVersePerceptFrame& Out)+{+ if (Observer.PendingHurt.Num() == 0)+ {+ return;+ }+ float Damage = 0.f;+ const FVerseHitEvent& Last = Observer.PendingHurt.Last();+ for (const FVerseHitEvent& Hit : Observer.PendingHurt)+ {+ Damage += Hit.Damage;+ }+ // Direction toward the shooter, uniformly within the +-8 deg cone (bot.md 3.2).+ const FVector From = -FVector(Last.Direction).GetSafeNormal();+ const FVector Noisy = Observer.Rng.ConeDirection(From, VersePerception::HurtDirectionErrorDeg);++ Out.bHasHurt = true;+ Out.Hurt.PerceptId = Observer.NextPerceptId++;+ Out.Hurt.IncomingDirection = Noisy.GetSafeNormal();+ Out.Hurt.Damage = Damage;+ Out.Hurt.Source = Last.Source;+ Out.Hurt.ServerTimeMs = NowMs;+ Observer.PendingHurt.Reset();+}++void FVersePerceptionModel::BuildHud(FObserver& Observer, uint32 NowMs, FVersePerceptFrame& Out)+{+ Out.Hud.Append(Observer.PendingHud);+ Observer.PendingHud.Reset();+}diff --git a/unreal/Verse/Source/VerseCombat/Private/Perception/VersePerceptionService.cpp b/unreal/Verse/Source/VerseCombat/Private/Perception/VersePerceptionService.cppnew file mode 100644index 0000000000..f5d3d06c6b--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Private/Perception/VersePerceptionService.cpp@@ -0,0 +1,410 @@+#include "Perception/VersePerceptionService.h"++#include "Components/SkeletalMeshComponent.h"+#include "Damage/VerseCombatStateComponent.h"+#include "Destruction/VerseDestructionInterfaces.h"+#include "Engine/World.h"+#include "EngineUtils.h"+#include "Events/VerseEventHub.h"+#include "GameFramework/Character.h"+#include "GameFramework/Controller.h"+#include "GameFramework/Pawn.h"+#include "GameFramework/PlayerState.h"+#include "Movement/VerseMovementQuery.h"+#include "Noise/VerseAudibilityTable.h"+#include "Perception/VersePlainSightQuery.h"+#include "Stats/Stats.h"++const FName UVersePerceptionService::SampleBones[8] = {+ TEXT("Head"),+ TEXT("Neck"),+ TEXT("Spine_03"),+ TEXT("Hips"),+ TEXT("UpperArm_L"),+ TEXT("UpperArm_R"),+ TEXT("Calf_L"),+ TEXT("Calf_R"),+};++const FName UVersePerceptionService::EyeBone(TEXT("Camera"));++namespace+{+ const IVerseMovementQuery* FindMovementQuery(const APawn& Pawn)+ {+ if (const IVerseMovementQuery* OnPawn = Cast<IVerseMovementQuery>(const_cast<APawn*>(&Pawn)))+ {+ return OnPawn;+ }+ TInlineComponentArray<UActorComponent*> Components(&Pawn);+ for (UActorComponent* Component : Components)+ {+ if (const IVerseMovementQuery* Query = Cast<IVerseMovementQuery>(Component))+ {+ return Query;+ }+ }+ return nullptr;+ }++ const USkeletalMeshComponent* FindMesh(const APawn& Pawn)+ {+ if (const ACharacter* Character = Cast<ACharacter>(&Pawn))+ {+ if (Character->GetMesh())+ {+ return Character->GetMesh();+ }+ }+ return Pawn.FindComponentByClass<USkeletalMeshComponent>();+ }++ bool BoneLocation(const USkeletalMeshComponent* Mesh, const FName& Bone, FVector& Out)+ {+ if (!Mesh || !Mesh->GetSkeletalMeshAsset() || Mesh->GetBoneIndex(Bone) == INDEX_NONE)+ {+ return false;+ }+ Out = Mesh->GetBoneLocation(Bone);+ return true;+ }++ EVerseStance StanceOf(const APawn& Pawn, const IVerseMovementQuery* Query)+ {+ if (Query)+ {+ return Query->GetStance();+ }+ const ACharacter* Character = Cast<ACharacter>(&Pawn);+ return Character && Character->bIsCrouched ? EVerseStance::Crouch : EVerseStance::Stand;+ }+}++UVersePerceptionService* UVersePerceptionService::Get(const UObject* WorldContextObject)+{+ const UWorld* World = WorldContextObject ? WorldContextObject->GetWorld() : nullptr;+ return World ? World->GetSubsystem<UVersePerceptionService>() : nullptr;+}++void UVersePerceptionService::Initialize(FSubsystemCollectionBase& Collection)+{+ Collection.InitializeDependency(UVerseEventHub::StaticClass());+ Super::Initialize(Collection);+ SetSightQuery(NewObject<UVersePlainSightQuery>(this));+ Audibility = NewObject<UVerseAudibilityTable>(this);+ BindHub();+}++void UVersePerceptionService::Deinitialize()+{+ UnbindHub();+ Registered.Reset();+ Super::Deinitialize();+}++bool UVersePerceptionService::DoesSupportWorldType(const EWorldType::Type WorldType) const+{+ return WorldType == EWorldType::Game || WorldType == EWorldType::PIE;+}++TStatId UVersePerceptionService::GetStatId() const+{+ RETURN_QUICK_DECLARE_CYCLE_STAT(UVersePerceptionService, STATGROUP_Tickables);+}++void UVersePerceptionService::BindHub()+{+ UVerseEventHub* HubPtr = UVerseEventHub::Get(this);+ if (!HubPtr)+ {+ return;+ }+ Hub = HubPtr;+ NoiseHandle = HubPtr->OnNoise.AddUObject(this, &UVersePerceptionService::HandleNoise);+ FireHandle = HubPtr->OnFire.AddUObject(this, &UVersePerceptionService::HandleFire);+ ReloadHandle = HubPtr->OnReload.AddUObject(this, &UVersePerceptionService::HandleReload);+ HitHandle = HubPtr->OnHit.AddUObject(this, &UVersePerceptionService::HandleHit);+ DeathHandle = HubPtr->OnDeath.AddUObject(this, &UVersePerceptionService::HandleDeath);+ ArenaHandle = HubPtr->OnArenaSwitch.AddUObject(this, &UVersePerceptionService::HandleArenaSwitch);+}++void UVersePerceptionService::UnbindHub()+{+ if (UVerseEventHub* HubPtr = Hub.Get())+ {+ HubPtr->OnNoise.Remove(NoiseHandle);+ HubPtr->OnFire.Remove(FireHandle);+ HubPtr->OnReload.Remove(ReloadHandle);+ HubPtr->OnHit.Remove(HitHandle);+ HubPtr->OnDeath.Remove(DeathHandle);+ HubPtr->OnArenaSwitch.Remove(ArenaHandle);+ }+ Hub.Reset();+}++int32 UVersePerceptionService::PlayerIdOf(const AController& Controller)+{+ return Controller.PlayerState ? Controller.PlayerState->GetPlayerId() : INDEX_NONE;+}++bool UVersePerceptionService::IsServer() const+{+ const UWorld* World = GetWorld();+ return World && World->GetNetMode() != NM_Client;+}++void UVersePerceptionService::RegisterObserver(AController* Observer, const FVersePerceptionProfile& Profile)+{+ if (!Observer)+ {+ return;+ }+ UnregisterObserver(Observer);+ FRegistered& Entry = Registered.AddDefaulted_GetRef();+ Entry.Controller = Observer;+ Entry.PlayerId = PlayerIdOf(*Observer);+ Model.AddObserver(Entry.PlayerId, Profile);+}++void UVersePerceptionService::UnregisterObserver(AController* Observer)+{+ for (int32 Index = Registered.Num() - 1; Index >= 0; --Index)+ {+ if (Registered[Index].Controller.Get() == Observer || !Registered[Index].Controller.IsValid())+ {+ Model.RemoveObserver(Registered[Index].PlayerId);+ Registered.RemoveAt(Index);+ }+ }+}++bool UVersePerceptionService::IsRegistered(const AController* Observer) const+{+ return Registered.ContainsByPredicate([Observer](const FRegistered& Entry) { return Entry.Controller.Get() == Observer; });+}++void UVersePerceptionService::SetSightQuery(TScriptInterface<IVersePenetrationQuery> Query)+{+ SightQueryObject = Query.GetObject();+ SightQuery = Query.GetInterface();+}++void UVersePerceptionService::SetAudibilityTable(const UVerseAudibilityTable* Table)+{+ if (Table)+ {+ Audibility = Table;+ }+}++void UVersePerceptionService::SetVisibilityFactorProvider(TFunction<float(const FVector&)> Provider)+{+ VisibilityProvider = MoveTemp(Provider);+}++void UVersePerceptionService::SetLevelBands(float InMidMinZCm, float InUpperMinZCm)+{+ MidMinZCm = InMidMinZCm;+ UpperMinZCm = InUpperMinZCm;+}++void UVersePerceptionService::SetSelfPerceptFiller(TFunction<void(const APawn&, FVerseSelfPercept&)> Filler)+{+ SelfFiller = MoveTemp(Filler);+}++void UVersePerceptionService::SetBodyFiller(TFunction<void(const APawn&, FVersePerceptionBody&)> Filler)+{+ BodyFiller = MoveTemp(Filler);+}++void UVersePerceptionService::HandleReload(const FVerseReloadEvent& Event)+{+ Model.OnReload(Event);+}++void UVersePerceptionService::HandleNoise(const FVerseNoiseEvent& Event)+{+ Model.OnNoise(Event);+}++void UVersePerceptionService::HandleFire(const FVerseFireEvent& Event)+{+ Model.OnFire(Event);+}++void UVersePerceptionService::HandleHit(const FVerseHitEvent& Event)+{+ Model.OnHit(Event);+}++void UVersePerceptionService::HandleDeath(const FVerseDeathEvent& Event)+{+ TOptional<FVersePerceptionBody> Killer;+ if (const UWorld* World = GetWorld())+ {+ for (TActorIterator<APawn> It(World); It; ++It)+ {+ const APlayerState* State = It->GetPlayerState();+ if (State && State->GetPlayerId() == Event.KillerId)+ {+ Killer = MakeBody(**It, Event.KillerId);+ break;+ }+ }+ }+ Model.OnDeath(Event, Killer.GetPtrOrNull());+}++void UVersePerceptionService::HandleArenaSwitch(const FVerseArenaSwitchEvent& Event)+{+ Model.ResetEvents();+}++FVersePerceptionBody UVersePerceptionService::MakeBody(const APawn& Pawn, int32 PlayerId)+{+ FVersePerceptionBody Body;+ Body.PlayerId = PlayerId;+ const IVerseMovementQuery* Query = FindMovementQuery(Pawn);+ const USkeletalMeshComponent* Mesh = FindMesh(Pawn);++ Body.Velocity = Pawn.GetVelocity();+ Body.FacingYawDeg = float(Pawn.GetActorRotation().Yaw);+ const FRotator Aim = Pawn.GetBaseAimRotation();+ Body.FacingPitchDeg = float(FRotator::NormalizeAxis(Aim.Pitch));+ Body.Stance = StanceOf(Pawn, Query);+ Body.LeanQuantized = Query ? Query->GetLeanQuantized() : 0;+ if (const UVerseCombatStateComponent* Combat = Pawn.FindComponentByClass<UVerseCombatStateComponent>())+ {+ Body.bAlive = Combat->Phase != EVerseCombatPhase::Dead;+ Body.bSpawnProtected = Combat->bSpawnProtected;+ }++ if (!BoneLocation(Mesh, SampleBones[int32(EVerseSightSample::Pelvis)], Body.Pelvis))+ {+ Body.Pelvis = Pawn.GetActorLocation();+ }+ bool bAllBones = Mesh != nullptr;+ for (int32 Index = 0; Index < 8 && bAllBones; ++Index)+ {+ bAllBones = BoneLocation(Mesh, SampleBones[Index], Body.SamplePoints[Index]);+ }+ if (!bAllBones)+ {+ Body.SetSamplePointsFromStance();+ }++ if (!BoneLocation(Mesh, EyeBone, Body.Eye))+ {+ FRotator Unused;+ Pawn.GetActorEyesViewPoint(Body.Eye, Unused);+ }+ Body.View = Aim;+ return Body;+}++void UVersePerceptionService::GatherBodies(TArray<FVersePerceptionBody>& OutBodies) const+{+ OutBodies.Reset();+ const UWorld* World = GetWorld();+ if (!World)+ {+ return;+ }+ for (TActorIterator<APawn> It(World); It; ++It)+ {+ const APlayerState* State = It->GetPlayerState();+ if (!State)+ {+ continue;+ }+ FVersePerceptionBody& Body = OutBodies.Add_GetRef(MakeBody(**It, State->GetPlayerId()));+ if (BodyFiller)+ {+ BodyFiller(**It, Body);+ }+ }+ // Actor iteration order is not part of the contract; sort so frames are deterministic (B5).+ OutBodies.Sort([](const FVersePerceptionBody& A, const FVersePerceptionBody& B) { return A.PlayerId < B.PlayerId; });+}++FVersePerceptionWorld UVersePerceptionService::MakeWorld() const+{+ FVersePerceptionWorld World;+ if (IVersePenetrationQuery* Query = SightQuery)+ {+ World.TestSight = [Query](const FVector& Eye, const FVector& Target) { return Query->TestSight(Eye, Target); };+ }+ World.VisibilityFactor = VisibilityProvider;+ World.Audibility = Audibility.Get();+ World.MidMinZCm = MidMinZCm;+ World.UpperMinZCm = UpperMinZCm;+ return World;+}++void UVersePerceptionService::Tick(float DeltaTime)+{+ if (IsServer())+ {+ StepPerception(DeltaTime);+ }+}++void UVersePerceptionService::StepPerception(float DeltaS)+{+ const UWorld* World = GetWorld();+ if (!World || Registered.Num() == 0)+ {+ return;+ }+ LastStepDeltaS = DeltaS;+ TArray<FVersePerceptionBody> Bodies;+ GatherBodies(Bodies);+ const FVersePerceptionWorld PerceptionWorld = MakeWorld();+ const uint32 NowMs = uint32(FMath::RoundToInt64(World->GetTimeSeconds() * 1000.0));++ // Copy: a delegate may unregister an observer.+ const TArray<FRegistered> Entries = Registered;+ for (const FRegistered& Entry : Entries)+ {+ AController* Controller = Entry.Controller.Get();+ if (!Controller)+ {+ continue;+ }+ FVersePerceptionObserverInput Input;+ if (const APawn* Pawn = Controller->GetPawn())+ {+ const FVersePerceptionBody* Own =+ Bodies.FindByPredicate([&Entry](const FVersePerceptionBody& Body) { return Body.PlayerId == Entry.PlayerId; });+ FVersePerceptionBody Body = Own ? *Own : MakeBody(*Pawn, Entry.PlayerId);+ if (!Own && BodyFiller)+ {+ BodyFiller(*Pawn, Body);+ }+ Input.Self.Location = Pawn->GetActorLocation();+ Input.Self.Velocity = Body.Velocity;+ Input.Self.EyeLocation = Body.Eye;+ Input.Self.ViewRotation = Controller->GetControlRotation();+ Input.Self.Stance = Body.Stance;+ Input.Self.bSpawnProtected = Body.bSpawnProtected;+ Input.Self.Phase = Body.bAlive ? EVerseCombatPhase::Alive : EVerseCombatPhase::Dead;+ if (const UVerseCombatStateComponent* Combat = Pawn->FindComponentByClass<UVerseCombatStateComponent>())+ {+ Input.Self.Phase = Combat->Phase;+ }+ Input.bAds = Body.bAds;+ Input.AdsFovDeg = Body.AdsFovDeg;+ if (SelfFiller)+ {+ SelfFiller(*Pawn, Input.Self);+ }+ }+ else+ {+ Input.Self.Phase = EVerseCombatPhase::Dead;+ }+ const FVersePerceptFrame Frame = Model.BuildFrame(Entry.PlayerId, Input, Bodies, PerceptionWorld, NowMs, DeltaS);+ OnPerceptFrame.Broadcast(Controller, Frame);+ }+}diff --git a/unreal/Verse/Source/VerseCombat/Private/Perception/VersePlainSightQuery.cpp b/unreal/Verse/Source/VerseCombat/Private/Perception/VersePlainSightQuery.cppnew file mode 100644index 0000000000..91759c3da1--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Private/Perception/VersePlainSightQuery.cpp@@ -0,0 +1,22 @@+#include "Perception/VersePlainSightQuery.h"++#include "CollisionQueryParams.h"+#include "Engine/World.h"++TArray<FVersePenetrationHit> UVersePlainSightQuery::TraceBolt(const FVector& Origin, const FVector& Dir, float MaxDist,+ float Power, float Damage, uint8 RadiusMm, int32 MaxPieces) const+{+ return {};+}++bool UVersePlainSightQuery::TestSight(const FVector& Eye, const FVector& Target) const+{+ const UWorld* World = GetWorld();+ if (!World)+ {+ return true;+ }+ static const FName TraceTag(TEXT("VerseSight"));+ FCollisionQueryParams Params(TraceTag, false);+ return !World->LineTraceTestByChannel(Eye, Target, SightChannel, Params);+}diff --git a/unreal/Verse/Source/VerseCombat/Private/Perception/VersePlainSightQuery.h b/unreal/Verse/Source/VerseCombat/Private/Perception/VersePlainSightQuery.hnew file mode 100644index 0000000000..ddd151a8fe--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Private/Perception/VersePlainSightQuery.h@@ -0,0 +1,26 @@+#pragma once++#include "CoreMinimal.h"+#include "Destruction/VerseDestructionInterfaces.h"+#include "UObject/Object.h"+#include "VerseCollision.h"++#include "VersePlainSightQuery.generated.h"++/**+ * Stand-in for WP03's penetration query until it lands (work-packages WP07 "Depends on"): sight+ * is a plain line trace on the VerseSight channel, where pawns, glass and grating do not block.+ * Holes in intact pieces are not honoured (the piece proxy blocks); TraceBolt enters nothing.+ */+UCLASS()+class UVersePlainSightQuery : public UObject, public IVersePenetrationQuery+{+ GENERATED_BODY()++public:+ static constexpr ECollisionChannel SightChannel = VerseCollision::Sight;++ virtual TArray<FVersePenetrationHit> TraceBolt(const FVector& Origin, const FVector& Dir, float MaxDist, float Power,+ float Damage, uint8 RadiusMm, int32 MaxPieces) const override;+ virtual bool TestSight(const FVector& Eye, const FVector& Target) const override;+};diff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Perception/Fakes/FakeVersePenetrationQuery.h b/unreal/Verse/Source/VerseCombat/Private/Tests/Perception/Fakes/FakeVersePenetrationQuery.hnew file mode 100644index 0000000000..56a79cf0e0--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Perception/Fakes/FakeVersePenetrationQuery.h@@ -0,0 +1,71 @@+#pragma once++#if WITH_DEV_AUTOMATION_TESTS++#include "CoreMinimal.h"+#include "Destruction/VerseDestructionInterfaces.h"++namespace VerseCombatPerceptionTests+{+ /** An occluder: an opaque box, optionally with see-through holes (boxes through its thickness). */+ struct FFakeOccluder+ {+ FBox Box = FBox(ForceInit);+ TArray<FBox> Holes;+ };++ /**+ * Fake of WP03's IVersePenetrationQuery (work-packages 0.3): sight is blocked by opaque boxes+ * unless the segment enters the box through one of its holes. Implements the contract exactly.+ */+ class FFakeVersePenetrationQuery : public IVersePenetrationQuery+ {+ public:+ TArray<FFakeOccluder> Occluders;+ mutable int32 SightCalls = 0;++ FFakeOccluder& AddWall(const FVector& Min, const FVector& Max)+ {+ FFakeOccluder& Occluder = Occluders.AddDefaulted_GetRef();+ Occluder.Box = FBox(Min, Max);+ return Occluder;+ }++ virtual TArray<FVersePenetrationHit> TraceBolt(const FVector& Origin, const FVector& Dir, float MaxDist, float Power,+ float Damage, uint8 RadiusMm, int32 MaxPieces) const override+ {+ return {};+ }++ virtual bool TestSight(const FVector& Eye, const FVector& Target) const override+ {+ ++SightCalls;+ for (const FFakeOccluder& Occluder : Occluders)+ {+ FVector HitLocation;+ FVector HitNormal;+ float HitTime = 0.f;+ if (!FMath::LineExtentBoxIntersection(Occluder.Box, Eye, Target, FVector::ZeroVector, HitLocation, HitNormal, HitTime))+ {+ continue;+ }+ bool bThroughHole = false;+ for (const FBox& Hole : Occluder.Holes)+ {+ if (Hole.ExpandBy(0.1).IsInside(HitLocation))+ {+ bThroughHole = true;+ break;+ }+ }+ if (!bThroughHole)+ {+ return false;+ }+ }+ return true;+ }+ };+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseCombat/Private/Tests/Perception/VersePerceptionTest.cpp b/unreal/Verse/Source/VerseCombat/Private/Tests/Perception/VersePerceptionTest.cppnew file mode 100644index 0000000000..f4674efcc8--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Private/Tests/Perception/VersePerceptionTest.cpp@@ -0,0 +1,757 @@+#include "Bot/VerseBotTier.h"+#include "Bot/VersePerceptTypes.h"+#include "Engine/Engine.h"+#include "Engine/World.h"+#include "Events/VerseEventHub.h"+#include "GameFramework/PlayerController.h"+#include "HAL/FileManager.h"+#include "HAL/PlatformTime.h"+#include "Misc/AutomationTest.h"+#include "Misc/FileHelper.h"+#include "Misc/Paths.h"+#include "Noise/VerseAudibilityTable.h"+#include "Perception/VersePerceptionModel.h"+#include "Perception/VersePerceptionService.h"+#include "Serialization/MemoryWriter.h"+#include "Tests/Perception/Fakes/FakeVersePenetrationQuery.h"+#include "VerseGameplayTags.h"+#include "VerseRng.h"++#if WITH_DEV_AUTOMATION_TESTS++// Verse.Combat.Perception.*: the fairness boundary of contracts/bot.md 3 (WP07.1-7.4) and the+// percept-boundary acceptance tests A7.1 (F2), A7.2 (heard error) and A7.6 (perception cost).++#define VERSE_PERCEPTION_TEST_FLAGS (EAutomationTestFlags_ApplicationContextMask | EAutomationTestFlags::EngineFilter)++namespace VerseCombatPerceptionTests+{+ constexpr int32 ObserverId = 1;+ constexpr int32 TargetId = 2;+ constexpr float TickS = 1.f / 60.f;++ FString ProofDir(const TCHAR* SubTask)+ {+ return FPaths::ProjectSavedDir() / TEXT("Harness/proof/WP07") / SubTask;+ }++ void SaveProof(const TCHAR* SubTask, const TCHAR* File, const FString& Json)+ {+ const FString Dir = ProofDir(SubTask);+ IFileManager::Get().MakeDirectory(*Dir, true);+ FFileHelper::SaveStringToFile(Json, *(Dir / File));+ }++ struct FPerceptionScene+ {+ FFakeVersePenetrationQuery Sight;+ UVerseAudibilityTable* Audibility = nullptr;+ FVersePerceptionModel Model;+ FVersePerceptionObserverInput Observer;+ FVersePerceptionBody Target;+ uint32 NowMs = 1000;++ explicit FPerceptionScene(uint32 Seed = 7)+ {+ Audibility = NewObject<UVerseAudibilityTable>();+ Audibility->AddToRoot();+ FVersePerceptionProfile Profile;+ Profile.Seed = Seed;+ Model.AddObserver(ObserverId, Profile);+ Observer.Self.Location = FVector(0.0, 0.0, 0.0);+ Observer.Self.EyeLocation = FVector(0.0, 0.0, 165.0);+ Observer.Self.ViewRotation = FRotator(0.f, 0.f, 0.f);+ Target.PlayerId = TargetId;+ SetTarget(FVector(1000.0, 0.0, 95.0));+ }++ ~FPerceptionScene()+ {+ Audibility->RemoveFromRoot();+ }++ void SetTarget(const FVector& Pelvis, EVerseStance Stance = EVerseStance::Stand)+ {+ Target.Pelvis = Pelvis;+ Target.Stance = Stance;+ Target.SetSamplePointsFromStance();+ }++ FVersePerceptionWorld World() const+ {+ FVersePerceptionWorld Out;+ const FFakeVersePenetrationQuery* Query = &Sight;+ Out.TestSight = [Query](const FVector& Eye, const FVector& Point) { return Query->TestSight(Eye, Point); };+ Out.Audibility = Audibility;+ return Out;+ }++ FVersePerceptFrame Tick()+ {+ NowMs += 17;+ const FVersePerceptionBody Bodies[1] = {Target};+ return Model.BuildFrame(ObserverId, Observer, Bodies, World(), NowMs, TickS);+ }++ FVerseNoiseEvent Noise(const FGameplayTag& Tag, const FVector& Location) const+ {+ FVerseNoiseEvent Event;+ Event.Noise = Tag;+ Event.SourceId = TargetId;+ Event.Location = Location;+ Event.ServerTime = float(double(NowMs) / 1000.0);+ return Event;+ }+ };++ TArray<uint8> FrameBytes(const FVersePerceptFrame& Frame)+ {+ TArray<uint8> Bytes;+ FMemoryWriter Writer(Bytes);+ FVersePerceptFrame Copy = Frame;+ FVersePerceptFrame::StaticStruct()->SerializeItem(Writer, &Copy, nullptr);+ return Bytes;+ }+}++using namespace VerseCombatPerceptionTests;++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePerceptionConeTest, "Verse.Combat.Perception.Cone", VERSE_PERCEPTION_TEST_FLAGS)++bool FVersePerceptionConeTest::RunTest(const FString& Parameters)+{+ using EZone = FVersePerceptionModel::EConeZone;+ const FVector Eye(0.0, 0.0, 0.0);+ const FRotator View(0.f, 0.f, 0.f);+ const FVersePerceptionModel::FCone Hip = FVersePerceptionModel::ConeFor(false, 70.f);+ auto At = [&](float YawDeg, float PitchDeg) { return FRotator(PitchDeg, YawDeg, 0.f).Vector() * 1000.0; };++ TestEqual(TEXT("hip cone half-angle 55"), Hip.HalfAngleDeg, 55.f);+ TestTrue(TEXT("ahead is inside"), FVersePerceptionModel::Classify(Eye, View, Hip, At(0.f, 0.f)) == EZone::Inside);+ TestTrue(TEXT("54 deg inside"), FVersePerceptionModel::Classify(Eye, View, Hip, At(54.f, 0.f)) == EZone::Inside);+ TestTrue(TEXT("56 deg peripheral"), FVersePerceptionModel::Classify(Eye, View, Hip, At(-56.f, 0.f)) == EZone::Peripheral);+ TestTrue(TEXT("79 deg peripheral"), FVersePerceptionModel::Classify(Eye, View, Hip, At(79.f, 0.f)) == EZone::Peripheral);+ TestTrue(TEXT("81 deg outside"), FVersePerceptionModel::Classify(Eye, View, Hip, At(81.f, 0.f)) == EZone::Outside);+ TestTrue(TEXT("behind outside"), FVersePerceptionModel::Classify(Eye, View, Hip, At(180.f, 0.f)) == EZone::Outside);+ TestTrue(TEXT("39 deg up inside"), FVersePerceptionModel::Classify(Eye, View, Hip, At(0.f, 39.f)) == EZone::Inside);+ TestTrue(TEXT("41 deg up outside"), FVersePerceptionModel::Classify(Eye, View, Hip, At(0.f, 41.f)) == EZone::Outside);++ const FVersePerceptionModel::FCone Ads = FVersePerceptionModel::ConeFor(true, 70.f);+ TestEqual(TEXT("ADS half-angle = half ADS FOV + 3"), Ads.HalfAngleDeg, 38.f);+ TestEqual(TEXT("ADS vertical 35"), Ads.VerticalHalfAngleDeg, 35.f);+ TestTrue(TEXT("ADS 40 deg is peripheral"), FVersePerceptionModel::Classify(Eye, View, Ads, At(40.f, 0.f)) == EZone::Peripheral);+ TestTrue(TEXT("ADS 36 deg up outside"), FVersePerceptionModel::Classify(Eye, View, Ads, At(0.f, 36.f)) == EZone::Outside);+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePerceptionSightTest, "Verse.Combat.Perception.Sight", VERSE_PERCEPTION_TEST_FLAGS)++bool FVersePerceptionSightTest::RunTest(const FString& Parameters)+{+ {+ FPerceptionScene Scene;+ const FVersePerceptFrame Frame = Scene.Tick();+ if (TestEqual(TEXT("open view: one sighting"), Frame.Sightings.Num(), 1))+ {+ const FVerseSightPercept& Sight = Frame.Sightings[0];+ TestEqual(TEXT("all 8 sample points visible"), int32(Sight.VisibleMask), 0xFF);+ TestFalse(TEXT("not peripheral"), Sight.bPeripheral);+ TestEqual(TEXT("pelvis reported"), Sight.PelvisLocation, Scene.Target.Pelvis);+ TestTrue(TEXT("percept id set"), Sight.PerceptId != 0);+ }+ }+ {+ // Low cover: only head, neck, shoulders and upper torso over a 120 cm wall.+ FPerceptionScene Scene;+ Scene.Sight.AddWall(FVector(900.0, -200.0, 0.0), FVector(920.0, 200.0, 120.0));+ const FVersePerceptFrame Frame = Scene.Tick();+ if (TestEqual(TEXT("partial: one sighting"), Frame.Sightings.Num(), 1))+ {+ const uint8 Mask = Frame.Sightings[0].VisibleMask;+ TestTrue(TEXT("head visible"), (Mask & (1 << int32(EVerseSightSample::Head))) != 0);+ TestTrue(TEXT("knees hidden"), (Mask & (1 << int32(EVerseSightSample::KneeLeft))) == 0);+ TestTrue(TEXT("pelvis hidden"), (Mask & (1 << int32(EVerseSightSample::Pelvis))) == 0);+ }+ }+ {+ // Peripheral band: slow target not noticed, fast or firing target noticed.+ FPerceptionScene Scene;+ Scene.SetTarget(FRotator(0.f, 70.f, 0.f).Vector() * 1000.0 + FVector(0.0, 0.0, 95.0));+ Scene.Target.Velocity = FVector(100.0, 0.0, 0.0);+ TestEqual(TEXT("peripheral slow: unseen"), Scene.Tick().Sightings.Num(), 0);+ Scene.Target.Velocity = FVector(300.0, 0.0, 0.0);+ const FVersePerceptFrame Fast = Scene.Tick();+ if (TestEqual(TEXT("peripheral fast: seen"), Fast.Sightings.Num(), 1))+ {+ TestTrue(TEXT("flagged peripheral"), Fast.Sightings[0].bPeripheral);+ }+ Scene.Target.Velocity = FVector::ZeroVector;+ Scene.Target.bFiring = true;+ TestEqual(TEXT("peripheral firing: seen"), Scene.Tick().Sightings.Num(), 1);++ // The same from the shooter's own OnFire event (the service path): noticed while the+ // muzzle flash shows, with the weapon it fired; not after.+ Scene.Target.bFiring = false;+ TestEqual(TEXT("peripheral still: unseen"), Scene.Tick().Sightings.Num(), 0);+ FVerseFireEvent Fire;+ Fire.ShooterId = TargetId;+ Fire.WeaponId = TEXT("Test.Rifle");+ Fire.Origin = FVector_NetQuantize10(Scene.Target.Eye);+ Fire.Direction = FVector_NetQuantizeNormal(FVector(0.0, 1.0, 0.0));+ Fire.ServerTime = float(double(Scene.NowMs + 17) / 1000.0);+ Scene.Model.OnFire(Fire);+ const FVersePerceptFrame Fired = Scene.Tick();+ if (TestEqual(TEXT("peripheral, OnFire: seen"), Fired.Sightings.Num(), 1))+ {+ TestTrue(TEXT("OnFire: peripheral flag"), Fired.Sightings[0].bPeripheral);+ TestTrue(TEXT("OnFire: weapon shown"), Fired.Sightings[0].HeldWeaponId == FName(TEXT("Test.Rifle")));+ }+ for (int32 Tick = 0; Tick < 12; ++Tick)+ {+ Scene.Tick();+ }+ TestEqual(TEXT("peripheral, 0.2 s after the shot: unseen"), Scene.Tick().Sightings.Num(), 0);+ }+ {+ // A reload event shows the reload animation to a looking observer until it ends.+ FPerceptionScene Scene;+ FVerseReloadEvent Reload;+ Reload.PlayerId = TargetId;+ Reload.WeaponId = TEXT("Test.Rifle");+ Reload.StartServerTime = float(double(Scene.NowMs) / 1000.0);+ Reload.EndServerTime = Reload.StartServerTime + 0.5f;+ Scene.Model.OnReload(Reload);+ const FVersePerceptFrame During = Scene.Tick();+ TestTrue(TEXT("reload: seen reloading"), During.Sightings.Num() == 1 && During.Sightings[0].bReloading);+ for (int32 Tick = 0; Tick < 40; ++Tick)+ {+ Scene.Tick();+ }+ const FVersePerceptFrame After = Scene.Tick();+ TestTrue(TEXT("reload: done after its end"), After.Sightings.Num() == 1 && !After.Sightings[0].bReloading);+ }+ {+ // Awareness: behind the observer within 2 m is noticed, at 2.5 m it is not.+ FPerceptionScene Scene;+ Scene.SetTarget(FVector(-150.0, 0.0, 95.0));+ Scene.Target.Velocity = FVector(-300.0, 0.0, 0.0);+ Scene.Target.FacingYawDeg = 33.f;+ Scene.Target.bReloading = true;+ Scene.Target.HeldWeaponId = TEXT("Test.Weapon");+ const FVersePerceptFrame Felt = Scene.Tick();+ if (TestEqual(TEXT("1.5 m behind: felt"), Felt.Sightings.Num(), 1))+ {+ const FVerseSightPercept& Sight = Felt.Sightings[0];+ TestEqual(TEXT("felt: position"), Sight.PelvisLocation, Scene.Target.Pelvis);+ TestEqual(TEXT("felt: no visible sample point"), int32(Sight.VisibleMask), 0);+ TestTrue(TEXT("felt: no visual fields"), Sight.Velocity.IsZero() && Sight.FacingYawDeg == 0.f && !Sight.bReloading &&+ Sight.HeldWeaponId.IsNone());+ }+ Scene.Target.Velocity = FVector::ZeroVector;+ Scene.Target.FacingYawDeg = 0.f;+ Scene.Target.bReloading = false;+ Scene.Target.HeldWeaponId = NAME_None;+ Scene.SetTarget(FVector(-250.0, 0.0, 95.0));+ TestEqual(TEXT("2.5 m behind: unseen"), Scene.Tick().Sightings.Num(), 0);+ }+ {+ // Dark zone: VisibilityFactor 0.5 delays the first sighting by ReactionMs mean (320 ms).+ FPerceptionScene Scene;+ FVersePerceptionWorld World = Scene.World();+ World.VisibilityFactor = [](const FVector&) { return 0.5f; };+ const FVersePerceptionBody Bodies[1] = {Scene.Target};+ int32 FirstSeenMs = -1;+ const uint32 Start = Scene.NowMs;+ for (int32 Tick = 0; Tick < 60 && FirstSeenMs < 0; ++Tick)+ {+ Scene.NowMs += 10;+ if (Scene.Model.BuildFrame(ObserverId, Scene.Observer, Bodies, World, Scene.NowMs, 0.01f).Sightings.Num() > 0)+ {+ FirstSeenMs = int32(Scene.NowMs - Start);+ }+ }+ TestTrue(TEXT("dark zone: seen after about 320 ms"), FirstSeenMs >= 320 && FirstSeenMs <= 340);+ }+ {+ // Dead bodies and the observer's own body are never sighted.+ FPerceptionScene Scene;+ Scene.Target.bAlive = false;+ TestEqual(TEXT("dead: unseen"), Scene.Tick().Sightings.Num(), 0);+ Scene.Target.bAlive = true;+ Scene.Target.PlayerId = ObserverId;+ TestEqual(TEXT("own body: unseen"), Scene.Tick().Sightings.Num(), 0);+ }+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePerceptionF2Test, "Verse.Combat.Perception.F2", VERSE_PERCEPTION_TEST_FLAGS)++bool FVersePerceptionF2Test::RunTest(const FString& Parameters)+{+ TMap<FString, double> Report;++ // A7.1 a: opaque piece, silent opponent: 0 sightings and 0 heard over 60 s, while the view sweeps.+ {+ FPerceptionScene Scene;+ Scene.Sight.AddWall(FVector(500.0, -400.0, 0.0), FVector(520.0, 400.0, 400.0));+ Scene.SetTarget(FVector(700.0, 0.0, 95.0));+ int32 Sightings = 0;+ int32 Heard = 0;+ for (int32 Tick = 0; Tick < 3600; ++Tick)+ {+ Scene.Observer.Self.ViewRotation.Yaw = float(FMath::Fmod(Tick * 0.5, 360.0));+ const FVersePerceptFrame Frame = Scene.Tick();+ Sightings += Frame.Sightings.Num();+ Heard += Frame.Heard.Num();+ }+ TestEqual(TEXT("A7.1 opaque: 0 sightings over 60 s"), Sightings, 0);+ TestEqual(TEXT("A7.1 opaque: 0 heard over 60 s"), Heard, 0);+ Report.Add(TEXT("opaqueSightings"), Sightings);+ Report.Add(TEXT("opaqueHeard"), Heard);+ }++ // A7.1 a2: the same within the 2 m awareness radius: 1.5 m behind an opaque wall, silent,+ // in any view direction: never sighted (felt needs a clear line; bot.md B2).+ {+ FPerceptionScene Scene;+ Scene.Sight.AddWall(FVector(60.0, -400.0, 0.0), FVector(80.0, 400.0, 400.0));+ Scene.SetTarget(FVector(150.0, 0.0, 95.0));+ int32 Sightings = 0;+ for (int32 Tick = 0; Tick < 3600; ++Tick)+ {+ Scene.Observer.Self.ViewRotation.Yaw = float(FMath::Fmod(Tick * 0.5, 360.0));+ Sightings += Scene.Tick().Sightings.Num();+ }+ TestEqual(TEXT("A7.1 opaque at 1.5 m: 0 sightings over 60 s"), Sightings, 0);+ Report.Add(TEXT("opaqueAt1_5mSightings"), Sightings);+ }++ // A7.1 b: wall with a hole: seen exactly on the ticks where TestSight passes for a sample in the cone.+ {+ FPerceptionScene Scene;+ FFakeOccluder& Wall = Scene.Sight.AddWall(FVector(500.0, -600.0, 0.0), FVector(520.0, 600.0, 400.0));+ Wall.Holes.Add(FBox(FVector(495.0, -40.0, 110.0), FVector(525.0, 40.0, 190.0)));+ const FVersePerceptionModel::FCone Cone = FVersePerceptionModel::ConeFor(false, 70.f);+ int32 Seen = 0;+ int32 Mismatch = 0;+ for (int32 Tick = 0; Tick < 1200; ++Tick)+ {+ // Walks back and forth behind the wall, 4 m behind it.+ const double Y = -500.0 + FMath::Fmod(Tick * 2.0, 1000.0);+ Scene.SetTarget(FVector(900.0, Y, 95.0));+ bool bExpected = false;+ for (const FVector& Point : Scene.Target.SamplePoints)+ {+ bExpected |= FVersePerceptionModel::Classify(Scene.Observer.Self.EyeLocation, Scene.Observer.Self.ViewRotation,+ Cone, Point) == FVersePerceptionModel::EConeZone::Inside &&+ Scene.Sight.TestSight(Scene.Observer.Self.EyeLocation, Point);+ }+ const bool bSeen = Scene.Tick().Sightings.Num() > 0;+ Seen += bSeen ? 1 : 0;+ Mismatch += bSeen != bExpected ? 1 : 0;+ }+ TestEqual(TEXT("A7.1 hole: seen only when TestSight passes"), Mismatch, 0);+ TestTrue(TEXT("A7.1 hole: seen through the hole sometimes"), Seen > 0 && Seen < 1200);+ Report.Add(TEXT("holeTicksSeen"), Seen);+ Report.Add(TEXT("holeMismatches"), Mismatch);+ }++ // A7.1 c: crouch walking raises no noise event (bot.md 3.2); at 3 m for 60 s nothing is heard.+ // Walking does raise Noise.Footstep.Walk (4 m): heard at 3 m, not at 5 m.+ {+ FPerceptionScene Scene;+ Scene.Sight.AddWall(FVector(150.0, -400.0, 0.0), FVector(170.0, 400.0, 400.0));+ Scene.SetTarget(FVector(300.0, 0.0, 60.0), EVerseStance::Crouch);+ int32 CrouchHeard = 0;+ for (int32 Tick = 0; Tick < 3600; ++Tick)+ {+ CrouchHeard += Scene.Tick().Heard.Num();+ }+ TestEqual(TEXT("A7.1 crouch walk at 3 m: never heard"), CrouchHeard, 0);+ Report.Add(TEXT("crouchHeard"), CrouchHeard);++ int32 WalkHeard3 = 0;+ for (int32 Step = 0; Step < 100; ++Step)+ {+ Scene.Model.OnNoise(Scene.Noise(VerseTags::Noise_Footstep_Walk, FVector(300.0, 0.0, 0.0)));+ WalkHeard3 += Scene.Tick().Heard.Num();+ }+ int32 WalkHeard5 = 0;+ for (int32 Step = 0; Step < 100; ++Step)+ {+ Scene.Model.OnNoise(Scene.Noise(VerseTags::Noise_Footstep_Walk, FVector(500.0, 0.0, 0.0)));+ WalkHeard5 += Scene.Tick().Heard.Num();+ }+ TestEqual(TEXT("walk at 3 m: heard every step"), WalkHeard3, 100);+ TestEqual(TEXT("walk at 5 m: never heard (4 m range)"), WalkHeard5, 0);+ Report.Add(TEXT("walkHeardAt3m"), WalkHeard3);+ Report.Add(TEXT("walkHeardAt5m"), WalkHeard5);+ }++ FString Json = TEXT("{\n \"test\": \"F2 percept boundary (A7.1)\",\n");+ for (const TPair<FString, double>& Item : Report)+ {+ Json += FString::Printf(TEXT(" \"%s\": %g,\n"), *Item.Key, Item.Value);+ }+ // Case c only shows that perception adds no noise of its own; that a crouching pawn raises no+ // footstep event is the movement layer's (WP01), driven through the service once it lands.+ Json += TEXT(" \"crouchCaseIsPlaceholderUntilWP01\": true,\n");+ Json += FString::Printf(TEXT(" \"pass\": %s\n}\n"), HasAnyErrors() ? TEXT("false") : TEXT("true"));+ SaveProof(TEXT("7.9"), TEXT("f2_percept_boundary.json"), Json);+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePerceptionHeardErrorTest, "Verse.Combat.Perception.HeardError", VERSE_PERCEPTION_TEST_FLAGS)++bool FVersePerceptionHeardErrorTest::RunTest(const FString& Parameters)+{+ // A7.2: 10,000 heard shots at random positions, half behind a wall (x 1.5). The error divided by+ // the model sd has sd 1 within 10 %; no percept equals the true location.+ FPerceptionScene Scene(1234);+ Scene.Sight.AddWall(FVector(100.0, -5000.0, 0.0), FVector(120.0, 5000.0, 3000.0));+ FVerseRng Rng(99);+ const FVersePerceptionProfile Profile = *Scene.Model.FindProfile(ObserverId);+ double SumZ2 = 0.0;+ double SumZ = 0.0;+ int32 Count = 0;+ int32 EqualTrue = 0;+ int32 SdMismatch = 0;+ int32 LevelCorrect = 0;+ int32 NoLos = 0;+ for (int32 Sample = 0; Sample < 10000; ++Sample)+ {+ const double Dist = Rng.Range(200.0, 4000.0);+ const double Angle = Rng.Range(0.0, 2.0 * UE_DOUBLE_PI);+ const FVector Truth(Dist * FMath::Cos(Angle), Dist * FMath::Sin(Angle), 100.0);+ Scene.Model.OnNoise(Scene.Noise(VerseTags::Noise_Shot, Truth));+ const FVersePerceptFrame Frame = Scene.Tick();+ if (Frame.Heard.Num() != 1)+ {+ AddError(TEXT("a shot is heard across the arena"));+ return false;+ }+ const FVerseHeardPercept& Heard = Frame.Heard[0];+ const bool bLos = Scene.Sight.TestSight(Scene.Observer.Self.EyeLocation, Truth);+ NoLos += bLos ? 0 : 1;+ const double DistM = FVector::Dist(Scene.Observer.Self.EyeLocation, Truth) / 100.0;+ const double ModelSdM =+ (Profile.HearingErrorBaseM + Profile.HearingErrorPerM * DistM) * 1.0 * (bLos ? 1.0 : 1.5);+ SdMismatch += FMath::Abs(Heard.ErrorSdM - ModelSdM) > 1e-3 ? 1 : 0;+ EqualTrue += (Heard.Location.X == Truth.X && Heard.Location.Y == Truth.Y && Heard.Location.Z == Truth.Z) ? 1 : 0;+ const double Zx = (Heard.Location.X - Truth.X) / (ModelSdM * 100.0);+ const double Zy = (Heard.Location.Y - Truth.Y) / (ModelSdM * 100.0);+ SumZ2 += Zx * Zx + Zy * Zy;+ SumZ += Zx + Zy;+ Count += 2;+ LevelCorrect += Heard.LevelGuess == EVerseArenaLevel::Floor ? 1 : 0;+ }+ const double Mean = SumZ / Count;+ const double Sd = FMath::Sqrt(SumZ2 / Count - Mean * Mean);+ const double LevelRate = double(LevelCorrect) / 10000.0;+ TestTrue(FString::Printf(TEXT("A7.2 error sd ratio %.4f within 10 %% of the model"), Sd), Sd >= 0.9 && Sd <= 1.1);+ TestEqual(TEXT("A7.2 no percept equals the true location"), EqualTrue, 0);+ TestEqual(TEXT("reported sd equals the model sd"), SdMismatch, 0);+ TestTrue(TEXT("both line-of-sight cases sampled"), NoLos > 500 && NoLos < 9500);+ TestTrue(FString::Printf(TEXT("level guess correct rate %.3f about 0.9"), LevelRate), FMath::Abs(LevelRate - 0.9) < 0.015);++ SaveProof(TEXT("7.3"), TEXT("heard_error.json"),+ FString::Printf(TEXT("{\n \"test\": \"A7.2 heard error\",\n \"samples\": 10000,\n \"errorSdOverModelSd\": %.5f,\n")+ TEXT(" \"meanZ\": %.5f,\n \"equalToTruth\": %d,\n \"noLineOfSight\": %d,\n \"levelCorrectRate\": %.4f,\n")+ TEXT(" \"pass\": %s\n}\n"),+ Sd, Mean, EqualTrue, NoLos, LevelRate, HasAnyErrors() ? TEXT("false") : TEXT("true")));+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePerceptionHearingRulesTest, "Verse.Combat.Perception.Hearing", VERSE_PERCEPTION_TEST_FLAGS)++bool FVersePerceptionHearingRulesTest::RunTest(const FString& Parameters)+{+ FPerceptionScene Scene;+ // Own noises are never heard.+ FVerseNoiseEvent Own = Scene.Noise(VerseTags::Noise_Shot, FVector(100.0, 0.0, 0.0));+ Own.SourceId = ObserverId;+ Scene.Model.OnNoise(Own);+ TestEqual(TEXT("own shot not heard"), Scene.Tick().Heard.Num(), 0);++ // An unknown tag is never heard.+ Scene.Model.OnNoise(Scene.Noise(FGameplayTag(), FVector(100.0, 0.0, 0.0)));+ TestEqual(TEXT("untagged event not heard"), Scene.Tick().Heard.Num(), 0);++ // Ranges: reload 7 m, fracture scales with loudness (x 40 m).+ Scene.Model.OnNoise(Scene.Noise(VerseTags::Noise_Reload, FVector(650.0, 0.0, 0.0)));+ TestEqual(TEXT("reload at 6.5 m heard"), Scene.Tick().Heard.Num(), 1);+ Scene.Model.OnNoise(Scene.Noise(VerseTags::Noise_Reload, FVector(750.0, 0.0, 0.0)));+ TestEqual(TEXT("reload at 7.5 m not heard"), Scene.Tick().Heard.Num(), 0);+ FVerseNoiseEvent Fracture = Scene.Noise(VerseTags::Noise_Fracture, FVector(1500.0, 0.0, 0.0));+ Fracture.SourceId = -1;+ Fracture.Loudness = 0.5f;+ Scene.Model.OnNoise(Fracture);+ TestEqual(TEXT("tile fracture (0.5) at 15 m heard (20 m)"), Scene.Tick().Heard.Num(), 1);+ Fracture.Loudness = 0.2f;+ Scene.Model.OnNoise(Fracture);+ TestEqual(TEXT("bolt hole (0.2) at 15 m not heard (8 m)"), Scene.Tick().Heard.Num(), 0);++ // Impact: exact point, sd 0.+ Scene.Model.OnNoise(Scene.Noise(VerseTags::Noise_Impact, FVector(200.0, 50.0, 30.0)));+ const FVersePerceptFrame Impact = Scene.Tick();+ if (TestEqual(TEXT("impact within 3 m heard"), Impact.Heard.Num(), 1))+ {+ TestEqual(TEXT("impact at the impact point"), Impact.Heard[0].Location, FVector(200.0, 50.0, 30.0));+ TestEqual(TEXT("impact sd 0"), Impact.Heard[0].ErrorSdM, 0.f);+ }++ // Heard Z is the guessed level's height, never the true height.+ Scene.Model.OnNoise(Scene.Noise(VerseTags::Noise_Shot, FVector(800.0, 0.0, 123.0)));+ const FVersePerceptFrame Shot = Scene.Tick();+ if (TestEqual(TEXT("shot heard"), Shot.Heard.Num(), 1))+ {+ TestTrue(TEXT("Z from the level guess"), Shot.Heard[0].Location.Z != 123.0);+ }++ // Profile from the tier.+ UVerseBotTier* Tier = NewObject<UVerseBotTier>();+ if (TestTrue(TEXT("hard start values"), UVerseBotTier::ApplyStartValues(TEXT("hard"), *Tier)))+ {+ const FVersePerceptionProfile Profile = FVersePerceptionModel::MakeProfile(*Tier, 42);+ TestEqual(TEXT("hard hearing base 1.9"), Profile.HearingErrorBaseM, 1.9f);+ TestEqual(TEXT("hard hearing per m 0.065"), Profile.HearingErrorPerM, 0.065f);+ TestEqual(TEXT("hard reaction mean 270"), Profile.ReactionMs.X, 270.f);+ TestTrue(TEXT("seed carried"), Profile.Seed == 42u);+ }+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePerceptionEventsTest, "Verse.Combat.Perception.Events", VERSE_PERCEPTION_TEST_FLAGS)++bool FVersePerceptionEventsTest::RunTest(const FString& Parameters)+{+ FPerceptionScene Scene;+ Scene.SetTarget(FVector(-3000.0, 0.0, 95.0)); // behind, unseen++ // Hurt: direction toward the shooter within +-8 deg.+ FVerseHitEvent Hit;+ Hit.InstigatorId = TargetId;+ Hit.VictimId = ObserverId;+ Hit.Direction = FVector(1.0, 0.0, 0.0); // bolt flies +X, shooter is at -X+ Hit.Damage = 20.f;+ Scene.Model.OnHit(Hit);+ Scene.Model.OnHit(Hit);+ const FVersePerceptFrame Hurt = Scene.Tick();+ TestTrue(TEXT("hurt percept"), Hurt.bHasHurt);+ TestEqual(TEXT("hurt damage summed"), Hurt.Hurt.Damage, 40.f);+ const double HurtAngle = FMath::RadiansToDegrees(FMath::Acos(FVector::DotProduct(Hurt.Hurt.IncomingDirection, FVector(-1.0, 0.0, 0.0))));+ TestTrue(TEXT("hurt direction within 8 deg"), HurtAngle <= 8.0 + 1e-3);+ TestFalse(TEXT("hurt is one tick"), Scene.Tick().bHasHurt);++ // Hit markers to the instigator only; spawn-protected hits give nothing.+ FVersePerceptionProfile Profile;+ Scene.Model.AddObserver(TargetId, Profile);+ FVerseHitEvent Own;+ Own.InstigatorId = ObserverId;+ Own.VictimId = TargetId;+ Own.bHeadshot = true;+ Scene.Model.OnHit(Own);+ const FVersePerceptFrame Marker = Scene.Tick();+ if (TestEqual(TEXT("one hit marker"), Marker.Hud.Num(), 1))+ {+ TestTrue(TEXT("headshot marker"), Marker.Hud[0].Kind == EVerseHudEventKind::HeadshotMarker);+ }+ Own.bBlockedBySpawnProtection = true;+ Scene.Model.OnHit(Own);+ TestEqual(TEXT("blocked hit: no marker"), Scene.Tick().Hud.Num(), 0);++ // Kill feed and respawn feed; the victim's kill cam shows the killer's position.+ FVersePerceptionBody Killer = Scene.Target;+ FVerseDeathEvent Death;+ Death.VictimId = ObserverId;+ Death.KillerId = TargetId;+ Death.ServerTime = float(double(Scene.NowMs) / 1000.0);+ Death.RespawnAt = Death.ServerTime + 3.f;+ Scene.Model.OnDeath(Death, &Killer);+ const FVersePerceptFrame Kill = Scene.Tick();+ if (TestEqual(TEXT("kill feed entry"), Kill.Hud.Num(), 1))+ {+ TestTrue(TEXT("kind kill"), Kill.Hud[0].Kind == EVerseHudEventKind::Kill);+ TestTrue(TEXT("kill cam shows killer"), Kill.Hud[0].bKillerPositionShown);+ TestEqual(TEXT("killer position"), Kill.Hud[0].KillerPosition, Killer.Pelvis);+ }+ FVerseDeathEvent Other = Death;+ Other.VictimId = TargetId;+ Other.KillerId = ObserverId;+ Scene.Model.OnDeath(Other, nullptr);+ int32 Respawned = 0;+ for (int32 Tick = 0; Tick < 240; ++Tick)+ {+ for (const FVerseHudEvent& Hud : Scene.Tick().Hud)+ {+ Respawned += Hud.Kind == EVerseHudEventKind::OpponentRespawned && Hud.VictimId == TargetId ? 1 : 0;+ }+ }+ TestEqual(TEXT("opponent respawn in the feed once"), Respawned, 1);++ // Bolts: an opponent bolt crossing the view is seen; the observer's own bolt is not.+ FPerceptionScene Bolts;+ FVerseFireEvent Fire;+ Fire.ShooterId = TargetId;+ Fire.Origin = FVector(2000.0, -1000.0, 150.0);+ Fire.Direction = FVector(0.0, 1.0, 0.0);+ Fire.ServerTime = float(double(Bolts.NowMs) / 1000.0);+ Bolts.Model.OnFire(Fire);+ Bolts.SetTarget(FVector(-3000.0, 0.0, 95.0));+ int32 BoltPercepts = 0;+ for (int32 Tick = 0; Tick < 30; ++Tick)+ {+ BoltPercepts += Bolts.Tick().Bolts.Num();+ }+ TestTrue(TEXT("opponent bolt seen in flight"), BoltPercepts > 0);+ FPerceptionScene OwnBolt;+ Fire.ShooterId = ObserverId;+ Fire.ServerTime = float(double(OwnBolt.NowMs) / 1000.0);+ OwnBolt.Model.OnFire(Fire);+ int32 OwnPercepts = 0;+ for (int32 Tick = 0; Tick < 30; ++Tick)+ {+ OwnPercepts += OwnBolt.Tick().Bolts.Num();+ }+ TestEqual(TEXT("own bolt is no percept"), OwnPercepts, 0);+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePerceptionDeterminismTest, "Verse.Combat.Perception.Determinism", VERSE_PERCEPTION_TEST_FLAGS)++bool FVersePerceptionDeterminismTest::RunTest(const FString& Parameters)+{+ // Same seed, same events: bit-identical frames (B5). Different seed: different hearing error.+ auto Run = [](uint32 Seed) {+ FPerceptionScene Scene(Seed);+ TArray<uint8> All;+ for (int32 Tick = 0; Tick < 600; ++Tick)+ {+ if (Tick % 7 == 0)+ {+ Scene.Model.OnNoise(Scene.Noise(VerseTags::Noise_Footstep_Run, FVector(400.0, 300.0, 0.0)));+ }+ Scene.Observer.Self.ViewRotation.Yaw = float(Tick % 360);+ All.Append(FrameBytes(Scene.Tick()));+ }+ return All;+ };+ TestTrue(TEXT("same seed: identical frames"), Run(5) == Run(5));+ TestTrue(TEXT("other seed: other frames"), Run(5) != Run(6));+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePerceptionCostTest, "Verse.Combat.Perception.Cost", VERSE_PERCEPTION_TEST_FLAGS)++bool FVersePerceptionCostTest::RunTest(const FString& Parameters)+{+ // A7.6: perception at most 0.15 ms per observer per tick (sight traces through the fake query;+ // the real trace cost belongs to WP03's TestSight).+ FPerceptionScene Scene;+ for (int32 Index = 0; Index < 40; ++Index)+ {+ const double X = 300.0 + Index * 70.0;+ Scene.Sight.AddWall(FVector(X, -800.0 + Index * 10.0, 0.0), FVector(X + 20.0, -700.0 + Index * 10.0, 300.0));+ }+ Scene.SetTarget(FVector(1500.0, 200.0, 95.0));+ double Best = TNumericLimits<double>::Max();+ double Total = 0.0;+ int32 Frames = 0;+ for (int32 Batch = 0; Batch < 5; ++Batch)+ {+ const double Start = FPlatformTime::Seconds();+ for (int32 Tick = 0; Tick < 600; ++Tick)+ {+ if (Tick % 10 == 0)+ {+ Scene.Model.OnNoise(Scene.Noise(VerseTags::Noise_Footstep_Sprint, FVector(800.0, 300.0, 0.0)));+ }+ Scene.Target.Velocity = FVector(450.0, 0.0, 0.0);+ Scene.Tick();+ }+ const double Elapsed = FPlatformTime::Seconds() - Start;+ Best = FMath::Min(Best, Elapsed / 600.0);+ Total += Elapsed;+ Frames += 600;+ }+ const double BestMs = Best * 1000.0;+ const double MeanMs = Total / Frames * 1000.0;+ TestTrue(FString::Printf(TEXT("A7.6 perception %.4f ms per observer per tick <= 0.15"), BestMs), BestMs <= 0.15);+ SaveProof(TEXT("7.6"), TEXT("perception_cost.json"),+ FString::Printf(TEXT("{\n \"test\": \"A7.6 perception cost\",\n \"msPerObserverTickBestBatch\": %.5f,\n")+ TEXT(" \"msPerObserverTickMean\": %.5f,\n \"budgetMs\": 0.15,\n \"occluders\": 40,\n \"pass\": %s\n}\n"),+ BestMs, MeanMs, HasAnyErrors() ? TEXT("false") : TEXT("true")));+ return true;+}++IMPLEMENT_SIMPLE_AUTOMATION_TEST(FVersePerceptionServiceTest, "Verse.Combat.Perception.Service", VERSE_PERCEPTION_TEST_FLAGS)++bool FVersePerceptionServiceTest::RunTest(const FString& Parameters)+{+ // WP07.1: the service exists in a game world, registers observers and sends one frame per step.+ UWorld* World = UWorld::CreateWorld(EWorldType::Game, false, TEXT("VersePerceptionServiceTest"));+ if (!TestNotNull(TEXT("world"), World))+ {+ return false;+ }+ FWorldContext& Context = GEngine->CreateNewWorldContext(EWorldType::Game);+ Context.SetCurrentWorld(World);++ UVersePerceptionService* Service = UVersePerceptionService::Get(World);+ if (TestNotNull(TEXT("service in a game world"), Service))+ {+ FActorSpawnParameters Params;+ Params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;+ APlayerController* Controller = World->SpawnActor<APlayerController>(Params);+ if (TestNotNull(TEXT("controller"), Controller))+ {+ int32 Frames = 0;+ const FDelegateHandle Handle = Service->OnPerceptFrame.AddLambda(+ [&Frames, Controller](AController* Observer, const FVersePerceptFrame&) { Frames += Observer == Controller ? 1 : 0; });+ Service->RegisterObserver(Controller, FVersePerceptionProfile());+ TestTrue(TEXT("registered"), Service->IsRegistered(Controller));+ Service->StepPerception(TickS);+ Service->StepPerception(TickS);+ TestEqual(TEXT("one frame per step"), Frames, 2);+ Service->UnregisterObserver(Controller);+ TestFalse(TEXT("unregistered"), Service->IsRegistered(Controller));+ Service->StepPerception(TickS);+ TestEqual(TEXT("no frame after unregister"), Frames, 2);+ Service->OnPerceptFrame.Remove(Handle);+ }++ // Hub wiring: a shot and a reload on the hub become what a look at the shooter shows.+ if (UVerseEventHub* Hub = UVerseEventHub::Get(World))+ {+ const float NowS = 2.f;+ FVerseFireEvent Fire;+ Fire.ShooterId = TargetId;+ Fire.WeaponId = TEXT("Test.Rifle");+ Fire.ServerTime = NowS;+ Hub->OnFire.Broadcast(Fire);+ FVersePerceptionBody Body;+ Body.PlayerId = TargetId;+ const FVersePerceptionBody Firing = Service->GetModel().ApplyCues(Body, NowS + 0.05f);+ TestTrue(TEXT("hub OnFire: shooter shows firing"), Firing.bFiring);+ TestTrue(TEXT("hub OnFire: weapon"), Firing.HeldWeaponId == FName(TEXT("Test.Rifle")));+ TestFalse(TEXT("hub OnFire: flash over after 0.5 s"), Service->GetModel().ApplyCues(Body, NowS + 0.5f).bFiring);+ FVerseReloadEvent Reload;+ Reload.PlayerId = TargetId;+ Reload.StartServerTime = NowS + 1.f;+ Reload.EndServerTime = NowS + 2.f;+ Hub->OnReload.Broadcast(Reload);+ TestTrue(TEXT("hub OnReload: reloading"), Service->GetModel().ApplyCues(Body, NowS + 1.5f).bReloading);+ TestFalse(TEXT("hub OnReload: done"), Service->GetModel().ApplyCues(Body, NowS + 2.5f).bReloading);+ }+ else+ {+ AddError(TEXT("no event hub in the game world"));+ }+ }++ GEngine->DestroyWorldContext(World);+ World->DestroyWorld(false);+ return true;+}++#endif // WITH_DEV_AUTOMATION_TESTSdiff --git a/unreal/Verse/Source/VerseCombat/Public/Perception/VersePerceptionModel.h b/unreal/Verse/Source/VerseCombat/Public/Perception/VersePerceptionModel.hnew file mode 100644index 0000000000..9b79b6c9c8--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Public/Perception/VersePerceptionModel.h@@ -0,0 +1,247 @@+#pragma once++#include "Bot/VersePerceptTypes.h"+#include "Combat/VerseCombatTypes.h"+#include "CoreMinimal.h"+#include "Templates/Function.h"+#include "VerseRng.h"++class UVerseAudibilityTable;+class UVerseBotTier;++// The world-independent core of the fairness boundary (contracts/bot.md 2, 3; work-packages WP07).+// UVersePerceptionService gathers world truth from actors into FVersePerceptionBody snapshots and+// hub events, and this model turns them into FVersePerceptFrame per observer with all perception+// error applied. Keeping the rules here, free of UWorld, makes them unit-testable with a fake+// sight query and bit-deterministic (bot.md B5, F3): the model draws from an observer's RNG+// stream only for percepts that observer actually receives.++namespace VersePerception+{+ /** bot.md 3.1: half of the shipped 100 deg horizontal FOV plus 5 deg. */+ constexpr float ViewHalfAngleDeg = 55.f;+ /** Outer edge of the peripheral band. */+ constexpr float PeripheralHalfAngleDeg = 80.f;+ constexpr float VerticalHalfAngleDeg = 40.f;+ constexpr float AdsVerticalHalfAngleDeg = 35.f;+ /** ADS: half the ADS FOV plus this margin. */+ constexpr float AdsMarginDeg = 3.f;+ /** Within this distance the opponent is noticed in any direction. */+ constexpr float AwarenessRadiusCm = 200.f;+ /** Peripheral band: only a target faster than this (or firing) is noticed. */+ constexpr float PeripheralSpeedCmS = 200.f;+ /** Hearing error is multiplied by this without line of sight to the source. */+ constexpr float NoLineOfSightErrorMul = 1.5f;+ /** Level guess: correct with this probability when the source is within one level. */+ constexpr float LevelGuessNear = 0.9f;+ constexpr float LevelGuessFar = 0.7f;+ /** Hurt percept direction error, degrees (uniform, yaw; pitch at half). */+ constexpr float HurtDirectionErrorDeg = 8.f;+ /** Bolts fly at about 300 m/s (README Projectiles). */+ constexpr float BoltSpeedCmS = 30000.f;+ /** A bolt the model was not told ended expires after this. */+ constexpr float BoltMaxLifeS = 1.0f;+ /** Default ADS field of view until weapons (WP02) provide theirs. */+ constexpr float DefaultAdsFovDeg = 70.f;+ /** A shot keeps its shooter "firing" (muzzle flash visible) this long, seconds. */+ constexpr float FiringVisibleS = 0.1f;+}++/** World truth of one perceivable body for one tick. Only the service and tests fill it. */+struct VERSECOMBAT_API FVersePerceptionBody+{+ int32 PlayerId = INDEX_NONE;+ bool bAlive = true;+ /** Pelvis (the Hips bone), world cm. */+ FVector Pelvis = FVector::ZeroVector;+ FVector Velocity = FVector::ZeroVector;+ float FacingYawDeg = 0.f;+ float FacingPitchDeg = 0.f;+ EVerseStance Stance = EVerseStance::Stand;+ int8 LeanQuantized = 0;+ bool bAds = false;+ float AdsFovDeg = VersePerception::DefaultAdsFovDeg;+ FName HeldWeaponId;+ bool bReloading = false;+ bool bSpawnProtected = false;+ /** Fired this tick (noticed in the peripheral band). */+ bool bFiring = false;+ /** The 8 hit-zone sample points in EVerseSightSample order, world cm. */+ FVector SamplePoints[8];+ /** The Camera bone, world cm. */+ FVector Eye = FVector::ZeroVector;+ FRotator View = FRotator::ZeroRotator;++ FVersePerceptionBody();++ /** Sample points from a standing (or crouched, prone) capsule at Pelvis; for tests and pawns without the rig. */+ void SetSamplePointsFromStance();+};++/** What the model asks of the world. Every callback answers about geometry, never about a pawn. */+struct VERSECOMBAT_API FVersePerceptionWorld+{+ /** IVersePenetrationQuery::TestSight: sight from Eye to Target (holes honoured, pawns ignored). */+ TFunction<bool(const FVector& Eye, const FVector& Target)> TestSight;++ /** Arena VisibilityFactor at a point, 1 = lit; dark zones are below 1 (bot.md 3.1). Optional. */+ TFunction<float(const FVector& Location)> VisibilityFactor;++ /** Height band of a point; optional, default bands below. */+ TFunction<EVerseArenaLevel(const FVector& Location)> LevelOf;++ /** Nominal floor height of a level, world cm; a heard percept reports this Z (never the true one). */+ TFunction<float(EVerseArenaLevel Level)> LevelHeightCm;++ /** The audibility table (DA_Audibility). Must be set. */+ const UVerseAudibilityTable* Audibility = nullptr;++ /** Default bands when LevelOf is not set: below MidMinZ floor, below UpperMinZ mid, else upper. */+ float MidMinZCm = 350.f;+ float UpperMinZCm = 750.f;++ EVerseArenaLevel ResolveLevel(const FVector& Location) const;+ float ResolveLevelHeight(EVerseArenaLevel Level) const;+ float ResolveVisibility(const FVector& Location) const;+ bool Sight(const FVector& Eye, const FVector& Target) const;+};++/** Per-tick inputs for one observer. */+struct VERSECOMBAT_API FVersePerceptionObserverInput+{+ FVerseSelfPercept Self;+ bool bAds = false;+ float AdsFovDeg = VersePerception::DefaultAdsFovDeg;+};++/**+ * The perception model for all observers. Not thread-safe; one per server world.+ * Order of calls per tick: events (OnNoise, OnFire, OnHit, OnDeath) as they happen, then+ * BuildFrame once per observer. Events are queued per observer and evaluated at BuildFrame with+ * the observer's eye at that tick.+ */+class VERSECOMBAT_API FVersePerceptionModel+{+public:+ /** Profile values the tier owns (bot.md 9.1 Perception group), with the observer's RNG seed. */+ static FVersePerceptionProfile MakeProfile(const UVerseBotTier& Tier, uint32 Seed);++ void AddObserver(int32 PlayerId, const FVersePerceptionProfile& Profile);+ void RemoveObserver(int32 PlayerId);+ bool HasObserver(int32 PlayerId) const;+ const FVersePerceptionProfile* FindProfile(int32 PlayerId) const;+ TArray<int32> GetObserverIds() const;++ /** A noise event (server only). Heard by every observer except its source. */+ void OnNoise(const FVerseNoiseEvent& Event);+ /**+ * A shot: tracks the bolt so observers can see it in flight, and marks the shooter as firing+ * (FiringVisibleS) with the weapon it fired, which a sighting may then show.+ */+ void OnFire(const FVerseFireEvent& Event);+ /** A reload: the shooter shows the reload animation from start to end (unless cancelled). */+ void OnReload(const FVerseReloadEvent& Event);+ /** A hit: hurt percept for the victim, hit marker for the instigator; ends the bolt. */+ void OnHit(const FVerseHitEvent& Event);+ /** A death: kill feed for everyone; respawn feed at RespawnAt. KillerBody is the killer's truth for the kill cam. */+ void OnDeath(const FVerseDeathEvent& Event, const FVersePerceptionBody* KillerBody);++ /**+ * One frame for one observer. Bodies is everything perceivable this tick (the observer's own+ * body may be in it and is skipped). NowMs is server time; DeltaS the time since the last call.+ */+ FVersePerceptFrame BuildFrame(int32 ObserverId, const FVersePerceptionObserverInput& Input,+ TConstArrayView<FVersePerceptionBody> Bodies, const FVersePerceptionWorld& World, uint32 NowMs, float DeltaS);++ /** What a look at Body shows this tick: the body plus the cues of its own events (firing, weapon, reload). */+ FVersePerceptionBody ApplyCues(const FVersePerceptionBody& Body, float NowS) const { return WithCues(Body, NowS); }++ /** Drop live bolts and queued events (destruction full reset, arena switch). Observers stay. */+ void ResetEvents();++ /** Pure geometry (tests): the cone a view sees. */+ struct FCone+ {+ float HalfAngleDeg = VersePerception::ViewHalfAngleDeg;+ float VerticalHalfAngleDeg = VersePerception::VerticalHalfAngleDeg;+ float PeripheralHalfAngleDeg = VersePerception::PeripheralHalfAngleDeg;+ };+ static FCone ConeFor(bool bAds, float AdsFovDeg);++ enum class EConeZone : uint8+ {+ Outside,+ Peripheral,+ Inside+ };+ static EConeZone Classify(const FVector& Eye, const FRotator& View, const FCone& Cone, const FVector& Point);++private:+ struct FContact+ {+ /** Server time the target became visible without a break; for the dark-zone notice delay. */+ uint32 VisibleSinceMs = 0;+ bool bVisibleLastTick = false;+ };++ struct FLiveBolt+ {+ int32 ShooterId = INDEX_NONE;+ uint16 ShotCounter = 0;+ FVector Origin = FVector::ZeroVector;+ FVector Direction = FVector::ForwardVector;+ float StartS = 0.f;+ /** Seconds of flight until the bolt ended (hit); infinite until known. */+ float EndFlightS = TNumericLimits<float>::Max();+ };++ /** What other players can see a body do, from its own events (firing, weapon, reload). */+ struct FBodyCues+ {+ float LastFireS = -1.f;+ FName Weapon;+ float ReloadStartS = 0.f;+ float ReloadEndS = -1.f;+ };++ /** Body plus the cues from its events (an explicit flag on the body wins). */+ FVersePerceptionBody WithCues(const FVersePerceptionBody& Body, float NowS) const;++ struct FPendingRespawn+ {+ int32 PlayerId = INDEX_NONE;+ uint32 AtMs = 0;+ };++ struct FObserver+ {+ int32 PlayerId = INDEX_NONE;+ FVersePerceptionProfile Profile;+ FVerseRng Rng;+ uint32 NextPerceptId = 1;+ TMap<int32, FContact> Contacts;+ TArray<FVerseNoiseEvent> PendingNoise;+ TArray<FVerseHitEvent> PendingHurt;+ TArray<FVerseHudEvent> PendingHud;+ uint32 LastFrameMs = 0;+ bool bHasFrame = false;+ };++ FObserver* Find(int32 PlayerId);++ void BuildSightings(FObserver& Observer, const FVersePerceptionObserverInput& Input,+ TConstArrayView<FVersePerceptionBody> Bodies, const FVersePerceptionWorld& World, uint32 NowMs, FVersePerceptFrame& Out);+ void BuildBolts(FObserver& Observer, const FVersePerceptionObserverInput& Input, const FVersePerceptionWorld& World,+ uint32 NowMs, float DeltaS, FVersePerceptFrame& Out);+ void BuildHeard(FObserver& Observer, const FVersePerceptionObserverInput& Input, const FVersePerceptionWorld& World,+ uint32 NowMs, FVersePerceptFrame& Out);+ void BuildHurt(FObserver& Observer, uint32 NowMs, FVersePerceptFrame& Out);+ void BuildHud(FObserver& Observer, uint32 NowMs, FVersePerceptFrame& Out);++ TArray<FObserver> Observers;+ TArray<FLiveBolt> Bolts;+ TArray<FPendingRespawn> Respawns;+ TMap<int32, FBodyCues> Cues;+ /** Latest server time seen, seconds (bolt flight clock). */+ float ClockS = 0.f;+};diff --git a/unreal/Verse/Source/VerseCombat/Public/Perception/VersePerceptionService.h b/unreal/Verse/Source/VerseCombat/Public/Perception/VersePerceptionService.hnew file mode 100644index 0000000000..b8c8eb78cf--- /dev/null+++ b/unreal/Verse/Source/VerseCombat/Public/Perception/VersePerceptionService.h@@ -0,0 +1,132 @@+#pragma once++#include "Bot/VersePerceptTypes.h"+#include "CoreMinimal.h"+#include "Perception/VersePerceptionModel.h"+#include "Subsystems/WorldSubsystem.h"+#include "UObject/ScriptInterface.h"++#include "VersePerceptionService.generated.h"++class AController;+class APawn;+class IVersePenetrationQuery;+class UVerseAudibilityTable;+class UVerseEventHub;++DECLARE_MULTICAST_DELEGATE_TwoParams(FOnVersePerceptFrame, AController* /*Observer*/, const FVersePerceptFrame& /*Frame*/);++/**+ * The fairness boundary (contracts/bot.md 2, frozen interface): a server world subsystem that+ * turns world truth into one FVersePerceptFrame per registered observer per tick, with all+ * perception error applied before a percept leaves it. Bots and harness person models read only+ * these frames. The rules live in FVersePerceptionModel; this class gathers truth from pawns and+ * hub events and runs the model once per server tick.+ */+UCLASS()+class VERSECOMBAT_API UVersePerceptionService : public UTickableWorldSubsystem+{+ GENERATED_BODY()++public:+ /** The service of the object's world, or nullptr. */+ static UVersePerceptionService* Get(const UObject* WorldContextObject);++ /** Start producing frames for Observer (its pawn's eye, its player state id). */+ void RegisterObserver(AController* Observer, const FVersePerceptionProfile& Profile);+ void UnregisterObserver(AController* Observer);+ bool IsRegistered(const AController* Observer) const;++ /** One frame per registered observer per tick. Server only. */+ FOnVersePerceptFrame OnPerceptFrame;++ /** Sight query (WP03 penetration query when it lands). Default: a plain trace on VerseSight. */+ void SetSightQuery(TScriptInterface<IVersePenetrationQuery> Query);++ /** DA_Audibility; default: a transient table with the contract rows. */+ void SetAudibilityTable(const UVerseAudibilityTable* Table);++ /** Arena data hooks: dark zones and height levels (bot.md 3.1, 3.2). */+ void SetVisibilityFactorProvider(TFunction<float(const FVector&)> Provider);+ void SetLevelBands(float MidMinZCm, float UpperMinZCm);++ /**+ * Fills the HUD part of a self percept the service cannot read itself yet (health, armour,+ * magazine, reserve, gadgets: WP02). Called after the service filled position, view, stance+ * and combat phase.+ */+ void SetSelfPerceptFiller(TFunction<void(const APawn&, FVerseSelfPercept&)> Filler);++ /**+ * Fills what a look at a pawn shows that the service cannot read itself yet: ADS and its field+ * of view (WP01), the held weapon and the reload animation (WP02). Called after MakeBody. Firing,+ * the last fired weapon and reloads already come from the hub's OnFire and OnReload events.+ */+ void SetBodyFiller(TFunction<void(const APawn&, FVersePerceptionBody&)> Filler);++ /** Run one perception tick now (tests and the headless harness step the world themselves). */+ void StepPerception(float DeltaS);++ const FVersePerceptionModel& GetModel() const { return Model; }++ // UTickableWorldSubsystem+ virtual void Initialize(FSubsystemCollectionBase& Collection) override;+ virtual void Deinitialize() override;+ virtual bool DoesSupportWorldType(const EWorldType::Type WorldType) const override;+ virtual void Tick(float DeltaTime) override;+ virtual TStatId GetStatId() const override;++ /** Truth snapshot of a pawn (eye from the Camera bone, sample points from the hit-zone bones). */+ static FVersePerceptionBody MakeBody(const APawn& Pawn, int32 PlayerId);++ /** The bone names the sample points read, in EVerseSightSample order (art-pipeline.md 12.1). */+ static const FName SampleBones[8];+ static const FName EyeBone;++private:+ struct FRegistered+ {+ TWeakObjectPtr<AController> Controller;+ int32 PlayerId = INDEX_NONE;+ };++ void BindHub();+ void UnbindHub();+ void HandleNoise(const FVerseNoiseEvent& Event);+ void HandleFire(const FVerseFireEvent& Event);+ void HandleReload(const FVerseReloadEvent& Event);+ void HandleHit(const FVerseHitEvent& Event);+ void HandleDeath(const FVerseDeathEvent& Event);+ void HandleArenaSwitch(const FVerseArenaSwitchEvent& Event);++ void GatherBodies(TArray<FVersePerceptionBody>& OutBodies) const;+ FVersePerceptionWorld MakeWorld() const;+ static int32 PlayerIdOf(const AController& Controller);+ bool IsServer() const;++ FVersePerceptionModel Model;+ TArray<FRegistered> Registered;++ UPROPERTY(Transient)+ TObjectPtr<UObject> SightQueryObject;+ IVersePenetrationQuery* SightQuery = nullptr;++ UPROPERTY(Transient)+ TObjectPtr<const UVerseAudibilityTable> Audibility;++ TFunction<float(const FVector&)> VisibilityProvider;+ TFunction<void(const APawn&, FVerseSelfPercept&)> SelfFiller;+ TFunction<void(const APawn&, FVersePerceptionBody&)> BodyFiller;+ float MidMinZCm = 350.f;+ float UpperMinZCm = 750.f;++ TWeakObjectPtr<UVerseEventHub> Hub;+ FDelegateHandle NoiseHandle;+ FDelegateHandle FireHandle;+ FDelegateHandle ReloadHandle;+ FDelegateHandle HitHandle;+ FDelegateHandle DeathHandle;+ FDelegateHandle ArenaHandle;++ float LastStepDeltaS = 0.f;+};