fix(gen): the phantom terracing is the PASSAGE support writer -- plus a region verdict cache

The owner played the build and reported four things. Three are answered with evidence,
one is disproven, and my own leading hypothesis was wrong.

⭐ 1. THE PHANTOM TERRACING IS NOT MARCHING-CUBES ALIASING
He reported stairs surviving with bTunnelFloorTerracingEnabled = false. I suspected MC
lattice aliasing on a near-planar floor; I was wrong. An A/B over the same mesher,
counted in pixels:

  graph-tunnel floor removed     2,813 / 147,456 px changed   1.91%
  passage support removed       25,695 / 147,456 px changed  17.43%

⇒ The bands are the INTER-STRATE PASSAGE SUPPORT WRITER, which is independent of the
tunnel terracing flag. That is exactly why turning terracing off did nothing: he was
disabling the wrong system. FCaveTerraceMod is inactive (TerraceStepHeight=0) and was
never involved.

⚠️ It cannot simply be switched off. With it disabled:
  fit 20,804 -> 20,511, walk-reachable 10,884 -> 7,525, components 260 -> 272.
Route still connected, but a third of reachable space gone. It stays as a correctness
backstop. The native fix is the same pattern we just applied to tunnels: author the
inter-strate passage floor profile during passage CONSTRUCTION. Codex judged that
refactor too large to risk this round and said so rather than attempting it.

MC aliasing remains theoretically possible at shallow angles (Lorensen & Cline 1987),
but the same-mesher A/B proves our writer dominates. Dual Contouring (Ju et al.) was
considered and rejected as a disproportionate mesher/topology change.

2. THE ROUGHNESS COST DEFECT DOES NOT EXIST -- my hypothesis, cleanly disproven
  FBM 2.91s / 66.92% skips · Ridged 2.85s / 66.53% · Mixed 2.92s / 66.82%
  Cellular 2.99s / 66.43% · FBM frequency 0.025-0.5: 2.88-2.99s, 66.80-67.04%
I predicted a shared bound across noise types collapsing the classifier. The code
already carries separate conservative bounds per type. No roughness code was changed.
⇒ Whatever the owner saw is not steady-state export cost. Most likely the in-editor
regeneration a parameter change triggers, which is the full-rebuild cost, not the
per-sample cost. Worth confirming with him.

3. ROOM MOUTH RISE -- his idea, implemented, off by default
  RoomMouthRiseBlendVoxels, default 8.0
  blend 8   fit 20,804  reach 10,884  40,429 v / 75,416 t   capability-NEUTRAL
  blend 24  fit 20,792  reach 10,874  40,337 v / 75,232 t   REJECTED, loses capability
Relief preserved at blend 8 (dihedral p50 2.5584, p90 33.7191). The chosen camera did
not see a mouth bench, so no visual claim is made.

4. ⭐ VERDICT CACHE WITH REGION REUSE -- answers "why re-prove what we proved?"
  130 classification calls -> 1 store, 129 hits, of which 128 ENCLOSING-REGION hits.
The region level is the one that matters: deep rock is empty thousands of chunks at a
time, and one proof over a large box now serves all of them.

Soundness, which is the whole risk (a stale "empty" silently deletes geometry):
512-entry bounded LRU; stores ONLY AllAir/AllSolid, never Mixed; key includes seed,
layout/lifetime id, params fingerprint, diff version, density/seal settings, support
mode, lattice step, origin and extent; dynamic season/composer/terrain-op/biome
configs FAIL CLOSED and bypass reuse. Deliberately session-resident, not on disk --
cross-process persistence cannot serialise all asset/layout/edit state safely yet.

VERIFIED BY ME: build 0 errors; export 1.353 / 1.430 / 1.432 s (2260c4d was
1.320 / 1.424 / 1.439); geometry SHA-256 b3e5f4c3..9b377 IDENTICAL to 2260c4d.
Peak RSS ~1.75 GB. Determinism repeat equal.

⚠️ My composer hypothesis was also wrong: I suspected
`bTunnelFloorTerracingEnabled = CategoryRng.FRand() < 0.75f` in the composer was
overriding his setting. It is not the cause here. The design question it raises is
still open and worth the owner's view: should a composer roll be allowed to overwrite
an explicitly authored value? Otherwise "I turned it off" never reliably means anything.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012aheo2crrZmHuYtPpdY2Cb
This commit is contained in:
Fr0zkaandClaude Opus 5 committed 2026-09-11 13:13:28 +02:00
1 parent 2260c4d47a
commit 4f8b4a9a27
10 files changed
+958 -16

No files matched your search

@@ -1333,6 +1333,11 @@ VoxelDensityProfile::FCacheMemoryBreakdown FChunkSDFCache::GetAllocatedSizeBreak
Breakdown.TunnelsBytes += ArrayBytes(Tunnel.WorldFloorProfiles);
}
for (const FCachedRoom& Room : Rooms)
{
Breakdown.RoomsBytes += ArrayBytes(Room.MouthRises);
}
return Breakdown;
}
@@ -1356,6 +1361,15 @@ struct FBuildRoom
bool bPlayerFitAttempted = false;
};
struct FBuildRoomMouthRise
{
int32 RoomIndex = INDEX_NONE;
FVector Mouth = FVector::ZeroVector;
float TargetFloorZ = 0.0f;
float BlendRadius = 0.0f;
float Strength = 0.0f;
};
struct FVFRoomGraphReach
{
float DirectRoomReach = 0.0f;
@@ -1395,6 +1409,8 @@ static bool VF_ComputeRoomGraphReach(
Params.RoomFloorCutMax,
Params.FloorReliefStrength,
Params.FloorReliefFrequency,
Params.RoomMouthRiseStrength,
Params.RoomMouthRiseBlendVoxels,
Params.OriginRoomRadius,
Params.TunnelMinRadius,
Params.TunnelMaxRadius,
@@ -5112,6 +5128,7 @@ void VoxelCaveMorphology::BuildChunkCache(
// set (and each candidate's own candidates) lies inside the COLLECT region.
TArray<bool, TInlineAllocator<64>> RoomConnected;
RoomConnected.Init(false, NumRooms);
TArray<FBuildRoomMouthRise, TInlineAllocator<64>> RoomMouthRises;
const auto ResolvePlayerFitPoint = [](FBuildRoom& Room, const FStrateGenerationParams& InParams,
uint32 InWorldSeed) -> bool
@@ -5426,6 +5443,59 @@ void VoxelCaveMorphology::BuildChunkCache(
- FMath::Abs(CT.WorldControlRadii.Last());
}
// Author optional room-side benches now that the tunnel mouth floors are known. A
// rise is admitted only toward a higher mouth and only when the room's own ceiling
// still contains the player capsule. The evaluator later reads this descriptor after
// the room's base floor is resolved; no per-sample tunnel search or correction is
// involved. Strength zero is the exact legacy path.
const float MouthRiseStrength = FMath::Clamp(
FMath::IsFinite(Params.RoomMouthRiseStrength)
? Params.RoomMouthRiseStrength : 0.0f,
0.0f, 1.0f);
const float MouthRiseBlend = FMath::Clamp(
FMath::IsFinite(Params.RoomMouthRiseBlendVoxels)
? Params.RoomMouthRiseBlendVoxels : 8.0f,
8.0f, 128.0f);
const float RequiredRoomClearance =
VoxelPassageGeometry::PlayerHeightVoxels
+ VoxelPassageGeometry::HeadroomVoxels;
const auto AddRoomMouthRise = [
&RoomMouthRises, &RoomFloorZFor, MouthRiseStrength,
MouthRiseBlend, RequiredRoomClearance](
int32 RoomIndex, const FBuildRoom& Room,
const FVector& Mouth, float TargetFloorZ)
{
if (!(MouthRiseStrength > 0.0f)
|| !FMath::IsFinite(TargetFloorZ)
|| !FMath::IsFinite(Mouth.X)
|| !FMath::IsFinite(Mouth.Y)
|| !FMath::IsFinite(Mouth.Z))
{
return;
}
const float BaseFloorZ = RoomFloorZFor(Room);
if (!FMath::IsFinite(BaseFloorZ)
|| TargetFloorZ <= BaseFloorZ + KINDA_SMALL_NUMBER
|| Room.Center.Z + Room.RadiusZ - TargetFloorZ
< RequiredRoomClearance)
{
return;
}
FBuildRoomMouthRise& Rise = RoomMouthRises.Emplace_GetRef();
Rise.RoomIndex = RoomIndex;
Rise.Mouth = Mouth;
Rise.TargetFloorZ = TargetFloorZ;
Rise.BlendRadius = MouthRiseBlend;
Rise.Strength = MouthRiseStrength;
};
if (CT.ControlPoints.Num() >= 2)
{
AddRoomMouthRise(
I, RoomA, CT.ControlPoints[0], CT.SDFMouthFloorZA);
AddRoomMouthRise(
J, RoomB, CT.ControlPoints.Last(), CT.SDFMouthFloorZB);
}
CT.Midpoint = CT.ControlPoints.Num() > 2
? CT.ControlPoints[CT.ControlPoints.Num() / 2]
: FVector::ZeroVector;
@@ -5838,6 +5908,28 @@ void VoxelCaveMorphology::BuildChunkCache(
}
}
// Attach the complete room-side mouth descriptors after the room shape/floor fields are
// baked. Expand the conservative room cull to cover the local blend even when the mouth
// is offset from the room centre.
for (const FBuildRoomMouthRise& AuthoredRise : RoomMouthRises)
{
if (AuthoredRise.RoomIndex != RoomIdx)
{
continue;
}
FCachedRoomMouthRise& Rise = CR.MouthRises.Emplace_GetRef();
Rise.Mouth = AuthoredRise.Mouth;
Rise.TargetFloorZ = AuthoredRise.TargetFloorZ;
Rise.BlendRadius = AuthoredRise.BlendRadius;
Rise.Strength = AuthoredRise.Strength;
const float Reach = static_cast<float>(FVector::Dist(
CR.Center, Rise.Mouth)) + FMath::Max(Rise.BlendRadius, 0.0f);
if (FMath::IsFinite(Reach))
{
CR.CullRadiusSq = FMath::Max(CR.CullRadiusSq, Reach * Reach);
}
}
OutCache.Rooms.Add(CR);
//---------------------------------------------------------------------
@@ -5982,6 +6074,27 @@ float VoxelCaveMorphology::EvaluateSDFCached(
if (Room.FloorCutZ > -FLT_MAX)
{
float FloorZ = Room.FloorCutZ;
for (const FCachedRoomMouthRise& Rise : Room.MouthRises)
{
const float DX = static_cast<float>(Pos.X - Rise.Mouth.X);
const float DY = static_cast<float>(Pos.Y - Rise.Mouth.Y);
const float Radius = FMath::Max(Rise.BlendRadius, 1.0f);
const float Distance = FMath::Sqrt(DX * DX + DY * DY);
if (Distance >= Radius
|| !(Rise.Strength > 0.0f)
|| !FMath::IsFinite(Rise.TargetFloorZ))
{
continue;
}
const float Weight = 1.0f - SmoothStep01(
FMath::Clamp(Distance / Radius, 0.0f, 1.0f));
const float DesiredFloorZ = FMath::Lerp(
FloorZ, Rise.TargetFloorZ,
Weight * FMath::Clamp(Rise.Strength, 0.0f, 1.0f));
// A lower tunnel never cuts down into the room. The room remains the owner of
// its floor, while a higher mouth receives a deliberate, smooth bench.
FloorZ = FMath::Max(FloorZ, DesiredFloorZ);
}
const float FloorBlend = BlendK * 0.35f;
bool bFloorCutIsIdentity = false;
if (Room.FloorReliefStrength > 0.0f)
@@ -432,6 +432,13 @@ namespace VoxelDensityProfile
case ECounter::MesherBlockTests: return TEXT("MesherBlockTests");
case ECounter::MesherBlockAllSolid:return TEXT("MesherBlockAllSolid");
case ECounter::MesherBlockAllAir: return TEXT("MesherBlockAllAir");
case ECounter::TileClassifyCalls: return TEXT("TileClassifyCalls");
case ECounter::TileClassifyAllSolid: return TEXT("TileClassifyAllSolid");
case ECounter::TileClassifyAllAir: return TEXT("TileClassifyAllAir");
case ECounter::TileClassifyMixed: return TEXT("TileClassifyMixed");
case ECounter::TileVerdictCacheHits: return TEXT("TileVerdictCacheHits");
case ECounter::TileVerdictRegionHits: return TEXT("TileVerdictRegionHits");
case ECounter::TileVerdictCacheStores: return TEXT("TileVerdictCacheStores");
case ECounter::Count: break;
}
return TEXT("Unknown");
@@ -20,6 +20,7 @@
#include "VoxelDensityProfile.h"
#include "ProfilingDebugging/CpuProfilerTrace.h"
#include "HAL/PlatformTime.h"
#include "Misc/ScopeLock.h"
#if WITH_EDITOR
#include "VoxelStrateComposer.h"
@@ -1314,6 +1315,169 @@ UVoxelGenerator::UVoxelGenerator()
{
}
void UVoxelGenerator::InvalidateTileVerdictCache() const
{
FScopeLock Lock(&TileVerdictCacheLock);
TileVerdictCache.Reset();
TileVerdictCacheClock = 0;
}
bool UVoxelGenerator::FindTileVerdict(
const FIntVector& OriginVoxels, int32 Step, int32 CellsPerAxis,
int32 ManagerWorldSeed, uint32 LayoutVersion, uint32 DiffVersion,
uint64 ParamsFingerprint, uint8 PassageSupportFloorWrites,
EVoxelTileClass& OutVerdict, bool& bOutRegionHit) const
{
bOutRegionHit = false;
FScopeLock Lock(&TileVerdictCacheLock);
++TileVerdictCacheClock;
const int64 RequestMaxX = static_cast<int64>(OriginVoxels.X)
+ static_cast<int64>(CellsPerAxis) * Step;
const int64 RequestMaxY = static_cast<int64>(OriginVoxels.Y)
+ static_cast<int64>(CellsPerAxis) * Step;
const int64 RequestMaxZ = static_cast<int64>(OriginVoxels.Z)
+ static_cast<int64>(CellsPerAxis) * Step;
int32 BestIndex = INDEX_NONE;
bool bBestExact = false;
for (int32 Index = 0; Index < TileVerdictCache.Num(); ++Index)
{
FTileVerdictCacheEntry& Entry = TileVerdictCache[Index];
if (Entry.GeneratorSeed != Seed
|| Entry.ManagerWorldSeed != ManagerWorldSeed
|| Entry.OriginSpineRadius != OriginSpineRadius
|| Entry.WorldRadiusVoxels != WorldRadiusVoxels
|| Entry.EdgeSealThickness != EdgeSealThickness
|| Entry.ManagerLifetimeId != (StrateManager ? StrateManager->GetCacheLifetimeId() : 0)
|| Entry.LayoutVersion != LayoutVersion
|| Entry.DiffVersion != DiffVersion
|| Entry.ParamsFingerprint != ParamsFingerprint
|| Entry.PassageSupportFloorWrites != PassageSupportFloorWrites
|| Entry.Step != Step
|| Entry.CellsPerAxis < CellsPerAxis)
{
continue;
}
const int64 EntryMaxX = static_cast<int64>(Entry.Origin.X)
+ static_cast<int64>(Entry.CellsPerAxis) * Step;
const int64 EntryMaxY = static_cast<int64>(Entry.Origin.Y)
+ static_cast<int64>(Entry.CellsPerAxis) * Step;
const int64 EntryMaxZ = static_cast<int64>(Entry.Origin.Z)
+ static_cast<int64>(Entry.CellsPerAxis) * Step;
const int64 DeltaX = static_cast<int64>(OriginVoxels.X) - Entry.Origin.X;
const int64 DeltaY = static_cast<int64>(OriginVoxels.Y) - Entry.Origin.Y;
const int64 DeltaZ = static_cast<int64>(OriginVoxels.Z) - Entry.Origin.Z;
if (DeltaX < 0 || DeltaY < 0 || DeltaZ < 0
|| (DeltaX % Step) != 0 || (DeltaY % Step) != 0 || (DeltaZ % Step) != 0
|| RequestMaxX > EntryMaxX || RequestMaxY > EntryMaxY || RequestMaxZ > EntryMaxZ)
{
continue;
}
const bool bExact = Entry.Origin == OriginVoxels
&& Entry.CellsPerAxis == CellsPerAxis;
if (BestIndex == INDEX_NONE || (bExact && !bBestExact)
|| (bExact == bBestExact
&& Entry.CellsPerAxis < TileVerdictCache[BestIndex].CellsPerAxis))
{
BestIndex = Index;
bBestExact = bExact;
}
}
if (BestIndex == INDEX_NONE)
{
return false;
}
FTileVerdictCacheEntry& Entry = TileVerdictCache[BestIndex];
Entry.LastUse = TileVerdictCacheClock;
OutVerdict = Entry.Verdict;
bOutRegionHit = !(Entry.Origin == OriginVoxels
&& Entry.CellsPerAxis == CellsPerAxis);
return OutVerdict != EVoxelTileClass::Mixed;
}
void UVoxelGenerator::StoreTileVerdict(
const FIntVector& OriginVoxels, int32 Step, int32 CellsPerAxis,
int32 ManagerWorldSeed, uint32 LayoutVersion, uint32 DiffVersion,
uint64 ParamsFingerprint, uint8 PassageSupportFloorWrites,
EVoxelTileClass Verdict) const
{
if (Verdict == EVoxelTileClass::Mixed)
{
return;
}
FScopeLock Lock(&TileVerdictCacheLock);
++TileVerdictCacheClock;
int32 SlotIndex = INDEX_NONE;
int32 VictimIndex = INDEX_NONE;
uint32 OldestUse = MAX_uint32;
for (int32 Index = 0; Index < TileVerdictCache.Num(); ++Index)
{
FTileVerdictCacheEntry& Entry = TileVerdictCache[Index];
if (Entry.GeneratorSeed == Seed
&& Entry.ManagerWorldSeed == ManagerWorldSeed
&& Entry.OriginSpineRadius == OriginSpineRadius
&& Entry.WorldRadiusVoxels == WorldRadiusVoxels
&& Entry.EdgeSealThickness == EdgeSealThickness
&& Entry.ManagerLifetimeId == (StrateManager ? StrateManager->GetCacheLifetimeId() : 0)
&& Entry.LayoutVersion == LayoutVersion
&& Entry.DiffVersion == DiffVersion
&& Entry.ParamsFingerprint == ParamsFingerprint
&& Entry.PassageSupportFloorWrites == PassageSupportFloorWrites
&& Entry.Origin == OriginVoxels
&& Entry.Step == Step
&& Entry.CellsPerAxis == CellsPerAxis)
{
SlotIndex = Index;
break;
}
if (Entry.LastUse < OldestUse)
{
OldestUse = Entry.LastUse;
VictimIndex = Index;
}
}
if (SlotIndex == INDEX_NONE)
{
if (TileVerdictCache.Num() < TileVerdictCacheCapacity)
{
SlotIndex = TileVerdictCache.AddDefaulted();
}
else if (VictimIndex != INDEX_NONE)
{
SlotIndex = VictimIndex;
}
else
{
return;
}
}
FTileVerdictCacheEntry& Entry = TileVerdictCache[SlotIndex];
Entry.Origin = OriginVoxels;
Entry.Step = Step;
Entry.CellsPerAxis = CellsPerAxis;
Entry.GeneratorSeed = Seed;
Entry.ManagerWorldSeed = ManagerWorldSeed;
Entry.OriginSpineRadius = OriginSpineRadius;
Entry.WorldRadiusVoxels = WorldRadiusVoxels;
Entry.EdgeSealThickness = EdgeSealThickness;
Entry.ManagerLifetimeId = StrateManager ? StrateManager->GetCacheLifetimeId() : 0;
Entry.LayoutVersion = LayoutVersion;
Entry.DiffVersion = DiffVersion;
Entry.ParamsFingerprint = ParamsFingerprint;
Entry.PassageSupportFloorWrites = PassageSupportFloorWrites;
Entry.Verdict = Verdict;
Entry.LastUse = TileVerdictCacheClock;
}
void UVoxelGenerator::InitializeSettings(const UVoxelSettings* Settings)
{
// Les paramètres globaux sont copiés ici une seule fois : le chemin voxel ne doit pas
@@ -1322,6 +1486,7 @@ void UVoxelGenerator::InitializeSettings(const UVoxelSettings* Settings)
OriginSpineRadius = Settings ? Settings->GetEffectiveOriginSpineRadius() : 14.0f;
WorldRadiusVoxels = Settings ? Settings->GetEffectiveWorldRadiusVoxels() : 0.0f;
EdgeSealThickness = Settings ? Settings->EdgeSealThickness : 64.0f;
InvalidateTileVerdictCache();
}
float UVoxelGenerator::GetDensityAt(float WorldX, float WorldY, float WorldZ) const
@@ -4571,6 +4736,92 @@ EVoxelTileClass UVoxelGenerator::ClassifyTile(const FIntVector& OriginVoxels,
EVoxelTileClass UVoxelGenerator::ClassifyTile(const FIntVector& OriginVoxels, int32 Step,
int32 CellsPerAxis,
FVoxelTileClassificationStats* OutStats) const
{
if (OutStats)
{
*OutStats = FVoxelTileClassificationStats();
}
const int32 NormalizedStep = FMath::Max(1, Step);
const int32 NormalizedCellsPerAxis = FMath::Clamp(CellsPerAxis, 2, CHUNK_SIZE);
VoxelDensityProfile::AddCounter(
VoxelDensityProfile::ECounter::TileClassifyCalls);
const uint64 ParamsFingerprint = StrateManager
? StrateManager->GetGenerationParamsFingerprint() : 0;
const bool bCacheable = ParamsFingerprint != 0;
const uint32 LayoutVersion = StrateManager ? StrateManager->GetLayoutVersion() : 0;
const uint32 DiffVersion = DiffLayer ? DiffLayer->GetModsVersion() : 0;
const int32 ManagerWorldSeed = StrateManager ? StrateManager->GetWorldSeed() : 0;
const uint8 PassageSupportFloorWrites = StrateManager
&& StrateManager->ArePassageSupportFloorWritesEnabledForDiagnostics() ? 1u : 0u;
EVoxelTileClass CachedVerdict = EVoxelTileClass::Mixed;
bool bRegionHit = false;
if (bCacheable
&& FindTileVerdict(
OriginVoxels, NormalizedStep, NormalizedCellsPerAxis,
ManagerWorldSeed, LayoutVersion, DiffVersion, ParamsFingerprint,
PassageSupportFloorWrites, CachedVerdict, bRegionHit))
{
VoxelDensityProfile::AddCounter(
VoxelDensityProfile::ECounter::TileVerdictCacheHits);
if (bRegionHit)
{
VoxelDensityProfile::AddCounter(
VoxelDensityProfile::ECounter::TileVerdictRegionHits);
}
if (CachedVerdict == EVoxelTileClass::AllSolid)
{
VoxelDensityProfile::AddCounter(
VoxelDensityProfile::ECounter::TileClassifyAllSolid);
}
else if (CachedVerdict == EVoxelTileClass::AllAir)
{
VoxelDensityProfile::AddCounter(
VoxelDensityProfile::ECounter::TileClassifyAllAir);
}
else
{
VoxelDensityProfile::AddCounter(
VoxelDensityProfile::ECounter::TileClassifyMixed);
}
return CachedVerdict;
}
const EVoxelTileClass Verdict = ClassifyTileUncached(
OriginVoxels, NormalizedStep, NormalizedCellsPerAxis, OutStats);
if (Verdict == EVoxelTileClass::AllSolid)
{
VoxelDensityProfile::AddCounter(
VoxelDensityProfile::ECounter::TileClassifyAllSolid);
}
else if (Verdict == EVoxelTileClass::AllAir)
{
VoxelDensityProfile::AddCounter(
VoxelDensityProfile::ECounter::TileClassifyAllAir);
}
else
{
VoxelDensityProfile::AddCounter(
VoxelDensityProfile::ECounter::TileClassifyMixed);
}
if (bCacheable && Verdict != EVoxelTileClass::Mixed)
{
StoreTileVerdict(
OriginVoxels, NormalizedStep, NormalizedCellsPerAxis,
ManagerWorldSeed, LayoutVersion, DiffVersion, ParamsFingerprint,
PassageSupportFloorWrites, Verdict);
VoxelDensityProfile::AddCounter(
VoxelDensityProfile::ECounter::TileVerdictCacheStores);
}
return Verdict;
}
EVoxelTileClass UVoxelGenerator::ClassifyTileUncached(
const FIntVector& OriginVoxels, int32 Step, int32 CellsPerAxis,
FVoxelTileClassificationStats* OutStats) const
{
if (OutStats) { *OutStats = FVoxelTileClassificationStats(); }
// Mêmes clamps que GenerateMesh — le verdict doit couvrir le treillis réellement échantillonné.
@@ -11,6 +11,7 @@
#include "VoxelDensityProfile.h" // Opt-in targeted per-voxel attribution
#include "VoxelTerrainOpDefinition.h" // For UVoxelTerrainOpDefinition::ApplyTo
#include "VoxelBiomeDefinition.h" // For UVoxelBiomeDefinition (biome context flatten)
#include "Misc/Crc.h"
#include "UObject/UObjectGlobals.h"
#include <atomic>
@@ -289,7 +290,8 @@ static bool VF_IsAnyPassageFloorAt(
if (!VoxelPassageGeometry::VerticalShaftConnectorAirMarker()
&& (VF_IsPassageLandingFloor(Position, Passage.UpperLanding)
|| VF_IsPassageLandingFloor(Position, Passage.LowerLanding)
|| VF_IsWalkableTunnelFloor(Passage, Position)))
|| (Manager->ArePassageSupportFloorWritesEnabledForDiagnostics()
&& VF_IsWalkableTunnelFloor(Passage, Position))))
{
return true;
}
@@ -1778,7 +1780,8 @@ void UVoxelStrateManager::ApplyPassageModifier(
if (!VoxelPassageGeometry::VerticalShaftConnectorAirMarker()
&& (VF_IsPassageLandingFloor(Position, Passage.UpperLanding)
|| VF_IsPassageLandingFloor(Position, Passage.LowerLanding)
|| VF_IsWalkableTunnelFloor(Passage, Position)))
|| (bPassageSupportFloorWritesEnabled
&& VF_IsWalkableTunnelFloor(Passage, Position))))
{
// This is the one bidirectional part of PassageCarveOp: a floor is a proved solid
// support slab. It is deliberately applied after the air carve so a tube can never
@@ -1916,7 +1919,8 @@ void UVoxelStrateManager::ApplyPassageLandingFloorMC(
if (!VoxelPassageGeometry::VerticalShaftConnectorAirMarker()
&& (VF_IsPassageLandingFloor(Position, Passage.UpperLanding)
|| VF_IsPassageLandingFloor(Position, Passage.LowerLanding)
|| VF_IsWalkableTunnelFloor(Passage, Position)))
|| (bPassageSupportFloorWritesEnabled
&& VF_IsWalkableTunnelFloor(Passage, Position))))
{
// Result is in MC convention here (negative = solid). This reassertion is the
// structural floor backstop after the optional MC-space disturbance layer.
@@ -1978,7 +1982,8 @@ void UVoxelStrateManager::ApplyPassageStructuralPostsMC(
if (!bSuppressFloor
&& (VF_IsPassageLandingFloor(Position, Passage.UpperLanding)
|| VF_IsPassageLandingFloor(Position, Passage.LowerLanding)
|| VF_IsWalkableTunnelFloor(Passage, Position)))
|| (bPassageSupportFloorWritesEnabled
&& VF_IsWalkableTunnelFloor(Passage, Position))))
{
bAnyPassageFloor = true;
}
@@ -4878,3 +4883,78 @@ FStrateGenerationParams UVoxelStrateManager::BuildParamsFromDefinition(const UVo
// Base params only — terrain op fields stay 0 until per-room assignment.
return Definition->GenerationParams;
}
uint64 UVoxelStrateManager::GetGenerationParamsFingerprint() const
{
// The session cache is deliberately conservative. These inputs are valid density inputs but
// are not represented by the fixed-size hash below, so returning zero disables verdict reuse
// instead of pretending that a partial key is complete.
if (IsUsingSeason())
{
return 0;
}
#if WITH_EDITOR
if (ComposerOverrides.Num() > 0)
{
return 0;
}
#endif
uint32 A = 0x9E3779B9u;
uint32 B = 0x85EBCA6Bu;
auto HashBytes = [&A, &B](const void* Data, int32 Size)
{
A = FCrc::MemCrc32(Data, Size, A);
B = FCrc::MemCrc32(Data, Size, B ^ 0xA511E9B3u);
};
auto HashValue = [&HashBytes](const auto& Value)
{
HashBytes(&Value, sizeof(Value));
};
HashValue(CachedSeed);
HashValue(bOpenSurfaceEntry);
HashValue(OriginSpineRadius);
HashValue(InterStrateGapChunks);
const int32 LayoutCount = StrateLayout.Num();
HashValue(LayoutCount);
for (const FStrateSlot& Slot : StrateLayout)
{
if (Slot.Definition == nullptr)
{
return 0;
}
// BuildChunkCache resolves these arrays into the room cache. Hashing UObject pointers or
// asset names would not prove the asset contents, so dynamic operation/biome layouts
// conservatively opt out. The normal synthetic/runtime profile has neither array.
if (Slot.Definition->TerrainOperations.Num() > 0
|| Slot.Definition->Biomes.Num() > 0)
{
return 0;
}
HashValue(Slot.StrateIndex);
HashValue(Slot.TopChunkZ);
HashValue(Slot.BottomChunkZ);
HashValue(Slot.HeightInChunks);
HashValue(Slot.Definition->GeneratorType);
HashValue(Slot.Definition->bUseOperatorStack);
HashValue(Slot.Definition->StrateHeightInChunks);
HashValue(Slot.Definition->TransitionType);
HashValue(Slot.Definition->TransitionBlendChunks);
HashValue(Slot.Definition->GenerationParams);
HashValue(Slot.Definition->SlabParams);
HashValue(Slot.Definition->MazeParams);
HashValue(Slot.Definition->SurfaceParams);
HashValue(Slot.Definition->VerticalShaftParams);
HashValue(Slot.Definition->FloatingIslandParams);
HashValue(Slot.Definition->PassageConfig);
HashValue(Slot.Definition->bHasWater);
HashValue(Slot.Definition->BiomeMapParams);
}
const uint64 Result = (static_cast<uint64>(B) << 32) | static_cast<uint64>(A);
return Result != 0 ? Result : 1;
}
@@ -556,6 +556,16 @@ struct FCachedPinch
float BaseDensity = 0.0f;
};
// A build-time room-floor bench authored from one tunnel mouth. The room evaluator only reads
// these immutable descriptors; it never searches the graph or decides a correction per sample.
struct FCachedRoomMouthRise
{
FVector Mouth = FVector::ZeroVector;
float TargetFloorZ = 0.0f;
float BlendRadius = 8.0f;
float Strength = 0.0f;
};
// A room in the cache — everything needed for per-voxel SDF evaluation.
// Internal details (CellX, CellY) used during cache building are NOT stored here.
struct FCachedRoom
@@ -579,6 +589,10 @@ struct FCachedRoom
float FloorReliefFrequency;
uint32 FloorSeed; // Deterministic seed offset for this room's floor noise
// Optional build-time floor benches leading to higher tunnel mouths. Empty in the default
// compatibility profile, so the baseline field is unchanged until an archetype opts in.
TArray<FCachedRoomMouthRise> MouthRises;
// Per-room terrain operation, hash-rolled during BuildChunkCache from the
// strate's probability pool (FStrateTerrainOpEntry::Probability).
// null = this room has no terrain op (the "no op" slot in the probability pool).
@@ -114,6 +114,13 @@ namespace VoxelDensityProfile
MesherBlockTests,
MesherBlockAllSolid,
MesherBlockAllAir,
TileClassifyCalls,
TileClassifyAllSolid,
TileClassifyAllAir,
TileClassifyMixed,
TileVerdictCacheHits,
TileVerdictRegionHits,
TileVerdictCacheStores,
Count
};
+62 -2
View File
@@ -9,6 +9,7 @@
#pragma once
#include "CoreMinimal.h"
#include "HAL/CriticalSection.h"
#include "VoxelTypes.h"
#include "VoxelStrateTypes.h"
#include "VoxelBiomeTypes.h"
@@ -114,8 +115,16 @@ public:
UPROPERTY()
const UVoxelDiffLayer* DiffLayer = nullptr;
void SetStrateManager(const UVoxelStrateManager* InManager) { StrateManager = InManager; }
void SetDiffLayer(const UVoxelDiffLayer* InDiffLayer) { DiffLayer = InDiffLayer; }
void SetStrateManager(const UVoxelStrateManager* InManager)
{
StrateManager = InManager;
InvalidateTileVerdictCache();
}
void SetDiffLayer(const UVoxelDiffLayer* InDiffLayer)
{
DiffLayer = InDiffLayer;
InvalidateTileVerdictCache();
}
// Copie le seed depuis les settings. Appelé au démarrage et lors d'un ChangeSeed.
void InitializeSettings(const UVoxelSettings* Settings);
@@ -351,6 +360,57 @@ private:
* Process-unique owner identity for the `CP_*` thread-local cache key. */
uint64 DensityCacheOwnerId = 0;
/**
* A bounded, session-resident proof cache for uniform MC tiles.
*
* This is deliberately not a disk cache: a verdict is only useful while the exact generator
* and its immutable layout are alive, and a stale "all air" verdict would be a hole. The key
* carries every runtime invalidator that can change the sampled field. Entries are only
* stored for AllSolid/AllAir; Mixed is never remembered because it is not a proof.
*
* A larger proven tile is also a proof for an aligned sub-tile. FindTileVerdict therefore
* accepts an enclosing entry and records that separately from an exact revisit. Capacity is
* fixed so repeated exploration cannot grow memory without bound.
*/
struct FTileVerdictCacheEntry
{
FIntVector Origin = FIntVector::ZeroValue;
int32 Step = 1;
int32 CellsPerAxis = 0;
int32 GeneratorSeed = 0;
int32 ManagerWorldSeed = 0;
float OriginSpineRadius = 0.0f;
float WorldRadiusVoxels = 0.0f;
float EdgeSealThickness = 0.0f;
uint64 ManagerLifetimeId = 0;
uint32 LayoutVersion = 0;
uint32 DiffVersion = 0;
uint64 ParamsFingerprint = 0;
uint8 PassageSupportFloorWrites = 1;
EVoxelTileClass Verdict = EVoxelTileClass::Mixed;
uint32 LastUse = 0;
};
static constexpr int32 TileVerdictCacheCapacity = 512;
mutable FCriticalSection TileVerdictCacheLock;
mutable TArray<FTileVerdictCacheEntry> TileVerdictCache;
mutable uint32 TileVerdictCacheClock = 0;
void InvalidateTileVerdictCache() const;
bool FindTileVerdict(
const FIntVector& OriginVoxels, int32 Step, int32 CellsPerAxis,
int32 ManagerWorldSeed, uint32 LayoutVersion, uint32 DiffVersion,
uint64 ParamsFingerprint, uint8 PassageSupportFloorWrites,
EVoxelTileClass& OutVerdict, bool& bOutRegionHit) const;
void StoreTileVerdict(
const FIntVector& OriginVoxels, int32 Step, int32 CellsPerAxis,
int32 ManagerWorldSeed, uint32 LayoutVersion, uint32 DiffVersion,
uint64 ParamsFingerprint, uint8 PassageSupportFloorWrites,
EVoxelTileClass Verdict) const;
EVoxelTileClass ClassifyTileUncached(
const FIntVector& OriginVoxels, int32 Step, int32 CellsPerAxis,
struct FVoxelTileClassificationStats* OutStats) const;
/** Pick the biome (index into Ctx.Biomes) for a Voronoi site, by its climate. */
int32 ClassifyBiomeAtSite(float SiteX, float SiteY, const FBiomeContext& Ctx, uint32 SiteHash) const;
@@ -240,6 +240,26 @@ public:
* live edit) can never serve a stale strate index or passage shortlist. */
uint32 GetLayoutVersion() const { return PassagesVersion; }
/**
* Fingerprint of the immutable density inputs used by the generator.
*
* Returns zero when the manager has dynamic inputs that this compact cache key intentionally
* does not serialize (seasons, composer recipes, biome maps, or terrain-op assets). Zero is a
* fail-closed answer: callers must skip verdict reuse rather than risk an old all-air proof.
*/
uint64 GetGenerationParamsFingerprint() const;
/** Diagnostic-only switch for isolating the inter-strate support writer. */
void SetPassageSupportFloorWritesEnabledForDiagnostics(bool bEnabled)
{
bPassageSupportFloorWritesEnabled = bEnabled;
}
bool ArePassageSupportFloorWritesEnabledForDiagnostics() const
{
return bPassageSupportFloorWritesEnabled;
}
/**
* Get the strate definition for a specific chunk coordinate.
*
@@ -499,6 +519,9 @@ protected:
// VoxelSettings::InterStrateGapChunks during Initialize().
int32 InterStrateGapChunks = 0;
// Production is true. This diagnostic switch never changes the passage carve or air contract.
bool bPassageSupportFloorWritesEnabled = true;
// Per-passage tunnel shape now lives on each UVoxelStrateDefinition::PassageConfig
// (the upper strate of each boundary controls its own descent tunnels).
@@ -272,6 +272,8 @@ enum class EVoxelStrateTransition : uint8
LERPF(RoomFloorCutMax) \
LERPF(FloorReliefStrength) \
LERPF(FloorReliefFrequency) \
LERPF(RoomMouthRiseStrength) \
LERPF(RoomMouthRiseBlendVoxels) \
LERPF(OriginRoomRadius) \
SNAPF(OriginRoomMaxConnections) \
/* Cave morphology — tunnels */ \
@@ -559,6 +561,17 @@ struct VOXELFORGE_API FStrateGenerationParams
meta = (ClampMin = "0.001", EditCondition = "RoomFloorCutMin < 1.0"))
float FloorReliefFrequency = 0.015f;
// Optional local room-floor bench that rises toward a higher tunnel mouth. It is authored
// from the build-time tunnel descriptor, not discovered by a post-generation validator.
// Strength 0 keeps the legacy room/tunnel hand-off; 1 reaches the compatible mouth floor.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Cave Morphology|Rooms|Mouth Blend",
meta = (ClampMin = "0.0", ClampMax = "1.0"))
float RoomMouthRiseStrength = 0.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Cave Morphology|Rooms|Mouth Blend",
meta = (ClampMin = "8.0", ClampMax = "128.0"))
float RoomMouthRiseBlendVoxels = 8.0f;
// How much variety in room shapes (0 = all ellipsoids, 1 = full variety).
// At 0: every room is a smooth ellipsoid (uniform, organic caves).
// At 0.5: some rooms become angular (rounded boxes) or elongated (capsules).