Author SHA1 Message Date
Fr0zkaandClaude Opus 5.5 aa67bd31f5 wip(L6, side branch): screen-space far gate; no-op cutoff removed; cost within noise vs L4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ED33VnqepD4YY6gDAAA832
2026-10-19 21:10:08 +02:00
Fr0zkaandClaude Opus 5.5 b21a19d561 wip(L5, side branch): Linux offscreen captures + sampled far-LOD gate + no-op octave cutoff
Not for assembler/world: no octave qualifies under the cutoff's supremum criterion (world
unchanged), and the build is +4.6% slower than L4 with the flag off (reviewer interleaved W12).
Keeps the working EGL/GLES capture path and a gate whose metric is vertical height error, which
overstates screen error on steep slopes; its "exact far meshes exceed 1 px / 126 px pop" claims are
unconfirmed. See Linux5/REPORT.md "Orchestrator review".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ED33VnqepD4YY6gDAAA832
2026-10-19 20:39:41 +02:00
33 changed files with 322 additions and 4471 deletions

No files matched your search

-63
View File
@@ -570,15 +570,6 @@ ApplyModification` (BlueprintCallable) + `EditorCarveSphere/EditorFillSphere` (C
driven by `EditorBrush*` props.
### 8.10 Performance invariants (DON'T regress)
- **Far display mesh budget (L15)** (`WorldAssemblyEvaluatorVersion` 7): recipes may explicitly
declare `far_display_mesh` for LOD3+ display generation. With no declaration, the L14 mesh path
remains byte-for-byte selected. This setting must never alter LOD0–2, exact field queries,
collision, edits, or server state. A declared reduction must pass the same-LOD screen gate at the
closest displayed distance: at most 1.0 px geometry displacement, at most 1/255 normalized
shading/material delta, no worse swap pop, and no new holes, cracks, or floating pieces. Connector
wall repairs are safety geometry: retain every station/ray needed to close the existing gaps. Keep
the setting in the shared Core path so all recipe routes use the same declaration and evaluator.
- **Streaming** (`UpdateChunksAroundPosition`): rebuild/cull the desired set only when the player
crosses a level-0 chunk boundary, an anchor moves, or a rebuild is forced; use the stamped
desired map for the cull and idle via `bAllChunksLoaded`. On every rebuild, pending requests whose
@@ -741,15 +732,6 @@ driven by `EditorBrush*` props.
its default member initialization was never observable; removing that generated TLS leaf avoids
constructor work without changing a height or density. Integer queries still read the cached
payload, and fractional queries still use the same direct locals.
- **Core shared column cache (L7)**: `Heightfield2D` and FloatingIslands keep their `FLazy`
worker-local caches as the first tier. A world-owned, fixed-size four-way table is the second
tier, keyed by recipe and plan identity plus content hash, exact XY, and an optional exact
sub-domain identity (FloatingIslands uses the island stable ID). Hits read versioned atomic
entries without taking a lock; misses take only their set's spin lock, recheck, compute once, and
publish. The tables are bounded and die with the world after its tile work has drained. This
deliberately adds shared reads on column-cache hits while preserving the no-lock hot-path rule;
S14's purely worker-local cache remains the first lookup. Keep large worker-local storage behind
`FLazy`, and do not make cache values or keys depend on engine objects.
- **Sampler unknown-source audit**: the earlier plugin-side `FSurfaceColumn` constructor PCs no longer
occur after the trivial-payload change. The largest remaining LOD0 unknown cluster in the final
sampler raw CSV is `UnrealEditor-Core.dll + RVA 0xC080` (runtime PCs around
@@ -1815,51 +1797,6 @@ page was added: cross-worker repeats alone do not establish a net page-cache win
immutable-page lifetime rules would add ownership and memory cost. Round 18 changed no output or
recipe version. See [`Standalone/Research/WorldAssemblerM3/Round18/REPORT.md`](Standalone/Research/WorldAssemblerM3/Round18/REPORT.md).
### 8.35 Shared Core column cache — World Assembler L7
L7 measured 1.34 million repeated formula evaluations on the W12 L1 view before sharing: 83.6%
were another worker's XY, 4.0% were same-worker repeats after eviction, and 12.0% were halo/normal
repeats. The world-owned shared second tier cut measured formula executions by 60.9% and improved
median whole-view-ready time by 19.0%; moving 8 m and generating 144 entering tiles improved median
wall time by 36.1%. Peak RSS rose by about 66 MiB. The cache is a bounded exact-value table rather
than published pages; no scheduling affinity or page prefetch was needed to clear the measured
whole-view threshold.
The thread-local first tier remains because it avoids shared atomics for local hits. The shared
table has no lock on hits; only a miss takes a set-local spin lock. FloatingIslands' cache identity
includes its island stable ID because distinct anchors can request the same XY with different
column metrics. All W1/W12 L1 hashes, exact queries, and the seed-0 FloatingIslands fixture match
the pre-L7 binary with Clang FP contraction off and GCC defaults. See
[`Standalone/Research/WorldAssemblerM3/Linux7/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux7/REPORT.md).
### 8.36 Route-invariant Core density — World Assembler M3 L13
For an unedited Core world, tile density, mesh, payload, and topology are a function of the world
manifest/recipe, seed, and tile key. The reviewed manifest field is authoritative: SurfaceWorld uses
its `Heightfield2D`, while FloatingIslands uses its `FloatingIslandFieldV1`. `World::densityAt` and
tile generation read the same `FStandaloneShapeWorld` instance. A compiled analytic region page
retains bounded spatial bins for page ownership and routing, but `SetSharedDensitySource` binds it to
that base shape before publication; density, lattice, detail, classification, and solid queries
delegate to the shared evaluator. This keeps exact queries, collision occupancy signs, page tiles,
and base tiles on one field. Player edits remain explicit versioned overlays on that world state.
The route-binding change increments `WorldAssemblyEvaluatorVersion` from 5 to 6. Do not restore a
page-local legacy evaluator: it disagrees with the reviewed field. Uniform-block proof audits must
fill and check page tiles against the evaluator they actually sample. This is the shared Core path;
the Unreal adapter and its asynchronous MPSC/Epoch flow are unchanged. See
[`Standalone/Research/WorldAssemblerM3/Linux13/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux13/REPORT.md).
### 8.37 Screen-gated far display budget — World Assembler M3 L15
Evaluator version 7 adds the optional, serialized `far_display_mesh` recipe declaration for
display-only LOD3+ refinement and connector repair. A missing declaration selects the existing L14
path; exact queries, LOD0–2, collision, edits, and route binding stay on their existing shared Core
evaluators. The acceptance gate compares against today's same-LOD display mesh, reports geometry and
fixed-light/material shading deltas, checks every displayed tile, and measures each adjacent LOD
swap before and after. It rejects any new hole, crack, or floating piece, including lost connector
panels. No tested L15 candidate met the full budget, so no declaration is enabled by default. See
[`Standalone/Research/WorldAssemblerM3/Linux15/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux15/REPORT.md).
## 9. Multiplayer model (listen-server first, dedicated-friendly)
> **Status: transport is DESIGN ONLY — nothing is networked in-tree yet** (no `Replicated`/`HasAuthority`/RPCs; a
+1 -31
View File
@@ -158,8 +158,7 @@ remains `0`, and lateral regions remain gated off.
| `VoxelForge.Build.cs` | Deps: Core, CoreUObject, Engine, **GameplayTags**, **RealtimeMeshComponent**, `VoxelForgeCore`. `AVoxelWorld::bUseVoxelForgeCore` opts into the Core runtime route; it defaults off. |
| `../../VoxelForgeCore/VoxelForgeCore.Build.cs` | C++20 runtime module. Reads `Standalone/Core/core_sources.txt`, validates one include shim per canonical source, and fails UBT on missing, extra, or mismatched shims. No unity/PCH; private copied implementation stays under `vfcore::detail`. |
| `../../VoxelForgeCore/Private/Manifest/VFCore_*.cpp` | Eighteen one-source UBT shims that include canonical files under `Standalone/`; they do not copy Core implementation. The API-boundary row includes `Core/src/VoxelForgeCore.cpp` directly. |
| `../../Standalone/Core/include/VoxelForgeCore/ThreadLocalStorage.h` | `VoxelForgeCoreThreadLocal::FLazy<T>`: thread-local handle that heap-allocates a worker-private cache on first use. Large worker-local caches use it (HeightfieldColumnCache, IslandColumnCache, GFloorReliefCache, GRoomGraphCache, GSurfColCache, tunnel/diff caches). See ARCHITECTURE §8.10. |
| `../../Standalone/Core/include/VoxelForgeCore/SharedColumnCache.h` | Bounded four-way second-tier cache for exact per-column values. Readers use versioned atomic slots without a lock; misses use a set-local spin lock. World-owned lifetime, recipe/plan identity and content hashes, XY and optional sub-domain identity. SurfaceWorld and FloatingIslands share this mechanism; see ARCHITECTURE §8.35. |
| `../../Standalone/Core/include/VoxelForgeCore/ThreadLocalStorage.h` | `VoxelForgeCoreThreadLocal::FLazy<T>`: thread-local handle that heap-allocates a worker-private cache on first use. All large Core and legacy caches use it (HeightfieldColumnCache, IslandColumnCache, GFloorReliefCache, GRoomGraphCache, GSurfColCache, tunnel/diff caches). See ARCHITECTURE §8.10. |
| `../../Standalone/Core/src/CoreNamespacePreamble.h` | First include of every Core TU. Forces FP contraction off per compiler (Clang/MSVC/GCC pragmas; unknown compiler = `#error`) and defines `vfcore::fp_contract::selfTest`, which `World::compile` runs before building: a fused multiply-add (e.g. Clang `-ffp-contract=fast`) refuses world generation. The world depends on contraction (Linux2/Linux3 reports), so never remove either. |
| `../../VoxelForgeCore/Private/ModuleEntry/` | Unreal module entry and an isolated `CoreMinimal.h` shim for the actual engine header. |
| `../../Standalone/Core/include/VoxelForgeCore/VoxelForgeCore.h` | Standard-library-only public Core API. `VOXELFORGECORE_API` exports the API from the Unreal module and is empty for standalone builds. |
@@ -1118,35 +1117,6 @@ restores the S13 path for the negative control. Runtime CVar capture lives in
cold-path decision are in
[`Standalone/Research/WorldAssemblerM3/Round18/REPORT.md`](Standalone/Research/WorldAssemblerM3/Round18/REPORT.md).
### 3.21 LOD1 uniform-block proof — World Assembler M3 Linux9
`FStandaloneShapeWorld::IsNativeSurfaceBox` gates the step-2 proof to a single native SurfaceWorld
stratum. `ClassifyBoxDetailed(..., bUseNativeLatticeProof)` delegates to
`Heightfield2D::classifyLatticeBox`, whose ground/cap extrema cover the MC lattice and normal halo.
`UVoxelMarchingCubesMesher::GenerateMesh` sparsely fills only Mixed blocks and their sample halo;
Mixed/Unknown remains on the fill path. The headless `--audit-uniform-block-proofs` forces sample
verification, while `--profile-lod-work` reports per-LOD filled samples; both are off by default.
Implementation and evidence: [`Standalone/Research/WorldAssemblerM3/Linux9/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux9/REPORT.md).
### 3.22 Route-invariant Core density — World Assembler M3 Linux13
| Symbol | Canonical file | Role |
|---|---|---|
| `FStandaloneShapeWorld::SetSharedDensitySource`, `SharedDensitySource` | `Standalone/Core/src/ShapeWorldInternal.h`, bound before publication in `Standalone/Core/src/VoxelForgeCore.cpp` | Makes compiled analytic pages delegate field, lattice, detail, classification, and solid queries to the Core world's base shape; `WorldAssemblyEvaluatorVersion` is 7, including optional far display-mesh recipe settings. |
The base manifest field is authoritative for tile generation and exact queries. See ARCHITECTURE
§8.36 and [`Standalone/Research/WorldAssemblerM3/Linux13/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux13/REPORT.md).
### 3.23 Screen-gated far display mesh — World Assembler M3 L15
`ApplyFarDisplayMeshDeclaration` in `Standalone/Source/WorldAssemblyPrototype.h` parses the optional
`far_display_mesh` recipe block; `WorldAssemblyEvaluatorVersion` 7 serializes and hashes it.
`VoxelForgeCore::World::generateTile` consumes its display-only refinement and connector settings.
No declaration keeps the L14 output path. `Standalone/Source/LinuxScreenSpaceGate.h` compares every
desired LOD3–8 tile against today's same-LOD mesh and audits geometry, shading, swaps, and connector
coverage. The measured candidates and null result are in
[`Standalone/Research/WorldAssemblerM3/Linux15/REPORT.md`](Standalone/Research/WorldAssemblerM3/Linux15/REPORT.md).
## 4. The density pipeline (most-edited hot path)
### 4.1 `GetDensityWithParams` (TunnelNetwork) — VoxelGenerator.cpp:3749
+4 -40
View File
@@ -146,10 +146,6 @@ public:
FVoxelForgeCoreTaskScheduler Scheduler;
std::unordered_set<VoxelForgeCore::TileKey, VoxelForgeCore::TileKeyHash> RetainedTiles;
FCriticalSection RetainedTilesLock;
FCriticalSection ShapeReadinessLock;
std::unordered_set<VoxelForgeCore::TileKey, VoxelForgeCore::TileKeyHash> ShapeFreeTiles;
std::unordered_set<VoxelForgeCore::TileKey, VoxelForgeCore::TileKeyHash> ShapeDependentTiles;
std::atomic<bool> bSnapshotReady{false};
std::atomic<bool> bReady{false};
std::atomic<bool> bInitialFailed{false};
std::atomic<bool> bRegionCompileInFlight{false};
@@ -7693,7 +7689,6 @@ bool AVoxelWorld::InitializeVoxelForgeCoreWorld(FString& OutFailureReason)
Request.includeFarWorld = true;
VoxelForgeCoreState = State;
State->bSnapshotReady.store(true, std::memory_order_release);
ActiveTaskCount.fetch_add(1, std::memory_order_relaxed);
UE::Tasks::Launch(TEXT("VoxelForgeCoreCompile"),
[this, State, Request, InitialDesired, ActiveCoreClipRadius, ActiveCoreMaxClipLevel,
@@ -7713,17 +7708,10 @@ bool AVoxelWorld::InitializeVoxelForgeCoreWorld(FString& OutFailureReason)
std::string Error;
bool bCompiled = false;
bCompiled = State->World->compile(Request, State->Scheduler, Error);
if (bCompiled)
{
// The initial compile builds into local state and atomically publishes an immutable
// shape. Proven native-only tiles may hold shared WorldLock readers during this work;
// take the writer only for region retention after publication.
// La compilation initiale construit un etat local puis publie une forme immuable.
// Les tuiles natives validees gardent le verrou lecteur partage; le verrou ecrivain
// ne sert qu'a retenir les regions apres publication.
FWriteScopeLock Lock(State->WorldLock);
if (State->World)
bCompiled = State->World->compile(Request, State->Scheduler, Error);
if (bCompiled)
{
State->World->retainTileRegions(InitialDesired);
FScopeLock RetainedLock(&State->RetainedTilesLock);
@@ -13031,33 +13019,9 @@ void AVoxelWorld::LoadCoreTile(const FVoxelTileKey& Tile, EVoxelTileWorkPriority
return;
}
}
if (PendingTiles.Contains(Tile)) return;
if (PendingTiles.Contains(Tile) || !IsVoxelForgeCoreReady()) return;
const TSharedPtr<FVoxelForgeCoreRuntimeState, ESPMode::ThreadSafe> State = VoxelForgeCoreState;
if (!State.IsValid()||State->bInitialFailed.load(std::memory_order_acquire)
||State->bRegionCompileFailed.load(std::memory_order_acquire)
||State->bShuttingDown.load(std::memory_order_acquire))return;
const bool bShapeReady=State->bReady.load(std::memory_order_acquire);
if(!bShapeReady)
{
if(!State->bSnapshotReady.load(std::memory_order_acquire))return;
const VoxelForgeCore::TileKey CoreKey{
{Tile.Coord.X,Tile.Coord.Y,Tile.Coord.Z},Tile.Level};
bool bShapeFree=false;
{
FScopeLock ReadinessLock(&State->ShapeReadinessLock);
if(State->ShapeFreeTiles.contains(CoreKey))bShapeFree=true;
else if(State->ShapeDependentTiles.contains(CoreKey))return;
else
{
FReadScopeLock WorldReadLock(State->WorldLock);
if(!State->World)return;
bShapeFree=State->World->isTileShapeFree(CoreKey);
if(bShapeFree)State->ShapeFreeTiles.insert(CoreKey);
else State->ShapeDependentTiles.insert(CoreKey);
}
}
if(!bShapeFree)return;
}
if (!State.IsValid() || State->bRegionCompileFailed.load(std::memory_order_acquire)) return;
if (IsStreamingResultBacklogCapped())
{
StreamingResultBacklogCapStops.fetch_add(1, std::memory_order_relaxed);
@@ -1,183 +0,0 @@
#pragma once
#include <array>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include <thread>
#include <type_traits>
#include <utility>
namespace VoxelForgeCoreShared
{
// Exact input identity for a pure XY column value. LOD is deliberately not part of this key:
// the same recipe/plan column has the same bits at every sampling step.
struct FColumnCacheKey
{
std::uint64_t recipeIdentity = 0;
std::uint64_t recipeContentHash = 0;
std::uint64_t planIdentity = 0;
std::uint64_t planContentHash = 0;
std::int64_t xSubvoxels = 0;
std::int64_t ySubvoxels = 0;
// Optional exact sub-domain identity for recipes with several independent columns
// at the same XY (for example, a floating-island anchor).
std::uint64_t contextIdentity = 0;
std::array<std::uint64_t, 7> words() const noexcept
{
return {recipeIdentity, recipeContentHash, planIdentity, planContentHash,
static_cast<std::uint64_t>(xSubvoxels), static_cast<std::uint64_t>(ySubvoxels),
contextIdentity};
}
};
// A bounded, world-owned second-level cache. Existing thread-local caches stay first, so
// their ordinary hit path remains private and lock-free. Shared hits read atomic words; only
// a shared miss takes the set spin lock. Entries are four-way set associative, evict on
// collision, and carry pointer identities plus content hashes to reject stale reuse.
// Les caches TLS restent le premier niveau; seul un defaut partage prend le verrou du groupe.
template <typename TValue, std::size_t SetCount, std::size_t Ways = 4>
class TSharedColumnValueCache
{
static_assert(SetCount > 0 && (SetCount & (SetCount - 1)) == 0,
"column cache set count must be a power of two");
static_assert(Ways > 0 && Ways <= 16, "unsupported column cache associativity");
static_assert(std::is_trivially_copyable_v<TValue>,
"shared column values must be trivially copyable");
static constexpr std::size_t ValueWordCount = (sizeof(TValue) + 7) / 8;
using FKeyWords = std::array<std::uint64_t, 7>;
using FValueWords = std::array<std::uint64_t, ValueWordCount>;
struct FEntry
{
std::atomic<std::uint64_t> Version{0};
std::atomic<std::uint64_t> Tag{0};
std::array<std::atomic<std::uint64_t>, 7> Key{};
std::array<std::atomic<std::uint64_t>, ValueWordCount> Value{};
};
struct FSet
{
std::atomic_flag Writer = ATOMIC_FLAG_INIT;
std::uint8_t NextWay = 0;
std::array<FEntry, Ways> Entries{};
};
struct FSpinGuard
{
explicit FSpinGuard(std::atomic_flag& value) : Flag(value)
{
while (Flag.test_and_set(std::memory_order_acquire))
std::this_thread::yield();
}
~FSpinGuard() { Flag.clear(std::memory_order_release); }
std::atomic_flag& Flag;
};
public:
TSharedColumnValueCache() : Sets(std::make_unique<FSet[]>(SetCount)) {}
TSharedColumnValueCache(const TSharedColumnValueCache&) = delete;
TSharedColumnValueCache& operator=(const TSharedColumnValueCache&) = delete;
static TSharedColumnValueCache* setThreadActive(TSharedColumnValueCache* value) noexcept
{
TSharedColumnValueCache* previous = Active;
Active = value;
return previous;
}
static TSharedColumnValueCache* threadActive() noexcept { return Active; }
template <typename TFactory>
TValue getOrCompute(const FColumnCacheKey& key, TFactory&& factory,
bool& computed)
{
computed = false;
const FKeyWords keyWords = key.words();
const std::uint64_t tag = Hash(keyWords);
const std::size_t setIndex = static_cast<std::size_t>(tag) & (SetCount - 1);
FSet& set = Sets[setIndex];
TValue value{};
if (TryReadSet(set, keyWords, tag, value)) return value;
FSpinGuard lock(set.Writer);
if (TryReadSet(set, keyWords, tag, value)) return value;
value = std::forward<TFactory>(factory)();
computed = true;
FValueWords valueWords{};
std::memcpy(valueWords.data(), &value, sizeof(TValue));
std::size_t replacement = Ways;
for (std::size_t way = 0; way < Ways; ++way)
if (set.Entries[way].Version.load(std::memory_order_seq_cst) == 0)
{ replacement = way; break; }
if (replacement == Ways)
{
replacement = set.NextWay;
set.NextWay = static_cast<std::uint8_t>((set.NextWay + 1) % Ways);
}
FEntry& entry = set.Entries[replacement];
std::uint64_t version = entry.Version.load(std::memory_order_seq_cst);
if (version & 1u) ++version;
entry.Version.store(version + 1, std::memory_order_seq_cst);
for (std::size_t word = 0; word < keyWords.size(); ++word)
entry.Key[word].store(keyWords[word], std::memory_order_seq_cst);
for (std::size_t word = 0; word < valueWords.size(); ++word)
entry.Value[word].store(valueWords[word], std::memory_order_seq_cst);
entry.Tag.store(tag, std::memory_order_seq_cst);
entry.Version.store(version + 2, std::memory_order_seq_cst);
return value;
}
private:
static std::uint64_t Hash(const FKeyWords& words) noexcept
{
std::uint64_t hash = 0x9E3779B185EBCA87ull;
for (const std::uint64_t word : words)
{
hash ^= word + 0x9E3779B97F4A7C15ull + (hash << 6) + (hash >> 2);
hash ^= hash >> 30;
hash *= 0xBF58476D1CE4E5B9ull;
hash ^= hash >> 27;
hash *= 0x94D049BB133111EBull;
hash ^= hash >> 31;
}
return hash == 0 ? 1 : hash;
}
static bool TryRead(const FEntry& entry, const FKeyWords& keyWords,
std::uint64_t tag, TValue& out)
{
const std::uint64_t before = entry.Version.load(std::memory_order_seq_cst);
if (before == 0 || (before & 1u)
|| entry.Tag.load(std::memory_order_seq_cst) != tag) return false;
FKeyWords foundKey{};
for (std::size_t word = 0; word < foundKey.size(); ++word)
foundKey[word] = entry.Key[word].load(std::memory_order_seq_cst);
if (foundKey != keyWords) return false;
FValueWords foundValue{};
for (std::size_t word = 0; word < foundValue.size(); ++word)
foundValue[word] = entry.Value[word].load(std::memory_order_seq_cst);
const std::uint64_t after = entry.Version.load(std::memory_order_seq_cst);
if (before != after || (after & 1u)) return false;
std::memcpy(&out, foundValue.data(), sizeof(TValue));
return true;
}
static bool TryReadSet(const FSet& set, const FKeyWords& keyWords,
std::uint64_t tag, TValue& out)
{
for (const FEntry& entry : set.Entries)
if (TryRead(entry, keyWords, tag, out)) return true;
return false;
}
std::unique_ptr<FSet[]> Sets;
inline static thread_local TSharedColumnValueCache* Active = nullptr;
};
}
@@ -110,19 +110,9 @@ namespace VoxelForgeCore
enum class TileClass : std::uint8_t { allSolid, allAir, mixed, unknown };
struct HeightfieldColumnEvaluation
{
std::int64_t x = 0, y = 0;
std::uint64_t sequence = 0;
bool outsideTileFootprint = false;
};
struct TileGenerationStats
{
TileClass tileClass = TileClass::unknown;
bool nativeOnlyRoute = false;
bool analyticRegionPageRoute = false;
bool nativeSurfaceTile = false;
std::uint64_t solidBoxes = 0;
std::uint64_t airBoxes = 0;
std::uint64_t mixedBoxes = 0;
@@ -134,13 +124,6 @@ namespace VoxelForgeCore
std::uint64_t columnCacheHits = 0;
std::uint64_t columnCacheMisses = 0;
std::uint64_t columnCacheConflictMisses = 0;
std::uint64_t sharedColumnCacheHits = 0;
std::uint64_t columnEvaluations = 0;
std::uint64_t uniformBlockProofsChecked = 0;
std::uint64_t uniformBlockProofSamplesChecked = 0;
std::uint64_t uniformBlockProofFallbackBlocks = 0;
std::uint64_t uniformBlockProofUnknownBlocks = 0;
std::uint64_t uniformBlockProofViolations = 0;
double classificationMilliseconds = 0.0;
double columnComputeMilliseconds = 0.0;
double columnEvaluationExclusiveMilliseconds = 0.0;
@@ -170,26 +153,6 @@ namespace VoxelForgeCore
double farHorizonMilliseconds = 0.0;
std::uint64_t farStratumFieldCalls = 0;
std::uint64_t farConnectorFieldCalls = 0;
std::uint64_t farStratumColumnPointCalls = 0;
std::uint64_t farStratumColumnCacheHits = 0;
std::uint64_t farStratumColumnCacheMisses = 0;
std::uint64_t farStratumColumnConflictMisses = 0;
std::uint64_t farStratumSharedColumnCacheHits = 0;
std::uint64_t farStratumColumnEvaluations = 0;
std::uint64_t farConnectorColumnPointCalls = 0;
std::uint64_t farConnectorColumnCacheHits = 0;
std::uint64_t farConnectorColumnCacheMisses = 0;
std::uint64_t farConnectorColumnConflictMisses = 0;
std::uint64_t farConnectorSharedColumnCacheHits = 0;
std::uint64_t farConnectorColumnEvaluations = 0;
double farStratumColumnComputeMilliseconds = 0.0;
double farConnectorColumnComputeMilliseconds = 0.0;
// Opt-in quality audit at the L14 route-wall stations and four axial rays.
std::uint64_t farConnectorAuditRays = 0;
std::uint64_t farConnectorAuditHoles = 0;
std::uint64_t farConnectorAuditFloating = 0;
std::vector<std::uint64_t> farConnectorAuditHoleIds;
std::vector<std::uint64_t> farConnectorAuditFloatingIds;
std::uint64_t farShellTrianglesAdded = 0;
std::uint64_t horizonGroundTriangles = 0;
std::uint64_t horizonGroundTrianglesRemoved = 0;
@@ -205,7 +168,7 @@ namespace VoxelForgeCore
bool capRefined = false;
std::uint64_t columnEvaluationWorkerHash = 0;
bool columnCoordinateCaptureComplete = true;
std::vector<HeightfieldColumnEvaluation> evaluatedColumnCoordinates;
std::vector<std::array<std::int64_t, 2>> evaluatedColumnCoordinates;
};
struct TileMesh
@@ -255,9 +218,7 @@ namespace VoxelForgeCore
// L'assembleur v1 encode coordonnees et scalaires en 1/256 de voxel, independamment des tuiles.
inline constexpr std::int64_t WorldAssemblySubvoxelsPerVoxel = 256;
inline constexpr std::uint32_t WorldAssemblySchemaVersion = 1;
// Version 6 binds every compiled tile page to the world's base density evaluator.
// Version 7 adds optional, display-only far-mesh quality declarations.
inline constexpr std::uint32_t WorldAssemblyEvaluatorVersion = 7;
inline constexpr std::uint32_t WorldAssemblyEvaluatorVersion = 5;
enum class FieldChannel : std::uint32_t
{
@@ -319,17 +280,6 @@ namespace VoxelForgeCore
std::int64_t biomeClimateReliefWavelengthSubvoxels = 256 * 3333;
std::int64_t biomeClimateMoistureWavelengthSubvoxels = 256 * 2500;
std::int64_t biomeClimateReliefContrastQ16 = 2ll << 16;
// Optional display-only mesh budget. Zero leaves the L14 far-mesh path unchanged.
// Budget is in 1/1000 pixel at the closest display distance.
std::uint32_t farDisplayGeometryBudgetMillipixels = 0;
// Scale/mask change only display refinement density at the selected LODs.
// A zero scale or mask leaves the current refinement grids intact.
std::uint32_t farRefinementGridScale = 0;
std::uint32_t farRefinementLodMask = 0;
// Connector scale 0 and ray mask 0 preserve the current station/ray pattern.
std::uint32_t farConnectorStationScale = 0;
std::uint32_t farConnectorRayMask = 0;
bool farConnectorReuseStationRadii = false;
std::vector<WorldAssemblyBiomeProfileV1> biomes;
std::uint64_t contentHash = 0;
};
@@ -701,12 +651,10 @@ namespace VoxelForgeCore
std::uint64_t columnHits = 0;
std::uint64_t columnMisses = 0;
std::uint64_t columnConflictMisses = 0;
std::uint64_t sharedColumnHits = 0;
std::uint64_t columnEvaluations = 0;
double columnComputeMilliseconds = 0.0;
bool captureCoordinates = false;
bool coordinateCaptureComplete = true;
std::vector<HeightfieldColumnEvaluation> evaluatedCoordinates;
std::vector<std::array<std::int64_t, 2>> evaluatedCoordinates;
};
struct FieldInfluenceBounds
@@ -757,9 +705,6 @@ namespace VoxelForgeCore
std::int64_t maximumZSubvoxels, std::int32_t stepVoxels) const noexcept;
static void resetThreadColumnCacheStats(bool captureCoordinates = false,
bool clearCache = false, std::uint32_t octaveDrop = 0) noexcept;
static void setThreadColumnCaptureBounds(std::int64_t minimumXSubvoxels,
std::int64_t minimumYSubvoxels, std::int64_t maximumXSubvoxels,
std::int64_t maximumYSubvoxels) noexcept;
static void setThreadColumnOctaveDrop(std::uint32_t octaveDrop) noexcept;
static std::uint32_t threadColumnOctaveDrop() noexcept;
static void setThreadColumnInterpolationStrideSubvoxels(std::int64_t stride) noexcept;
@@ -1083,9 +1028,6 @@ namespace VoxelForgeCore
std::int32_t bandMaxZVoxel = 2147483647;
bool hashDensity = false;
bool captureDensitySamples = false;
// Diagnostic only; materialize the full density lattice even when block proofs
// establish that the tile has no surface.
bool forceFullDensityCapture = false;
bool skipUvAndColors = false;
bool skipUv = false;
bool skipColors = false;
@@ -1096,13 +1038,9 @@ namespace VoxelForgeCore
// Opt-in diagnostic only; records XY columns evaluated by this LOD8 tile.
// Diagnostic seulement; enregistre les colonnes XY evaluees par cette tuile LOD8.
bool captureColumnCoordinates = false;
bool useSharedColumnCache = true;
// Separate cold pass only; samples the MC inner stages without changing output.
// Passe froide separee seulement; mesure les etapes internes MC sans changer la sortie.
bool profileMesherStages = false;
// Diagnostic only; fills and checks every lattice sample in blocks certified uniform.
// Diagnostic seulement; evalue et verifie tous les echantillons des blocs uniformes.
bool auditUniformBlockProofs = false;
// Negative control for the shared XY-column cache; 1 restores the old direct-map indexing.
// Controle negatif du cache XY partage; 1 restaure l'ancien indexage direct.
bool legacyDirectMappedColumnCache = false;
@@ -1117,25 +1055,10 @@ namespace VoxelForgeCore
// Incremente quand le plafond lointain change. Les hashes LOD4-8 incluent cette version;
// densite et hashes LOD0-3 restent inchanges.
std::uint32_t farHorizonVersion = 3;
// Research-only override of the recipe declaration; used by same-LOD controls.
bool overrideFarDisplayMesh = false;
std::uint32_t farDisplayGeometryBudgetMillipixels = 0;
std::uint32_t farRefinementGridScale = 0;
std::uint32_t farRefinementLodMask = 0;
std::uint32_t farConnectorStationScale = 0;
std::uint32_t farConnectorRayMask = 0;
bool farConnectorReuseStationRadii = false;
bool diagnosticRemoveFarConnectorPanels = false;
bool diagnosticAuditFarConnectorCoverage = false;
// Linux research controls for reproducing L5 negative controls. Defaults preserve output.
std::uint32_t diagnosticGlobalOctaveDrop = 0;
std::uint32_t diagnosticCellStride = 1;
std::uint32_t diagnosticColumnInterpolationStride = 1;
// Diagnostic negative control only: deliberately bypass the native-only readiness
// proof and require the sampling guard to reject any shape-dependent tile.
// Controle negatif diagnostique: contourne volontairement la preuve native seule
// et exige que la garde rejette toute tuile dependante de la forme.
bool diagnosticForceNativeOnly = false;
};
class VFCORE_API World
@@ -1153,26 +1076,16 @@ namespace VoxelForgeCore
// True only when a fine tile needs a separately compiled region before generation.
// Vrai seulement si une tuile fine doit attendre la compilation d'une region dediee.
bool needsTileRegion(const TileKey& tile) const;
// Conservative precompile proof: true only for a tile that can sample the native
// SurfaceWorld heightfield throughout its padded mesh domain without compiled shape data.
// Preuve prudente avant compilation: vrai seulement si toute la zone maillee avec marge
// utilise le champ SurfaceWorld natif, sans lire la forme compilee.
bool isTileShapeFree(const TileKey& tile) const;
// Compile missing detail regions for entering fine tiles. Generated tile keys map to
// bounded, world-aligned pages. The default analyticOnly path builds each page's
// primitives/bins and evaluates density on demand without rasterizing unused lattice
// volumes. Set false to use fixed absolute packed pages. The optional count is newly
// covered tile keys; regions stay resident until retainTileRegions.
// Compile les regions de detail manquantes. Les tuiles entrantes sont regroupees en pages
// bornees alignees au monde; analyticOnly construit les primitives et bins sans rasteriser
// de volume inutilise. Sinon, utilise les pages compactes fixes; le compteur indique les
// nouvelles tuiles couvertes et retainTileRegions libere les anciennes regions.
// shared world-coordinate regions. The default analyticOnly path coalesces each entering
// LOD slab, builds its primitives/bins, and evaluates density on demand without
// rasterizing unused lattice volumes. Set false to use fixed absolute packed pages. The
// optional count is newly covered tile keys; regions stay resident until retainTileRegions.
bool compileTileRegion(std::span<const TileKey> tiles, std::uint32_t workerLimit,
const JobScheduler& scheduler, std::string& error,
std::size_t* outCompiledTiles = nullptr,
TileRegionCompileStats* outStats = nullptr,
bool analyticOnly = true,
bool diagnosticIncludeBaseCoveredTiles = false);
bool analyticOnly = true);
void retainTileRegions(std::span<const TileKey> desiredTiles);
void buildFarWorld();
bool isCompiled() const noexcept;
@@ -55,7 +55,6 @@
#include "Json.h"
#include "VoxelForgeCore/VoxelForgeCore.h"
#include "VoxelForgeCore/ThreadLocalStorage.h"
#include "VoxelForgeCore/SharedColumnCache.h"
// Keep Core's expression-level FMA behavior fixed regardless of the toolchain setting.
// Clang's "fast" mode ignores the pragma, so Core's runtime self-test rejects that build.
+4 -120
View File
@@ -242,8 +242,7 @@ inline bool FindFarConnectorRadiusNearNominal(const FStandaloneShapeWorld& Shape
}
inline void AppendFarConnectorShells(const FStandaloneShapeWorld& Shape,const FVoxelTileKey& Key,
int32 Step,int32 Cells,FVoxelMeshData& Mesh,int32 StationScale=1,
uint32 RayMask=0x0fu,bool bReuseStationRadii=false)
int32 Step,int32 Cells,FVoxelMeshData& Mesh)
{
if(Key.Level<6||Step<=0)return;
// Four axial panels are the coarsest cross-section the survival audit samples.
@@ -314,8 +313,7 @@ inline void AppendFarConnectorShells(const FStandaloneShapeWorld& Shape,const FV
if(!bIntersects||TMax-TMin<1.0e-6)continue;
// LOD7 and LOD8 share a 256-voxel connector station grid; near LOD keeps 128-voxel checks.
// LOD7 et LOD8 partagent des stations aux 256 voxels; pres du joueur, garder les pas de 128.
const double ConnectorStationStep=(Key.Level>=7?std::max(256.0,static_cast<double>(Step)):128.0)
*std::max(1,StationScale);
const double ConnectorStationStep=Key.Level>=7?std::max(256.0,static_cast<double>(Step)):128.0;
const int32 AxialSampleCount=std::max(1,static_cast<int32>(std::ceil(Length/ConnectorStationStep)));
std::vector<uint8> MissingMasks(static_cast<size_t>(AxialSampleCount),0);
std::vector<std::array<double,4>> SourceRadii(static_cast<size_t>(AxialSampleCount));
@@ -334,7 +332,6 @@ inline void AppendFarConnectorShells(const FStandaloneShapeWorld& Shape,const FV
const double DetectionTolerance=MatchTolerance*0.98;
for(int32 DirectionIndex=0;DirectionIndex<4;++DirectionIndex)
{
if((RayMask&(1u<<DirectionIndex))==0)continue;
const FVector& Direction=RadialDirections[DirectionIndex];
if(!ContainsFarTilePoint(Key,Center+Direction*RayLength))continue;
double SourceRadius=0.0,SourceUncertainty=0.0;
@@ -391,13 +388,7 @@ inline void AppendFarConnectorShells(const FStandaloneShapeWorld& Shape,const FV
{Ring.Radii[DirectionIndex]=Connector.Radius;continue;}
double Radius=Connector.Radius;
double RadiusUncertainty=0.0;
const int32 NearestStation=std::clamp(static_cast<int32>(std::lround(
T*AxialSampleCount-0.5)),0,AxialSampleCount-1);
const double ReusedRadius=bReuseStationRadii
?SourceRadii[static_cast<size_t>(NearestStation)][DirectionIndex]:0.0;
if(ReusedRadius>0.0)
Radius=ReusedRadius;
else if(!FindFarConnectorRadiusNearNominal(Shape,Center,
if(!FindFarConnectorRadiusNearNominal(Shape,Center,
RadialDirections[DirectionIndex],Connector.Radius,Radius,RadiusUncertainty)
&&!FindFarConnectorSurfaceRadius(Shape,Center,RadialDirections[DirectionIndex],
Connector.Radius,Radius))
@@ -441,8 +432,7 @@ inline void AppendFarConnectorShells(const FStandaloneShapeWorld& Shape,const FV
}
}
std::vector<FRing> Rings;
const double MaxRingStep=(Key.Level>=7?std::max(256.0,static_cast<double>(Step)):128.0)
*std::max(1,StationScale);
const double MaxRingStep=Key.Level>=7?std::max(256.0,static_cast<double>(Step)):128.0;
double CurrentT=RunMin;
Rings.push_back(MakeRing(CurrentT,RunStart,RunEnd,RunRadiusMask));
while(CurrentT<RunMax-1.0e-7)
@@ -824,112 +814,6 @@ inline void AppendFarConnectorShells(const FStandaloneShapeWorld& Shape,const FV
Mesh.NumSurfaceVertices=OldSurfaceVertices+AddedVertices;
}
struct FFarConnectorCoverageAudit
{
std::uint64_t Rays=0;
std::uint64_t Holes=0;
std::uint64_t Floating=0;
std::vector<std::uint64_t> HoleIds;
std::vector<std::uint64_t> FloatingIds;
};
inline std::uint64_t FarConnectorAuditRayId(const FVoxelTileKey& Key,uint32 Connector,
int32 Station,int32 Direction)
{
std::uint64_t Hash=14695981039346656037ull;
const auto Add=[&](std::uint64_t Value,int Bytes)
{
for(int Byte=0;Byte<Bytes;++Byte)
{Hash^=static_cast<uint8>(Value>>(Byte*8));Hash*=1099511628211ull;}
};
Add(static_cast<uint32>(Key.Coord.X),4);Add(static_cast<uint32>(Key.Coord.Y),4);
Add(static_cast<uint32>(Key.Coord.Z),4);Add(static_cast<uint32>(Key.Level),4);
Add(Connector,4);Add(static_cast<uint32>(Station),4);Add(static_cast<uint32>(Direction),4);
return Hash?Hash:1;
}
inline FFarConnectorCoverageAudit AuditFarConnectorCoverage(const FStandaloneShapeWorld& Shape,
const FVoxelTileKey& Key,int32 Step,int32 Cells,const FVoxelMeshData& Mesh)
{
FFarConnectorCoverageAudit Audit;
if(Key.Level<6||Step<=0||Mesh.Triangles.Num()<3)return Audit;
const FIntVector TileOrigin=Key.OriginVoxels();
const int32 TileExtent=Key.ExtentVoxels();
FFarMeshSegmentIndex MeshIndex(Mesh,TileOrigin,TileExtent,Cells,Step);
const auto& Connectors=Shape.GetFarConnectorSegments();
std::vector<uint32> CandidateIndices;
Shape.FindFarConnectorCandidates(
FIntVector(TileOrigin.X-64,TileOrigin.Y-64,TileOrigin.Z-64),
FIntVector(TileOrigin.X+TileExtent+64,TileOrigin.Y+TileExtent+64,TileOrigin.Z+TileExtent+64),
CandidateIndices);
for(const uint32 ConnectorIndex:CandidateIndices)
{
if(ConnectorIndex>=Connectors.size())continue;
const auto& Connector=Connectors[ConnectorIndex];
const FVector Delta=Connector.End-Connector.Start;
const double Length=std::sqrt(Delta.X*Delta.X+Delta.Y*Delta.Y+Delta.Z*Delta.Z);
if(Length<=1.0e-6)continue;
const FVector Axis=Delta/Length;
FVector U=FVector::CrossProduct(Axis,FVector::UpVector);
if(U.SizeSquared()<0.01)U=FVector::CrossProduct(Axis,FVector::RightVector);
U.Normalize();
FVector V=FVector::CrossProduct(Axis,U);V.Normalize();
const FVector Directions[4]={U,U*-1.0,V,V*-1.0};
const double Deltas[3]={Delta.X,Delta.Y,Delta.Z};
const double Starts[3]={Connector.Start.X,Connector.Start.Y,Connector.Start.Z};
const double Low[3]={TileOrigin.X-Connector.Radius,TileOrigin.Y-Connector.Radius,
TileOrigin.Z-Connector.Radius};
const double High[3]={TileOrigin.X+TileExtent+Connector.Radius,
TileOrigin.Y+TileExtent+Connector.Radius,TileOrigin.Z+TileExtent+Connector.Radius};
double TMin=0.0,TMax=1.0;
bool bIntersects=true;
for(int32 AxisIndex=0;AxisIndex<3;++AxisIndex)
{
if(std::abs(Deltas[AxisIndex])<1.0e-9)
{if(Starts[AxisIndex]<Low[AxisIndex]||Starts[AxisIndex]>High[AxisIndex])bIntersects=false;continue;}
double A=(Low[AxisIndex]-Starts[AxisIndex])/Deltas[AxisIndex];
double B=(High[AxisIndex]-Starts[AxisIndex])/Deltas[AxisIndex];
if(A>B)std::swap(A,B);
TMin=std::max(TMin,A);TMax=std::min(TMax,B);
if(TMin>TMax){bIntersects=false;break;}
}
if(!bIntersects||TMax-TMin<1.0e-6)continue;
const double StationStep=Key.Level>=7?std::max(256.0,static_cast<double>(Step)):128.0;
const int32 StationCount=std::max(1,static_cast<int32>(std::ceil(Length/StationStep)));
const double RayLength=Connector.Radius*2.0+32.0;
const double MatchTolerance=std::max(8.0,static_cast<double>(Connector.Radius)*0.35);
const double DetectionTolerance=MatchTolerance*0.98;
const double SourceRadiusBand=std::max(16.0,static_cast<double>(Connector.Radius)*0.75);
for(int32 Station=0;Station<StationCount;++Station)
{
const FVector Center=Connector.Start+Delta*((static_cast<double>(Station)+0.5)/StationCount);
if(!ContainsFarTilePoint(Key,Center))continue;
for(int32 DirectionIndex=0;DirectionIndex<4;++DirectionIndex)
{
if(!ContainsFarTilePoint(Key,Center+Directions[DirectionIndex]*RayLength))continue;
double SourceRadius=0.0,Uncertainty=0.0;
const bool bSource=FindFarConnectorRadiusNearNominal(Shape,Center,
Directions[DirectionIndex],Connector.Radius,SourceRadius,Uncertainty)
||FindFarConnectorSurfaceRadius(Shape,Center,Directions[DirectionIndex],
Connector.Radius,SourceRadius);
const double MeshDifference=MeshIndex.NearestHitDifference(Center,
Directions[DirectionIndex],RayLength,bSource?SourceRadius:Connector.Radius);
if(bSource&&std::abs(SourceRadius-Connector.Radius)<=SourceRadiusBand)
{
++Audit.Rays;
if(!std::isfinite(MeshDifference)||MeshDifference>DetectionTolerance)
Audit.HoleIds.push_back(FarConnectorAuditRayId(Key,ConnectorIndex,Station,DirectionIndex));
}
else if(std::isfinite(MeshDifference)&&MeshDifference<=DetectionTolerance)
Audit.FloatingIds.push_back(FarConnectorAuditRayId(Key,ConnectorIndex,Station,DirectionIndex));
}
}
}
Audit.Holes=Audit.HoleIds.size();
Audit.Floating=Audit.FloatingIds.size();
return Audit;
}
struct FFarMeshColumnIndex
{
FFarMeshColumnIndex(const FVoxelMeshData& InMesh,const FIntVector& InOrigin,int32 InExtent,
+34 -67
View File
@@ -425,9 +425,6 @@ namespace floating_island_detail
struct FIslandColumnCacheEntry
{
bool bValid=false;
const FloatingIslandRecipeV1* RecipeIdentity=nullptr;
const FloatingIslandPlanV1* PlanIdentity=nullptr;
std::uint64_t RecipeContentHash=0,PlanContentHash=0;
std::uint32_t Seed=0;
std::uint64_t StableId=0;
std::int64_t SampleX=0,SampleY=0,CenterX=0,CenterY=0,TopZ=0,Radius=0,TopHalf=0;
@@ -435,12 +432,9 @@ namespace floating_island_detail
double DeltaX=0.0,DeltaY=0.0,Radial=0.0,Angle=0.0,LobePhase=0.0,TopSurface=0.0;
};
using FSharedIslandColumnCache =
VoxelForgeCoreShared::TSharedColumnValueCache<FIslandColumnCacheEntry,16384,4>;
inline const FIslandColumnCacheEntry& IslandColumnCache(
const FloatingIslandRecipeV1& recipe,const FloatingIslandPlanV1& plan,
const FloatingIslandAnchorV1& island,double x,double y)
const FloatingIslandRecipeV1& recipe,const FloatingIslandAnchorV1& island,
double x,double y)
{
// Density samples arrive on integer Core lattice columns; reuse the exact column metrics
// across Z samples without changing the field value or touching shared world state.
@@ -456,10 +450,7 @@ namespace floating_island_detail
std::uint64_t IndexKey=island.stableId
^(static_cast<std::uint64_t>(SampleX)*0x9e3779b97f4a7c15ull)
^(static_cast<std::uint64_t>(SampleY)*0xc2b2ae3d27d4eb4full)
^(static_cast<std::uint64_t>(recipe.seed)<<23)
^recipe.contentHash^std::rotl(plan.contentHash,17)
^static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(&recipe))
^std::rotl(static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(&plan)),31);
^(static_cast<std::uint64_t>(recipe.seed)<<23);
IndexKey^=IndexKey>>33;
IndexKey*=0xff51afd7ed558ccdull;
IndexKey^=IndexKey>>33;
@@ -468,9 +459,7 @@ namespace floating_island_detail
for(std::size_t Way=0;Way<Ways;++Way)
{
FIslandColumnCacheEntry& Entry=cache[Base+Way];
const bool bKeyMatches=Entry.bValid&&Entry.RecipeIdentity==&recipe
&&Entry.PlanIdentity==&plan&&Entry.RecipeContentHash==recipe.contentHash
&&Entry.PlanContentHash==plan.contentHash&&Entry.Seed==recipe.seed
const bool bKeyMatches=Entry.bValid&&Entry.Seed==recipe.seed
&&Entry.StableId==island.stableId
&&Entry.SampleX==SampleX&&Entry.SampleY==SampleY
&&Entry.CenterX==island.centerSubvoxels[0]
@@ -484,53 +473,32 @@ namespace floating_island_detail
if(!Entry.bValid)Replacement=&Entry;
}
const auto build=[&]()
{
FIslandColumnCacheEntry Entry;
Entry.bValid=true;
Entry.RecipeIdentity=&recipe;
Entry.PlanIdentity=&plan;
Entry.RecipeContentHash=recipe.contentHash;
Entry.PlanContentHash=plan.contentHash;
Entry.Seed=recipe.seed;
Entry.StableId=island.stableId;
Entry.SampleX=SampleX;
Entry.SampleY=SampleY;
Entry.CenterX=island.centerSubvoxels[0];
Entry.CenterY=island.centerSubvoxels[1];
Entry.TopZ=island.topZSubvoxels;
Entry.Radius=island.radiusSubvoxels;
Entry.TopHalf=island.topHalfSubvoxels;
Entry.TopFlattenQ16=recipe.topFlattenQ16;
Entry.ContourWarp=recipe.contourWarpSubvoxels;
Entry.DeltaX=x-static_cast<double>(island.centerSubvoxels[0]);
Entry.DeltaY=y-static_cast<double>(island.centerSubvoxels[1]);
Entry.Radial=std::hypot(Entry.DeltaX,Entry.DeltaY);
Entry.Angle=std::atan2(Entry.DeltaY,Entry.DeltaX);
Entry.LobePhase=LobePhase(recipe,island);
const double EffectiveRadius=std::max(1.0,static_cast<double>(island.radiusSubvoxels)
+LobeOffsetWithPhase(recipe,Entry.Angle,static_cast<double>(island.topZSubvoxels),
Entry.LobePhase));
const double Edge=std::clamp(Entry.Radial/EffectiveRadius,0.0,1.0);
const double Drop=(1.0-Q16ToDouble(recipe.topFlattenQ16))
*static_cast<double>(island.topHalfSubvoxels)*2.0*Edge*Edge;
Entry.TopSurface=static_cast<double>(island.topZSubvoxels)-Drop;
return Entry;
};
FIslandColumnCacheEntry Entry{};
if(auto* shared=FSharedIslandColumnCache::threadActive())
{
const VoxelForgeCoreShared::FColumnCacheKey key{
static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(&recipe)),
recipe.contentHash,
static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(&plan)),
plan.contentHash,SampleX,SampleY,island.stableId};
bool computed=false;
Entry=shared->getOrCompute(key,build,computed);
}
else Entry=build();
*Replacement=Entry;
return *Replacement;
FIslandColumnCacheEntry& Entry=*Replacement;
Entry.bValid=true;
Entry.Seed=recipe.seed;
Entry.StableId=island.stableId;
Entry.SampleX=SampleX;
Entry.SampleY=SampleY;
Entry.CenterX=island.centerSubvoxels[0];
Entry.CenterY=island.centerSubvoxels[1];
Entry.TopZ=island.topZSubvoxels;
Entry.Radius=island.radiusSubvoxels;
Entry.TopHalf=island.topHalfSubvoxels;
Entry.TopFlattenQ16=recipe.topFlattenQ16;
Entry.ContourWarp=recipe.contourWarpSubvoxels;
Entry.DeltaX=x-static_cast<double>(island.centerSubvoxels[0]);
Entry.DeltaY=y-static_cast<double>(island.centerSubvoxels[1]);
Entry.Radial=std::hypot(Entry.DeltaX,Entry.DeltaY);
Entry.Angle=std::atan2(Entry.DeltaY,Entry.DeltaX);
Entry.LobePhase=LobePhase(recipe,island);
const double EffectiveRadius=std::max(1.0,static_cast<double>(island.radiusSubvoxels)
+LobeOffsetWithPhase(recipe,Entry.Angle,static_cast<double>(island.topZSubvoxels),
Entry.LobePhase));
const double Edge=std::clamp(Entry.Radial/EffectiveRadius,0.0,1.0);
const double Drop=(1.0-Q16ToDouble(recipe.topFlattenQ16))
*static_cast<double>(island.topHalfSubvoxels)*2.0*Edge*Edge;
Entry.TopSurface=static_cast<double>(island.topZSubvoxels)-Drop;
return Entry;
}
inline std::int64_t ScaledQ16(std::int64_t value, std::int64_t scaleQ16)
@@ -673,7 +641,6 @@ namespace floating_island_detail
}
inline double IslandDensity(const FloatingIslandRecipeV1& recipe,
const FloatingIslandPlanV1& plan,
const FloatingIslandAnchorV1& island,
double x, double y, double z)
{
@@ -698,7 +665,7 @@ namespace floating_island_detail
std::max({z - top, radial - envelope, bottomZ - z}), x, y, z);
}
const FIslandColumnCacheEntry& Column=IslandColumnCache(recipe,plan,island,x,y);
const FIslandColumnCacheEntry& Column=IslandColumnCache(recipe,island,x,y);
const double dx=Column.DeltaX;
const double dy=Column.DeltaY;
const double radial=Column.Radial;
@@ -766,7 +733,7 @@ namespace floating_island_detail
double result = static_cast<double>(MaxDensity);
for (const auto& island : plan.islands)
{
double group = IslandDensity(recipe, plan, island,
double group = IslandDensity(recipe, island,
static_cast<double>(x), static_cast<double>(y), static_cast<double>(z));
for (const auto& edge : plan.clusterEdges)
{
@@ -802,7 +769,7 @@ namespace floating_island_detail
const auto evaluateLocalGroup = [&](std::size_t islandIndex)
{
const auto& island = plan.islands[islandIndex];
double group = IslandDensity(recipe, plan, island,
double group = IslandDensity(recipe, island,
static_cast<double>(x), static_cast<double>(y), static_cast<double>(z));
for (const std::uint32_t edgeIndex : featureIndices)
{
@@ -828,7 +795,7 @@ namespace floating_island_detail
const auto evaluateDistantGroup = [&](std::size_t islandIndex)
{
const auto& island = plan.islands[islandIndex];
double group = IslandDensity(recipe, plan, island,
double group = IslandDensity(recipe, island,
static_cast<double>(x), static_cast<double>(y), static_cast<double>(z));
for (const auto& edge : plan.clusterEdges)
{
+25 -249
View File
@@ -319,7 +319,6 @@ public:
Owner=&World;WorldAssembly=InWorldAssembly;
WorkerCount=std::clamp(Workers,1,16);DetailVariant=Variant;
Scheduler=InScheduler;RoundTunnelsEnabled=bInRoundTunnels;
bUseNativeManifestFields=true;
bAnalyticOnly=false;
bProfileDetailBand=bInProfileDetailBand;
for(int32 A=0;A<3;++A)
@@ -471,16 +470,10 @@ public:
bool BuildAnalyticRegion(FStandaloneOwnerWorld& World,const FIntVector& MinVoxels,
const FIntVector& MaxVoxels,const FIntVector& ClipMinVoxels,
const FIntVector& ClipMaxVoxels,EDetailVariant Variant,
bool bInRoundTunnels,
const VoxelForgeCore::WorldAssemblyManifest* InWorldAssembly,
std::string& Error)
bool bInRoundTunnels,std::string& Error)
{
using Clock=std::chrono::steady_clock;
Owner=&World;WorldAssembly=InWorldAssembly;
WorkerCount=1;DetailVariant=Variant;Scheduler=nullptr;
// Analytic pages retain their bounded owner bins for route bookkeeping. Once published,
// the Core world binds each page to its base shape as the single density evaluator.
bUseNativeManifestFields=true;
Owner=&World;WorkerCount=1;DetailVariant=Variant;Scheduler=nullptr;
RoundTunnelsEnabled=bInRoundTunnels;bAnalyticOnly=true;bProfileDetailBand=false;
for(int32 A=0;A<3;++A)
{
@@ -494,13 +487,7 @@ public:
const auto Stage=Clock::now();
BuildLayerBounds();BuildOwnerPrimitives();
if(RoundTunnelsEnabled)BuildRoundTunnelPrimitives();
// Analytic regions never build packed interval lines. Their exact-density fallback only
// reads the sparse 3D primitive bins; allocating the dense per-axis line-bin grids here
// scales with the region's XY bounding rectangle and is both unnecessary and unbounded.
// Les regions analytiques n'utilisent pas les intervalles compactes; leur repli exact lit
// les bins 3D clairsemes. Les grilles denses par axe croitraient avec la surface XY sans
// servir ce chemin.
BuildSpatialBins(LineBinSize,false);
BuildSpatialBins(LineBinSize);
Stats.ShapeSeconds=std::chrono::duration<double>(Clock::now()-Stage).count();
Stats.PrimitiveCount=Primitives.size();
if(Primitives.empty())
@@ -510,59 +497,6 @@ public:
return true;
}
void InitializeNativeSurfaceOnly(FStandaloneOwnerWorld& World,
const VoxelForgeCore::WorldAssemblyManifest* InWorldAssembly,
const FIntVector& InMinimum,const FIntVector& InMaximum)
{
Owner=&World;WorldAssembly=InWorldAssembly;
NativeOnlyMinimum=InMinimum;NativeOnlyMaximum=InMaximum;
bUseNativeManifestFields=true;bNativeOnly=true;bAnalyticOnly=true;Built=true;
NativeOnlyViolations.store(0,std::memory_order_relaxed);
}
bool BuildShapeDependencyProof(FStandaloneOwnerWorld& World,
const FIntVector& MinVoxels,const FIntVector& MaxVoxels,bool bInRoundTunnels)
{
Owner=&World;WorkerCount=1;RoundTunnelsEnabled=bInRoundTunnels;
bAnalyticOnly=true;bNativeOnly=false;Stats={};
for(int32 Axis=0;Axis<3;++Axis)
{
Min[Axis]=(&MinVoxels.X)[Axis]-2;Max[Axis]=(&MaxVoxels.X)[Axis]+2;
ClipMin[Axis]=(&MinVoxels.X)[Axis];ClipMax[Axis]=(&MaxVoxels.X)[Axis];
Size[Axis]=Max[Axis]-Min[Axis]+1;
if(Size[Axis]<=0||Size[Axis]>4096||ClipMax[Axis]<ClipMin[Axis])return false;
}
BuildLayerBounds();BuildOwnerPrimitives();
if(RoundTunnelsEnabled)BuildRoundTunnelPrimitives();
return true;
}
bool HasShapeDependencyInBox(const FIntVector& Origin,int32 Step,int32 Cells) const
{
const int32 Pad=std::max(Step,1);
const int32 BMin[3]={Origin.X-Pad,Origin.Y-Pad,Origin.Z-Pad};
const int32 BMax[3]={Origin.X+(Cells+1)*Step,Origin.Y+(Cells+1)*Step,
Origin.Z+(Cells+1)*Step};
for(const FPrimitive& Primitive:Primitives)
{
bool bOverlaps=true;
for(int32 Axis=0;Axis<3;++Axis)
bOverlaps=bOverlaps&&Primitive.Max[Axis]+DetailBand>=BMin[Axis]
&&Primitive.Min[Axis]-DetailBand<=BMax[Axis];
if(bOverlaps)return true;
}
for(const FInterval& Range:LayerRanges)
if(Range.Lo<=BMax[2]&&Range.Hi>=BMin[2]
&&(Range.Lo>=BMin[2]||Range.Hi<=BMax[2]))return true;
return false;
}
bool IsNativeOnly() const { return bNativeOnly; }
uint32 GetNativeOnlyViolationCount() const
{ return NativeOnlyViolations.load(std::memory_order_relaxed); }
void RecordNativeOnlyViolation() const
{ NativeOnlyViolations.fetch_add(1,std::memory_order_relaxed); }
const FBuildStats& GetStats() const { return Stats; }
bool IsBuilt() const { return Built; }
bool HasFarWorld() const { return FarBuilt; }
@@ -991,9 +925,6 @@ public:
}
}
void SetSharedDensitySource(const FStandaloneShapeWorld* Source)
{ SharedDensitySource=Source==this?nullptr:Source; }
bool HasEditTransaction() const { return !EditBrushes.empty(); }
FIntVector GetEditBoundsMin() const { return EditBoundsMin; }
FIntVector GetEditBoundsMax() const { return EditBoundsMax; }
@@ -1020,16 +951,6 @@ public:
// edge interpolation and normals to the existing mesher.
float DensityAt(float X,float Y,float Z) const
{
if(SharedDensitySource)return SharedDensitySource->DensityAt(X,Y,Z);
if(bNativeOnly)
{
if(!NativeOnlyContains(X,Y,Z))
{RecordNativeOnlyViolation();return 0.0f;}
float NativeDensity=0.0f;
if(!NativeSurfaceDensityAt(X,Y,Z,NativeDensity))
{RecordNativeOnlyViolation();return 0.0f;}
return NativeDensity;
}
float IslandDensity=0.0f;
if(NativeFloatingIslandDensityAt(X,Y,Z,IslandDensity))
{
@@ -1054,18 +975,6 @@ public:
float DensityAtLattice(int32 X,int32 Y,int32 Z) const
{
if(SharedDensitySource)return SharedDensitySource->DensityAtLattice(X,Y,Z);
if(bNativeOnly)
{
if(!NativeOnlyContains(static_cast<float>(X),static_cast<float>(Y),
static_cast<float>(Z)))
{RecordNativeOnlyViolation();return 0.0f;}
float NativeDensity=0.0f;
if(!NativeSurfaceDensityAt(static_cast<float>(X),static_cast<float>(Y),
static_cast<float>(Z),NativeDensity))
{RecordNativeOnlyViolation();return 0.0f;}
return NativeDensity;
}
float IslandDensity=0.0f;
if(NativeFloatingIslandDensityAt(static_cast<float>(X),static_cast<float>(Y),
static_cast<float>(Z),IslandDensity))
@@ -1094,16 +1003,6 @@ public:
float DensityAtUnclamped(float X,float Y,float Z) const
{
if(SharedDensitySource)return SharedDensitySource->DensityAtUnclamped(X,Y,Z);
if(bNativeOnly)
{
if(!NativeOnlyContains(X,Y,Z))
{RecordNativeOnlyViolation();return 0.0f;}
float NativeDensity=0.0f;
if(!NativeSurfaceDensityAt(X,Y,Z,NativeDensity))
{RecordNativeOnlyViolation();return 0.0f;}
return NativeDensity;
}
float IslandDensity=0.0f;
if(NativeFloatingIslandDensityAt(X,Y,Z,IslandDensity))
{
@@ -1123,10 +1022,7 @@ public:
VoxelForgeCore::DetailFieldSample DetailSampleAt(float X,float Y,float Z) const
{
if(SharedDensitySource)return SharedDensitySource->DetailSampleAt(X,Y,Z);
VoxelForgeCore::DetailFieldSample Sample;
if(bNativeOnly)
{RecordNativeOnlyViolation();return Sample;}
AnalyticDensityAt(X,Y,Z,false,&Sample.displacement,
&Sample.caveInfluence,&Sample.floorInfluence);
return Sample;
@@ -1142,19 +1038,8 @@ public:
void DensityAtLatticeX8(int32 XStart,int32 XStep,int32 Y,int32 Z,
int32 Count,float OutDensity[8]) const
{
if(SharedDensitySource)
{
SharedDensitySource->DensityAtLatticeX8(XStart,XStep,Y,Z,Count,OutDensity);
return;
}
Count=std::clamp(Count,0,8);
if(Count==0)return;
if(bNativeOnly)
{
for(int32 Lane=0;Lane<Count;++Lane)
OutDensity[Lane]=DensityAtLattice(XStart+Lane*XStep,Y,Z);
return;
}
bool bHasLegacySurfaceSample=false;
bool bHasNativeIslandSample=false;
for(int32 Lane=0;Lane<Count;++Lane)
@@ -1253,8 +1138,6 @@ private:
float* OutFloorInfluence=nullptr,
bool bApplyEdits=true) const
{
if(SharedDensitySource)return SharedDensitySource->AnalyticDensityAt(X,Y,Z,
bClampNearZero,OutDetailDisplacement,OutCaveInfluence,OutFloorInfluence,bApplyEdits);
if(OutDetailDisplacement)*OutDetailDisplacement=0.0f;
if(OutCaveInfluence)*OutCaveInfluence=0.0f;
if(OutFloorInfluence)*OutFloorInfluence=0.0f;
@@ -1317,21 +1200,12 @@ public:
bool GetNativeSurfaceHeightsAt(float X,float Y,int32 ChunkZ,
float& OutGroundZ,float& OutCeilingZ) const
{
if(SharedDensitySource)
return SharedDensitySource->GetNativeSurfaceHeightsAt(X,Y,ChunkZ,OutGroundZ,OutCeilingZ);
if(!WorldAssembly||!Owner||!Owner->Manager||!Owner->Generator
||!std::isfinite(X)||!std::isfinite(Y))return false;
const std::int64_t chunkMinimum=static_cast<std::int64_t>(ChunkZ)*CHUNK_SIZE;
const std::int64_t chunkMaximum=chunkMinimum+CHUNK_SIZE;
if(bNativeOnly&&(!NativeOnlyContainsColumn(X,Y)
||chunkMaximum<NativeOnlyMinimum.Z||chunkMinimum>NativeOnlyMaximum.Z
||Owner->Manager->GetGeneratorTypeForChunk(FIntVector(0,0,ChunkZ))
!=ECaveGeneratorType::SurfaceWorld))
{RecordNativeOnlyViolation();return false;}
if(Owner->Manager->GetGeneratorTypeForChunk(FIntVector(0,0,ChunkZ))
!=ECaveGeneratorType::SurfaceWorld)return false;
const int32 StrateIndex=Owner->Manager->GetStrateIndex(
static_cast<float>((static_cast<double>(ChunkZ)*CHUNK_SIZE+CHUNK_SIZE/2)*VOXEL_SIZE));
static_cast<float>((static_cast<double>(ChunkZ*CHUNK_SIZE+CHUNK_SIZE/2))*VOXEL_SIZE));
const auto* Plan=FindWorldAssemblyStratum(StrateIndex,ChunkZ);
if(!Plan)return false;
constexpr double Scale=static_cast<double>(VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel);
@@ -1353,49 +1227,8 @@ public:
EVoxelTileClass ClassifyBox(const FIntVector& Origin,int32 Step,int32 Cells) const
{ return ClassifyBoxDetailed(Origin,Step,Cells).Verdict; }
bool IsNativeSurfaceBox(const FIntVector& Origin,int32 Step,int32 Cells) const
FBoxClassification ClassifyBoxDetailed(const FIntVector& Origin,int32 Step,int32 Cells) const
{
if(SharedDensitySource)return SharedDensitySource->IsNativeSurfaceBox(Origin,Step,Cells);
if(!WorldAssembly||!Owner||!Owner->Manager||Step<=0||Cells<=0)return false;
const int32 Pad=std::max(Step,1);
const int32 BMin=Origin.Z-Pad;
const int32 BMax=Origin.Z+(Cells+1)*Step;
const int32 FirstChunk=FMath::FloorToInt(static_cast<float>(BMin)
/static_cast<float>(CHUNK_SIZE));
const int32 LastChunk=FMath::FloorToInt(static_cast<float>(BMax)
/static_cast<float>(CHUNK_SIZE));
const VoxelForgeCore::WorldAssemblyStratumPlanV1* Plan=nullptr;
for(int32 ChunkZ=FirstChunk;ChunkZ<=LastChunk;++ChunkZ)
{
const auto It=std::find_if(WorldAssembly->plan.strates.begin(),
WorldAssembly->plan.strates.end(),[ChunkZ](const auto& Entry)
{return ChunkZ<=Entry.topChunkZ&&ChunkZ>=Entry.bottomChunkZ;});
if(It==WorldAssembly->plan.strates.end())return false;
const auto* Candidate=&*It;
if(Plan&&Plan!=Candidate)return false;
if(Owner->Manager->GetGeneratorTypeForChunk(FIntVector(0,0,ChunkZ))
!=ECaveGeneratorType::SurfaceWorld)return false;
Plan=Candidate;
}
if(bNativeOnly)
{
const int32 BMinX=Origin.X-Pad,BMinY=Origin.Y-Pad;
const int32 BMaxX=Origin.X+(Cells+1)*Step;
const int32 BMaxY=Origin.Y+(Cells+1)*Step;
if(BMinX<NativeOnlyMinimum.X||BMinY<NativeOnlyMinimum.Y
||BMin<NativeOnlyMinimum.Z||BMaxX>NativeOnlyMaximum.X
||BMaxY>NativeOnlyMaximum.Y||BMax>NativeOnlyMaximum.Z)
{RecordNativeOnlyViolation();return false;}
}
if(bNativeOnly&&!Plan)RecordNativeOnlyViolation();
return Plan!=nullptr;
}
FBoxClassification ClassifyBoxDetailed(const FIntVector& Origin,int32 Step,int32 Cells,
bool bUseNativeLatticeProof=false) const
{
if(SharedDensitySource)
return SharedDensitySource->ClassifyBoxDetailed(Origin,Step,Cells,bUseNativeLatticeProof);
using Clock=std::chrono::steady_clock;
const auto Start=Clock::now();
const int32 Pad=std::max(Step,1);
@@ -1421,7 +1254,7 @@ public:
{
bSurfaceOverlap=true;
const int32 StrateIndex=Owner->Manager->GetStrateIndex(
static_cast<float>((static_cast<double>(ChunkZ)*CHUNK_SIZE+CHUNK_SIZE/2)*VOXEL_SIZE));
static_cast<float>((static_cast<double>(ChunkZ*CHUNK_SIZE+CHUNK_SIZE/2))*VOXEL_SIZE));
const auto* Candidate=FindWorldAssemblyStratum(StrateIndex,ChunkZ);
if(!Candidate||(SurfacePlan&&SurfacePlan!=Candidate))
bBadPlan=true;
@@ -1446,7 +1279,7 @@ public:
{
bIslandOverlap=true;
const int32 StrateIndex=Owner->Manager->GetStrateIndex(
static_cast<float>((static_cast<double>(ChunkZ)*CHUNK_SIZE+CHUNK_SIZE/2)*VOXEL_SIZE));
static_cast<float>((static_cast<double>(ChunkZ*CHUNK_SIZE+CHUNK_SIZE/2))*VOXEL_SIZE));
const auto* Candidate=FindWorldAssemblyFloatingIslandStratum(StrateIndex,ChunkZ);
if(!Candidate||(IslandPlan&&IslandPlan!=Candidate))bBadPlan=true;
IslandPlan=Candidate;
@@ -1467,19 +1300,6 @@ public:
else ++Counts.MixedBoxes;
return Result;
};
if(bNativeOnly)
{
const bool bInsideProofBox=BMin[0]>=NativeOnlyMinimum.X
&&BMin[1]>=NativeOnlyMinimum.Y&&BMin[2]>=NativeOnlyMinimum.Z
&&BMax[0]<=NativeOnlyMaximum.X&&BMax[1]<=NativeOnlyMaximum.Y
&&BMax[2]<=NativeOnlyMaximum.Z;
if(!bInsideProofBox||!bSurfaceOverlap||bIslandOverlap||bOtherStrateOverlap
||bBadPlan||!EditBrushes.empty())
{
RecordNativeOnlyViolation();
return Finish(EVoxelTileClass::Mixed,true);
}
}
// A box crossing recipes cannot use one field interval; unknown composition stays Mixed.
// Une boite qui traverse plusieurs recettes reste Mixed, car l'intervalle d'un seul champ ne suffit pas.
if(bBadPlan||(bSurfaceOverlap&&(bIslandOverlap||bOtherStrateOverlap))
@@ -1490,37 +1310,27 @@ public:
&&EditBoundsMin.Y<=BMax[1]&&EditBoundsMax.Y>=BMin[1]
&&EditBoundsMin.Z<=BMax[2]&&EditBoundsMax.Z>=BMin[2])
return Finish(EVoxelTileClass::Mixed,true);
// The native interval path below is the exact field selected first by DensityAtLattice
// for SurfaceWorld and FloatingIslands. Legacy analytic primitives/layer bounds cannot
// modify that field; only the explicit edit transaction above can. Keep their guards on
// the legacy classifier path, where those overlays do participate in density.
if(!bNativeOnly&&(!bUseNativeLatticeProof||(!bSurfaceOverlap&&!bIslandOverlap)))
for(int32 BZ=FloorDiv(BMin[2],ActiveSpatialBinSize);BZ<=FloorDiv(BMax[2],ActiveSpatialBinSize);++BZ)
for(int32 BY=FloorDiv(BMin[1],ActiveSpatialBinSize);BY<=FloorDiv(BMax[1],ActiveSpatialBinSize);++BY)
for(int32 BX=FloorDiv(BMin[0],ActiveSpatialBinSize);BX<=FloorDiv(BMax[0],ActiveSpatialBinSize);++BX)
{
for(int32 BZ=FloorDiv(BMin[2],ActiveSpatialBinSize);BZ<=FloorDiv(BMax[2],ActiveSpatialBinSize);++BZ)
for(int32 BY=FloorDiv(BMin[1],ActiveSpatialBinSize);BY<=FloorDiv(BMax[1],ActiveSpatialBinSize);++BY)
for(int32 BX=FloorDiv(BMin[0],ActiveSpatialBinSize);BX<=FloorDiv(BMax[0],ActiveSpatialBinSize);++BX)
const auto It=SpatialBins.find({BX,BY,BZ});if(It==SpatialBins.end())continue;
for(uint32 Id:It->second)
{
const auto It=SpatialBins.find({BX,BY,BZ});if(It==SpatialBins.end())continue;
for(uint32 Id:It->second)
{
const FPrimitive& P=Primitives[Id];bool Overlap=true;
for(int32 A=0;A<3;++A)
Overlap &= P.Max[A]+DetailBand>=BMin[A]&&P.Min[A]-DetailBand<=BMax[A];
if(Overlap)return Finish(EVoxelTileClass::Mixed);
}
const FPrimitive& P=Primitives[Id];bool Overlap=true;
for(int32 A=0;A<3;++A)
Overlap &= P.Max[A]+DetailBand>=BMin[A]&&P.Min[A]-DetailBand<=BMax[A];
if(Overlap)return Finish(EVoxelTileClass::Mixed);
}
for(const FInterval& R:LayerRanges)
if(R.Lo<=BMax[2]&&R.Hi>=BMin[2]
&&(R.Lo>=BMin[2]||R.Hi<=BMax[2]))
return Finish(EVoxelTileClass::Mixed);
}
for(const FInterval& R:LayerRanges)
if(R.Lo<=BMax[2]&&R.Hi>=BMin[2]
&&(R.Lo>=BMin[2]||R.Hi<=BMax[2]))
return Finish(EVoxelTileClass::Mixed);
if(bSurfaceOverlap)
{
if(!WorldAssembly||!SurfacePlan)return Finish(EVoxelTileClass::Mixed,true);
const VoxelForgeCore::Heightfield2D Block(WorldAssembly->recipe,*SurfacePlan);
// classifyLatticeBox takes the exact extrema of ground/cap columns at every
// MC lattice XY in this box. Since density is min(z-ground, cap-z), those extrema
// bound every lattice sample in Z without a noise amplitude guess.
const auto Verdict=Block.classifyLatticeBox(
static_cast<int64>(BMin[0])*VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel,
static_cast<int64>(BMin[1])*VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel,
@@ -1576,7 +1386,6 @@ public:
bool IsRock(int32 X,int32 Y,int32 Z) const
{
if(SharedDensitySource)return SharedDensitySource->IsRock(X,Y,Z);
if(!Contains(X,Y,Z))return EvaluateFast(X,Y,Z);
const size_t Line=static_cast<size_t>(Y-Min[1])*Size[0]
+static_cast<size_t>(X-Min[0]);
@@ -2034,21 +1843,6 @@ public:
}
private:
bool NativeOnlyContainsColumn(float X,float Y) const
{
return std::isfinite(X)&&std::isfinite(Y)
&&X>=NativeOnlyMinimum.X&&X<=NativeOnlyMaximum.X
&&Y>=NativeOnlyMinimum.Y&&Y<=NativeOnlyMaximum.Y;
}
bool NativeOnlyContains(float X,float Y,float Z) const
{
return std::isfinite(X)&&std::isfinite(Y)&&std::isfinite(Z)
&&X>=NativeOnlyMinimum.X&&X<=NativeOnlyMaximum.X
&&Y>=NativeOnlyMinimum.Y&&Y<=NativeOnlyMaximum.Y
&&Z>=NativeOnlyMinimum.Z&&Z<=NativeOnlyMaximum.Z;
}
static FClassificationThreadStats& ThreadClassificationStats()
{
static thread_local FClassificationThreadStats Stats;
@@ -2077,13 +1871,13 @@ private:
bool NativeSurfaceDensityAt(float X,float Y,float Z,float& OutDensity) const
{
if(!bUseNativeManifestFields||!WorldAssembly||!Owner||!Owner->Manager||!Owner->Generator
if(!WorldAssembly||!Owner||!Owner->Manager||!Owner->Generator
||!std::isfinite(X)||!std::isfinite(Y)||!std::isfinite(Z))return false;
const int32 ChunkZ=FMath::FloorToInt(Z/static_cast<float>(CHUNK_SIZE));
if(Owner->Manager->GetGeneratorTypeForChunk(FIntVector(0,0,ChunkZ))
!=ECaveGeneratorType::SurfaceWorld)return false;
const int32 StrateIndex=Owner->Manager->GetStrateIndex(
static_cast<float>((static_cast<double>(ChunkZ)*CHUNK_SIZE+CHUNK_SIZE/2)*VOXEL_SIZE));
static_cast<float>((static_cast<double>(ChunkZ*CHUNK_SIZE+CHUNK_SIZE/2))*VOXEL_SIZE));
const auto* Plan=FindWorldAssemblyStratum(StrateIndex,ChunkZ);
if(!Plan)return false;
constexpr double Scale=static_cast<double>(VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel);
@@ -2102,9 +1896,8 @@ private:
bool NativeFloatingIslandDensityAt(float X,float Y,float Z,float& OutDensity) const
{
if(!bUseNativeManifestFields||!WorldAssembly||!Owner||!Owner->Manager||!Owner->Generator
||!std::isfinite(X)||!std::isfinite(Y)||!std::isfinite(Z))
return false;
if(!WorldAssembly||!Owner||!Owner->Manager||!Owner->Generator
||!std::isfinite(X)||!std::isfinite(Y)||!std::isfinite(Z))return false;
// Convert Core query Z back to the owner's legacy chunk coordinate.
// Convertir Z du Core vers la coordonnee de chunk legacy du proprietaire.
const double CoreVoxelsPerLegacyChunk=GetCoreVoxelsPerOwnerChunk();
@@ -2112,7 +1905,7 @@ private:
if(Owner->Manager->GetGeneratorTypeForChunk(FIntVector(0,0,ChunkZ))
!=ECaveGeneratorType::FloatingIslands)return false;
const int32 StrateIndex=Owner->Manager->GetStrateIndex(
static_cast<float>((static_cast<double>(ChunkZ)*CHUNK_SIZE+CHUNK_SIZE/2)*VOXEL_SIZE));
static_cast<float>((static_cast<double>(ChunkZ*CHUNK_SIZE+CHUNK_SIZE/2))*VOXEL_SIZE));
const auto* Plan=FindWorldAssemblyFloatingIslandStratum(StrateIndex,ChunkZ);
if(!Plan)return false;
constexpr double Scale=static_cast<double>(VoxelForgeCore::WorldAssemblySubvoxelsPerVoxel);
@@ -4844,18 +4637,7 @@ public:
void DensityAtLatticeZRun(int32 X,int32 Y,int32 ZStart,int32 ZStep,
int32 Count,float* OutDensity) const
{
if(SharedDensitySource)
{
SharedDensitySource->DensityAtLatticeZRun(X,Y,ZStart,ZStep,Count,OutDensity);
return;
}
if(Count<=0||OutDensity==nullptr)return;
if(bNativeOnly)
{
for(int32 Lane=0;Lane<Count;++Lane)
OutDensity[Lane]=DensityAtLattice(X,Y,ZStart+Lane*ZStep);
return;
}
bool bHasLegacySurfaceSample=false;
for(int32 Lane=0;Lane<Count;++Lane)
bHasLegacySurfaceSample|=UsesLegacySurfaceField(static_cast<float>(X),
@@ -5379,7 +5161,6 @@ private:
FStandaloneOwnerWorld* Owner=nullptr;
const VoxelForgeCore::WorldAssemblyManifest* WorldAssembly=nullptr;
const FStandaloneShapeWorld* SharedDensitySource=nullptr;
int32 WorkerCount=6;
const VoxelForgeCore::JobScheduler* Scheduler=nullptr;
bool RoundTunnelsEnabled=false;
@@ -5393,11 +5174,6 @@ private:
size_t WordsPerZ=0;
EDetailVariant DetailVariant=EDetailVariant::Coherent;
bool Built=false;
bool bNativeOnly=false;
bool bUseNativeManifestFields=false;
FIntVector NativeOnlyMinimum=FIntVector::ZeroValue;
FIntVector NativeOnlyMaximum=FIntVector::ZeroValue;
mutable std::atomic<uint32> NativeOnlyViolations{0};
bool FarBuilt=false;
std::vector<FInterval> LayerRanges;
std::vector<FLayerField> LayerFields;
+49 -487
View File
@@ -13,8 +13,6 @@
#include <set>
#include <functional>
#include <thread>
#include <new>
#include <stdexcept>
namespace vfcore::detail
{
@@ -343,7 +341,7 @@ namespace VoxelForgeCore
FNativeCapRefinementStats RefineFarNativeGround(const FStandaloneOwnerWorld& Owner,
const WorldAssemblyManifest& Manifest,const FVoxelTileKey& Key,int32 MeshStepVoxels,
int32 InteriorStepOverride,int32 RefinementGridScale,FVoxelMeshData& Mesh)
int32 InteriorStepOverride,FVoxelMeshData& Mesh)
{
FNativeCapRefinementStats Stats;
if(Key.Level<5||!Owner.Generator)return Stats;
@@ -354,12 +352,11 @@ namespace VoxelForgeCore
const int32 RequestedStep=Key.Level==8
?(InteriorStepOverride>0?InteriorStepOverride:MeshStepVoxels)
:std::min(BoundaryStepVoxels,1<<Key.Level);
const int32 ScaledRequestedStep=RequestedStep*std::max(1,RefinementGridScale);
const int32 GridStepVoxels=Key.Level==8
?((ScaledRequestedStep<BoundaryStepVoxels||ScaledRequestedStep%BoundaryStepVoxels!=0
||TileExtent<=0||TileExtent%ScaledRequestedStep!=0)
?BoundaryStepVoxels:std::max(BoundaryStepVoxels,ScaledRequestedStep))
:ScaledRequestedStep;
?((RequestedStep<BoundaryStepVoxels||RequestedStep%BoundaryStepVoxels!=0
||TileExtent<=0||TileExtent%RequestedStep!=0)
?BoundaryStepVoxels:std::max(BoundaryStepVoxels,RequestedStep))
:RequestedStep;
if(TileExtent<=0||TileExtent%GridStepVoxels!=0)return Stats;
const std::vector<int32> GridCoordinates=
BuildNativeHorizonGridCoordinates(TileExtent,GridStepVoxels);
@@ -645,7 +642,7 @@ namespace VoxelForgeCore
FNativeCapRefinementStats RefineFarNativeCap(const FStandaloneOwnerWorld& Owner,
const WorldAssemblyManifest& Manifest,const FVoxelTileKey& Key,int32 MeshStepVoxels,
int32 InteriorStepOverride,int32 RefinementGridScale,FVoxelMeshData& Mesh)
int32 InteriorStepOverride,FVoxelMeshData& Mesh)
{
FNativeCapRefinementStats Stats;
if(Key.Level<4||!Owner.Generator)return Stats;
@@ -655,12 +652,11 @@ namespace VoxelForgeCore
:(Key.Level<5?std::min(BoundaryStepVoxels,1<<Key.Level):BoundaryStepVoxels);
const FIntVector TileOrigin=Key.OriginVoxels();
const int32 TileExtent=Key.ExtentVoxels();
const int32 ScaledRequestedStep=RequestedStep*std::max(1,RefinementGridScale);
const int32 EffectiveGridStep=Key.Level==8
?((ScaledRequestedStep<BoundaryStepVoxels||ScaledRequestedStep%BoundaryStepVoxels!=0
||TileExtent<=0||TileExtent%ScaledRequestedStep!=0)
?BoundaryStepVoxels:std::max(BoundaryStepVoxels,ScaledRequestedStep))
:ScaledRequestedStep;
?((RequestedStep<BoundaryStepVoxels||RequestedStep%BoundaryStepVoxels!=0
||TileExtent<=0||TileExtent%RequestedStep!=0)
?BoundaryStepVoxels:std::max(BoundaryStepVoxels,RequestedStep))
:RequestedStep;
constexpr int64 Scale=WorldAssemblySubvoxelsPerVoxel;
if(TileExtent<=0||TileExtent%EffectiveGridStep!=0)return Stats;
const std::vector<int32> GridCoordinates=
@@ -947,11 +943,6 @@ namespace VoxelForgeCore
std::shared_ptr<const WorldAssemblyManifest> worldAssembly;
WorldConfiguration configuration;
std::unique_ptr<FStandaloneShapeWorld> shape;
std::atomic<bool> shapeReady{false};
std::unique_ptr<world_assembly_detail::FSharedHeightfieldColumnCache>
sharedHeightfieldColumns;
std::unique_ptr<floating_island_detail::FSharedIslandColumnCache>
sharedIslandColumns;
ShapeBuildRequest buildRequest;
mutable std::shared_mutex tileRegionMutex;
std::unordered_map<TileKey,std::shared_ptr<FStandaloneShapeWorld>,TileKeyHash> tileRegions;
@@ -962,23 +953,6 @@ namespace VoxelForgeCore
std::uint64_t lastSequence=0;
};
struct FScopedSharedColumnCaches
{
using FHeightfieldCache=world_assembly_detail::FSharedHeightfieldColumnCache;
using FIslandCache=floating_island_detail::FSharedIslandColumnCache;
FHeightfieldCache* PreviousHeightfield=nullptr;
FIslandCache* PreviousIslands=nullptr;
FScopedSharedColumnCaches(FHeightfieldCache* Heightfield,FIslandCache* Islands)
: PreviousHeightfield(FHeightfieldCache::setThreadActive(Heightfield)),
PreviousIslands(FIslandCache::setThreadActive(Islands)) {}
~FScopedSharedColumnCaches()
{
FHeightfieldCache::setThreadActive(PreviousHeightfield);
FIslandCache::setThreadActive(PreviousIslands);
}
};
World::World(ResolvedWorldSnapshot snapshot):impl_(std::make_unique<Impl>())
{
if(snapshot.data_)
@@ -986,151 +960,15 @@ namespace VoxelForgeCore
impl_->owner=snapshot.data_->owner;
impl_->worldAssembly=snapshot.data_->worldAssembly;
impl_->configuration=snapshot.data_->configuration;
if(impl_->worldAssembly)
{
if(!impl_->worldAssembly->plan.strates.empty())
impl_->sharedHeightfieldColumns=
std::make_unique<world_assembly_detail::FSharedHeightfieldColumnCache>();
if(!impl_->worldAssembly->floatingIslands.empty())
impl_->sharedIslandColumns=
std::make_unique<floating_island_detail::FSharedIslandColumnCache>();
}
}
}
World::~World()=default;
World::World(World&&) noexcept=default;
World& World::operator=(World&&) noexcept=default;
namespace
{
template<class TImpl>
bool NativeOnlyBoundsForTile(const TImpl& impl,const TileKey& key,
FIntVector& minimum,FIntVector& maximum)
{
if(!impl.owner||key.lod!=0||key.lod>=impl.configuration.fullResolutionLodCount)
return false;
constexpr std::int64_t TileExtent=CHUNK_SIZE;
const std::int64_t skirt=impl.owner->CoreVoxelSizeMicrons>0
?static_cast<std::int64_t>(std::ceil(std::abs(
static_cast<double>(impl.owner->SkirtCells)
*static_cast<double>(impl.owner->OwnerVoxelSizeMicrons)
/static_cast<double>(impl.owner->CoreVoxelSizeMicrons)))):0;
const std::int64_t pad=std::max<std::int64_t>(8,skirt+4);
const std::int64_t coordinates[3]={key.coordinate.x,key.coordinate.y,key.coordinate.z};
std::int64_t low[3]{},high[3]{};
for(int axis=0;axis<3;++axis)
{
const std::int64_t origin=coordinates[axis]*TileExtent;
low[axis]=origin-pad;
high[axis]=origin+TileExtent+pad;
if(low[axis]<std::numeric_limits<std::int32_t>::min()+4ll
||high[axis]>std::numeric_limits<std::int32_t>::max()-4ll)return false;
}
minimum=FIntVector(static_cast<int32>(low[0]),static_cast<int32>(low[1]),
static_cast<int32>(low[2]));
maximum=FIntVector(static_cast<int32>(high[0]),static_cast<int32>(high[1]),
static_cast<int32>(high[2]));
return true;
}
bool IntersectsBox(const std::array<std::int64_t,3>& minimum,
const std::array<std::int64_t,3>& maximum,
const std::int64_t tileMinimum[3],const std::int64_t tileMaximum[3])
{
for(int axis=0;axis<3;++axis)
if(maximum[axis]<tileMinimum[axis]||minimum[axis]>tileMaximum[axis])
return false;
return true;
}
bool RouteTouchesBox(const WorldAssemblyStratumPlanV1& plan,
const std::int64_t tileMinimum[3],const std::int64_t tileMaximum[3])
{
if(plan.route.empty())return false;
const std::int64_t constraintRadius=std::max<std::int64_t>(0,
plan.routeConstraints.capsuleRadiusSubvoxels)
+std::max<std::int64_t>(0,plan.routeConstraints.capsuleHeightSubvoxels)/2;
for(std::size_t index=0;index<plan.route.size();++index)
{
const auto& point=plan.route[index];
const std::int64_t radius=std::max(constraintRadius,
std::max<std::int64_t>(0,point.radiusSubvoxels));
std::array<std::int64_t,3> low{},high{};
for(int axis=0;axis<3;++axis)
{
low[axis]=point.positionSubvoxels[axis]-radius;
high[axis]=point.positionSubvoxels[axis]+radius;
}
if(IntersectsBox(low,high,tileMinimum,tileMaximum))return true;
if(index+1>=plan.route.size())continue;
const auto& next=plan.route[index+1];
const std::int64_t segmentRadius=std::max(radius,
std::max(constraintRadius,std::max<std::int64_t>(0,next.radiusSubvoxels)));
for(int axis=0;axis<3;++axis)
{
low[axis]=std::min(point.positionSubvoxels[axis],next.positionSubvoxels[axis])
-segmentRadius;
high[axis]=std::max(point.positionSubvoxels[axis],next.positionSubvoxels[axis])
+segmentRadius;
}
if(IntersectsBox(low,high,tileMinimum,tileMaximum))return true;
}
return false;
}
bool OwnerPassageTouchesBox(const FStandaloneOwnerWorld& owner,
const FIntVector& minimum,const FIntVector& maximum)
{
const double ownerToCore=owner.OwnerVoxelSizeMicrons>0
&&owner.CoreVoxelSizeMicrons>0
?static_cast<double>(owner.OwnerVoxelSizeMicrons)
/static_cast<double>(owner.CoreVoxelSizeMicrons):1.0;
const double padding=(std::max(8.0,static_cast<double>(owner.SkirtCells)+4.0)
/ownerToCore)+64.0;
const double tileMinimum[3]={static_cast<double>(minimum.X),
static_cast<double>(minimum.Y),static_cast<double>(minimum.Z)};
const double tileMaximum[3]={static_cast<double>(maximum.X),
static_cast<double>(maximum.Y),static_cast<double>(maximum.Z)};
const auto SegmentTouches=[&](const FVector& a,const FVector& b,double radius)
{
for(int axis=0;axis<3;++axis)
{
const double pointA=(&a.X)[axis]*ownerToCore;
const double pointB=(&b.X)[axis]*ownerToCore;
const double expansion=(radius+padding)*ownerToCore;
if(std::max(pointA,pointB)+expansion<tileMinimum[axis]
||std::min(pointA,pointB)-expansion>tileMaximum[axis])return false;
}
return true;
};
for(const FVoxelPassage& passage:owner.Manager->GetPassages())
{
const auto& points=passage.ControlPoints;
if(points.Num()<2)
{
if(SegmentTouches(passage.UpperPoint,passage.LowerPoint,passage.Radius))
return true;
continue;
}
for(int32 index=0;index+1<points.Num();++index)
{
const double radius=std::max({static_cast<double>(passage.Radius),
passage.ControlRadii.IsValidIndex(index)
?static_cast<double>(passage.ControlRadii[index]):0.0,
passage.ControlRadii.IsValidIndex(index+1)
?static_cast<double>(passage.ControlRadii[index+1]):0.0});
if(SegmentTouches(points[index],points[index+1],radius))return true;
}
}
return false;
}
}
bool World::compile(const ShapeBuildRequest& request,const JobScheduler& scheduler,std::string& error)
{
if(!impl_->owner){error="resolved world snapshot is empty";return false;}
if(impl_->shapeReady.load(std::memory_order_acquire))
{error="world shape is already compiled";return false;}
if(!::vfcore::fp_contract::selfTest())
{
error="Core startup refused: floating-point contraction self-test detected a fused multiply-add; this compiler/flag combination is unsupported for world generation";
@@ -1150,74 +988,13 @@ namespace VoxelForgeCore
std::unique_lock lock(impl_->tileRegionMutex);
impl_->tileRegions.clear();
impl_->tileRegionCount.store(0,std::memory_order_release);
impl_->shapeReady.store(true,std::memory_order_release);
}
return ok;
}
bool World::isTileShapeFree(const TileKey& key) const
{
if(!impl_||!impl_->owner||!impl_->worldAssembly||!impl_->owner->Manager
||!impl_->owner->Generator||!impl_->editLog.empty())return false;
FIntVector boundsMin,boundsMax;
if(!NativeOnlyBoundsForTile(*impl_,key,boundsMin,boundsMax))return false;
const std::int64_t tileMinimum[3]={boundsMin.X,boundsMin.Y,boundsMin.Z};
const std::int64_t tileMaximum[3]={boundsMax.X,boundsMax.Y,boundsMax.Z};
const int32 firstSurfaceChunk=FloorDiv(boundsMin.Z,CHUNK_SIZE);
const int32 lastSurfaceChunk=FloorDiv(boundsMax.Z,CHUNK_SIZE);
const WorldAssemblyStratumPlanV1* selectedPlan=nullptr;
for(int32 chunkZ=firstSurfaceChunk;chunkZ<=lastSurfaceChunk;++chunkZ)
{
if(impl_->owner->Manager->GetGeneratorTypeForChunk(FIntVector(0,0,chunkZ))
!=ECaveGeneratorType::SurfaceWorld)return false;
const int32 strateIndex=impl_->owner->Manager->GetStrateIndex(
static_cast<float>((static_cast<double>(chunkZ)*CHUNK_SIZE
+CHUNK_SIZE*0.5)*VOXEL_SIZE));
const auto found=std::find_if(impl_->worldAssembly->plan.strates.begin(),
impl_->worldAssembly->plan.strates.end(),[strateIndex,chunkZ](const auto& plan)
{return plan.strateIndex==strateIndex&&chunkZ<=plan.topChunkZ
&&chunkZ>=plan.bottomChunkZ;});
if(found==impl_->worldAssembly->plan.strates.end()
||(selectedPlan&&selectedPlan!=&*found))return false;
selectedPlan=&*found;
}
if(!selectedPlan||!Heightfield2D(impl_->worldAssembly->recipe,*selectedPlan).isValid())
return false;
const double coreVoxelsPerOwnerChunk=static_cast<double>(CHUNK_SIZE)
*static_cast<double>(impl_->owner->OwnerVoxelSizeMicrons)
/static_cast<double>(std::max(1u,impl_->owner->CoreVoxelSizeMicrons));
const int32 firstIslandChunk=FMath::FloorToInt(
static_cast<double>(boundsMin.Z)/coreVoxelsPerOwnerChunk);
const int32 lastIslandChunk=FMath::FloorToInt(
static_cast<double>(boundsMax.Z)/coreVoxelsPerOwnerChunk);
for(int32 chunkZ=firstIslandChunk;chunkZ<=lastIslandChunk;++chunkZ)
if(impl_->owner->Manager->GetGeneratorTypeForChunk(FIntVector(0,0,chunkZ))
==ECaveGeneratorType::FloatingIslands)return false;
constexpr std::int64_t scale=WorldAssemblySubvoxelsPerVoxel;
const std::int64_t subMinimum[3]={tileMinimum[0]*scale,tileMinimum[1]*scale,
tileMinimum[2]*scale};
const std::int64_t subMaximum[3]={tileMaximum[0]*scale,tileMaximum[1]*scale,
tileMaximum[2]*scale};
for(const WorldAssemblyFeatureV1& feature:selectedPlan->features)
if(IntersectsBox(feature.minimumSubvoxels,feature.maximumSubvoxels,
subMinimum,subMaximum))return false;
if(RouteTouchesBox(*selectedPlan,subMinimum,subMaximum))return false;
if(OwnerPassageTouchesBox(*impl_->owner,boundsMin,boundsMax))return false;
FStandaloneShapeWorld proofGeometry;
if(!proofGeometry.BuildShapeDependencyProof(*impl_->owner,boundsMin,boundsMax,
impl_->owner->Generator->bStandaloneResearchRoundTunnels))return false;
const FIntVector tileOrigin=ToNative(key).OriginVoxels();
if(proofGeometry.HasShapeDependencyInBox(tileOrigin,1,CHUNK_SIZE))return false;
return true;
}
bool World::needsTileRegion(const TileKey& key) const
{
if(!impl_||!impl_->owner||!impl_->shapeReady.load(std::memory_order_acquire)
||!impl_->shape||!impl_->shape->IsBuilt()
if(!impl_||!impl_->owner||!impl_->shape||!impl_->shape->IsBuilt()
||key.lod<0||key.lod>=impl_->configuration.fullResolutionLodCount)
return false;
if(CoveredByBaseShape(impl_->buildRequest,impl_->configuration,key))return false;
@@ -1228,20 +1005,14 @@ namespace VoxelForgeCore
bool World::compileTileRegion(std::span<const TileKey> tiles,std::uint32_t workerLimit,
const JobScheduler& scheduler,std::string& error,
std::size_t* outCompiledTiles,
TileRegionCompileStats* outStats,bool analyticOnly,
bool diagnosticIncludeBaseCoveredTiles)
TileRegionCompileStats* outStats,bool analyticOnly)
{
if(outCompiledTiles)*outCompiledTiles=0;
if(outStats)*outStats={};
try
{
if(!impl_||!impl_->owner||!impl_->shapeReady.load(std::memory_order_acquire)
||!impl_->shape||!impl_->shape->IsBuilt())
if(!impl_||!impl_->owner||!impl_->shape||!impl_->shape->IsBuilt())
{error="the base world must be compiled before adding tile regions";return false;}
if(tiles.empty())return true;
constexpr std::int64_t RegionPadding=10;
struct FPendingRegion
{
TileKey pageKey;
@@ -1260,31 +1031,15 @@ namespace VoxelForgeCore
const TileKey& key=tiles[inputIndex];
if(key.lod<0||key.lod>8)
{error="tile region contains an invalid LOD";return false;}
if(key.lod>=impl_->configuration.fullResolutionLodCount)continue;
const std::int64_t extent=static_cast<std::int64_t>(CHUNK_SIZE)
*(std::int64_t{1}<<key.lod);
const std::int32_t coordinates[3]={key.coordinate.x,key.coordinate.y,
key.coordinate.z};
for(int axis=0;axis<3;++axis)
{
const std::int64_t origin=static_cast<std::int64_t>(coordinates[axis])*extent;
if(origin<std::numeric_limits<std::int32_t>::min()+RegionPadding
||origin+extent>std::numeric_limits<std::int32_t>::max()-RegionPadding)
{error="tile region coordinate is out of range";return false;}
}
if(!diagnosticIncludeBaseCoveredTiles
&&CoveredByBaseShape(impl_->buildRequest,impl_->configuration,key))continue;
if(key.lod>=impl_->configuration.fullResolutionLodCount
||CoveredByBaseShape(impl_->buildRequest,impl_->configuration,key))continue;
if(impl_->tileRegions.contains(key)||!seenTiles.insert(key).second)continue;
// Keep every region's bounds spatially finite. A large camera step can bring in
// disjoint tiles across the whole view; coalescing an entire LOD slab makes the
// dense axis-bin grid grow with the bounding rectangle of all of them at once.
// Garder chaque region spatialement bornee: un grand deplacement peut amener des
// tuiles disjointes; fusionner tout un niveau ferait croitre les bins avec son
// grand rectangle englobant.
const TileKey pageKey=ShapePageKey(key);
auto [found,inserted]=regionByPage.try_emplace(pageKey,pendingRegions.size());
if(inserted)pendingRegions.push_back({pageKey,{}});
pendingRegions[found->second].tiles.push_back(key);
// Analytic regions evaluate only requested fine tiles and can safely coalesce a
// whole entering LOD slab. Packed pages retain their fixed absolute parent cells.
const TileKey pageKey=analyticOnly?TileKey{{0,0,0},key.lod}:ShapePageKey(key);
auto [found,inserted]=regionByPage.try_emplace(pageKey,pendingRegions.size());
if(inserted)pendingRegions.push_back({pageKey,{}});
pendingRegions[found->second].tiles.push_back(key);
}
}
if(pendingRegions.empty())return true;
@@ -1321,8 +1076,7 @@ namespace VoxelForgeCore
const FIntVector fineMax(regionMax.X+PagePad,regionMax.Y+PagePad,regionMax.Z+PagePad);
auto region=std::make_shared<FStandaloneShapeWorld>();
if(!region->BuildAnalyticRegion(*impl_->owner,fineMin,fineMax,regionMin,regionMax,
ToNative(base.detail),base.roundTunnels,impl_->worldAssembly.get(),
regionErrors[index]))return;
ToNative(base.detail),base.roundTunnels,regionErrors[index]))return;
compiledRegions[index]=std::move(region);
};
struct FAnalyticBuildContext
@@ -1388,40 +1142,19 @@ namespace VoxelForgeCore
compiledRegions[i]=std::move(region);
}
}
for(const auto& region:compiledRegions)
if(region)region->SetSharedDensitySource(impl_->shape.get());
{
std::unordered_map<TileKey,std::shared_ptr<FStandaloneShapeWorld>,TileKeyHash> publish;
publish.reserve(stats.tileKeysCovered);
for(std::size_t i=0;i<pendingRegions.size();++i)
for(const TileKey& key:pendingRegions[i].tiles)
publish.try_emplace(key,compiledRegions[i]);
const std::size_t candidates=publish.size();
std::unique_lock lock(impl_->tileRegionMutex);
impl_->tileRegions.reserve(impl_->tileRegions.size()+candidates);
impl_->tileRegions.merge(publish);
compiledTileCount=candidates-publish.size();
for(std::size_t i=0;i<pendingRegions.size();++i)
{
for(const TileKey& key:pendingRegions[i].tiles)
if(impl_->tileRegions.try_emplace(key,compiledRegions[i]).second)++compiledTileCount;
}
impl_->tileRegionCount.store(impl_->tileRegions.size(),std::memory_order_release);
}
stats.wallSeconds=std::chrono::duration<double>(Clock::now()-compileStart).count();
if(outCompiledTiles)*outCompiledTiles=compiledTileCount;
if(outStats)*outStats=stats;
return true;
}
catch(const std::bad_alloc&)
{
if(outCompiledTiles)*outCompiledTiles=0;
if(outStats)*outStats={};
error="region OOM";
return false;
}
catch(const std::length_error&)
{
if(outCompiledTiles)*outCompiledTiles=0;
if(outStats)*outStats={};
error="region size";
return false;
}
}
void World::retainTileRegions(std::span<const TileKey> desiredTiles)
@@ -1438,17 +1171,14 @@ namespace VoxelForgeCore
}
void World::buildFarWorld()
{ if(impl_&&impl_->shapeReady.load(std::memory_order_acquire)&&impl_->shape)impl_->shape->BuildFarWorld(); }
bool World::isCompiled() const noexcept
{ return impl_&&impl_->shapeReady.load(std::memory_order_acquire); }
bool World::hasFarWorld() const noexcept
{ return impl_&&impl_->shapeReady.load(std::memory_order_acquire)
&&impl_->shape&&impl_->shape->HasFarWorld(); }
{ if(impl_->shape)impl_->shape->BuildFarWorld(); }
bool World::isCompiled() const noexcept { return impl_&&impl_->shape&&impl_->shape->IsBuilt(); }
bool World::hasFarWorld() const noexcept { return impl_&&impl_->shape&&impl_->shape->HasFarWorld(); }
ShapeBuildStats World::buildStats() const
{
ShapeBuildStats out;
if(!impl_||!impl_->shapeReady.load(std::memory_order_acquire)||!impl_->shape)return out;
if(!impl_||!impl_->shape)return out;
const auto& stats=impl_->shape->GetStats();
out.shapeSeconds=stats.ShapeSeconds;out.intervalSeconds=stats.IntervalSeconds;
out.surfaceSeconds=stats.SurfaceSeconds;out.farShapeSeconds=stats.FarShapeSeconds;
@@ -1458,19 +1188,18 @@ namespace VoxelForgeCore
}
float World::densityAt(Vec3d position) const
{ return impl_&&impl_->shapeReady.load(std::memory_order_acquire)&&impl_->shape?impl_->shape->DensityAt(static_cast<float>(position.x),static_cast<float>(position.y),static_cast<float>(position.z)):0.0f; }
{ return impl_&&impl_->shape?impl_->shape->DensityAt(static_cast<float>(position.x),static_cast<float>(position.y),static_cast<float>(position.z)):0.0f; }
float World::unclampedDensityAt(Vec3d position) const
{ return impl_&&impl_->shapeReady.load(std::memory_order_acquire)&&impl_->shape?impl_->shape->DensityAtUnclamped(static_cast<float>(position.x),static_cast<float>(position.y),static_cast<float>(position.z)):0.0f; }
{ return impl_&&impl_->shape?impl_->shape->DensityAtUnclamped(static_cast<float>(position.x),static_cast<float>(position.y),static_cast<float>(position.z)):0.0f; }
DetailFieldSample World::detailSampleAt(Vec3d position) const
{ return impl_&&impl_->shapeReady.load(std::memory_order_acquire)&&impl_->shape?impl_->shape->DetailSampleAt(static_cast<float>(position.x),static_cast<float>(position.y),static_cast<float>(position.z)):DetailFieldSample{}; }
{ return impl_&&impl_->shape?impl_->shape->DetailSampleAt(static_cast<float>(position.x),static_cast<float>(position.y),static_cast<float>(position.z)):DetailFieldSample{}; }
float World::densityAtLattice(Vec3i position) const
{ return impl_&&impl_->shapeReady.load(std::memory_order_acquire)&&impl_->shape?impl_->shape->DensityAtLattice(position.x,position.y,position.z):0.0f; }
{ return impl_&&impl_->shape?impl_->shape->DensityAtLattice(position.x,position.y,position.z):0.0f; }
bool World::isSolidAt(Vec3d position) const { return densityAt(position)<0.0f; }
bool World::isSolidAlongSegment(Vec3d start,Vec3d end,double spacing) const
{
if(!impl_||!impl_->shapeReady.load(std::memory_order_acquire)||!impl_->shape
||!std::isfinite(spacing)||spacing<=0.0)return false;
if(!impl_||!impl_->shape||!std::isfinite(spacing)||spacing<=0.0)return false;
const double dx=end.x-start.x,dy=end.y-start.y,dz=end.z-start.z;
const double length=std::sqrt(dx*dx+dy*dy+dz*dz);
const std::size_t intervals=std::max<std::size_t>(1,static_cast<std::size_t>(std::ceil(length/spacing)));
@@ -1484,7 +1213,7 @@ namespace VoxelForgeCore
TileClass World::classifyBox(Vec3i origin,std::int32_t step,std::int32_t cells) const
{
if(!impl_||!impl_->shapeReady.load(std::memory_order_acquire)||!impl_->shape)return TileClass::mixed;
if(!impl_||!impl_->shape)return TileClass::mixed;
const EVoxelTileClass result=impl_->shape->ClassifyBox(ToNative(origin),step,cells);
return result==EVoxelTileClass::AllSolid?TileClass::allSolid:
result==EVoxelTileClass::AllAir?TileClass::allAir:TileClass::mixed;
@@ -1606,69 +1335,17 @@ namespace VoxelForgeCore
// Les tuiles proches n'avaient aucun conflit; garder leur acces simple et associer les LOD grossiers.
Heightfield2D::setThreadColumnCacheLegacyDirectMapped(
options.legacyDirectMappedColumnCache||key.lod<=2);
if(!impl_||!impl_->owner)
{ error="resolved world snapshot is empty";return std::nullopt; }
const WorldAssemblyRecipeV1* FarRecipe=impl_->worldAssembly?&impl_->worldAssembly->recipe:nullptr;
std::uint32_t FarDisplayBudget=FarRecipe?FarRecipe->farDisplayGeometryBudgetMillipixels:0;
std::uint32_t FarRefinementScale=FarRecipe?FarRecipe->farRefinementGridScale:0;
std::uint32_t FarRefinementLodMask=FarRecipe?FarRecipe->farRefinementLodMask:0;
std::uint32_t FarConnectorStationScale=FarRecipe?FarRecipe->farConnectorStationScale:0;
std::uint32_t FarConnectorRayMask=FarRecipe?FarRecipe->farConnectorRayMask:0;
bool bFarConnectorReuseStationRadii=FarRecipe&&FarRecipe->farConnectorReuseStationRadii;
if(options.overrideFarDisplayMesh)
{
FarDisplayBudget=options.farDisplayGeometryBudgetMillipixels;
FarRefinementScale=options.farRefinementGridScale;
FarRefinementLodMask=options.farRefinementLodMask;
FarConnectorStationScale=options.farConnectorStationScale;
FarConnectorRayMask=options.farConnectorRayMask;
bFarConnectorReuseStationRadii=options.farConnectorReuseStationRadii;
}
const auto ValidFarScale=[](std::uint32_t Value)
{return Value==0||Value==2||Value==4||Value==8;};
if((FarDisplayBudget!=0&&FarDisplayBudget!=1000)
||!ValidFarScale(FarRefinementScale)
||!ValidFarScale(FarConnectorStationScale)
||(FarRefinementLodMask&~0x1f0u)!=0||FarConnectorRayMask>0x0fu
||(FarRefinementScale!=0&&FarRefinementLodMask==0))
{error="far display mesh override is outside the recipe's supported 1 px settings";return std::nullopt;}
const std::uint32_t ActiveFarRefinementScale=FarDisplayBudget==1000
&&(FarRefinementLodMask&(1u<<std::clamp(key.lod,0,31)))!=0
?FarRefinementScale:0;
const int32 ActiveConnectorStationScale=FarDisplayBudget==1000
&&FarConnectorStationScale!=0?static_cast<int32>(FarConnectorStationScale):1;
const uint32 ActiveConnectorRayMask=FarDisplayBudget==1000
&&FarConnectorRayMask!=0?FarConnectorRayMask:0x0fu;
const bool bShapeReady=impl_->shapeReady.load(std::memory_order_acquire);
const bool bNativeOnly=!bShapeReady||options.diagnosticForceNativeOnly;
if(!bShapeReady&&!options.diagnosticForceNativeOnly&&!isTileShapeFree(key))
{error="tile is shape-dependent and must wait for shape compilation";return std::nullopt;}
if(!bNativeOnly&&(!impl_->shape||!impl_->shape->IsBuilt()))
{error="world shape publication is incomplete";return std::nullopt;}
FScopedSharedColumnCaches sharedColumnCaches(options.useSharedColumnCache
?impl_->sharedHeightfieldColumns.get():nullptr,
options.useSharedColumnCache?impl_->sharedIslandColumns.get():nullptr);
if(!impl_||!impl_->owner||!impl_->shape||!impl_->shape->IsBuilt())
{ error="world must be compiled before generating tiles";return std::nullopt; }
const auto& world=*impl_->owner;
FStandaloneShapeWorld nativeOnlyShape;
FIntVector nativeOnlyMinimum,nativeOnlyMaximum;
std::shared_ptr<FStandaloneShapeWorld> page;
if(bNativeOnly)
{
if(!NativeOnlyBoundsForTile(*impl_,key,nativeOnlyMinimum,nativeOnlyMaximum))
{error="shape-free guard: tile has no bounded native-only domain";return std::nullopt;}
if(!options.diagnosticForceNativeOnly&&!isTileShapeFree(key))
{error="shape-free guard: tile failed the native-only readiness proof";return std::nullopt;}
nativeOnlyShape.InitializeNativeSurfaceOnly(*impl_->owner,impl_->worldAssembly.get(),
nativeOnlyMinimum,nativeOnlyMaximum);
}
else if(impl_->tileRegionCount.load(std::memory_order_acquire)!=0)
if(impl_->tileRegionCount.load(std::memory_order_acquire)!=0)
{
std::shared_lock lock(impl_->tileRegionMutex);
if(const auto found=impl_->tileRegions.find(key);found!=impl_->tileRegions.end())
page=found->second;
}
const FStandaloneShapeWorld* tileShapeContext=bNativeOnly?&nativeOnlyShape:
(page?page.get():impl_->shape.get());
const FStandaloneShapeWorld* tileShapeContext=page?page.get():impl_->shape.get();
UVoxelMarchingCubesMesher mesher;
mesher.SetGenerator(world.Generator.get());
mesher.SetGeometryVoxelSizeCm(static_cast<float>(world.CoreVoxelSizeMicrons)/10000.0f);
@@ -1725,12 +1402,6 @@ namespace VoxelForgeCore
}
if(!sharpFeatures.IsEmpty())
{
if(bNativeOnly)
{
nativeOnlyShape.RecordNativeOnlyViolation();
error="shape-free guard: tile intersects a shape feature";
return std::nullopt;
}
// Streamed analytic pages omit the native assembly plan. Use the immutable base
// shape only for tagged tiles so their mesher samples the same field as the tags.
// Les pages analytiques omettent le plan natif ; utiliser la base uniquement pour
@@ -1787,14 +1458,9 @@ namespace VoxelForgeCore
FVoxelMarchingCubesStageTimings McStageTimings;
TileMesh out;out.key=key;
out.diagnostics.featureRefinedResolution=bFeatureRefinedResolution;
if(options.profileMesherStages)
{
out.diagnostics.nativeOnlyRoute=bNativeOnly;
out.diagnostics.analyticRegionPageRoute=page&&page->IsAnalyticOnly();
}
const bool bHasWorldAssembly=impl_->worldAssembly!=nullptr;
const bool bNeedsFarShell=bHasWorldAssembly&&key.lod>=7
&&(tileShape.HasFarWorld()||(bShapeReady&&impl_->shape->HasFarWorld()));
&&(tileShape.HasFarWorld()||impl_->shape->HasFarWorld());
bool bOverlapsPlayerEdit=false;
if(tileShape.HasEditTransaction())
{
@@ -1834,15 +1500,6 @@ namespace VoxelForgeCore
FStandaloneShapeWorld::ResetThreadClassificationStats();
VoxelForgeCore::Heightfield2D::resetThreadColumnCacheStats(
options.captureColumnCoordinates);
if(options.captureColumnCoordinates)
{
constexpr std::int64_t SubvoxelsPerVoxel=WorldAssemblySubvoxelsPerVoxel;
VoxelForgeCore::Heightfield2D::setThreadColumnCaptureBounds(
static_cast<std::int64_t>(origin.X)*SubvoxelsPerVoxel,
static_cast<std::int64_t>(origin.Y)*SubvoxelsPerVoxel,
static_cast<std::int64_t>(origin.X+extent)*SubvoxelsPerVoxel,
static_cast<std::int64_t>(origin.Y+extent)*SubvoxelsPerVoxel);
}
bool bNativeSurfaceTile=false;
bool bNativeSurfaceBandSafe=false;
double classificationColumnComputeMilliseconds=0.0;
@@ -1855,8 +1512,6 @@ namespace VoxelForgeCore
VoxelForgeCore::Heightfield2D::threadColumnCacheStats().columnComputeMilliseconds
-columnMillisecondsBeforeClassification);
bNativeSurfaceTile=Classification.bNativeSurface;
if(options.profileMesherStages)
out.diagnostics.nativeSurfaceTile=bNativeSurfaceTile;
// NativeSurfaceDensityAt consumes only the bounded manifest heightfield and its
// bounded type-2/type-4 features. Unknown tile occupancy does not make that Z support
// unknown; edits and cross-strate tiles are still excluded below.
@@ -1873,8 +1528,7 @@ namespace VoxelForgeCore
}
if((out.diagnostics.tileClass==TileClass::allSolid
||out.diagnostics.tileClass==TileClass::allAir)
&&!options.hashDensity&&!options.captureDensitySamples&&!bNeedsFarShell
&&!options.auditUniformBlockProofs)
&&!options.hashDensity&&!options.captureDensitySamples&&!bNeedsFarShell)
{
out.diagnostics.meshingSkipped=true;
const auto Counts=FStandaloneShapeWorld::GetThreadClassificationStats();
@@ -1890,8 +1544,6 @@ namespace VoxelForgeCore
out.diagnostics.columnCacheHits=Columns.columnHits;
out.diagnostics.columnCacheMisses=Columns.columnMisses;
out.diagnostics.columnCacheConflictMisses=Columns.columnConflictMisses;
out.diagnostics.sharedColumnCacheHits=Columns.sharedColumnHits;
out.diagnostics.columnEvaluations=Columns.columnEvaluations;
out.diagnostics.classificationMilliseconds=Counts.Milliseconds;
out.diagnostics.classificationExclusiveMilliseconds=std::max(0.0,
Counts.Milliseconds-classificationColumnComputeMilliseconds);
@@ -1915,7 +1567,7 @@ namespace VoxelForgeCore
int32 MeshBandMinZVoxel=options.bandMinZVoxel;
int32 MeshBandMaxZVoxel=options.bandMaxZVoxel;
bool bNativeHeightfieldBandLimited=false;
if(bHasWorldAssembly&&bNativeSurfaceBandSafe&&!(page&&page->IsAnalyticOnly())
if(bHasWorldAssembly&&bNativeSurfaceBandSafe
&&!options.hashDensity&&!options.captureDensitySamples&&world.Manager!=nullptr)
{
// La surface 2D et les bornes de volume du manifeste definissent tout le support Z.
@@ -2051,31 +1703,15 @@ namespace VoxelForgeCore
const double ColumnMillisecondsBeforeMeshing=
VoxelForgeCore::Heightfield2D::threadColumnCacheStats().columnComputeMilliseconds;
const auto MarchingCubesStart=std::chrono::steady_clock::now();
FVoxelUniformBlockProofAuditStats BlockProofAudit;
FVoxelMeshData mesh=mesher.GenerateMesh(origin,MeshStep,MeshCells,nullptr,
MeshBandMinZVoxel,MeshBandMaxZVoxel,&sampleCount,nullptr,nullptr,
(options.hashDensity||options.captureDensitySamples)?&densityValues:nullptr,
options.profileMesherStages?&McStageTimings:nullptr,
options.auditUniformBlockProofs?&BlockProofAudit:nullptr,
options.forceFullDensityCapture);
if(options.auditUniformBlockProofs)
{
out.diagnostics.uniformBlockProofsChecked=BlockProofAudit.CheckedBlocks;
out.diagnostics.uniformBlockProofSamplesChecked=BlockProofAudit.CheckedSamples;
out.diagnostics.uniformBlockProofFallbackBlocks=BlockProofAudit.FallbackBlocks;
out.diagnostics.uniformBlockProofUnknownBlocks=BlockProofAudit.UnknownBlocks;
out.diagnostics.uniformBlockProofViolations=BlockProofAudit.Violations;
}
options.profileMesherStages?&McStageTimings:nullptr);
if(bDiagnosticColumnSampling)
{
Heightfield2D::setThreadColumnOctaveDrop(PreviousOctaveDrop);
Heightfield2D::setThreadColumnInterpolationStrideSubvoxels(PreviousInterpolationStride);
}
if(bNativeOnly&&tileShape.GetNativeOnlyViolationCount()!=0)
{
error="shape-free guard caught a mesher read outside the native SurfaceWorld field";
return std::nullopt;
}
const double MarchingCubesWallMilliseconds=std::chrono::duration<double,std::milli>(
std::chrono::steady_clock::now()-MarchingCubesStart).count();
const double ColumnMillisecondsAfterMeshing=
@@ -2110,23 +1746,12 @@ namespace VoxelForgeCore
std::chrono::steady_clock::now()-MeshingStart).count();
out.diagnostics.farHorizonVersion=key.lod>=4?options.farHorizonVersion:0;
const auto FarShellStart=std::chrono::steady_clock::now();
const FStandaloneShapeWorld& farShape=tileShape.HasFarWorld()?tileShape:
(bShapeReady?*impl_->shape:tileShape);
const FStandaloneShapeWorld& farShape=tileShape.HasFarWorld()?tileShape:*impl_->shape;
out.diagnostics.farShellRepairSkipped=bSkipFarShellRepair;
if(farShape.HasFarWorld()&&!bSkipFarShellRepair)
{
const auto BeforeStratum=FStandaloneShapeWorld::GetThreadClassificationStats();
const int32 BeforeStratumTriangles=mesh.Triangles.Num()/3;
std::array<std::uint64_t,6> BeforeStratumColumnCacheStats;
double BeforeStratumColumnComputeMilliseconds;
if(options.profileMesherStages)
{
const auto& Columns=VoxelForgeCore::Heightfield2D::threadColumnCacheStats();
BeforeStratumColumnCacheStats={Columns.pointCalls,Columns.columnHits,
Columns.columnMisses,Columns.columnConflictMisses,
Columns.sharedColumnHits,Columns.columnEvaluations};
BeforeStratumColumnComputeMilliseconds=Columns.columnComputeMilliseconds;
}
const auto StratumStart=std::chrono::steady_clock::now();
AppendFarStratumShells(world,farShape,nativeKey,step,mesh);
const auto AfterStratum=FStandaloneShapeWorld::GetThreadClassificationStats();
@@ -2134,79 +1759,20 @@ namespace VoxelForgeCore
std::chrono::steady_clock::now()-StratumStart).count();
out.diagnostics.farStratumFieldCalls=
AfterStratum.NativeFloatFieldCalls-BeforeStratum.NativeFloatFieldCalls;
if(options.profileMesherStages)
{
const auto& Columns=VoxelForgeCore::Heightfield2D::threadColumnCacheStats();
out.diagnostics.farStratumColumnPointCalls=
Columns.pointCalls-BeforeStratumColumnCacheStats[0];
out.diagnostics.farStratumColumnCacheHits=
Columns.columnHits-BeforeStratumColumnCacheStats[1];
out.diagnostics.farStratumColumnCacheMisses=
Columns.columnMisses-BeforeStratumColumnCacheStats[2];
out.diagnostics.farStratumColumnConflictMisses=
Columns.columnConflictMisses-BeforeStratumColumnCacheStats[3];
out.diagnostics.farStratumSharedColumnCacheHits=
Columns.sharedColumnHits-BeforeStratumColumnCacheStats[4];
out.diagnostics.farStratumColumnEvaluations=
Columns.columnEvaluations-BeforeStratumColumnCacheStats[5];
out.diagnostics.farStratumColumnComputeMilliseconds=
Columns.columnComputeMilliseconds-BeforeStratumColumnComputeMilliseconds;
}
out.diagnostics.farShellTrianglesAdded=static_cast<std::uint64_t>(
std::max(0,mesh.Triangles.Num()/3-BeforeStratumTriangles));
const auto BeforeConnector=AfterStratum;
const int32 BeforeConnectorTriangles=mesh.Triangles.Num()/3;
std::array<std::uint64_t,6> BeforeConnectorColumnCacheStats;
double BeforeConnectorColumnComputeMilliseconds;
if(options.profileMesherStages)
{
const auto& Columns=VoxelForgeCore::Heightfield2D::threadColumnCacheStats();
BeforeConnectorColumnCacheStats={Columns.pointCalls,Columns.columnHits,
Columns.columnMisses,Columns.columnConflictMisses,
Columns.sharedColumnHits,Columns.columnEvaluations};
BeforeConnectorColumnComputeMilliseconds=Columns.columnComputeMilliseconds;
}
const auto ConnectorStart=std::chrono::steady_clock::now();
if(!options.diagnosticRemoveFarConnectorPanels)
AppendFarConnectorShells(farShape,nativeKey,step,world.CoarseTileCells,mesh,
ActiveConnectorStationScale,ActiveConnectorRayMask,
FarDisplayBudget==1000&&bFarConnectorReuseStationRadii);
AppendFarConnectorShells(farShape,nativeKey,step,world.CoarseTileCells,mesh);
const auto AfterConnector=FStandaloneShapeWorld::GetThreadClassificationStats();
out.diagnostics.farConnectorShellMilliseconds=std::chrono::duration<double,std::milli>(
std::chrono::steady_clock::now()-ConnectorStart).count();
out.diagnostics.farConnectorFieldCalls=
AfterConnector.NativeFloatFieldCalls-BeforeConnector.NativeFloatFieldCalls;
if(options.profileMesherStages)
{
const auto& Columns=VoxelForgeCore::Heightfield2D::threadColumnCacheStats();
out.diagnostics.farConnectorColumnPointCalls=
Columns.pointCalls-BeforeConnectorColumnCacheStats[0];
out.diagnostics.farConnectorColumnCacheHits=
Columns.columnHits-BeforeConnectorColumnCacheStats[1];
out.diagnostics.farConnectorColumnCacheMisses=
Columns.columnMisses-BeforeConnectorColumnCacheStats[2];
out.diagnostics.farConnectorColumnConflictMisses=
Columns.columnConflictMisses-BeforeConnectorColumnCacheStats[3];
out.diagnostics.farConnectorSharedColumnCacheHits=
Columns.sharedColumnHits-BeforeConnectorColumnCacheStats[4];
out.diagnostics.farConnectorColumnEvaluations=
Columns.columnEvaluations-BeforeConnectorColumnCacheStats[5];
out.diagnostics.farConnectorColumnComputeMilliseconds=
Columns.columnComputeMilliseconds-BeforeConnectorColumnComputeMilliseconds;
}
out.diagnostics.farShellTrianglesAdded+=static_cast<std::uint64_t>(
std::max(0,mesh.Triangles.Num()/3-BeforeConnectorTriangles));
if(options.diagnosticAuditFarConnectorCoverage)
{
const auto Audit=AuditFarConnectorCoverage(farShape,nativeKey,step,
world.CoarseTileCells,mesh);
out.diagnostics.farConnectorAuditRays=Audit.Rays;
out.diagnostics.farConnectorAuditHoles=Audit.Holes;
out.diagnostics.farConnectorAuditFloating=Audit.Floating;
out.diagnostics.farConnectorAuditHoleIds=Audit.HoleIds;
out.diagnostics.farConnectorAuditFloatingIds=Audit.FloatingIds;
}
}
out.diagnostics.farShellMilliseconds=std::chrono::duration<double,std::milli>(
std::chrono::steady_clock::now()-FarShellStart).count();
@@ -2214,14 +1780,12 @@ namespace VoxelForgeCore
{
const auto HorizonStart=std::chrono::steady_clock::now();
FNativeCapRefinementStats GroundStats;
const int32 ActiveRefinementScale=ActiveFarRefinementScale>1
?static_cast<int32>(ActiveFarRefinementScale):1;
const double ColumnMillisecondsBeforeGround=
VoxelForgeCore::Heightfield2D::threadColumnCacheStats().columnComputeMilliseconds;
const auto GroundStart=std::chrono::steady_clock::now();
if(key.lod>=4)
GroundStats=RefineFarNativeGround(world,*impl_->worldAssembly,nativeKey,step,
options.lod8HorizonInteriorStepVoxels,ActiveRefinementScale,mesh);
options.lod8HorizonInteriorStepVoxels,mesh);
const double GroundWallMilliseconds=std::chrono::duration<double,std::milli>(
std::chrono::steady_clock::now()-GroundStart).count();
const double ColumnMillisecondsAfterGround=
@@ -2234,7 +1798,7 @@ namespace VoxelForgeCore
VoxelForgeCore::Heightfield2D::threadColumnCacheStats().columnComputeMilliseconds;
const auto CapStart=std::chrono::steady_clock::now();
const auto CapStats=RefineFarNativeCap(world,*impl_->worldAssembly,nativeKey,step,
options.lod8HorizonInteriorStepVoxels,ActiveRefinementScale,mesh);
options.lod8HorizonInteriorStepVoxels,mesh);
const double CapWallMilliseconds=std::chrono::duration<double,std::milli>(
std::chrono::steady_clock::now()-CapStart).count();
const double ColumnMillisecondsAfterCap=
@@ -2265,8 +1829,6 @@ namespace VoxelForgeCore
out.diagnostics.columnCacheHits=Columns.columnHits;
out.diagnostics.columnCacheMisses=Columns.columnMisses;
out.diagnostics.columnCacheConflictMisses=Columns.columnConflictMisses;
out.diagnostics.sharedColumnCacheHits=Columns.sharedColumnHits;
out.diagnostics.columnEvaluations=Columns.columnEvaluations;
out.diagnostics.columnComputeMilliseconds=Columns.columnComputeMilliseconds;
out.diagnostics.columnEvaluationExclusiveMilliseconds=Columns.columnComputeMilliseconds;
out.diagnostics.classificationMilliseconds=Counts.Milliseconds;
+11 -100
View File
@@ -5,7 +5,6 @@
#include "VoxelForgeCore/VoxelForgeCore.h"
#include <algorithm>
#include <atomic>
#include <bit>
#include <charconv>
#include <chrono>
@@ -122,9 +121,6 @@ WorldAssemblyFeatureColumnRangeV1 BuildWorldAssemblyFeatureColumnRangeV1(
namespace world_assembly_detail
{
using FSharedHeightfieldColumnCache =
VoxelForgeCoreShared::TSharedColumnValueCache<HeightfieldPointSample,131072,4>;
// Preserve recipe order without allocating or looking up metadata in the point loop.
// Garder l'ordre de recette sans allocation ni recherche de metadonnees par point.
struct FeatureRange
@@ -244,24 +240,6 @@ namespace world_assembly_detail
|| recipe.biomeBorderBlendSubvoxels < 0
|| recipe.biomeBorderBlendSubvoxels > recipe.biomeCellSizeSubvoxels)
{ error = "world assembly biome-map parameters are outside the supported fixed-scale range"; return false; }
if (recipe.evaluatorVersion >= 7)
{
constexpr std::uint32_t FarLodMask = 0x1f0u; // LOD4..8.
const bool anyFarSetting = recipe.farDisplayGeometryBudgetMillipixels != 0
|| recipe.farRefinementGridScale != 0 || recipe.farRefinementLodMask != 0
|| recipe.farConnectorStationScale != 0 || recipe.farConnectorRayMask != 0
|| recipe.farConnectorReuseStationRadii;
const auto validScale = [](std::uint32_t value)
{ return value == 0 || value == 2 || value == 4 || value == 8; };
if ((anyFarSetting && recipe.farDisplayGeometryBudgetMillipixels != 1000)
|| recipe.farDisplayGeometryBudgetMillipixels > 1000
|| !validScale(recipe.farRefinementGridScale)
|| (recipe.farRefinementLodMask & ~FarLodMask) != 0
|| !validScale(recipe.farConnectorStationScale)
|| recipe.farConnectorRayMask > 0x0fu
|| (recipe.farRefinementGridScale != 0 && recipe.farRefinementLodMask == 0))
{ error = "far display mesh declaration must use the 1 px budget and supported LOD, scale, and ray values"; return false; }
}
std::vector<std::uint32_t> ids;
ids.reserve(recipe.biomes.size());
for (const auto& biome : recipe.biomes)
@@ -449,16 +427,6 @@ namespace world_assembly_detail
HashWord(hash, static_cast<std::uint64_t>(recipe.biomeClimateMoistureWavelengthSubvoxels), 8);
HashWord(hash, static_cast<std::uint64_t>(recipe.biomeClimateReliefContrastQ16), 8);
}
if (recipe.evaluatorVersion >= 7)
{
HashWord(hash, 0x4641524449535037ull, 8);
HashWord(hash, recipe.farDisplayGeometryBudgetMillipixels, 4);
HashWord(hash, recipe.farRefinementGridScale, 4);
HashWord(hash, recipe.farRefinementLodMask, 4);
HashWord(hash, recipe.farConnectorStationScale, 4);
HashWord(hash, recipe.farConnectorRayMask, 4);
HashWord(hash, recipe.farConnectorReuseStationRadii ? 1u : 0u, 1);
}
HashWord(hash, recipe.biomes.size(), 4);
for (const auto& biome : recipe.biomes)
{
@@ -669,16 +637,6 @@ namespace world_assembly_detail
|| !ReadInteger(value.Get("climate_moisture_wavelength_q"), recipe.biomeClimateMoistureWavelengthSubvoxels)
|| !ReadInteger(value.Get("climate_relief_contrast_q16"), recipe.biomeClimateReliefContrastQ16)))
{ error = "world assembly recipe is missing evaluator-2 climate parameters"; return false; }
if (recipe.evaluatorVersion >= 7
&& (!ReadU32(value.Get("far_display_budget_millipixels"), recipe.farDisplayGeometryBudgetMillipixels)
|| !ReadU32(value.Get("far_refinement_grid_scale"), recipe.farRefinementGridScale)
|| !ReadU32(value.Get("far_refinement_lod_mask"), recipe.farRefinementLodMask)
|| !ReadU32(value.Get("far_connector_station_scale"), recipe.farConnectorStationScale)
|| !ReadU32(value.Get("far_connector_ray_mask"), recipe.farConnectorRayMask)
|| !std::holds_alternative<bool>(value.Get("far_connector_reuse_station_radii").Data)))
{ error = "world assembly recipe is missing evaluator-7 far display mesh parameters"; return false; }
if (recipe.evaluatorVersion >= 7)
recipe.farConnectorReuseStationRadii = std::get<bool>(value.Get("far_connector_reuse_station_radii").Data);
for (const auto& item : value.Get("biomes").AsArray())
{
WorldAssemblyBiomeProfileV1 biome;
@@ -740,14 +698,6 @@ namespace world_assembly_detail
out << ",\"climate_relief_wavelength_q\":" << recipe.biomeClimateReliefWavelengthSubvoxels
<< ",\"climate_moisture_wavelength_q\":" << recipe.biomeClimateMoistureWavelengthSubvoxels
<< ",\"climate_relief_contrast_q16\":" << recipe.biomeClimateReliefContrastQ16;
if (recipe.evaluatorVersion >= 7)
out << ",\"far_display_budget_millipixels\":" << recipe.farDisplayGeometryBudgetMillipixels
<< ",\"far_refinement_grid_scale\":" << recipe.farRefinementGridScale
<< ",\"far_refinement_lod_mask\":" << recipe.farRefinementLodMask
<< ",\"far_connector_station_scale\":" << recipe.farConnectorStationScale
<< ",\"far_connector_ray_mask\":" << recipe.farConnectorRayMask
<< ",\"far_connector_reuse_station_radii\":"
<< (recipe.farConnectorReuseStationRadii ? "true" : "false");
out << ",\"content_hash\":\"" << HashText(recipe.contentHash) << "\",\"biomes\":[";
for (std::size_t i = 0; i < recipe.biomes.size(); ++i)
{
@@ -1425,9 +1375,6 @@ namespace world_assembly_detail
std::array<std::uint8_t, HeightfieldColumnCacheSetCount>> HeightfieldColumnCacheNextWay;
inline thread_local HeightfieldColumnCacheStats HeightfieldColumnStats{};
inline thread_local bool HeightfieldColumnCacheLegacyDirectMapped=false;
inline thread_local std::array<std::int64_t,4> HeightfieldColumnCaptureBounds{};
inline thread_local bool HeightfieldColumnCaptureBoundsValid=false;
inline std::atomic<std::uint64_t> HeightfieldColumnCaptureSequence{0};
inline std::size_t HeightfieldColumnCacheSet(const WorldAssemblyRecipeV1& recipe,
const WorldAssemblyStratumPlanV1& plan,std::int64_t x,std::int64_t y) noexcept
@@ -1640,46 +1587,22 @@ namespace world_assembly_detail
replacement=&cache[first+replacementWay];
}
auto& entry=*replacement;
const auto start=std::chrono::steady_clock::now();
HeightfieldPointSample column=EvaluateColumn(recipe,plan,x,y);
HeightfieldColumnStats.columnComputeMilliseconds+=std::chrono::duration<double,std::milli>(
std::chrono::steady_clock::now()-start).count();
++HeightfieldColumnStats.columnMisses;
const auto compute=[&]()
if(HeightfieldColumnStats.captureCoordinates&&HeightfieldColumnStats.coordinateCaptureComplete)
{
const std::uint64_t sequence=HeightfieldColumnStats.captureCoordinates
?HeightfieldColumnCaptureSequence.fetch_add(1,std::memory_order_relaxed):0;
const auto start=std::chrono::steady_clock::now();
HeightfieldPointSample result=EvaluateColumn(recipe,plan,x,y);
HeightfieldColumnStats.columnComputeMilliseconds+=std::chrono::duration<double,std::milli>(
std::chrono::steady_clock::now()-start).count();
++HeightfieldColumnStats.columnEvaluations;
if(HeightfieldColumnStats.captureCoordinates
&&HeightfieldColumnStats.coordinateCaptureComplete)
try
{
try
{
const bool outside=HeightfieldColumnCaptureBoundsValid
&&(x<HeightfieldColumnCaptureBounds[0]||x>HeightfieldColumnCaptureBounds[2]
||y<HeightfieldColumnCaptureBounds[1]||y>HeightfieldColumnCaptureBounds[3]);
HeightfieldColumnStats.evaluatedCoordinates.push_back({x,y,sequence,outside});
}
catch(...)
{
HeightfieldColumnStats.coordinateCaptureComplete=false;
}
HeightfieldColumnStats.evaluatedCoordinates.push_back({x,y});
}
catch(...)
{
HeightfieldColumnStats.coordinateCaptureComplete=false;
}
return result;
};
HeightfieldPointSample column{};
if(auto* shared=FSharedHeightfieldColumnCache::threadActive())
{
const VoxelForgeCoreShared::FColumnCacheKey key{
static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(&recipe)),
recipe.contentHash,
static_cast<std::uint64_t>(reinterpret_cast<std::uintptr_t>(&plan)),
plan.contentHash,x,y};
bool computed=false;
column=shared->getOrCompute(key,compute,computed);
if(!computed)++HeightfieldColumnStats.sharedColumnHits;
}
else column=compute();
entry={&recipe,&plan,recipe.contentHash,plan.contentHash,x,y,column};
return column;
}
@@ -2164,22 +2087,10 @@ void Heightfield2D::resetThreadColumnCacheStats(bool captureCoordinates, bool cl
Stats.columnHits=0;
Stats.columnMisses=0;
Stats.columnConflictMisses=0;
Stats.sharedColumnHits=0;
Stats.columnEvaluations=0;
Stats.columnComputeMilliseconds=0.0;
Stats.captureCoordinates=captureCoordinates;
Stats.coordinateCaptureComplete=true;
Stats.evaluatedCoordinates.clear();
world_assembly_detail::HeightfieldColumnCaptureBoundsValid=false;
}
void Heightfield2D::setThreadColumnCaptureBounds(std::int64_t minimumXSubvoxels,
std::int64_t minimumYSubvoxels,std::int64_t maximumXSubvoxels,
std::int64_t maximumYSubvoxels) noexcept
{
world_assembly_detail::HeightfieldColumnCaptureBounds={minimumXSubvoxels,
minimumYSubvoxels,maximumXSubvoxels,maximumYSubvoxels};
world_assembly_detail::HeightfieldColumnCaptureBoundsValid=true;
}
void Heightfield2D::setThreadColumnCacheLegacyDirectMapped(bool enabled) noexcept
@@ -1,115 +0,0 @@
# Linux10 — startup and region crossing
**Result:** no world-generation optimization was shipped. The dominant spawn gate is full shape compilation; the current Core API does not let tiles consume a partially built shape safely. L10 adds opt-in phase and crossing telemetry to the headless research path.
Runs used CPUs 0–11, normal priority, at most `-j12`, a 6 GiB address-space cap, and the unchanged `powersave` governor. Peak monitored RSS was 624,996 KiB (610.3 MiB). Final builds: Clang 19 with FP contraction off, SHA-256 `7d5360e2baa637f8b2b4679df9616580bffe689afd101470e311260f0ecd4975`; GCC 14 default, `5041cf15019766f453eb59fe8ff7fc4cd98ca6a904208b645e3d7ca4584e1195`. The L9 Clang timing/hash baseline is `Standalone/bin/linux/VoxelForgeCoreHeadless-linux9-clang`, SHA-256 `0cd3f0ef993ced2c615418c6e2b37b83f57eff6d024d7d1568c30ea51490384a`.
## 1. Startup phases
SurfaceWorld seed 0, W12, no hash; five runs on the optimized Clang build. Wall and process CPU are medians. Process CPU sums work across threads. First-tile time is from cold start; its CPU column is CPU since pool start.
| Phase | Wall ms | Process CPU ms | Threads used |
|---|---:|---:|---|
| Owner data load and resolve | 5.05 | 5.05 | 1 |
| Assembly plan build | 51.04 | 51.03 | 1 |
| Core snapshot | 0.53 | 0.54 | 1 |
| First desired-set build, 2,553 tiles | 0.74 | 0.74 | 1 |
| Shape request setup | 0.03 | 0.03 | 1 |
| Shape compile | 222.59 | 856.79 | caller + up to 8 scheduler workers |
| Streamer setup | 0.01 | 0.01 | 1 |
| Worker-pool start | 0.41 | 1.27 | 12 requested; 8–11 had entered at print |
| First tile starts at 299.62 ms | — | 1.59 since pool start | 12/12 entered |
Shape-compile wall ranged 215.89–324.88 ms; first tile started at 286.56–409.76 ms. Owner load, plan, local shape setup, and far-parent construction are serial. Before the pool starts, there are no sleeping stream workers, but most of the 12 allowed CPUs are unused. During the interval and detail-band phases the scheduler uses at most 8 workers, leaving up to 4 CPUs unused.
The phase-trace mode’s whole-view median was 1.436 s, versus 1.372 s with tracing off. The phase runs are for decomposition only; the performance ranking and A/B below use the optimized build with tracing disabled and hashing off. In that flag-off path, shape wall time was 0.222 s median, consistent with the phase trace.
## 2. Shape contents and first-tile dependencies
| Shape phase | Wall ms | Process CPU ms | Work / concurrency |
|---|---:|---:|---|
| Local owner shapes and spatial bins | 40.46 | 40.44 | Extracts owner primitives; 1 thread |
| Rock intervals, signs, candidate bands | 40.20 | 187.14 | Packed column signs and candidate masks; up to 8 workers |
| Detail band and sign-edge distances | 81.00 | 568.78 | Applies coherent detail to candidate nodes and builds distance proxies; up to 8 workers |
| Route validation and shared-field setup | 1.12 | 1.13 | 5,642 passage samples; then shared primitive form |
| Far parents and bins | 55.56 | 55.57 | 6,050 far rooms / 18,348 links; 1 thread |
The compile extracts 18,348 owner primitives (71 rooms, 74 tunnels, 2 passages), covers 138,188,413 sign nodes, allocates 36.71 MiB of packed words and 263.57 MiB of proxy address capacity, and visits 214,538 detail candidates (6,098 flips).
For this SurfaceWorld fixture, the first LOD0 tile’s density queries take the native `Heightfield2D` path before packed-shape lookup. Far-parent shapes are not needed by that first tile. However, `World::generateTile` rejects requests until the full base shape is marked built, and `compileTileRegion` also requires that base shape. So the current API gates the near tile on the interval, detail, validation, and far-parent work even when that tile does not sample those arrays. Other recipes and fallback/query paths do use the analytic primitives and packed signs/proxies.
There is no seed-independent owner shape payload to cache at build time. The assembly plan is built from owner data; region pages also re-run owner primitive extraction, spatial-bin construction, and shared-field packing. Those immutable owner-derived structures are a possible per-world reuse target, but the measured short crossings below built no pages, so this run does not price that work.
## 3. Moving crossing
Hashing off, W12, same camera and already-streamed initial view. Region compile was called, but all entering fine keys were covered by the initial shape bounds; it built zero regions.
| Camera step | New tiles | LOD breakdown | Region compile | Tile work wall | Crossing total |
|---|---:|---|---:|---:|---:|
| 8 m | 144 | LOD2: 128, LOD3: 16 | 0.010 ms | 12.61 ms | 12.81 ms |
| 16 m | 288 | LOD0: 128, LOD1: 16, LOD2: 128, LOD3: 16 | 0.010 ms | 60.49 ms | 60.68 ms |
The 16 m crossing’s worker-time sum was 633 ms; its wall time was 60.5 ms. No plan or full shape compile repeated. A 24 m attempt terminated with `std::bad_alloc` after base shape compilation and before crossing metrics; the failing allocation site is unknown.
## 4. Ranked levers
| Rank | Lever | Upper bound from these measurements | Assessment |
|---:|---|---|---|
| 1 | Overlap near-tile work with shape compilation | 222.6 ms, 16.2% of 1.372 s whole-view-ready; first tile could start earlier by up to the compile time | Largest opportunity. Not built: tiles and region compilation currently require a fully built base shape. A safe version needs immutable partial-page publication and a wait before any tile reads an unfinished sign, proxy, primitive bin, or far field. |
| 2 | Defer far-parent construction until far tiles need it | 55.6 ms, at most 4.1% of whole-view-ready and 18.6% of the first-tile delay | Could improve spawn, but far and near paths share mutable spatial-bin state today. Needs separate immutable bins and a synchronized readiness state; no crossing benefit was measured. |
| 3 | Parallelize assembly-plan construction | 51.0 ms, at most 3.7% of whole-view-ready | Serial and seed/owner-specific. No safe deterministic parallel split was established. |
| 4 | Raise shape scheduler cap from 8 to 12 | About 121 ms currently lies in the two worker phases; ideal linear scaling saves about 40 ms (2.9% of whole-view-ready) | Below the 3% bar before overhead, and no crossing benefit. Not built. |
For any future partial or deferred build, hashes can fail if a tile observes a partially written sign/proxy array, if region publication races with tile lookup, or if shared bins change while a tile is sampling. The page must be immutable before publication; worker-count and timing tests must compare W1 with W12 and repeat W12. Any asynchronous result must also follow the Epoch/MPSC shutdown-drain rules.
## 5. Final-build timing and hashes
Five interleaved W12 runs, no hash. Pair values are `whole_view_ready / stream_wall` in seconds.
| Pair | L9 `7650abb` Clang | L10 Clang | Delta, ms |
|---:|---:|---:|---:|
| 1 | 1.336 / 1.050 | 1.346 / 1.060 | +10 / +10 |
| 2 | 1.351 / 1.062 | 1.365 / 1.073 | +14 / +11 |
| 3 | 1.359 / 1.073 | 1.374 / 1.083 | +15 / +10 |
| 4 | 1.363 / 1.077 | 1.375 / 1.081 | +12 / +4 |
| 5 | 1.387 / 1.089 | 1.372 / 1.092 | −15 / +3 |
| **Median** | **1.359 / 1.073** | **1.372 / 1.081** | **+13 / +8** |
The measurement-only candidate is +1.0% whole-view-ready and +0.7% stream median; this is no demonstrated speedup. Hashing was off for these timings.
Final rebuilt binaries passed SurfaceWorld and FloatingIslands seed-0 hash checks at W1, W8, and five W12 runs per compiler: Clang FP contraction off and GCC default. Every full-detail, whole-view, LOD0–8, and exact-query row matches the compiler-matched L9 baseline. Audit files: `Saved/Linux/l10_final_surface_hash_audit.txt` and `Saved/Linux/l10_islands_hash_audit.txt`.
| Recipe / scope | Density | Mesh | Payload | Topology |
|---|---|---|---|---|
| SurfaceWorld full detail | `0x0ee0579bd15cbbe4` | `0x32e5d4964d610fee` | `0x1932b96ee4b1d910` | `0x69743c6bad3447dc` |
| SurfaceWorld whole view | `0xc10697a8f48380c7` | `0xe75c9119a1498cd5` | `0x49a9a8d1835a6c8c` | `0xedcb23288b5e8724` |
| FloatingIslands full detail | `0x6d842d2878b08ef6` | `0x4b868a3184f08035` | `0x2cedf2236788752d` | `0xeac17d5e0cb5044a` |
| FloatingIslands whole view | `0x5be4d8cde79b2a76` | `0x96f75041f6861b3a` | `0x3700a516cc89d50c` | `0x6b99948d6eab4f21` |
Exact-query hashes also match: SurfaceWorld density `0xe4d4a8eb95b35933`, detail `0xefcba20c0c70c415`, collision `0xe604823a249029bf`; FloatingIslands density `0x61daded9c303becb`, detail `0xefcba20c0c70c415`, collision `0x84d37463be9b0573`.
## 6. Failed or retried runs
- One phase smoke omitted the explicit owner-data path and resolved it under `Standalone/bin/data`; reran with `Standalone/data/owner_world.json`.
- A no-camera phase smoke produced 2,370 tiles instead of the 2,553-tile fixture; discarded it and reran with the fixed camera.
- A malformed `--workers=w8` command exited during argument parsing; reran with numeric `--workers=8`.
- The first FloatingIslands matrix invocation omitted the three required streaming-mode switches. All 14 attempts exited before generation; corrected the command and all 14 final runs passed.
- The 24 m crossing attempt failed with `std::bad_alloc` as described above.
- The first hash-audit parser expected 13 rows; the actual audit contains 12 scopes. Corrected the parser and all final comparisons passed.
At spawn, the first tile starts about 300 ms after cold start, with roughly 223 ms in full shape compilation and 51 ms in the single-threaded plan; this round did not make that wait shorter. While moving, the 16 m crossing completed 288 entering tiles in about 61 ms and repeated no shape compile, so the measured delay was tile work rather than region setup.
## Orchestrator review (Claude)
- **Not committed:** the L10 telemetry code. It is +1.0% whole-view median with tracing off (4 of 5
pairs slower), and the rule is zero cost when off. Saved as `Saved/Linux/claude/l10-telemetry.patch`
(gitignored) for reuse; the tree is reset to `7650abb`.
- **Key finding, for L11:** the first SurfaceWorld tiles take the native `Heightfield2D` path and don't
read the cave shape, yet `World::generateTile` waits for the full base shape (~223 ms). A per-tile
readiness check (start tiles whose recipe path provably never touches shape arrays) is lever #1 in
safe form.
- **Open bug, for L11:** the 24 m crossing died with `std::bad_alloc` under the 6 GiB **address-space**
cap (`RLIMIT_AS`). That cap counts reservations, not resident memory; L10 also reports 263.57 MiB
of proxy address *capacity*. It is not yet known whether this is a real memory blow-up on larger
crossings or the cap counting reserved address space. L7's 32 m step also hit the 160M-node
interval bound.
@@ -1,74 +0,0 @@
# VoxelForge L11 — Linux report
## 24 m crossing crash
The crash is real. The original binary threw `std::bad_alloc` after base shape compilation with both 6 GiB and 16 GiB `RLIMIT_AS`; the 16 GiB run peaked at 476,128 KiB RSS and 1,542,284 KiB virtual size. The allocation trace identifies a 432,345,551,342,665,824-byte resize in `BuildSpatialBins`, reached from `BuildAnalyticRegion` during `World::compileTileRegion`. The crossing code had coalesced disjoint entering tiles into a large LOD rectangle and tried to allocate dense per-axis bins that the analytic fallback never reads. L10's 263.57 MiB figure is the proxies' reserved virtual capacity; RSS samples record resident usage separately.
Analytic regions now skip those dense bins and compile in world-aligned 128-voxel pages. Pages are built privately and published together; coordinate, `bad_alloc`, and size failures return errors before partial pages are published. On the final L11 binary, 24 m and 32 m both passed (16 pages each); 1,000 m passed with 2,260 entering keys, 72 pages, 63 ms region-build wall time, 700,232 KiB peak RSS, and 2,578,588 KiB peak virtual size. The fixed 24 m run peaked at 533,420 KiB RSS and 2,578,588 KiB virtual size. Crossing pages build no packed interval nodes (`lattice_nodes=0`) and do not expand the immutable base sign/proxy arrays; they add analytic primitive/bin data. `retainTileRegions` prunes pages outside the desired set. The largest empirically verified step is 1,000 m. Work follows the destination's entering tile set; once the old and new views are disjoint, its page count stays bounded by the active view as travel distance increases. Keys outside Core's signed 32-bit voxel range are rejected with `tile region coordinate is out of range` before page construction. The earlier L7 32 m / 160-million-node failure was the same unbounded region geometry.
| Step | Entering keys | Pages | Added interval nodes | Base proxy nodes / virtual capacity |
|---:|---:|---:|---:|---:|
| 24 m | 432 | 16 | 0 | 185,024 / 263.57 MiB |
| 1,000 m | 2,260 | 72 | 0 | 185,024 / 263.57 MiB |
## Shape readiness
`isTileShapeFree` accepts only LOD0 tiles whose padded mesh box maps to one valid SurfaceWorld plan, excludes FloatingIslands, plan features, routes, passages, edits, and overlaps with owner shape primitives or detail bounds. This covers the MC skirt and sample margin. Higher LODs are conservatively shape-dependent; the accepted path cannot use far parents. The native-only context is initialized without building sign arrays, proxies, owner primitive vectors, or spatial bins. Native sampling and classification paths check the padded bounds, reject unsupported fallbacks, and count any attempted shape-dependent read; tile generation then fails instead of returning a partial mesh.
The SurfaceWorld spawn view proved 27/27 near-ring tiles shape-free. A deliberately mis-marked distant tile `(0,0,100000,lod0)` reached the sampler and was rejected by the guard. After shape publication, native-only and full-shape generation matched all four hashes for all 27 tiles. Shape-dependent tiles waited for the release-published shape; tile jobs continue through the existing Epoch and MPSC result path, and published shape/page data is immutable. The FloatingIslands spawn proof accepted 0/27 tiles, so all waited for its shape. Slow-shape delay defaults to zero; audit and negative-control work is opt-in.
## No-hash timing pairs
Five interleaved W12 pairs, camera `0,-35,-487.94`, seed 0, Clang `-ffp-contract=off`, hashing off. Times are from process start. The L9 executable does not emit a first-tile completion event and starts tile workers only after shape compilation; its first-tile cell is therefore unavailable.
| Pair | First tile L9 / L11 | Near ring L9 / L11 | Whole view L9 / L11 |
|---:|---:|---:|---:|
| 1 | — / 153 ms | 343 / 166 ms | 1,439 / 1,429 ms |
| 2 | — / 160 ms | 424 / 173 ms | 1,526 / 1,447 ms |
| 3 | — / 145 ms | 347 / 163 ms | 1,447 / 1,443 ms |
| 4 | — / 146 ms | 353 / 170 ms | 1,457 / 1,449 ms |
| 5 | — / 153 ms | 376 / 173 ms | 1,478 / 1,464 ms |
| Median | — / 153 ms | 353 / 170 ms | 1,457 / 1,447 ms |
The delayed maximum-overlap W12 run held shape compilation for 1.5 s: first tile 133 ms, near ring 166 ms, shape ready 1.696 s. Shape-free and full-shape near-ring hashes matched, and whole-view, full-detail, per-LOD, and exact-query hashes matched the baseline.
## Hashes
All 28 configurations passed against L10's committed `b370908` baseline: SurfaceWorld and FloatingIslands, seed 0, W1/W8/W12, Clang `-ffp-contract=off` and GCC default, with five W12 repeats per compiler and recipe. Each run matched all 12 rows: full-detail, whole-view, nine LODs, and exact queries. The delayed-overlap run also matched.
| Recipe | Full-detail density / mesh / payload / topology | Whole-view density / mesh / payload / topology | Exact-query density & unclamped / detail / collision |
|---|---|---|---|
| SurfaceWorld | `0x0ee0579bd15cbbe4` / `0x32e5d4964d610fee` / `0x1932b96ee4b1d910` / `0x69743c6bad3447dc` | `0xc10697a8f48380c7` / `0xe75c9119a1498cd5` / `0x49a9a8d1835a6c8c` / `0xedcb23288b5e8724` | `0xe4d4a8eb95b35933` / `0xefcba20c0c70c415` / `0xe604823a249029bf` |
| FloatingIslands | `0x6d842d2878b08ef6` / `0x4b868a3184f08035` / `0x2cedf2236788752d` / `0xeac17d5e0cb5044a` | `0x5be4d8cde79b2a76` / `0x96f75041f6861b3a` / `0x3700a516cc89d50c` / `0x6b99948d6eab4f21` | `0x61daded9c303becb` / `0xefcba20c0c70c415` / `0x84d37463be9b0573` |
The per-LOD D/M/P/T rows match exactly in every configuration; the complete comparison is recorded in `Saved/Linux/l11_hash_audit.txt`.
## Failed and retried runs
- The 24 m reproduction failed with `std::bad_alloc` under both address-space caps (`l11-cross24-as6g.log`, `l11-cross24-as16g.log`); the allocation trace above isolated the oversized bin resize. Final-binary 24 m, 32 m, and 1,000 m reruns passed (`l11-final-cross-24m.log`, `l11-final-cross-32m.log`, `l11-final-cross-1000m.log`).
- The first readiness proof admitted 512 LOD0 keys (`l11-readiness-audit.log`, `l11-readiness-audit2.log`). Although the 27 near-ring equivalence check passed, distant owner-shape tiles changed the whole-view density hash. Tightening the proof to test owner primitive bounds reduced early admission to the 27 safe near-ring tiles and restored every hash (`l11-readiness-audit-final.log`).
- One rebuilt audit invocation omitted the owner JSON path and exited 2 before generation (`l11-readiness-audit-path-error.log`; `Standalone/bin/data/owner_world.json` was missing). It was rerun with `Standalone/data/owner_world.json` and passed.
- The required hash matrix and five timing pairs had no failed runs. All monitored run processes stayed below the 6,000,000,000-byte RSS ceiling; governor remained `powersave`.
The standalone Core/headless builds passed with Clang and GCC. The Unreal adapter change was source-reviewed but could not be built here because UnrealBuildTool/UnrealEditor are not installed on this Linux machine.
At spawn on SurfaceWorld, the near ring is ready at a 170 ms median versus 353 ms on L9, and the first L11 tile is ready at 153 ms median before shape publication; L9 gates tile work on shape compilation and does not report that milestone. For fast movement, destination-page work stays bounded through the tested 1 km crossing, while invalid Core coordinates return an error before allocation.
## Orchestrator review (Claude)
- **Re-run by me, 5 interleaved W12 pairs, no hashing.** Near ring (`neighborhood_ready`) L9
0.338/0.338/0.337/0.326/0.334 s vs L11 0.159/0.159/0.167/0.169/0.159 s (median 0.337 → 0.159 s,
−53%). Whole view 1.337 → 1.365 s median (+2.1%, 4 of 5 pairs slower): a small cost, accepted for a
2× faster spawn ring. W12 hash runs give density `c10697a8f48380c7`.
- **Crossings re-run by me on L11** (`--region-crossing --camera-step=S,0,0`): 24 m gives 432 tiles,
0.867 s wall, 10.05 worker-s, rc 0; 1,000 m gives 2,260 tiles, 5.90 s wall, 70.4 worker-s, rc 0. The L9
binary lacks the option, so the original crash rests on Luna's reproduction and allocation trace.
- **New finding, for L12:** the 24 m crossing costs ~23 ms of work per tile, against ~2 ms for L10's 16 m
crossing (288 tiles, 0.633 worker-s). Tiles outside the base shape bounds, served from analytic
region pages, look about 10× more expensive. That is a moving-player cost.
- **Concurrency read:** `World::compile` builds the shape privately, then sets `impl_->shape` and
`buildRequest` before a release store of `shapeReady`. Every shape reader acquire-checks
`shapeReady` first (short-circuit), and shape-free tiles use a private native-only context. Sound.
- **Unreal:** `Source/VoxelForge/Private/VoxelWorld.cpp` changed (compile outside the writer lock;
proven shape-free tiles start before `bReady`). It is NOT compiled here, so it must be built on the
owner's PC before it is trusted in game.
@@ -1,62 +0,0 @@
# VoxelForge L12 — Linux report
Governor stayed `powersave`. Builds and runs used CPUs 0–11, at most 12 jobs, a 6 GiB address-space cap, and RSS monitors. Clang and GCC builds passed; peak sampled RSS was 881 MiB for one GCC compiler process and 679 MiB for the 1 km crossing. The GCC build process group peaked at 4.35 GiB. No Unreal adapter files changed.
## LOD cost and change
The 24 m profile is like-for-like at LOD1 in the same SurfaceWorld crossing. L11 generated 160 LOD1 tiles: 32 base-shape tiles averaged 2.73 ms each, while 128 analytic-page tiles averaged 71.72 ms. Of the LOD1 worker time, 9.06 of 9.27 seconds went to the marching-cubes density grid; the page compiler added 15 ms and built no packed lattice nodes. The page route lacked the manifest input needed for the exact LOD1 block proofs. Across all 160 LOD1 tiles, the sample counter reported 5.64 million density samples, or 35,271 per tile.
Analytic pages now retain the immutable shared manifest for block classification while continuing to sample the legacy density field. The proof audit checked 27,479 blocks and 36,574,549 samples, with zero violations. On the plain 24 m profile, page-backed LOD1 fell to 5.60 ms per tile; all 160 LOD1 tiles reported 432,000 samples (2,700 per tile) and 435 ms in density-grid work. Base LOD1 tiles averaged 2.51 ms, so page tiles are now about 2.2× their base cost. No base-shape bounds changed; pages remain privately built, immutably published, and bounded, with 16 pages at 24/32 m and 72 at 1 km.
## Plain W12 crossings
Worker time is the sum across tile workers; per-tile values use that sum. L11 values are from the L11 executable and logs. L12 values include region compilation in wall time.
| Step | Tiles | L11 wall / worker-s / ms per tile | L12 wall / worker-s / ms per tile |
|---:|---:|---:|---:|
| 8 m | 144 | 0.038 s / 0.381 / 2.65 | 0.035 s / 0.360 / 2.50 |
| 16 m | 288 | 0.831 s / 9.476 / 32.90 | 0.125 s / 1.096 / 3.80 |
| 24 m | 432 | 0.869 s / 9.912 / 22.95 | 0.164 s / 1.596 / 3.69 |
| 32 m | 576 | 0.898 s / 10.261 / 17.81 | 0.172 s / 1.691 / 2.94 |
| 1 km | 2,260 | 5.892 s / 69.534 / 30.77 | 1.247 s / 14.003 / 6.20 |
All five L12 steps passed; peak crossing RSS was 679 MiB. The 8 m L11 comparison is `l12-baseline-8m-page.log`; 16 m is `l12-baseline-16m-page.log`; 24 m, 32 m, and 1 km are the L11 final crossing logs.
## Spawn and hashes
Three plain W12 spawn runs had medians of 146 ms first tile, 161 ms near ring, and 1.361 s whole view. L11 medians were 153 ms, 170 ms, and 1.447 s.
All 28 requested L1 hash configurations matched L11: SurfaceWorld and FloatingIslands seed 0, Clang `-ffp-contract=off` and GCC default, W1/W8/W12, with five W12 repeats. Every run matched all 12 rows: full detail, whole view, nine LODs, and exact queries. Clang/GCC full-detail and whole-view D/M/P/T plus exact-query values are unchanged from the L11 report. The L3 FP-contract preamble/self-test remains in place.
| Recipe | Full-detail density / mesh / payload / topology | Whole-view density / mesh / payload / topology | Exact density+unclamped / detail / collision |
|---|---|---|---|
| SurfaceWorld | `0x0ee0579bd15cbbe4` / `0x32e5d4964d610fee` / `0x1932b96ee4b1d910` / `0x69743c6bad3447dc` | `0xc10697a8f48380c7` / `0xe75c9119a1498cd5` / `0x49a9a8d1835a6c8c` / `0xedcb23288b5e8724` | `0xe4d4a8eb95b35933` / `0xefcba20c0c70c415` / `0xe604823a249029bf` |
| FloatingIslands | `0x6d842d2878b08ef6` / `0x4b868a3184f08035` / `0x2cedf2236788752d` / `0xeac17d5e0cb5044a` | `0x5be4d8cde79b2a76` / `0x96f75041f6861b3a` / `0x3700a516cc89d50c` / `0x6b99948d6eab4f21` | `0x61daded9c303becb` / `0xefcba20c0c70c415` / `0x84d37463be9b0573` |
The 24 m crossing hash also matches L11 at W1 and W12 (432 rows each): density `0x174588abdc8c0d2c`, mesh `0x4c401e27d9d05dea`, payload `0xeb10d9801c5ef125`, topology `0xf59d12304d0dcb4a`.
The route-verified base/page audit does **not** pass the requested exact-tile invariant. For `(0,-5,-31,lod1)`, the base density hash is `0xe0672dae7528f8d7` and page density hash is `0x882280f67bfddd77`; mesh, payload, and topology match. All 48 base-covered LOD1 candidates had density mismatches; 10 also differed in mesh/payload/topology. Across eight route-verified LOD0/LOD1 pairs, all eight density hashes differed. The base SurfaceWorld route uses manifest density while L11 pages use the legacy density evaluator; switching page samples to the base field would change the L11 crossing hashes. I kept the legacy page field to preserve the required crossing output, so this pre-existing parity conflict remains unresolved.
## Failed and retried runs
- An attempted 24 m base-shape expansion exited 2 at the 160-million-node bound (`l12-baseline-24m-base.log`). A separate per-tile native-only proof promotion failed with `region OOM` and was reverted (`l12-probe-cross24-profile-w12.log`).
- The first plain step command passed `32` as the camera distance while labeling it 8 m; output identified it as 32 m. It was retained as the 32 m result, and 8 m was rerun with the correct distance.
- The first FloatingIslands matrix omitted `--auto-surface-camera`, so it hashed the wrong 2,553-tile view. It was rerun with the L11 seed-0 island placement; all 28 corrected matrix configurations passed. The comparison helper also needed two small script fixes before it reported the final 28/28 result.
- One base/page audit initially treated a LOD2 base-route fallback (`page_keys=0`) as a match. The audit now verifies the generated route; that apparent pass was rejected and the route-verified parity failure above is the final result.
Walking into new ground should feel much better: the plain 24 m crossing fell from 0.869 s to 0.164 s, and the 1 km crossing from 5.892 s to 1.247 s. Page-backed LOD1 tiles are down from 71.7 to 5.6 ms each while the L11 crossing hashes stay exact; base/page density-hash parity remains a separate unresolved constraint.
## Orchestrator review (Claude)
- Re-run by me (W12, no hashing, 3 interleaved pairs): 24 m crossing L11 0.874/0.914/0.898 s vs L12
0.154/0.166/0.166 s (median 0.898 → 0.166 s, 5.4×). Spawn is unchanged (near ring 0.160–0.184 s).
The 24 m crossing hash (density `0x174588abdc8c0d2c`, mesh `0x4c401e27d9d05dea`) matches L11 at W1
and W12. Hash runs refill skipped samples, so time crossings with hashing off.
- **Soundness of page-tile skipping:** the proof audit figures (27,479 blocks / 36,574,549 samples)
are the base-shape audit from L9, not page tiles. The evidence for pages is the crossing hash
equalling L11 (which filled every sample). That is necessary but narrow: one crossing, one seed.
- ⚠️ **Route-dependent output (a pre-existing multiplayer bug, now measured):** the same tile key
gives different density from the base shape (manifest field) than from an analytic page (legacy
field). All 48 base-covered LOD1 candidates differed in density, 10 also in mesh/payload/topology.
A tile's geometry then depends on streaming history (spawned near it vs walked to it), which
breaks peer determinism. Top priority for L13.
@@ -1,140 +0,0 @@
# VoxelForge M3 Linux13 — route-invariant density
## Field decision and fix
The approved reference is the Core base shape built from the reviewed owner manifest: `Heightfield2D`
for SurfaceWorld and `FloatingIslandFieldV1` for FloatingIslands. L12's base route sampled that
field. Its analytic pages instead fell through to the copied legacy owner `GetDensityAt` evaluator,
so the same key could sample different values after the player crossed into a page. In the L12
SurfaceWorld audit, all 48 base-covered LOD1 candidates had different density; 10 also differed in
mesh, payload, and topology. A 214,375-sample L12 negative-control run measured max/mean density
delta `0.076171875 / 0.0133467594`, 29 sign changes, 170 edge-crossing changes, and up to 1.7778
voxels of surface displacement. The manifest field is the approved Core world and is the reference
kept here.
Changing the page manifest flag alone did not fix FloatingIslands: 8/8 page pairs still failed,
with max density delta `433.925781`, 262,676 sign changes, and 17,188 edge-crossing changes across
343,000 samples. The source fix binds each compiled page to its world's base `FStandaloneShapeWorld`
before publication. Page density, lattice, detail, classification, and solid queries now delegate
to that one evaluator; the legacy page-local evaluator is no longer an independent output route.
`WorldAssemblyEvaluatorVersion` is bumped from 5 to 6.
## Route parity
The L12 evaluator-v5 negative control fails as required: 5/5 selected base/page pairs mismatch. After the fix,
four audits passed: SurfaceWorld seeds 0, 1, and 17, plus FloatingIslands seed 0.
| Compared routes | Pairs | Mismatches |
|---|---:|---:|
| Base vs page (28 clipmap-requested pages; 26 base-covered page controls) | 54 | 0 |
| Base vs native-only shape-free route (SurfaceWorld LOD0) | 27 | 0 |
| Edited base vs edited page | 4 | 0 |
| Same key built in initial and moved-world history | 2 | 0 |
| Tile samples vs exact Core queries at LOD2–8 | 56 | 0 |
All 87 tile-generation pairs match density, mesh, payload, and topology hashes. The 56 higher-LOD
pairs compare the sampled tile lattice to direct `densityAt` / `densityAtLattice` queries; these
also match all sampled densities and solid/air signs. The owner fixture has
`full_res_clip_levels=2`, so analytic page routes exist only at LOD0–1. In total, page comparisons
covered 2,315,250 density samples with zero delta, sign, edge-crossing, or surface-root differences;
6,172,229 exact-query samples had zero mismatches. The audit exits nonzero on any output-hash,
sample, route-verification, exact-query, or proof-violation mismatch.
The history probe builds the same LOD0 key in a second Core world after a 96 m camera move. Both
SurfaceWorld and FloatingIslands match all four hashes across those two build histories. The edit
probe applies a sequence-1 density offset centered on a sampled sign crossing; it changes the field,
and edited base/page results still match.
### Page proof audit
The fill-and-check audit generated page tiles with full density capture and uniform-block proof
verification, so it checked the field those pages actually sample. Across the four audits it checked
1,274 blocks / 1,695,694 samples: 518 blocks used the exact fallback, 6 were unknown, and there were
zero false proofs or violations. SurfaceWorld walkability passed 5,642/5,642, 6,080/6,080, and
4,785/4,785 samples for seeds 0, 1, and 17; FloatingIslands passed 4,000/4,000. Shape readiness
passed 27/27 near-ring tiles where eligible. FloatingIslands has no eligible native-only tiles.
## Cost, hashing off
W12, seed 0, `--force-generate`, camera `0,-35,-487.94`, with the same crossing setup as L12:
| Move | Entering tiles | L12 crossing | L13 crossing | L13 peak RSS |
|---|---:|---:|---:|---:|
| 8 m | 144 | 0.0347 s | 0.0399 s | 468 MiB |
| 16 m | 288 | 0.1249 s | 0.0856 s | 513 MiB |
| 24 m | 432 | 0.1635 s | 0.1242 s | 512 MiB |
| 32 m | 576 | 0.1717 s | 0.1692 s | 511 MiB |
| 1 km | 2,260 | 1.2474 s | 0.7696 s | 673 MiB |
Three W12 spawn runs had medians of 157 ms first tile, 180 ms near ring, and 1.499 s whole view;
L12 medians were 146 ms, 161 ms, and 1.361 s. Each spawn run generated the same 2,553-tile
benchmark view. The final timings are in `Saved/Linux/l13-crossing-final-*.log` and
`Saved/Linux/l13-spawn-final-*.log`.
## Determinism and invariants
All 28 required configurations passed: SurfaceWorld and FloatingIslands seed 0; Clang
`-ffp-contract=off` and GCC default; W1/W8/W12, with five W12 repeats per compiler and recipe. Each
run matched all 12 rows (full detail, whole view, LOD0–8, exact queries) against L12/L11.
| Recipe | Full detail D/M/P/T | Whole view D/M/P/T | Exact density / unclamped / detail / collision |
|---|---|---|---|
| SurfaceWorld | `0x0ee0579bd15cbbe4 / 0x32e5d4964d610fee / 0x1932b96ee4b1d910 / 0x69743c6bad3447dc` | `0xc10697a8f48380c7 / 0xe75c9119a1498cd5 / 0x49a9a8d1835a6c8c / 0xedcb23288b5e8724` | `0xe4d4a8eb95b35933 / 0xe4d4a8eb95b35933 / 0xefcba20c0c70c415 / 0xe604823a249029bf` |
| FloatingIslands | `0x6d842d2878b08ef6 / 0x4b868a3184f08035 / 0x2cedf2236788752d / 0xeac17d5e0cb5044a` | `0x5be4d8cde79b2a76 / 0x96f75041f6861b3a / 0x3700a516cc89d50c / 0x6b99948d6eab4f21` | `0x61daded9c303becb / 0x61daded9c303becb / 0xefcba20c0c70c415 / 0x84d37463be9b0573` |
The crossing output changes as intended. The 24 m W1 and W12 moved-tile hashes match each other:
`0x337ca62131576728 / 0x7612f48e2ddbbaab / 0x69a67ed4add83b87 / 0xf11ac1ebd0f7ddb8` (D/M/P/T),
replacing L12's `0x174588abdc8c0d2c / 0x4c401e27d9d05dea / 0xeb10d9801c5ef125 / 0xf59d12304d0dcb4a`.
The L3 FP-contract preamble and runtime self-test, L4 `FLazy`, L7 shared column cache, L9/L12
proofs, and L11 native-only readiness/crash fixes were preserved. The L6 screen-space controls
still pass their six same-LOD checks and reject the missing/floating-surface, global-octave, and
stride-2 negative controls as required. Its whole gate still rejects the known far-field error over
the 1 px bound (exit 6); the route binding does not affect those LOD3–8 base-field comparisons.
The asynchronous MPSC/Epoch path and `ARCHITECTURE.md` §8.10 invariants are unchanged. No Unreal
adapter files were touched; the Core exact-query and collision-sign routes were checked, but Unreal
collision cooking was not built here. `ARCHITECTURE.md` §8.36 and `CODEMAP.md` §3.22 document the new
route law.
Builds and runs used CPUs 0–11, at most 12 workers, a 6 GiB address-space cap, and a 6,000,000,000
byte RSS monitor. The governor remained `powersave`. Peak sampled RSS was 904 MiB across runs
(673 MiB in the no-hash cost table); the GCC build process group peaked at 4.27 GiB. Clang and GCC
builds passed. No system changes or Unreal builds were made.
## Failed and retried runs
- `l13-route-baseline-s0-w12.log` exited 2 because the inferred binary-relative owner JSON path did
not exist; reruns used the explicit repository JSON. The first baseline capture used the wrong
camera, then an audit pass had empty proof-skipped density captures; the final L12 negative
control is `l13-route-baseline-s0-w12-r4.log`.
- `l13-route-fi-diagnostic.log` and `l13-route-fi-diagnostic-r2.log` intentionally exposed the
remaining FloatingIslands split before the shared-source binding; both exit 9 on 8/8 mismatches.
- `l13-route-edit-s0.log` exited 9 because its brush did not change the selected tile. Centering the
brush on a sampled sign crossing fixed the audit in `l13-route-edit-s0-r2.log`.
- `l13-route-history-sw-s0.log` exited 9 because the second-world probe exceeded the 4,096-node
region compiler envelope. The retry compiles one matching LOD0 anchor tile and passes.
- The first `l13-cost-*` measurements omitted `--force-generate` and used the owner JSON start;
those are not used above. The final crossing and spawn runs use L12's camera and force-generation
setting. The screen-space run's exit 6 is its expected far-field rejection, not a retried run.
- All final builds, the 28 hash runs, eight no-hash cost runs, and two crossing-hash runs completed
within their limits. No commit, push, or stash was made.
## Multiplayer note for the owner
Peers with the same manifest, seed, evaluator version 6, and tile key now reconstruct the same Core
density and tile output through each available base, page, or native-only route, regardless of
arrival history; terrain geometry still does not need to cross the network. Player edits remain an
explicit versioned diff that must be ordered and synchronized between peers.
## Orchestrator review (Claude)
- **Spawn cost re-run by me, 5 interleaved W12 pairs, no hashing:** whole view L12
1.385/1.405/1.419/1.443/1.460 s vs L13 1.401/1.448/1.430/1.435/1.451 s (median 1.419 → 1.435 s,
+1.1%, within noise); near ring 0.168 → 0.171 s. The +10% in the cost table above compares L13 runs
with L12 numbers from another session; interleaved, there is no measurable spawn regression.
- The fix is structural: pages are bound to their world's single base `FStandaloneShapeWorld`
evaluator before publication, so routes can't diverge by construction. The negative control fails
on L12 (5/5), and the 87 tile pairs, 56 exact-query pairs and 2.3M page samples show 0 mismatches
after. The page lifetime is safe because the base shape is owned by the `World` and outlives its pages.
- Crossing output changed, as intended (evaluator version 5 → 6); the spawn and island worlds are
unchanged.
@@ -1,157 +0,0 @@
# Linux14 — far spawn work
No mesh or density code changed. The source changes add opt-in profiling for far-shell column
lookups; counter snapshots are behind the existing profile guard, with no added timing or counter
increments when profiling is off. The final plain build has the same output as L13.
## Far LOD cost and ranking
The first table is from five interleaved, W12, hashing-off pairs: L13 binary before and L14 binary
after. Values are median worker-sums across that LOD; per-tile time is the L14 median divided by
tile count. The ranking is L6, L8, L4, L5, L7 on both binaries.
| LOD | Tiles | L13 → L14 median worker-s (s) | L14 worker-ms/tile |
|---:|---:|---:|---:|
| 4 | 320 | 1.600 → 1.572 | 4.91 |
| 5 | 144 | 1.421 → 1.411 | 9.80 |
| 6 | 96 | 2.624 → 2.585 | 26.93 |
| 7 | 48 | 1.152 → 1.158 | 24.13 |
| 8 | 153 | 2.044 → 2.046 | 13.37 |
Phase detail below is one W12 `--profile-lod-work` run on the final Clang binary. Cache counters
include all column work for that LOD, not just refinement. A “shared hit” is a hit from the
world-shared cache; formula evaluations equal local misses minus shared hits.
| LOD | Calls | Local hits / misses | Shared hits | Formula evaluations (per tile) | Column compute (ms) | MC non-column (ms) | Ground/cap non-column (ms) | Connector shell non-column (ms) | Skirt (ms) | Assembly (ms) |
|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
| 4 | 1,845,787 | 1,579,868 / 265,919 | 175,805 | 90,114 (282) | 521 | 472 | 385 | 0 | 186 | 3 |
| 5 | 877,542 | 701,124 / 176,418 | 105,477 | 70,941 (493) | 408 | 135 | 705 | 0 | 159 | 2 |
| 6 | 760,952 | 418,443 / 342,509 | 63,209 | 279,300 (2,909) | 1,594 | 90 | 474 | 210 | 158 | 2 |
| 7 | 337,328 | 257,969 / 79,359 | 8,878 | 70,481 (1,468) | 395 | 59 | 514 | 0 | 145 | 4 |
| 8 | 644,565 | 508,799 / 135,766 | 29,545 | 106,221 (694) | 608 | 374 | 783 | 0 | 278 | 6 |
MC and refinement column-compute / non-column times (ms) were L4 `221/472` MC and `281/385`
ground/cap; L5 `199/135` MC and `209/705` ground/cap; L6 `196/90` MC and `205/474` ground/cap;
L7 `184/59` MC and `211/514` ground/cap; L8 `413/374` MC and `195/783` ground/cap. The column
compute column overlaps those column portions. Timers are worker sums and may differ by a few ms
from their subphase sums.
Stratum shells made zero field calls at LOD4–8 and took under 0.03 ms total. The profiler run
measured about 1.408 s whole-view-ready; the unprofiled interleaved runs below are the timing result.
## Connector-shell repair
`AppendFarConnectorShells` is guarded to LOD6 and above. Coarse marching cubes can leave gaps in a
route connector wall, so the repair checks four axial rays at connector stations and adds only the
panels where the nearest coarse-mesh hit misses the source-field radius tolerance. LOD6 checks at
128-voxel stations; LOD7–8 use 256-voxel stations. Only LOD6 had repair candidates in this spawn
view: 5,066 triangles were added. The shell took 1.403 worker-s, including 1.193 s of column
evaluation (about 0.210 s shell work outside those evaluations).
The LOD6 repair made 251,475 source/column calls: 44,596 worker-local hits, 206,879 local misses,
30 shared-cache hits, and 206,849 formula evaluations. Thus 82.3% of calls evaluated a formula;
the work is mostly uncached. A cache miss can include a point evicted by the four-way worker cache,
so these counters do not prove every evaluated XY is unique. The L13-bound base evaluator already
feeds the shared exact-XY cache; neighboring LOD samples mostly use different XY coordinates, and
only 30 repair samples hit the shared cache. Reducing stations or rays would change the repair
geometry, and no bit-identical reduction was proved.
## Ground and cap refinement
Ground refinement starts at LOD5 (32-voxel grid there, 64 at LOD6, then 128 at LOD7–8). Cap
refinement starts at LOD4 (16-voxel grid there, then 128 at LOD5–7; LOD8 may use its configured
interior override). Both query exact `Heightfield2D` columns and use those values for heights,
normals, materials, clipping, and replacing nearby coarse faces. The existing shared cache is keyed
by recipe/plan and exact XY, so aligned samples can already be reused across tiles and levels. The
LOD-wide shared-hit counts are in the table above; they are not refinement-only counts.
Current safe skips are the plan Z-range check for ground and the cap-height-bound check for caps.
No additional tile/cell skip was shown to preserve every sample that affects output; a grid point
can also supply a neighboring normal or clipped cell. No new refinement sharing or skip was built.
## Ranked exact-output work
No exact-output change with a measured saving above 3% was proved, so no geometry optimization was
built. The ranked work buckets are:
1. Ground/cap refinement across LOD4–8: about 3.95 worker-s including its column work. Removing all
of it would be an unrealistic idealized 23% of 1.419 s at 12-way division; the sampled values
currently affect geometry/materials/normals.
2. LOD6 connector repair: 1.403 worker-s inclusive, an idealized upper bound near 8.2% at 12-way
division. Most calls are uncached, and the missing panels are required for the current mesh.
3. Far-LOD column formula work: 3.53 worker-s across LOD4–8, overlapping the two buckets above.
Exact-XY sharing is already active; no redundant set large enough to remove was demonstrated.
4. Marching-cubes non-column work is 1.13 worker-s and skirts 0.93 worker-s. Assembly is only
0.017 worker-s; stratum shells are negligible. No exact reduction was established.
These idealized conversions divide worker-s by 12 and are not predicted wall-time gains. The L6
screen-space gate was not used because this round made no geometry change.
## Interleaved cost, builds, and hashes
Five hashing-off W12 pairs ran in one session, alternating
`Standalone/bin/linux/VoxelForgeCoreHeadless-linux13-clang` and
`Standalone/bin/linux/VoxelForgeCoreHeadless-linux14-clang`. Every run generated 2,553 tiles at
seed 0 and camera `0,-35,-487.94,0,-22`.
| Pair | L13 whole-view-ready (s) | L14 whole-view-ready (s) |
|---:|---:|---:|
| 1 | 1.416 | 1.410 |
| 2 | 1.436 | 1.388 |
| 3 | 1.416 | 1.424 |
| 4 | 1.429 | 1.419 |
| 5 | 1.430 | 1.426 |
Median was 1.429 s before and 1.419 s after (−0.7%, within this run spread). The telemetry is
opt-in; the plain run shows no measurable cost when off.
Final binaries `Standalone/bin/linux/VoxelForgeCoreHeadless-linux14-clang` and
`Standalone/bin/linux/VoxelForgeCoreHeadless-linux14-gcc` were rebuilt with `Standalone/BuildLinux.sh`,
`-j12`, CPUs 0–11, and a 6 GiB address-space cap: Clang 19 with FP contraction off and GCC 14 with
default contraction. Builds passed. Runtime peak RSS was 926,520 KiB; largest individual
build-process RSS was 901,968 KiB (GCC), with a 4,557,196 KiB process-group peak. Governor remained
`powersave`.
The final hash matrix passed 28/28: SurfaceWorld seed 0 and FloatingIslands seed 0, Clang/GCC,
W1/W8/W12, with five W12 repeats per recipe/compiler. Full-detail, whole-view, all nine per-LOD,
and exact-query rows match L13 exactly. Route parity also passed for SurfaceWorld seeds 0,
1, and 17 and FloatingIslands seed 0: page/native-only routes, edits, history, higher-LOD exact
queries, and proof checks had zero mismatches. The final 24 m crossing hash matched at W1/W12 on
both compilers: `0x337ca62131576728 / 0x7612f48e2ddbbaab / 0x69a67ed4add83b87 / 0xf11ac1ebd0f7ddb8`
(density/mesh/payload/topology).
| Recipe | Full-detail D/M/P/T | Whole-view D/M/P/T | Exact density / unclamped / detail / collision |
|---|---|---|---|
| SurfaceWorld | `0x0ee0579bd15cbbe4 / 0x32e5d4964d610fee / 0x1932b96ee4b1d910 / 0x69743c6bad3447dc` | `0xc10697a8f48380c7 / 0xe75c9119a1498cd5 / 0x49a9a8d1835a6c8c / 0xedcb23288b5e8724` | `0xe4d4a8eb95b35933 / 0xe4d4a8eb95b35933 / 0xefcba20c0c70c415 / 0xe604823a249029bf` |
| FloatingIslands | `0x6d842d2878b08ef6 / 0x4b868a3184f08035 / 0x2cedf2236788752d / 0xeac17d5e0cb5044a` | `0x5be4d8cde79b2a76 / 0x96f75041f6861b3a / 0x3700a516cc89d50c / 0x6b99948d6eab4f21` | `0x61daded9c303becb / 0x61daded9c303becb / 0xefcba20c0c70c415 / 0x84d37463be9b0573` |
Hash logs and the 28-row comparator are in `Saved/Linux/l14-final-hash-*.log` and
`Saved/Linux/l14-final-hash-audit.txt`. Final route logs are `Saved/Linux/l14-final-route-*.log`;
crossing and pair logs use the `l14-final-crossing-*` and `l14-final-cost-*` names.
## Failed or retried runs
- The first SurfaceWorld hash matrix and first crossing checks omitted the spawn camera and used the
headless origin. Their comparisons differed from L13; all 14 SurfaceWorld configurations and all
four crossing configurations were rerun with the spawn camera and passed. FloatingIslands used
its auto-surface camera and matched on the first run.
- The first route probes also used the wrong camera selection. A later seed-1 probe used the fixed
seed-0 camera, exited 9 on two LOD2 exact-query checks, and was rerun with `--auto-surface-camera`;
the corrected seed-1 and seed-17 audits passed. The origin-camera route probes returned success
but were not used as reference results.
- Clang was rebuilt after the connector counters were added and again after folding aggregation
into the existing opt-in guard. Both Clang builds and the final GCC build succeeded. No run hit
the RSS, 15-minute stuck-step, or 30-minute limits.
Owner note: the highest measured far cost is still LOD6 connector repair, but its formula work is
mostly uncached and its panels preserve the coarse route wall. The final interleaved plain runs show
no measurable diagnostic overhead; no geometry change or L6 budget claim is made.
## Orchestrator review (Claude)
- Accepted as a counting round. Interleaved W12, no hashing: L13 1.429 s vs L14 1.419 s median, so the
opt-in counters cost nothing measurable when off; committed with the report.
- Conclusion: exact-output far work has no remaining lever above 3%. The big buckets
(ground/cap refinement ~3.95 worker-s, LOD6 connector repair ~1.40 worker-s) produce visible
geometry. Further far savings need geometry changes, judged against today's same-LOD mesh within
the owner's budget (1 px at 1440p, at the LOD's closest display distance, display only).
@@ -1,195 +0,0 @@
# Linux15 report
## Result
Null result. No far-mesh shortcut passed the full 1 px, shading, swap, and topology gates, so no
recipe enables one by default. Evaluator version 6→7 adds the optional `far_display_mesh` declaration;
omitting it keeps the L14 output path. The controls are in the shared Core layer and do not touch
LOD0–2, exact queries, collision, edits, or server state.
Candidates measured:
- Refinement grid scale ×2 at LOD4, 5, 6, 7, and 8. The all-tile LOD4 and LOD5 runs reject; the
remaining per-LOD probes exceed 1 px or change shading, and the LOD6–8 candidates worsen at
least one adjacent swap.
- Reusing connector station radii leaves geometry p99 at 1.07 px but reaches 15.23 px maximum;
shading delta reaches 0.667 and the normal changes by 73.3°.
- Coarsening refinement at LOD4–8 is the largest measured saving, but exceeds the display budget.
Halving connector station density also saves time but opens gaps. Removing
any one ray direction also opens gaps, and the removed-panel control finds 99 new holes.
## Screen-space gate
The gate samples 65×65 surface grids across all 1,145 displayed LOD3–8 tiles (5,208,134 samples;
skirts excluded). Geometry is projected normal displacement against today's same-LOD mesh at its
closest display distance, using 90° horizontal FOV and 2,560 px (0.000613592 rad/px). Shading delta
is the maximum of fixed-light normalized Lambert change and material selector/blend-channel change;
the limit is 1/255. Each number below is p50/p99/max. Exact-path baseline values are all zero.
The gate rejects geometry max above 1 px, shading max above 1/255, any worse per-sample swap,
missing surface, or new hole/crack/floater. Its own validation fails if S13, stride-2, missing
surface, floating surface, missing fine-ring, or removed-panel controls are not rejected; the
panel control must expose at least one new connector hole.
| LOD | Tiles | Geometry px: baseline → refine×2 all | Shading delta: baseline → refine×2 all | Refine×2 holes / cracks / floating |
|---:|---:|---:|---:|---:|
| 3 | 384 | 0/0/0 → 0/0/0 | 0/0/0 → 0/0/0 | 0 / 0 / 0 |
| 4 | 320 | 0/0/0 → 0/2.370/606.562 | 0/0/0 → 0/0.023529/1 | 254 / 400 / 254 |
| 5 | 144 | 0/0/0 → 0/12.728/95.453 | 0/0/0 → 0/1/1 | 1,183 / 76 / 138 |
| 6 | 96 | 0/0/0 → 0.023/13.408/799.596 | 0/0/0 → 0/1/1 | 476 / 0 / 201 |
| 7 | 48 | 0/0/0 → 0/13.242/248.905 | 0/0/0 → 0/1/1 | 30 / 0 / 1 |
| 8 | 153 | 0/0/0 → 0.158/19.250/187.465 | 0/0/0 → 0.003922/1/1 | 45 / 0 / 946 |
The selected-patch swap report compares each baseline with refine×2 all. Values are p50/p99/max px.
| Swap (distance) | Before | After refine×2 all |
|---|---:|---:|
| 3→2 (96 m) | 0.611/3.767/6.045 | 0.611/3.767/6.045 |
| 4→3 (192 m) | 0.752/4.630/7.513 | 0.752/4.630/7.513 |
| 5→4 (384 m) | 0/9.580/31.783 | 2.435/32.321/86.615 |
| 6→5 (768 m) | 0/9.754/70.340 | 0.343/19.142/78.077 |
| 7→6 (1,536 m) | 0/9.040/42.355 | 0.200/15.109/50.994 |
| 8→7 (3,072 m) | 0.826/18.030/47.182 | 1.528/24.547/64.449 |
The station×2 LOD6 screen scan measures 0/2/813.571 px, shading 0/0/1, with 1,349 holes and 1,690
floaters. Its connector audit counts missing ray stations by stable tile/ray/station ID: holes 8→221
(216 new), floating classifications 464→405 (111 new IDs). In the refine×2 all row above, the
screen scan reports those all-tile holes, cracks, and floaters. Station×2 leaves all six selected-patch
swap p50/p99/max rows at baseline values, including 6→5 at 0/9.754/70.340 px. All four ray directions are required:
the four one-ray-removed
controls create 1,008, 1,022, 1,171, and 1,158 new holes. The explicit panel-removal control creates
99 new holes. The exact-path audit has zero new holes, cracks, or floating pieces; its raw connector
audit counts remain 8 holes and 464 pre-existing floating classifications.
The LOD4×2 and LOD5×2 candidates also fail in isolation. Reusing station radii misses the LOD6
geometry and shading limits. The four one-ray-removed masks add 1,008, 1,022, 1,171, and 1,158
connector holes, respectively.
## Negative controls
- The S13 global-octave-drop and stride-2 column-interpolation controls are rejected at every LOD3–8.
- Missing displayed surface, a floating surface, and missing fine-ring surface controls are rejected.
- Removing connector panels is rejected with 99 new holes. The exact connector path has zero new
station IDs classified as holes, cracks, or floaters.
## Speed
Five interleaved W12 pairs per candidate, hashing off, same 2,553-tile L1 view.
`whole_view_ready` is the metric. Both candidates fail the quality gate.
Station×2 connector stations:
| Pair | L14 baseline | Station×2 | Change |
|---:|---:|---:|---:|
| 1 | 1.320 s | 1.304 s | −1.2% |
| 2 | 1.363 s | 1.330 s | −2.4% |
| 3 | 1.371 s | 1.332 s | −2.8% |
| 4 | 1.393 s | 1.341 s | −3.7% |
| 5 | 1.391 s | 1.345 s | −3.3% |
| Median | 1.371 s | 1.332 s | −2.8% (3.3% median paired gain) |
Refinement grid scale ×2 at LOD4–8:
| Pair | L14 baseline | Refine×2 all | Change |
|---:|---:|---:|---:|
| 1 | 1.305 s | 1.164 s | −10.8% |
| 2 | 1.336 s | 1.177 s | −11.9% |
| 3 | 1.362 s | 1.169 s | −14.2% |
| 4 | 1.378 s | 1.178 s | −14.5% |
| 5 | 1.384 s | 1.190 s | −14.0% |
| Median | 1.362 s | 1.177 s | −13.6% (14.0% median paired gain) |
## Hashes and invariants
The undeclared/default recipe path matches L14. LOD0–2 density/mesh/payload/topology hashes:
| LOD | Density | Mesh | Payload | Topology |
|---:|---|---|---|---|
| 0 | `769f2a706d585a72` | `33eeeb39fa443816` | `645621a1d968983f` | `c2457ed905036c9d` |
| 1 | `69cc5a5c0a2c60af` | `b48335f5410c57d5` | `d15c5480162ab8ba` | `feca1bd025823604` |
| 2 | `85deed5683a77202` | `53469895987aeea2` | `e55f8ae7e1532033` | `d5feb12a0e85c09b` |
Exact queries (density / unclamped / detail / collision) remain
`e4d4a8eb95b35933 / e4d4a8eb95b35933 / efcba20c0c70c415 / e604823a249029bf`. The 24 m crossing's
432 moved tiles match L14 at W1/W12 with Clang off and GCC default:
`337ca62131576728 / 7612f48e2ddbbaab / 69a67ed4add83b87 / f11ac1ebd0f7ddb8` (D/M/P/T).
Its LOD0–2 per-LOD hashes also match the three rows above.
Determinism passed 28/28 configurations: SurfaceWorld seed 0 and FloatingIslands seed 0, Clang 19
FP-contract off and GCC 14 default, W1/W8/W12 and five W12 repeats. All per-LOD and whole-view
hashes match L14. L13 route parity passed for SurfaceWorld seeds 0, 1, and 17 and FloatingIslands
seed 0; page, native-only, higher-LOD, edit, and history mismatch counts are zero.
The L3 FP-contract preamble/self-test, L4 `FLazy`, L7 shared cache, L9/L12 proofs, L11 readiness and
crash fix, L13 route binding, and CLAUDE.md async rules remain in place. The evaluator and optional
recipe declaration are shared by all recipes. Builds and runs used CPUs 0–11, up to W12, normal
priority, 6 GiB address-space limits, and the unchanged `powersave` governor. Peak RSS was 904,400 KB
(GCC build); peak runtime RSS was 736,432 KB. No run exceeded the time or memory limits.
## Capture pairs
JPEGs are 1280×720 and each is under 74 KB. Before is L14; after is the rejected refinement×2
candidate applied at LOD4–8.
The L1 view uses `(0,-35,-487.94) m`, yaw 0°, pitch −22°. Horizon uses the same location at pitch −2°.
The mesa frame aims from the L1 location at the L6 mesa band (`(-472,-1432,-463.151) m` in the
gate) with yaw −161° and pitch 0.9°.
| View | Before | After refine×2 all |
|---|---|---|
| L1 camera | [l1-camera-before.jpg](captures/l1-camera-before.jpg) (59 KB) | [l1-camera-after-refineall.jpg](captures/l1-camera-after-refineall.jpg) (57 KB) |
| Horizon | [horizon-before.jpg](captures/horizon-before.jpg) (63 KB) | [horizon-after-refineall.jpg](captures/horizon-after-refineall.jpg) (60 KB) |
| LOD6 mesa rim | [lod6-mesa-rim-before.jpg](captures/lod6-mesa-rim-before.jpg) (74 KB) | [lod6-mesa-rim-after-refineall.jpg](captures/lod6-mesa-rim-after-refineall.jpg) (67 KB) |
## Failed and retried runs
- The first Clang build wrapper exited 127 because `/usr/bin/time` is absent; the direct Clang
`-ffp-contract=off` build succeeded. GCC 14 default also built successfully.
- A later sequential-build monitor was interrupted after Clang completed and before its GCC step
launched. Clang and GCC were rebuilt separately with the same compiler settings and 6 GiB cap.
- The first hash matrix omitted `--seed=0` and was discarded. A second FloatingIslands matrix used
the SurfaceWorld spawn camera; it was rerun with the L14 auto-surface camera. The corrected matrix
passed all 28 configurations.
- Initial SurfaceWorld route probes used no camera for seed 0 (the 2,370-tile bound), omitted
`--region-crossing` for seed 0 (shape compiler safety bound), and used the fixed seed-0 camera for
seed 1 (LOD2/exact-query parity mismatch; seed 17 was not run with that setup). They were rerun
with L14's camera selection and region-crossing option; all four final route audits passed. The
first 24 m crossing also omitted `--region-crossing` and exceeded the shape-build safety bound;
all four corrected compiler/worker combinations passed.
- The first connector audit compared aggregate counts. It was replaced with stable per-ray station
ID comparison before the final gate. The initial L4 selected-tile gate missed a changed tile; the
all-desired-tile coverage gate found and rejected it. The full-view gate is used in the table above.
- The first JPEG encoding pass did not set CPU affinity or an address-space cap. All six files were
re-encoded under CPUs 0–11 and the 6 GiB cap; sizes and pixels stayed the same.
- The first five speed pairs included screen-gate color capture on ordinary streaming tiles. That
diagnostic copy is now enabled only for gate runs; all five cost pairs were rerun and the table
above uses only the final logs. The final exact gate passed and station×2 remained rejected.
- No builds, captures, final audits, or cost runs timed out or breached their memory limits. The
intentional candidate rejections are listed above, not treated as infrastructure failures.
Evidence logs are in `Saved/Linux`: the final baseline and station×2 all-tile gates are
`l15-final-gatecolors-exact.log` and `l15-final-gatecolors-station2.log`; the best-payoff
refinement×2 all-tile gate is `l15-final-gatecolors-refineall.log`. Single-LOD refinement coverage is in
`l15-gate-alltiles-refine-l4x2.log` and `l15-gate-alltiles-refine-l5x2.log`. Single-LOD refinement
and connector-ray probes are `l15-gate-refine-l{x}x2.log`, `l15-gate-reuse.log`, and
`l15-gate-rays{14,13,11,7}.log`. Hash, route, and crossing evidence is in
`l15-final-hash-audit.txt`, `l15-final-route-*.log`, and `l15-final-crossing-24m-*.log`; final
station×2 speed pairs are `l15-final-speed-pair{1..5}-{before,after}.log`; refinement×2 pairs are
`l15-final-speed-refineall-pair{1..5}-{before,after}.log`.
## Note for the owner
The default far terrain stays the same because every measured reduction exceeded the 1 px geometry
or shading limit, worsened a swap, or opened holes. Refinement×2 across LOD4–8 saves 13.6% by the
median whole-view ratio, but creates hundreds-pixel errors and visible gaps, so the captures show it
for review only and it is not enabled.
## Orchestrator review (Claude)
- I looked at the LOD6 mesa-rim pair. After refine×2, the jagged crests are visibly smoothed, black
holes appear in the cap/ceiling, and a dark sliver shows on the left horizon. That confirms the
gate's rejection: the instrument is right this time, not the world.
- **Not merged into `assembler/world`:** the candidate knobs and the evaluator 6→7 bump add no default
output and would invalidate version stamps for nothing. The full L15 code (the extended gate with
shading, swap and connector-ID audits, and the candidate controls) is kept on side branch
`wip/l15-far-budget`. `assembler/world` stays at L14 code plus this report.
- Conclusion of L14+L15: far terrain has no exact or within-budget saving left with today's design. The
remaining far cost is the price of the current refinement and connector-repair geometry.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 KiB

@@ -1,171 +0,0 @@
# Linux7 — shared terrain columns
**Decision: keep the shared second tier.** On the L1 view it cut median W12 whole-view time by
19.0%, well above the 3% threshold, and the 8 m camera crossing was also faster. All final output
hashes match the `9898e05` binary.
Runs used the `linux6` base, Clang 19 with FP contraction off, GCC 14 defaults, CPUs 0–11, normal
priority, a 6 GiB address-space cap, and the unchanged `powersave` governor. Static timings below
are three alternating base/candidate W12 runs of 2,553 tiles.
## 1. What was recomputed
Three complete W12 captures per mode on the L1 view. Counts below are medians of actual column
formula executions after worker-local cache misses, grouped by LOD. “Same worker” means the worker
had computed that XY before and later missed its local entry. Halo/normal repeats are separated
before worker attribution; the parenthesized value is the total computed halo/normal probes,
including unique ones. Each field's median is independent, so row medians can differ slightly from
their sums.
| LOD | Base total / unique XY | Same worker | Different worker | Halo repeats / probes | Shared total / unique XY |
|---:|---:|---:|---:|---:|---:|
| 0 | 556,134 / 128,240 | 22,307 | 358,908 | 46,679 / 70,972 | 135,720 / 127,370 |
| 1 | 452,626 / 104,284 | 16,393 | 287,791 | 39,245 / 59,082 | 85,658 / 85,479 |
| 2 | 144,251 / 32,274 | 14,667 | 74,377 | 22,933 / 30,942 | 28,019 / 28,019 |
| 3 | 91,158 / 33,256 | 0 | 46,387 | 11,564 / 20,339 | 16,213 / 16,213 |
| 4 | 272,776 / 91,325 | 100 | 167,083 | 14,266 / 28,089 | 90,105 / 90,065 |
| 5 | 178,511 / 71,957 | 1 | 98,687 | 7,892 / 20,042 | 70,932 / 70,930 |
| 6 | 342,763 / 280,334 | 20 | 56,204 | 6,205 / 19,977 | 279,266 / 279,202 |
| 7 | 79,400 / 71,468 | 1 | 4,951 | 2,980 / 14,329 | 70,492 / 70,492 |
| 8 | 137,062 / 106,219 | 0 | 22,138 | 8,704 / 22,609 | 106,219 / 106,219 |
Across the per-LOD medians, the base made 2.255 million formula evaluations: 919 thousand unique
XYs and 1.336 million repeats. Of the repeats, 83.6% were from another worker, 4.0% were same-worker
evictions, and 12.0% were halo/normal probes. The shared candidate made 883 thousand evaluations,
60.9% fewer; about 8.6 thousand repeats remained. This is mostly a worker-sharing problem, not a
local-cache-capacity problem.
## 2. Design
`SharedColumnCache.h` is a bounded, four-way second-tier value cache used by both `Heightfield2D`
and FloatingIslands. Its key includes recipe and plan pointer identity plus content hash, exact XY,
and an optional exact sub-domain identity; FloatingIslands supplies the island stable ID because
different anchors can use the same XY. LOD is omitted because the column value is LOD-independent.
The heightfield table has 524,288 slots and the island table has 65,536. Both are allocated with
the `World::Impl` and destroyed with it. The Standalone streamer stops and joins workers before
world teardown; engine shutdown must keep the same drain-before-destroy ordering as the existing
generator state.
The S14 `FLazy` thread-local caches stay first, so their hits remain worker-private. Shared hits read
versioned atomic entries without taking a lock; a miss takes a set-local spin lock, rechecks, then
computes and publishes. A hit racing with a slot replacement can fall through as a miss. Fixed
capacity bounds memory and replacement bounds reuse as the player moves. No page ring, prefetch, or
neighbor affinity was needed. The shared table is not an immutable page store; atomic fields and
version checks give readers a consistent value while a slot can be replaced. Workers only read
recipe/plan identity and content hashes; they do not mutate generator state or call UObject/engine
APIs. Epoch, shutdown, and MPSC result handling were not changed. The L3 FP-contract preamble and
self-test remain intact, as does the `FLazy` rule for large thread-local storage.
## 3. Speed and memory
| W12 static whole view | Base | Shared | Change |
|---|---:|---:|---:|
| `whole_view_ready` median | 2.165 s | 1.754 s | −19.0% |
| Peak RSS median (max) | 401.5 MiB (402.6) | 467.8 MiB (468.0) | +66.3 MiB median |
Per-LOD worker sum is the sum of tile worker seconds, not wall time. Values are medians across the
same three static runs.
| LOD | Base worker sum | Shared worker sum | Change |
|---:|---:|---:|---:|
| 0 | 3.830 s | 2.667 s | −30.4% |
| 1 | 5.301 s | 4.085 s | −22.9% |
| 2 | 1.296 s | 0.795 s | −38.7% |
| 3 | 1.116 s | 0.725 s | −35.1% |
| 4 | 2.692 s | 1.674 s | −37.8% |
| 5 | 1.911 s | 1.459 s | −23.7% |
| 6 | 2.903 s | 2.621 s | −9.7% |
| 7 | 1.242 s | 1.227 s | −1.2% |
| 8 | 2.318 s | 2.271 s | −2.0% |
The moving trial warmed the first view, moved the camera 8 m, then generated 144 entering tiles
(128 LOD0, 16 LOD1) on the same world and worker pool. It ran three times per cache mode.
| Moving check | Shared | Thread-local | Change |
|---|---:|---:|---:|
| New-tile wall median | 52.39 ms | 82.00 ms | −36.1% |
| LOD0 worker sum median | 403.44 ms | 693.67 ms | −41.8% |
| LOD1 worker sum median | 138.34 ms | 182.29 ms | −24.1% |
| Peak RSS median (max) | 466.1 MiB (466.9) | 466.1 MiB (467.6) | Same cache allocation in both modes |
## 4. Hashes
Every W1/W12 result matched the base for Clang FP contraction off and GCC default: full detail,
whole view, each LOD, and exact queries. The L1 base hashes are:
| Scope | Density | Mesh | Payload | Topology |
|---|---|---|---|---|
| Full detail, 960 tiles | `0x0ee0579bd15cbbe4` | `0x32e5d4964d610fee` | `0x1932b96ee4b1d910` | `0x69743c6bad3447dc` |
| Whole view, 2,553 tiles | `0xc10697a8f48380c7` | `0xe75c9119a1498cd5` | `0x49a9a8d1835a6c8c` | `0xedcb23288b5e8724` |
| LOD | Density | Mesh | Payload | Topology |
|---:|---|---|---|---|
| 0 | `0x769f2a706d585a72` | `0x33eeeb39fa443816` | `0x645621a1d968983f` | `0xc2457ed905036c9d` |
| 1 | `0x69cc5a5c0a2c60af` | `0xb48335f5410c57d5` | `0xd15c5480162ab8ba` | `0xfeca1bd025823604` |
| 2 | `0x85deed5683a77202` | `0x53469895987aeea2` | `0xe55f8ae7e1532033` | `0xd5feb12a0e85c09b` |
| 3 | `0x6518caefb3be7e7f` | `0xec513c90b853a614` | `0xf62fa1137ff17f82` | `0xccf1dcf681965816` |
| 4 | `0x62d4be96021992f4` | `0xf1e4c6efcc2615a9` | `0x9dc5f9c88be02f33` | `0xfe6f55125a07c3bf` |
| 5 | `0x5e4a8c38b8cea6fc` | `0x08ee56998aaf21e5` | `0x541eea8558f26cc8` | `0x6539374a8b3336d8` |
| 6 | `0xe036e95b9006945b` | `0x624a33f941a99b02` | `0x81b73e14f68bdf86` | `0x4de4c63ce1f80a56` |
| 7 | `0x8ee358af56a30d8d` | `0x46ab3c6184048b7c` | `0x0a6164b7e68e80c5` | `0x0c26b85bb03bc831` |
| 8 | `0xc3458e1cbdb9c471` | `0x46c03d0994d75192` | `0x8f89fc5bde12d230` | `0xd16dc0cf62031898` |
Exact queries (9 probes): density and unclamped `0xe4d4a8eb95b35933`, detail
`0xefcba20c0c70c415`, collision `0xe604823a249029bf`. The FloatingIslands seed-0 fixture also
passes at Clang/GCC W1/W12 with recipe hash `0x39a24198ad8cf88f`; its whole-view hash matches the
base: density `0xa8fc5f8f4eaf77a3`, mesh `0xfff7d8ac8923eb9a`, payload `0xd730c51d959c1c59`,
topology `0xbb33ddb76cd386be`.
## 5. Transfer estimate and Windows work
The majority of the opportunity is cross-worker, so it does not disappear just because the 5800X3D
has a larger L3. Same-worker evictions are only 4% of baseline repeats; that capacity-driven part
may shrink. The candidate adds about 66 MiB peak RSS, and a 96 MiB L3 could keep much of the shared
table resident, though other game data will compete for it. I expect the win to transfer and clear
3%, likely landing in the mid-single to low-double digits; that percentage is an estimate until the
5800X3D run.
Windows to-do:
1. Build the Core route with MSVC `/fp:precise`; keep the FP-contract self-test and check the
64-bit atomic slot path on the supported Windows target.
2. Run the W1/W12 whole-view, full-detail, per-LOD, exact-query, and seed-0 FloatingIslands checks
against the base binary.
3. Interleave three static W12 A/B runs on the 5800X3D, then repeat the 8 m camera crossing; record
peak RSS and the machine's unchanged governor.
4. Exercise real streaming shutdown/profile changes and confirm workers drain before world/cache
destruction, with Epoch checks and MPSC result queues still intact.
## 6. Failed and corrected runs
- The first Clang W1 hash invocation omitted the explicit data path; it exited 2 after resolving
`Standalone/bin/data/owner_world.json`. The retry passed with
`Standalone/data/owner_world.json` supplied.
- The first moving step was 32 m and failed the shape interval 160-million-node safety bound. The
benchmark was retried at 8 m, which completed three times in each cache mode.
- The first shared FloatingIslands cache key omitted the island stable ID. The W12 fixture exposed
an LOD4 hash mismatch. Adding the exact sub-domain ID fixed it; final hashes match at W1/W12 for
both compilers.
- An early fixture command passed `--seed=0`, which also overrode the surface-world seed. The final
fixture comparison omits that override; FloatingIslands itself still runs its seed-0 check.
- No run exceeded 30 minutes or remained stuck for 15 minutes. All final Clang and GCC builds
succeeded with 12 jobs.
## Owner note
Linux measured a 19.0% W12 whole-view gain and a 36.1% gain on the 8 m crossing, at about 66 MiB
more peak RSS. Please run the Windows hash matrix and static/moving A/B on the 5800X3D before using
the laptop percentage as an owner-machine estimate.
## Orchestrator review (Claude)
- **Concurrency read:** a seqlock over all-atomic fields (seq_cst), with the version checked before
and after the key/value loads; readers fall back to a miss on any mismatch. Writers hold the set
spin lock and mark the version odd while writing. There is no non-atomic shared access, so a
reader can't return a torn value. The per-tile scoped `setThreadActive`/restore binds each thread
to its own world's table. Default on (`useSharedColumnCache = true`).
- **Re-run by me** (W12, L1 view, interleaved): base `linux6` 2.014/2.059/2.092 s vs L7 `linux7shared`
1.657/1.730/1.729 s, then 1.718/1.705/1.722 s (median 2.059 → 1.722 s, -16%). The whole-view hash was
identical in all 8 L7 runs at W12, plus W1 (8.036 s) and W8 (1.799 s).
- Luna's island-key bug was caught by the W12 hash fixture before review, so the determinism check
works as intended.
@@ -1,69 +0,0 @@
# Linux8: work remaining after the shared cache
## Per-LOD profile
W12 work and stage times below are medians of five interleaved timing runs. Cache columns are call counts (`worker-local hit / shared hit / shared miss`); cache outcomes were not timed separately. Unique XY per tile is the median across three W12 coordinate-capture runs. Skirt time needs the optional mesher timer, so those values come from the final gated profile; mesh assembly is the five-run median. Stage timers do not add exactly to worker time because they omit classification and other work, and some are inclusive of column computation.
| LOD | Tiles | Work (s) | Columns (ms) | MC (ms) | Ground/cap (ms) | Far shell (ms) | Skirt/assembly (ms) | Samples/tile | Local/shared/miss calls | Unique XY/tile |
|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
| 0 | 512 | 2.649 | 462 | 1,348 | 0/0 | 0.09 | 281/80 | 10,383.8 | 9.400M/405k/136k | 265 |
| 1 | 448 | 4.064 | 309 | 3,487 | 0/0 | 0.08 | 186/76 | 42,875.0 | 19.354M/357k/86k | 191 |
| 2 | 448 | 0.781 | 133 | 575 | 0/0 | 0.08 | 99/35 | 4,133.8 | 1.743M/115k/28k | 63 |
| 3 | 384 | 0.730 | 89 | 591 | 0/0 | 0.07 | 108/33 | 6,859.0 | 2.130M/73k/16k | 42 |
| 4 | 320 | 1.640 | 508 | 651 | 0/372 | 0.06 | 187/102 | 6,859.0 | 1.718M/182k/90k | 282 |
| 5 | 144 | 1.419 | 397 | 275 | 650/22 | 0.03 | 157/72 | 6,859.0 | 698k/109k/71k | 493 |
| 6 | 96 | 2.551 | 1,569 | 237 | 409/58 | 1,379 | 161/71 | 6,859.0 | 418k/63k/279k | 2,909 |
| 7 | 48 | 1.201 | 393 | 200 | 294/208 | 0.00 | 149/99 | 6,859.0 | 258k/9k/70k | 1,469 |
| 8 | 153 | 2.186 | 584 | 661 | 447/308 | 0.01 | 263/182 | 6,859.0 | 508k/30k/106k | 694 |
## LOD6 and LOD1
LOD6 generated 279,207 distinct XY columns across 96 tiles (2,909 per tile), close to the 280,334 L7 count. A bracket around `AppendFarConnectorShells` measured 206,849 formula evaluations there, about 74% of LOD6's column evaluations, and 1.379 worker-seconds; MC used about 35k evaluations, ground refinement about 37k, and cap none. The repair runs at LOD6 while stratum-shell repair starts at LOD7. The final gate profile recorded 13,291 halo/normal probes and only 16 repeated halo columns, so they do not explain the spike. The gate samples native terrain and does not certify dropping connector-shell geometry; no connector-shell work was shown to be screen-inert.
LOD1 has zero feature-refined tiles: it uses the normal 32-cell lattice at step 2. Its 448 tiles each consumed 42,875 density samples (35³); LOD0 averaged 10,383.8, or 5.32M total versus LOD1's 19.21M. The mesher's 8-cell proof-block early-outs are enabled at step 1 and step 8, but deliberately disabled at step 2, so LOD0 can skip uniform blocks while LOD1 fills each tile's grid. MC is LOD1's cost: 3.487 worker-seconds, with 3.345 seconds in density-grid fill in the detailed run. Cell classification was 123 ms, normals 13 ms, interpolation 8 ms, and dedup/stream 59 ms. Column computation was 309 ms; halo/normal work is not the cause.
## Wall time and levers
The median W12 tile work was 17.299 worker-seconds, or 1.442 seconds at ideal use of 12 workers. Measured stream wall was 1.446 seconds, only 4 ms above that estimate. Whole-view readiness was 1.727 seconds: shape compilation was 215 ms and another 67 ms elapsed before stream work began in owner/plan/setup. The residual is startup, not an idle worker or a long tile tail.
The largest lever is LOD1 density-grid filling: 3.345 worker-seconds, a theoretical ceiling of 279 ms (16.2% of a 1.72-second view) if eliminated at perfect 12-way scaling. Next are LOD6 connector-shell repair at 1.379 worker-seconds (115 ms, 6.7%), LOD0 MC at 1.348 (112 ms, 6.5%), then LOD4 MC and LOD5 ground refinement at about 0.65 each (54 ms, 3.1%). These are upper bounds, not expected savings, and the work overlaps other stages. No product optimization was built: the candidates above threshold either produce required geometry or need an exact, output-preserving kernel change that this count round did not prove.
The L6 gate on the final W12 profile passed same-LOD regeneration at LOD3–8 and rejected all negative controls. The existing far mesh still fails its direct-field 1 px comparison at every LOD3–8 (maxima: 6.00, 7.93, 92.02, 70.34, 42.36, 47.18 px); this round changes no geometry. No recipe bump is needed.
## Interleaved W12 timing and hashes
`linux8` is the Clang 19 `-ffp-contract=off` measurement build; `linux8gcc` is GCC 14 default. Neither changes geometry. SHA256: L7 baseline `fbbd468e351c8a0e00c903a7988a3765158e9400ed6a0111898da4d7f5ae6c85`; Clang `linux8` `82b159359a754fb33c38a93c8b7cafe5d4cfc08c41582cbfd21328307f5e3c19`; GCC `linux8gcc` `5614db5158a3f404383eea27c3748d7cf05b3a0c545b9e95f272e09bed0ee300`.
| Pair | L7 `linux7shared` (s) | Clang `linux8` (s) | Delta |
|---:|---:|---:|---:|
| 1 | 1.733 | 1.677 | −56 ms |
| 2 | 1.670 | 1.702 | +32 ms |
| 3 | 1.685 | 1.727 | +42 ms |
| 4 | 1.692 | 1.727 | +35 ms |
| 5 | 1.725 | 1.741 | +16 ms |
| Median | 1.692 | 1.727 | +35 ms (+2.1%) |
Pair deltas range from −56 to +42 ms, so this diagnostic build shows no separable speed change. Every W12 pair had the same whole-view hashes: density `0xc10697a8f48380c7`, mesh `0xe75c9119a1498cd5`, payload `0x49a9a8d1835a6c8c`, topology `0xedcb23288b5e8724`. W1/W8/W12 and Clang/GCC also agreed on all nine per-LOD hashes and exact-query hashes: density/unclamped `0xe4d4a8eb95b35933`, detail `0xefcba20c0c70c415`, collision `0xe604823a249029bf`. Thus LOD0–2 and exact queries are unchanged from L7.
The final Clang and GCC builds took 29.876 s and 45.562 s; peak build RSS was 437,844 KiB and 901,892 KiB. Highest measured runtime RSS was 587,344 KiB. Runs used CPUs 0–11, `-j12`, a 6 GiB address-space limit, normal priority, and the unchanged `powersave` governor.
## Failed or retried runs
- `l8_build_clang.log` failed after 27.608 s: the first print patch referenced local phase sets outside their scope. The corrected `l8_build_clang_retry.log` and `l8_build_clang_retry2.log` succeeded; the later phase-instrumented `l8_build_clang_final.log` and `l8_build_gcc_final.log` also succeeded.
- The initial no-camera probes in `l8_hash_clang_w1.log`, `l8_hash_clang_w8.log`, `l8_hash_clang_w12.log`, and `l8_baseline_l7_hash_w1.log` generated 2,370 tiles, not this 2,553-tile fixture. They were discarded and rerun with `--camera=0,-35,-487.94,0,-22`.
- `l8_profile_gate_w12.log` and `l8_profile_gate_final.log` returned exit 6 because the gate correctly rejects the existing far-mesh field error. Same-LOD checks passed and all fault/negative controls were rejected as required. All corrected hash, profile-repeat, and speed runs exited 0; none timed out.
Build and runtime logs are in `Saved/Linux/l8_*.log`. No commit, push, or stash was made.
**Owner note:** LOD6's extra columns are predominantly connector-shell repair work, while LOD1 is expensive because all 448 tiles fill the normal density grid; neither points to wasted halo or normal work. The next useful experiment is a bit-exact LOD1 density-grid optimization, while any LOD6 resolution change needs a connector-specific screen gate first.
## Orchestrator review (Claude)
- **Why LOD1 fills every sample:** `VoxelMarchingCubesMesher.cpp` gates the 8-cell proof blocks to
`Step == 1 || Step == 8`, and its comment says steps 2/16/32 skip them because "their meshing work is
already smaller than repeating a full tile classifier per block" and to keep "the established
coarse-LOD latency profile". That tuning predates the Core heightfield path; on the owner's
SurfaceWorld view, LOD1's grid fill is now the largest single cost (3.35 worker-s). Next round: L9.
- Only this report is committed. Luna's L8 instrumentation (Core and pipeline diffs) stays uncommitted
in the tree for L9 to reuse or remove; its cost against L7 was +2.1% median with pair deltas from
-56 to +42 ms, which is not separable, so it doesn't go in until proven free.
@@ -1,149 +0,0 @@
# Linux9: LOD1 uniform-block proof
LOD1 now omits density fills only for 8-cell blocks proved uniform by the Core SurfaceWorld heightfield. It fills 924,232 samples across the 448 tiles (2,063 per tile), down from 19,208,000 (42,875 per tile): 95.2% fewer. All output hashes match the `4b1108b` baseline.
## Why the old gate excluded steps
`git blame` points to the original mesher gate: steps 2, 16 and 32 were disabled because the per-block classifier was expected to cost more than the smaller grids saved, and to preserve the old coarse-LOD latency. It gives no correctness reason at step 2; the history does not cite block edges, normal halos or skirts. Step 1 and step 8 were already enabled (step 8 is LOD2). This round enables step 2 for native SurfaceWorld tiles; steps 16/32 remain off pending a separate cost profile.
## Proof and fallback
The tile and each proof box must stay inside one native SurfaceWorld stratum, with no overlapping edit. For every XY lattice point in the padded 8-cell box, `Heightfield2D::classifyLatticeBox` evaluates the exact ground and cap columns at the step-2 stride. For density `min(z-ground, cap-z)`, `minZ > maxGround && maxZ < minCap` proves air; `maxZ < minGround || minZ > maxCap` proves solid. These extrema bound every discrete MC density sample; the box includes the cell samples and the one-sample normal halo (`-1..+9`). No nominal noise parameter is used as a bound.
Feature boxes that can add volume, edits, invalid input, mixed strata, and any Mixed/Unknown verdict stay on the exact fill path. The default FloatingIslands view does not use this Step-2 tile gate; its Unknown whole boxes (1,635) remain filled. The native classifier path is shared, and a W12 island audit also forced 9,216 uniform Step-2 candidates through fill-and-check.
The generic `Heightfield2D::interval` was sound but too broad here: it gave bounds `[-2,883,809, 1,032,090]` subvoxels around z=-2,114, so all 28,672 Step-2 blocks were Mixed. The exact lattice-column extrema produced useful verdicts instead.
## Soundness sweep
The audit bypassed block skipping and explicitly evaluated every density sample in each candidate's padded block, asserting that none contradicted the verdict. It covered three SurfaceWorld seeds and one FloatingIslands audit:
| Recipe / seed | Blocks checked | Density samples checked | Mixed fallbacks | Unknown | Violations |
|---|---:|---:|---:|---:|---:|
| SurfaceWorld 0 | 27,479 | 36,574,549 | 1,193 | 0 | 0 |
| SurfaceWorld 1 | 26,069 | 34,697,839 | 1,451 | 0 | 0 |
| SurfaceWorld 17 | 26,954 | 35,875,774 | 1,718 | 0 | 0 |
| SurfaceWorld total | 80,502 | 107,148,162 | 4,362 | 0 | 0 |
| FloatingIslands 0 | 9,216 | 12,266,496 | 0 | 0 | 0 |
A violation would be possible if the native density dispatch or `point()` stopped matching this column formula, if a new volume/edit overlay bypassed the Mixed guard, or if the padded lattice/normal halo changed without updating the proof bounds. Zero density is treated as Mixed by the audit.
## W12 samples and worker time
Sample counts compare L8's SurfaceWorld profile with the final L9 profile. Worker seconds are medians of five W12 no-hash runs against `linux7shared` and the Clang candidate. They are per-LOD sums across workers.
| LOD | L9 filled samples | Worker seconds baseline → L9 | Change |
|---:|---:|---:|---:|
| 0 | 5,316,500 | 2.398 → 2.395 | -0.1% |
| 1 | 924,232 | 1.213 → 0.920 | -24.1% |
| 2 | 932,824 | 0.452 → 0.456 | +0.8% |
| 3 | 1,858,789 | 0.540 → 0.549 | +1.6% |
| 4 | 2,085,136 | 1.535 → 1.545 | +0.6% |
| 5 | 987,696 | 1.378 → 1.395 | +1.2% |
| 6 | 658,464 | 2.559 → 2.564 | +0.2% |
| 7 | 329,232 | 1.134 → 1.139 | +0.4% |
| 8 | 1,049,427 | 2.055 → 2.082 | +1.3% |
LOD1 per tile is 42,875 → 2,063 samples.
LOD0 and LOD2–8 stayed within 1.6% of baseline worker time. LOD1's 4.064 worker-seconds in the L8 profile did not reproduce in the specified `linux7shared` binary's worker diagnostics: the five-run median there was 1.213 seconds. The exact-binary interleaved timing below is the comparable whole-view measure.
## W12 interleaved stream time
Baseline is `Standalone/bin/linux/VoxelForgeCoreHeadless-linux7shared`, SHA256 `fbbd468e351c8a0e00c903a7988a3765158e9400ed6a0111898da4d7f5ae6c85`. Each pair used the same seed, camera, 2,553 tiles and W12 settings.
| Pair | Baseline | Clang `-ffp-contract=off` | Delta |
|---:|---:|---:|---:|
| 1 | 1.079 s | 1.066 s | -1.2% |
| 2 | 1.109 s | 1.083 s | -2.3% |
| 3 | 1.145 s | 1.100 s | -3.9% |
| 4 | 1.125 s | 1.099 s | -2.3% |
| 5 | 1.126 s | 1.113 s | -1.2% |
| Median | 1.125 s | 1.099 s | -2.3% |
| Pair | Baseline | GCC 14 default | Delta |
|---:|---:|---:|---:|
| 1 | 1.073 s | 1.100 s | +2.5% |
| 2 | 1.091 s | 1.136 s | +4.1% |
| 3 | 1.104 s | 1.129 s | +2.3% |
| 4 | 1.123 s | 1.140 s | +1.5% |
| 5 | 1.123 s | 1.150 s | +2.4% |
| Median | 1.104 s | 1.136 s | +2.9% |
The baseline ELF contains GCC 14 and Clang 19 objects; the candidate GCC binary is GCC-only. As a compiler-matched control, five W12 pairs against the GCC-only `linux7gcc` baseline measured 1.154 s → 1.116 s (-3.3%). Thus the specified-binary GCC comparison is slower, while the matched GCC control is faster; the mixed-toolchain delta cannot be attributed to this change. The Clang candidate is faster than the specified binary.
FloatingIslands seed 0 hashes match at W1/W12 for both compilers. Five W12 no-hash pairs against `linux7shared` gave Clang 10.836 → 11.005 s (+1.6%, pair range -0.5% to +3.0%). GCC was 11.223 → 12.618 s (+12.4%), while five compiler-matched GCC pairs against `linux7gcc` were 12.498 → 12.529 s (+0.25%, pair range -0.5% to +1.3%). The default island path has no measurable same-compiler slowdown; the large `linux7shared` GCC delta is the same toolchain mismatch.
## Hashes
Every SurfaceWorld hash below matched the baseline at W1/W8/W12 for both compilers; W12 was repeated five times per compiler. FloatingIslands seed 0 matched at W1/W12 for both compilers. Per-LOD tuples are density / mesh / payload / topology.
SurfaceWorld full detail: density `0x0ee0579bd15cbbe4`, mesh `0x32e5d4964d610fee`, payload `0x1932b96ee4b1d910`, topology `0x69743c6bad3447dc`.
SurfaceWorld whole view: density `0xc10697a8f48380c7`, mesh `0xe75c9119a1498cd5`, payload `0x49a9a8d1835a6c8c`, topology `0xedcb23288b5e8724`.
SurfaceWorld exact queries (9 probes): density/unclamped `0xe4d4a8eb95b35933`, detail `0xefcba20c0c70c415`, collision `0xe604823a249029bf`.
| LOD | Density | Mesh | Payload | Topology |
|---:|---|---|---|---|
| 0 | `0x769f2a706d585a72` | `0x33eeeb39fa443816` | `0x645621a1d968983f` | `0xc2457ed905036c9d` |
| 1 | `0x69cc5a5c0a2c60af` | `0xb48335f5410c57d5` | `0xd15c5480162ab8ba` | `0xfeca1bd025823604` |
| 2 | `0x85deed5683a77202` | `0x53469895987aeea2` | `0xe55f8ae7e1532033` | `0xd5feb12a0e85c09b` |
| 3 | `0x6518caefb3be7e7f` | `0xec513c90b853a614` | `0xf62fa1137ff17f82` | `0xccf1dcf681965816` |
| 4 | `0x62d4be96021992f4` | `0xf1e4c6efcc2615a9` | `0x9dc5f9c88be02f33` | `0xfe6f55125a07c3bf` |
| 5 | `0x5e4a8c38b8cea6fc` | `0x08ee56998aaf21e5` | `0x541eea8558f26cc8` | `0x6539374a8b3336d8` |
| 6 | `0xe036e95b9006945b` | `0x624a33f941a99b02` | `0x81b73e14f68bdf86` | `0x4de4c63ce1f80a56` |
| 7 | `0x8ee358af56a30d8d` | `0x46ab3c6184048b7c` | `0x0a6164b7e68e80c5` | `0x0c26b85bb03bc831` |
| 8 | `0xc3458e1cbdb9c471` | `0x46c03d0994d75192` | `0x8f89fc5bde12d230` | `0xd16dc0cf62031898` |
FloatingIslands full detail: density `0x6d842d2878b08ef6`, mesh `0x4b868a3184f08035`, payload `0x2cedf2236788752d`, topology `0xeac17d5e0cb5044a`.
FloatingIslands whole view: density `0x5be4d8cde79b2a76`, mesh `0x96f75041f6861b3a`, payload `0x3700a516cc89d50c`, topology `0x6b99948d6eab4f21`.
FloatingIslands exact queries (9 probes): density/unclamped `0x61daded9c303becb`, detail `0xefcba20c0c70c415`, collision `0x84d37463be9b0573`.
| LOD | Density | Mesh | Payload | Topology |
|---:|---|---|---|---|
| 0 | `0xf2524906044ef994` | `0x15b2828701a06591` | `0x4cbbf7ade54321f7` | `0x2c0382f590d69610` |
| 1 | `0x71b4c8327ad91da7` | `0xfd2280177adb70c9` | `0xc6f695b969ca8573` | `0xb7b026366bc5b627` |
| 2 | `0x23925de354d86f14` | `0xd4b470b6aae75cab` | `0x38c39feddc72ca0c` | `0x8496f76d94d0e578` |
| 3 | `0x4cb68a60bc8a5103` | `0x30514ad73d41fd87` | `0x39a209d2ec7695b1` | `0xa2ffa199ba1e1215` |
| 4 | `0x0e95c8abbcf6fb37` | `0x966b891fbe67794a` | `0xf01627522109d362` | `0xd7bfb2fea0137c0c` |
| 5 | `0xf444ffed34a1bd20` | `0x7f3073ed3a711113` | `0xad32e4ea4a1b4d50` | `0x6fdba8d6e549193c` |
| 6 | `0x6a6b4f75b9583ec7` | `0xdbb540e17a46b981` | `0xe2374a66e9d12b22` | `0xd384b7c0c0247982` |
| 7 | `0x5c4e824aaa7e5f73` | `0x44857e6de8e89645` | `0xa4ac0bf1da59e406` | `0x94f425b0d77004c8` |
| 8 | `0x8ce5f96cb24bc365` | `0xa1406a9a6dcae02b` | `0x8b5e182d38fe352b` | `0x098f65c1a8cde739` |
## Instrumentation, builds and limits
Removed the L8 phase/stage probes from the normal path. Kept `--profile-lod-work` for per-LOD density sample counts and added `--audit-uniform-block-proofs`; both are off by default. Normal runs do not perform the audit fill-and-check pass or sample-count aggregation. The optional LOD0 MC (1.348 worker-s) and shape compile (215 ms) were counted in L8 and not changed.
No async task or epoch path changed. The L3 FP-contract preamble/self-test, L4 `FLazy`, L7 shared cache, ARCHITECTURE §8.10 two-pass MC/SSE noise/clipmap-streaming invariants, and generator density output remain unchanged.
Clang 19 (`-ffp-contract=off`) and GCC 14 default builds used `-j12`; SHA256s are `0cd3f0ef993ced2c615418c6e2b37b83f57eff6d024d7d1568c30ea51490384a` and `23fe40de558b1b6931469cc5e976a0e4f2ed5fb6c362bc746dcc64a38fa40e08`. Peak build RSS was 901,940 KiB; highest measured runtime RSS was 623,928 KiB. Runs used CPUs 0–11, a 6 GiB address-space limit, normal priority, and the unchanged `powersave` governor. No run exceeded 30 minutes or remained stuck for 15 minutes.
## Failed and retried runs
- The first build wrapper failed because `/usr/bin/time` is absent; direct builds succeeded. One RSS sampling wrapper hung on zombie handling and was interrupted; later measurements used a corrected monitor.
- Initial proof-audit commands exited 2 because the positional data file and required stream modes were missing. Corrected commands completed. The first broad global interval returned Mixed for all 28,672 blocks and was replaced by the exact lattice-column proof.
- An early all-step audit found two legacy step-8 uniform candidates whose exact filled-grid signs disagreed; the existing post-fill validator cleared them before skip. The new audit is scoped to the native step-2 proof; step 8 is unchanged.
- The first Clang retry failed to compile because `SampleGridPoint` was outside its lambda scope; it was corrected to call `DensityAtLattice` directly and rebuilt.
- The first hash comparison differed because a uniform-tile early return bypassed debug density capture. Step-2 hash runs now refill omitted samples after exercising sparse MC. A separate FloatingIslands mismatch came from changing `>= 0` to `> 0`; the legacy `>= 0` comparison was restored and both compiler hashes then matched.
**Owner note:** LOD1 now fills 95% fewer samples with zero proof violations, and all SurfaceWorld and FloatingIslands hashes match. The GCC W12 comparison against `linux7shared` is toolchain-confounded; GCC-to-GCC controls are flat or faster, while the Clang candidate is faster than the requested baseline.
## Orchestrator review (Claude)
- **Re-run by me, 5 interleaved W12 pairs, L1 view.** Without `--stream-hash` (game-like):
whole view L7 1.379/1.485/1.430/1.439/1.449 s vs L9 1.390/1.409/1.401/1.423/1.429 s (median
1.439 → 1.409 s, −2.1%); stream wall 1.140 → 1.112 s (−2.5%). With hashing on, the difference is
inside noise (1.748 vs 1.744 s), because hashing adds ~0.3 s. The whole-view hash is identical in
all runs.
- **The L8 lever was inflated by L8's own instrumentation.** L8's profile build reported LOD1 at
4.06 worker-s; the plain `linux7shared` binary spends 1.21. Per-LOD shares from instrumented builds
must be re-checked on a plain build before they're ranked.
- The "baseline ELF contains GCC and Clang objects" remark is expected: crt/libstdc++ objects always
come from GCC. The compiler-matched controls are the right comparison, as Luna did.
- Proof read: for native SurfaceWorld step-2 tiles the verdict uses exact column extrema over the
padded block (cells plus the −1..+9 normal halo) for density `min(z−ground, cap−z)`. Features, edits,
mixed strata and Unknown verdicts all fill. The 80,502-block audit found 0 violations.
+92 -393
View File
@@ -42,7 +42,6 @@ namespace StandaloneScreenSpaceGate
double MaximumSlopeDegrees=0.0;
std::array<std::uint64_t,4> SlopeSamples{};
std::array<double,4> SlopeP99{},SlopeMaximum{};
std::vector<double> SamplePixels;
bool Valid=false;
};
@@ -53,14 +52,6 @@ namespace StandaloneScreenSpaceGate
double SlopeY=0.0;
};
struct FMeshSurfaceHit
{
double Z=0.0;
std::array<double,3> Normal{};
std::array<std::uint8_t,4> Color{};
bool Ceiling=false;
};
struct FViewBasis
{
std::array<double,3> Right{};
@@ -171,7 +162,7 @@ namespace StandaloneScreenSpaceGate
{
int Side=65;
double MinimumX=0.0,MaximumX=0.0,MinimumY=0.0,MaximumY=0.0;
std::vector<std::vector<FMeshSurfaceHit>> Hits;
std::vector<std::vector<double>> Hits;
FHeightGrid()=default;
FHeightGrid(int InSide,double MinX,double MaxX,double MinY,double MaxY)
@@ -184,13 +175,13 @@ namespace StandaloneScreenSpaceGate
double Y(int Iy) const
{return MinimumY+(MaximumY-MinimumY)*Iy/(Side-1);}
void Add(int Ix,int Iy,const FMeshSurfaceHit& Hit)
void Add(int Ix,int Iy,double Z)
{
auto& Values=Hits[static_cast<std::size_t>(Iy)*Side+Ix];
Values.push_back(Hit);
Values.push_back(Z);
}
const std::vector<FMeshSurfaceHit>& At(int Ix,int Iy) const
const std::vector<double>& At(int Ix,int Iy) const
{return Hits[static_cast<std::size_t>(Iy)*Side+Ix];}
};
@@ -255,8 +246,6 @@ namespace StandaloneScreenSpaceGate
{
if(!Tile||Tile->Indices.size()<3)continue;
const std::size_t TriangleCount=Tile->Indices.size()/3;
const std::size_t CeilingStart=TriangleCount
-std::min<std::size_t>(TriangleCount,Tile->CeilingTriangleCount);
for(std::size_t Triangle=0;Triangle<TriangleCount;++Triangle)
{
if(Triangle<Tile->TriangleSkirtFaceMasks.size()
@@ -285,33 +274,15 @@ namespace StandaloneScreenSpaceGate
const double W1=((C[1]-A[1])*(X-C[0])+(A[0]-C[0])*(Y-C[1]))/Denominator;
const double W2=1.0-W0-W1;
if(W0<-1e-6||W1<-1e-6||W2<-1e-6)continue;
const auto& VA=Tile->Vertices[I0];
const auto& VB=Tile->Vertices[I1];
const auto& VC=Tile->Vertices[I2];
std::array<double,3> Normal{};
for(int Axis=0;Axis<3;++Axis)
Normal[Axis]=W0*VA.Normal[Axis]+W1*VB.Normal[Axis]+W2*VC.Normal[Axis];
const double NormalLength=std::sqrt(Normal[0]*Normal[0]
+Normal[1]*Normal[1]+Normal[2]*Normal[2]);
if(NormalLength>1.0e-12)
for(double& Component:Normal)Component/=NormalLength;
std::array<std::uint8_t,4> Color{};
if(Tile->VertexColors.size()==Tile->Vertices.size())
for(int Channel=0;Channel<4;++Channel)
Color[Channel]=static_cast<std::uint8_t>(std::clamp(std::lround(
W0*Tile->VertexColors[I0][Channel]
+W1*Tile->VertexColors[I1][Channel]
+W2*Tile->VertexColors[I2][Channel]),0l,255l));
Grid.Add(Ix,Iy,{W0*A[2]+W1*B[2]+W2*C[2],Normal,Color,Triangle>=CeilingStart});
Grid.Add(Ix,Iy,W0*A[2]+W1*B[2]+W2*C[2]);
}
}
}
for(auto& Values:Grid.Hits)
{
std::stable_sort(Values.begin(),Values.end(),[](const FMeshSurfaceHit& A,
const FMeshSurfaceHit& B){return A.Z<B.Z;});
Values.erase(std::unique(Values.begin(),Values.end(),[](const FMeshSurfaceHit& A,
const FMeshSurfaceHit& B){return std::abs(A.Z-B.Z)<0.02;}),Values.end());
std::sort(Values.begin(),Values.end());
Values.erase(std::unique(Values.begin(),Values.end(),[](double A,double B)
{return std::abs(A-B)<0.02;}),Values.end());
}
return Grid;
}
@@ -364,14 +335,14 @@ namespace StandaloneScreenSpaceGate
return Roots;
}
inline bool MatchNearest(const std::vector<FMeshSurfaceHit>& Hits,const std::vector<bool>& Used,
inline bool MatchNearest(const std::vector<double>& Hits,const std::vector<bool>& Used,
double Root,std::size_t& OutIndex,double& OutError)
{
double Best=std::numeric_limits<double>::infinity();std::size_t BestIndex=Hits.size();
for(std::size_t I=0;I<Hits.size();++I)
if(I>=Used.size()||!Used[I])
{
const double Error=std::abs(Hits[I].Z-Root);
const double Error=std::abs(Hits[I]-Root);
if(Error<Best){Best=Error;BestIndex=I;}
}
if(BestIndex==Hits.size())return false;
@@ -400,7 +371,7 @@ namespace StandaloneScreenSpaceGate
continue;
}
Used[HitIndex]=true;
AddError(Accumulator,MeshGrid.At(Ix,Iy)[HitIndex].Z-Root.ZMeters,
AddError(Accumulator,MeshGrid.At(Ix,Iy)[HitIndex]-Root.ZMeters,
Root,PixelBudgetMeters,View,MeshGrid.X(Ix),MeshGrid.Y(Iy));
++Row.Samples;
}
@@ -428,7 +399,7 @@ namespace StandaloneScreenSpaceGate
std::vector<bool> UsedReference(Reference.size(),false),UsedMesh(Mesh.size(),false);
for(std::size_t ReferenceIndex=0;ReferenceIndex<Reference.size();++ReferenceIndex)
{
const double ReferenceZ=Reference[ReferenceIndex].Z;
const double ReferenceZ=Reference[ReferenceIndex];
UsedReference[ReferenceIndex]=true;
std::size_t MeshIndex=0;double MeshError=0.0;
if(!MatchNearest(Mesh,UsedMesh,ReferenceZ,MeshIndex,MeshError))
@@ -445,7 +416,7 @@ namespace StandaloneScreenSpaceGate
if(BestRoot!=Roots.end()&&std::abs(BestRoot->ZMeters-ReferenceZ)<1.0)
Root=*BestRoot;
}
AddError(Accumulator,Mesh[MeshIndex].Z-Reference[ReferenceIndex].Z,
AddError(Accumulator,Mesh[MeshIndex]-Reference[ReferenceIndex],
Root,PixelBudgetMeters,View,ReferenceGrid.X(Ix),ReferenceGrid.Y(Iy));
}
for(std::size_t I=0;I<Mesh.size();++I)
@@ -455,110 +426,6 @@ namespace StandaloneScreenSpaceGate
return Row;
}
struct FMeshComparisonRow
{
FErrorRow Geometry;
std::uint64_t Holes=0,Cracks=0,Floating=0,MaterialMismatches=0;
double ShadeP50=0.0,ShadeP99=0.0,ShadeMaximum=0.0;
double NormalDegreesP50=0.0,NormalDegreesP99=0.0,NormalDegreesMaximum=0.0;
std::vector<double> GeometryPixels,ShadeValues,NormalAngles;
bool Valid=false;
};
inline std::array<double,3> UnitNormal(const FMeshSurfaceHit& Hit)
{
std::array<double,3> N=Hit.Normal;
const double Length=std::sqrt(N[0]*N[0]+N[1]*N[1]+N[2]*N[2]);
if(Length<=1.0e-12)return {0.0,0.0,Hit.Ceiling?-1.0:1.0};
for(double& Component:N)Component/=Length;
return N;
}
inline FMeshComparisonRow CompareMeshes(const FHeightGrid& Reference,
const FHeightGrid& Candidate,const FVoxelTileKey& Patch,double VoxelMeters,
double PixelBudgetMeters,const FViewBasis& View)
{
FMeshComparisonRow Row;Row.Valid=Reference.Side==Candidate.Side;
if(!Row.Valid)return Row;
FErrorAccumulator Geometry;
std::vector<double> ShadeValues,NormalAngles;
const std::size_t CellCount=static_cast<std::size_t>(Reference.Side)*Reference.Side;
ShadeValues.reserve(CellCount);NormalAngles.reserve(CellCount);
const double LightLength=std::sqrt(0.3*0.3+(-0.4)*(-0.4)+0.85*0.85);
const std::array<double,3> Light={0.3/LightLength,-0.4/LightLength,0.85/LightLength};
for(int Iy=0;Iy<Reference.Side;++Iy)
for(int Ix=0;Ix<Reference.Side;++Ix)
{
const auto& Before=Reference.At(Ix,Iy);
const auto& After=Candidate.At(Ix,Iy);
std::vector<bool> Used(After.size(),false);
for(std::size_t I=0;I<Before.size();++I)
{
std::size_t Matched=0;double Difference=0.0;
if(!MatchNearest(After,Used,Before[I].Z,Matched,Difference))
{
++Row.Holes;AddMissing(Geometry);ShadeValues.push_back(1.0);
NormalAngles.push_back(180.0);continue;
}
Used[Matched]=true;
const FMeshSurfaceHit& A=Before[I];
const FMeshSurfaceHit& B=After[Matched];
const auto NA=UnitNormal(A),NB=UnitNormal(B);
const double Dot=std::clamp(NA[0]*NB[0]+NA[1]*NB[1]+NA[2]*NB[2],-1.0,1.0);
constexpr double Pi=3.14159265358979323846;
const double Angle=std::acos(Dot)*180.0/Pi;
NormalAngles.push_back(Angle);
const double DiffuseA=std::max(0.0,NA[0]*Light[0]+NA[1]*Light[1]+NA[2]*Light[2]);
const double DiffuseB=std::max(0.0,NB[0]*Light[0]+NB[1]*Light[1]+NB[2]*Light[2]);
const bool bMaterialChanged=A.Color[0]!=B.Color[0]||A.Color[3]!=B.Color[3]
||A.Ceiling!=B.Ceiling;
if(bMaterialChanged)++Row.MaterialMismatches;
const double MaterialDelta=bMaterialChanged?1.0:std::max(
std::abs(static_cast<double>(A.Color[1])-B.Color[1]),
std::abs(static_cast<double>(A.Color[2])-B.Color[2]))/255.0;
ShadeValues.push_back(std::max(std::abs(DiffuseA-DiffuseB),MaterialDelta));
const double NX=NA[2]<0.0?NA[0]/std::max(1.0e-12,-NA[2])
:-NA[0]/std::max(1.0e-12,NA[2]);
const double NY=NA[2]<0.0?NA[1]/std::max(1.0e-12,-NA[2])
:-NA[1]/std::max(1.0e-12,NA[2]);
AddError(Geometry,B.Z-A.Z,{A.Z,NX,NY},PixelBudgetMeters,View,
Reference.X(Ix),Reference.Y(Iy));
}
for(std::size_t I=0;I<After.size();++I)
if(!Used[I])
{++Row.Floating;AddMissing(Geometry);ShadeValues.push_back(1.0);NormalAngles.push_back(180.0);}
}
for(int Iy=0;Iy<Reference.Side;++Iy)
for(int Ix=0;Ix<Reference.Side;++Ix)
{
const std::size_t Index=static_cast<std::size_t>(Iy)*Reference.Side+Ix;
const auto CheckEdge=[&](int NX,int NY)
{
if(NX>=Reference.Side||NY>=Reference.Side)return;
const auto& A=Reference.Hits[Index];
const auto& B=Reference.At(NX,NY);
const auto& CA=Candidate.Hits[Index];
const auto& CB=Candidate.At(NX,NY);
if(!A.empty()&&!B.empty()&&(CA.empty()!=CB.empty()))++Row.Cracks;
};
CheckEdge(Ix+1,Iy);CheckEdge(Ix,Iy+1);
}
Row.Geometry.Lod=Patch.Level;Row.Geometry.Valid=Row.Valid;
Row.Geometry.Missing=Row.Holes;Row.Geometry.Floating=Row.Floating;
FinalizeError(Row.Geometry,Geometry);
Row.ShadeP50=Percentile(ShadeValues,0.50);
Row.ShadeP99=Percentile(ShadeValues,0.99);
Row.ShadeMaximum=ShadeValues.empty()?0.0:*std::max_element(ShadeValues.begin(),ShadeValues.end());
Row.NormalDegreesP50=Percentile(NormalAngles,0.50);
Row.NormalDegreesP99=Percentile(NormalAngles,0.99);
Row.NormalDegreesMaximum=NormalAngles.empty()?0.0
:*std::max_element(NormalAngles.begin(),NormalAngles.end());
Row.GeometryPixels=std::move(Geometry.Pixels);
Row.ShadeValues=std::move(ShadeValues);
Row.NormalAngles=std::move(NormalAngles);
return Row;
}
inline FPopRow ComparePop(const FHeightGrid& Coarse,const FHeightGrid& Fine,
const FVoxelTileKey& Patch,double VoxelMeters,double PixelBudgetMeters,
const VoxelForgeCore::WorldAssemblyManifest& Assembly,const FViewBasis& View)
@@ -585,12 +452,11 @@ namespace StandaloneScreenSpaceGate
}
CoarseUsed[CoarseIndex]=true;
FineUsed[FineIndex]=true;
AddError(Accumulator,CoarseHits[CoarseIndex].Z-FineHits[FineIndex].Z,
AddError(Accumulator,CoarseHits[CoarseIndex]-FineHits[FineIndex],
Root,PixelBudgetMeters,View,Coarse.X(Ix),Coarse.Y(Iy));
++Row.Samples;
}
}
Row.SamplePixels=Accumulator.Pixels;
FErrorRow Stats;Stats.Lod=Patch.Level;Stats.Valid=true;
FinalizeError(Stats,Accumulator);
Row.Samples=Stats.Samples;Row.P50=Stats.P50;Row.P99=Stats.P99;Row.Maximum=Stats.Maximum;
@@ -606,16 +472,6 @@ namespace StandaloneScreenSpaceGate
return Row;
}
inline bool PopNotWorseAtAnySample(const FPopRow& Before,const FPopRow& After)
{
if(!Before.Valid||!After.Valid||Before.Samples<16
||Before.SamplePixels.size()!=After.SamplePixels.size()
||After.Cracks>Before.Cracks||After.Floating>Before.Floating)return false;
for(std::size_t I=0;I<Before.SamplePixels.size();++I)
if(After.SamplePixels[I]>Before.SamplePixels[I]+1.0e-4)return false;
return true;
}
inline std::array<double,9> ClosestDisplayedDistancesMeters(
const FStandaloneOwnerWorld& World,const FVector& CameraVoxels,
std::uint32_t VoxelSizeMicrons)
@@ -688,7 +544,6 @@ namespace StandaloneScreenSpaceGate
inline bool Run(const std::array<std::optional<FStandaloneCpuTile>,9>& SampleTiles,
FStandaloneStreamingGenerator& Streamer,
const std::vector<FVoxelTileKey>& DesiredKeys,
const VoxelForgeCore::WorldAssemblyManifest& Assembly,
const std::array<double,9>& Distances,std::uint32_t VoxelSizeMicrons,int MaxLod,
const std::array<std::int64_t,9>& PixelBudgetsSubvoxels,
@@ -697,26 +552,17 @@ namespace StandaloneScreenSpaceGate
const double VoxelMeters=static_cast<double>(VoxelSizeMicrons)/1000000.0;
const FViewBasis View=MakeViewBasis(CameraYawDegrees,CameraPitchDegrees);
std::array<double,9> Budgets{};
VoxelForgeCore::TileGenerationOptions BaselineOptions;
BaselineOptions.overrideFarDisplayMesh=true;
VoxelForgeCore::TileGenerationOptions CandidateOptions;
CandidateOptions.overrideFarDisplayMesh=true;
CandidateOptions.farDisplayGeometryBudgetMillipixels=Assembly.recipe.farDisplayGeometryBudgetMillipixels;
CandidateOptions.farRefinementGridScale=Assembly.recipe.farRefinementGridScale;
CandidateOptions.farRefinementLodMask=Assembly.recipe.farRefinementLodMask;
CandidateOptions.farConnectorStationScale=Assembly.recipe.farConnectorStationScale;
CandidateOptions.farConnectorRayMask=Assembly.recipe.farConnectorRayMask;
CandidateOptions.farConnectorReuseStationRadii=Assembly.recipe.farConnectorReuseStationRadii;
std::array<FErrorRow,9> ErrorRows{};
std::array<FPopRow,9> PopRows{};
bool GatePass=true;
constexpr double ShadeLimit=1.0/255.0;
std::printf("[ScreenSpaceGate] angular_pixel=%.9f rad (horizontal_fov=90deg,width=2560) lod>=3_geometry_limit=1.0px same_lod_reference=today mesh sampling=65x65 skirts=excluded shading=max(lambert-delta,material-selector-or-blend-delta) shade_limit=1/255 normal_probe_vox=1 view_yaw_deg=%.3f view_pitch_deg=%.3f\n",
std::printf("[ScreenSpaceGate] angular_pixel=%.9f rad (horizontal_fov=90deg,width=2560) lod>=3_limit=1.0px sampling=65x65 skirts=excluded metric=local_surface_normal_projected field_reference=direct-Heightfield2D-roots normal_probe_vox=1 view_yaw_deg=%.3f view_pitch_deg=%.3f\n",
OnePixelRadians,CameraYawDegrees,CameraPitchDegrees);
for(int Lod=0;Lod<=MaxLod&&Lod<9;++Lod)
{
Budgets[Lod]=Distances[Lod]*OnePixelRadians;
std::printf("[ScreenSpaceDistance] lod=%d closest_m=%.3f pixel_budget_m=%.6f pixel_budget_cm=%.3f pixel_budget_subvoxels=%lld rule=%s\n",
Lod,Distances[Lod],Budgets[Lod],Budgets[Lod]*100.0,
static_cast<long long>(PixelBudgetsSubvoxels[Lod]),Lod<3?"exact-2cm":"same_lod_1px");
static_cast<long long>(PixelBudgetsSubvoxels[Lod]),Lod<3?"exact-2cm":"1px");
}
const double LOD3CellMeters=static_cast<double>(CHUNK_SIZE*(1<<3))*VoxelMeters/64.0;
PrintKnownFailureControl(LOD3CellMeters,Distances[3],View);
@@ -732,117 +578,115 @@ namespace StandaloneScreenSpaceGate
const FStandaloneCpuTile* CoarsePtr=&CoarseTile;
const std::span<const FStandaloneCpuTile* const> CoarseSpan(&CoarsePtr,1);
const FHeightGrid CoarseGrid=Rasterize(CoarseSpan,CoarseTile.Key,VoxelMeters);
FStandaloneCpuTile BaselineTile=Streamer.GenerateDiagnostic(
CoarseTile.Key,0,1,true,&BaselineOptions,true);
const FStandaloneCpuTile* BaselinePointer=&BaselineTile;
const std::span<const FStandaloneCpuTile* const> BaselineSpan(&BaselinePointer,1);
const FHeightGrid BaselineGrid=Rasterize(BaselineSpan,BaselineTile.Key,VoxelMeters);
const FMeshComparisonRow MeshDelta=CompareMeshes(BaselineGrid,CoarseGrid,
CoarseTile.Key,VoxelMeters,Budgets[Lod],View);
const FErrorRow& Error=MeshDelta.Geometry;
const FStandaloneCpuTile ExactTile=Streamer.GenerateDiagnostic(
CoarseTile.Key,0,1,true);
const FStandaloneCpuTile* ExactPointer=&ExactTile;
const std::span<const FStandaloneCpuTile* const> ExactSpan(&ExactPointer,1);
const FHeightGrid ExactGrid=Rasterize(ExactSpan,ExactTile.Key,VoxelMeters);
ErrorRows[Lod]=CompareToReference(CoarseGrid,ExactGrid,CoarseTile.Key,VoxelMeters,
Budgets[Lod],Assembly,View);
const FErrorRow& Error=ErrorRows[Lod];
const bool LodPass=Error.Valid&&Error.Missing==0&&Error.Floating==0
&&MeshDelta.Cracks==0&&Error.Samples>=16&&Error.Maximum<=1.0
&&MeshDelta.ShadeMaximum<=ShadeLimit;
&&Error.Samples>=16&&Error.Maximum<=1.0;
GatePass=GatePass&&LodPass;
std::printf("[ScreenSpaceGateLOD] lod=%d key=(%d,%d,%d) samples=%llu geometry_px_p50=%.4f p99=%.4f max=%.4f shading_delta_p50=%.6f p99=%.6f max=%.6f normal_deg_p50=%.4f p99=%.4f max=%.4f material_mismatch=%llu holes=%llu cracks=%llu floating=%llu status=%s\n",
std::printf("[ScreenSpaceGateLOD] lod=%d key=(%d,%d,%d) samples=%llu normal_px_p50=%.4f p99=%.4f max=%.4f vertical_px_p50=%.4f p99=%.4f max=%.4f max_normal_m=%.6f max_xy_m=(%.3f,%.3f) max_slope_deg=%.2f missing=%llu floating=%llu status=%s\n",
Lod,CoarseTile.Key.Coord.X,CoarseTile.Key.Coord.Y,CoarseTile.Key.Coord.Z,
static_cast<unsigned long long>(Error.Samples),Error.P50,Error.P99,Error.Maximum,
MeshDelta.ShadeP50,MeshDelta.ShadeP99,MeshDelta.ShadeMaximum,
MeshDelta.NormalDegreesP50,MeshDelta.NormalDegreesP99,MeshDelta.NormalDegreesMaximum,
static_cast<unsigned long long>(MeshDelta.MaterialMismatches),
static_cast<unsigned long long>(MeshDelta.Holes),
static_cast<unsigned long long>(MeshDelta.Cracks),
static_cast<unsigned long long>(MeshDelta.Floating),
Error.VerticalP50,Error.VerticalP99,Error.VerticalMaximum,
Error.MaximumNormalDistanceMeters,Error.MaximumX,Error.MaximumY,
Error.MaximumSlopeDegrees,
static_cast<unsigned long long>(Error.Missing),static_cast<unsigned long long>(Error.Floating),
LodPass?"PASS":"REJECT");
PrintSlopeTail("same_lod",Lod,Error.SlopeSamples,Error.SlopeP99,Error.SlopeMaximum);
const FErrorRow FieldError=CompareToExact(CoarseGrid,CoarseTile.Key,VoxelMeters,
Budgets[Lod],Assembly,View);
const bool FieldPass=FieldError.Valid&&FieldError.Missing==0&&FieldError.Floating==0
&&FieldError.Samples>=16&&FieldError.Maximum<=1.0;
std::printf("[ScreenSpaceGateFieldLOD] lod=%d samples=%llu field_geometry_px_p50=%.4f p99=%.4f max=%.4f missing=%llu floating=%llu status=INFO_ONLY\n",
GatePass=GatePass&&FieldPass;
std::printf("[ScreenSpaceGateFieldLOD] lod=%d samples=%llu normal_px_p50=%.4f p99=%.4f max=%.4f vertical_px_p50=%.4f p99=%.4f max=%.4f max_normal_m=%.6f max_xyz_m=(%.3f,%.3f,%.3f) max_slope_deg=%.2f missing=%llu floating=%llu status=%s\n",
Lod,static_cast<unsigned long long>(FieldError.Samples),FieldError.P50,
FieldError.P99,FieldError.Maximum,
FieldError.P99,FieldError.Maximum,FieldError.VerticalP50,FieldError.VerticalP99,
FieldError.VerticalMaximum,FieldError.MaximumNormalDistanceMeters,
FieldError.MaximumX,FieldError.MaximumY,FieldError.MaximumDisplayedZ,
FieldError.MaximumSlopeDegrees,
static_cast<unsigned long long>(FieldError.Missing),
static_cast<unsigned long long>(FieldError.Floating));
static_cast<unsigned long long>(FieldError.Floating),FieldPass?"PASS":"REJECT");
PrintSlopeTail("field",Lod,FieldError.SlopeSamples,FieldError.SlopeP99,
FieldError.SlopeMaximum);
bool FaultControlsPass=true;
const FHeightGrid MissingGrid(BaselineGrid.Side,BaselineGrid.MinimumX,BaselineGrid.MaximumX,
BaselineGrid.MinimumY,BaselineGrid.MaximumY);
const FMeshComparisonRow MissingError=CompareMeshes(BaselineGrid,MissingGrid,
CoarseTile.Key,VoxelMeters,Budgets[Lod],View);
const bool MissingRejected=MissingError.Holes>0&&MissingError.Geometry.Maximum>1.0;
const FHeightGrid MissingGrid(ExactGrid.Side,ExactGrid.MinimumX,ExactGrid.MaximumX,
ExactGrid.MinimumY,ExactGrid.MaximumY);
const FErrorRow MissingError=CompareToReference(MissingGrid,ExactGrid,
CoarseTile.Key,VoxelMeters,Budgets[Lod],Assembly,View);
const bool MissingRejected=MissingError.Missing>0&&MissingError.Maximum>1.0;
FaultControlsPass=FaultControlsPass&&MissingRejected;
std::printf("[ScreenSpaceFaultInjection] lod=%d case=missing-displayed-surface holes=%llu status=%s\n",
Lod,static_cast<unsigned long long>(MissingError.Holes),
std::printf("[ScreenSpaceFaultInjection] lod=%d case=missing-displayed-surface missing=%llu status=%s\n",
Lod,static_cast<unsigned long long>(MissingError.Missing),
MissingRejected?"REJECTED_AS_REQUIRED":"GATE_FALSE_NEGATIVE");
FStandaloneCpuTile FloatingTile=BaselineTile;
FStandaloneCpuTile FloatingTile=CoarseTile;
const std::uint32_t FloatingVertexBase=static_cast<std::uint32_t>(FloatingTile.Vertices.size());
for(FStandaloneCpuVertex Vertex:BaselineTile.Vertices)
for(FStandaloneCpuVertex Vertex:CoarseTile.Vertices)
{
Vertex.Position[2]+=2.0f;
FloatingTile.Vertices.push_back(Vertex);
}
FloatingTile.VertexColors.insert(FloatingTile.VertexColors.end(),
BaselineTile.VertexColors.begin(),BaselineTile.VertexColors.end());
for(const std::uint32_t Index:BaselineTile.Indices)
for(const std::uint32_t Index:CoarseTile.Indices)
FloatingTile.Indices.push_back(FloatingVertexBase+Index);
FloatingTile.TriangleSkirtFaceMasks.insert(FloatingTile.TriangleSkirtFaceMasks.end(),
BaselineTile.TriangleSkirtFaceMasks.begin(),BaselineTile.TriangleSkirtFaceMasks.end());
CoarseTile.TriangleSkirtFaceMasks.begin(),CoarseTile.TriangleSkirtFaceMasks.end());
const FStandaloneCpuTile* FloatingPointer=&FloatingTile;
const std::span<const FStandaloneCpuTile* const> FloatingSpan(&FloatingPointer,1);
const FHeightGrid FloatingGrid=Rasterize(FloatingSpan,BaselineTile.Key,VoxelMeters);
const FMeshComparisonRow FloatingError=CompareMeshes(BaselineGrid,FloatingGrid,
CoarseTile.Key,VoxelMeters,Budgets[Lod],View);
const bool FloatingRejected=FloatingError.Floating>0||FloatingError.Geometry.Maximum>1.0;
const FHeightGrid FloatingGrid=Rasterize(FloatingSpan,CoarseTile.Key,VoxelMeters);
const FErrorRow FloatingError=CompareToReference(FloatingGrid,ExactGrid,
CoarseTile.Key,VoxelMeters,Budgets[Lod],Assembly,View);
const bool FloatingRejected=FloatingError.Floating>0||FloatingError.Maximum>1.0;
FaultControlsPass=FaultControlsPass&&FloatingRejected;
std::printf("[ScreenSpaceFaultInjection] lod=%d case=2m-floating-surface floating=%llu max_px=%.4f status=%s\n",
Lod,static_cast<unsigned long long>(FloatingError.Floating),FloatingError.Geometry.Maximum,
Lod,static_cast<unsigned long long>(FloatingError.Floating),FloatingError.Maximum,
FloatingRejected?"REJECTED_AS_REQUIRED":"GATE_FALSE_NEGATIVE");
std::vector<FStandaloneCpuTile> FineBeforeTiles,FineAfterTiles;
FineBeforeTiles.reserve(8);FineAfterTiles.reserve(8);
std::vector<FStandaloneCpuTile> FineTiles;
FineTiles.reserve(8);
for(int Dz=0;Dz<=1;++Dz)
for(int Dy=0;Dy<=1;++Dy)
for(int Dx=0;Dx<=1;++Dx)
{
const FVoxelTileKey FineKey(FIntVector(2*CoarseTile.Key.Coord.X+Dx,
2*CoarseTile.Key.Coord.Y+Dy,2*CoarseTile.Key.Coord.Z+Dz),Lod-1);
FStandaloneCpuTile FineBefore=Streamer.GenerateDiagnostic(
FineKey,0,1,true,&BaselineOptions,true);
FStandaloneCpuTile FineAfter=Streamer.GenerateDiagnostic(
FineKey,0,1,true,nullptr,true);
if(!FineBefore.Vertices.empty())FineBeforeTiles.push_back(std::move(FineBefore));
if(!FineAfter.Vertices.empty())FineAfterTiles.push_back(std::move(FineAfter));
FStandaloneCpuTile FineTile=Streamer.GenerateDiagnostic(FineKey);
if(!FineTile.Vertices.empty())FineTiles.push_back(std::move(FineTile));
}
std::vector<const FStandaloneCpuTile*> FineBeforePointers,FineAfterPointers;
FineBeforePointers.reserve(FineBeforeTiles.size());FineAfterPointers.reserve(FineAfterTiles.size());
for(const auto& Tile:FineBeforeTiles)FineBeforePointers.push_back(&Tile);
for(const auto& Tile:FineAfterTiles)FineAfterPointers.push_back(&Tile);
const auto FineBeforeSpan=std::span<const FStandaloneCpuTile* const>(
FineBeforePointers.data(),FineBeforePointers.size());
const auto FineAfterSpan=std::span<const FStandaloneCpuTile* const>(
FineAfterPointers.data(),FineAfterPointers.size());
const FHeightGrid FineBeforeGrid=Rasterize(FineBeforeSpan,CoarseTile.Key,VoxelMeters);
const FHeightGrid FineAfterGrid=Rasterize(FineAfterSpan,CoarseTile.Key,VoxelMeters);
const FPopRow PopBefore=ComparePop(BaselineGrid,FineBeforeGrid,CoarseTile.Key,VoxelMeters,
std::vector<const FStandaloneCpuTile*> FinePointers;
FinePointers.reserve(FineTiles.size());
for(const auto& Tile:FineTiles)FinePointers.push_back(&Tile);
const auto FineSpan=std::span<const FStandaloneCpuTile* const>(
FinePointers.data(),FinePointers.size());
const FHeightGrid FineGrid=Rasterize(FineSpan,CoarseTile.Key,VoxelMeters);
PopRows[Lod]=ComparePop(CoarseGrid,FineGrid,CoarseTile.Key,VoxelMeters,
Budgets[Lod],Assembly,View);
const FPopRow PopAfter=ComparePop(CoarseGrid,FineAfterGrid,CoarseTile.Key,VoxelMeters,
Budgets[Lod],Assembly,View);
const bool PopPass=PopNotWorseAtAnySample(PopBefore,PopAfter);
const FPopRow& Pop=PopRows[Lod];
const bool PopPass=Pop.Valid&&Pop.Cracks==0&&Pop.Floating==0&&Pop.Maximum<=1.0;
GatePass=GatePass&&PopPass;
std::printf("[ScreenSpaceSwap] swap=%d_to_%d distance_m=%.3f samples_before=%llu pop_before_px_p50=%.4f p99=%.4f max=%.4f pop_after_px_p50=%.4f p99=%.4f max=%.4f missing_root_samples_before=%llu after=%llu status=%s\n",
Lod,Lod-1,Distances[Lod],static_cast<unsigned long long>(PopBefore.Samples),
PopBefore.P50,PopBefore.P99,PopBefore.Maximum,PopAfter.P50,PopAfter.P99,PopAfter.Maximum,
static_cast<unsigned long long>(PopBefore.Cracks),static_cast<unsigned long long>(PopAfter.Cracks),
std::printf("[ScreenSpaceSwap] lod=%d_to_%d samples=%llu normal_px_p50=%.4f p99=%.4f max=%.4f vertical_px_p50=%.4f p99=%.4f max=%.4f max_normal_m=%.6f max_xyz_m=(%.3f,%.3f,%.3f) max_slope_deg=%.2f cracks=%llu floating=%llu status=%s\n",
Lod,Lod-1,static_cast<unsigned long long>(Pop.Samples),
Pop.P50,Pop.P99,Pop.Maximum,Pop.VerticalP50,Pop.VerticalP99,Pop.VerticalMaximum,
Pop.MaximumNormalDistanceMeters,Pop.MaximumX,Pop.MaximumY,
Pop.MaximumDisplayedZ,
Pop.MaximumSlopeDegrees,static_cast<unsigned long long>(Pop.Cracks),
static_cast<unsigned long long>(Pop.Floating),
PopPass?"PASS":"REJECT");
PrintSlopeTail("swap",Lod,Pop.SlopeSamples,Pop.SlopeP99,Pop.SlopeMaximum);
const FHeightGrid MissingFineGrid(BaselineGrid.Side,BaselineGrid.MinimumX,
BaselineGrid.MaximumX,BaselineGrid.MinimumY,BaselineGrid.MaximumY);
const FPopRow MissingFineError=ComparePop(BaselineGrid,MissingFineGrid,
const FHeightGrid MissingFineGrid(CoarseGrid.Side,CoarseGrid.MinimumX,
CoarseGrid.MaximumX,CoarseGrid.MinimumY,CoarseGrid.MaximumY);
const FPopRow MissingFineError=ComparePop(CoarseGrid,MissingFineGrid,
CoarseTile.Key,VoxelMeters,Budgets[Lod],Assembly,View);
const bool CrackRejected=MissingFineError.Cracks>0&&MissingFineError.Maximum>1.0;
FaultControlsPass=FaultControlsPass&&CrackRejected;
GatePass=GatePass&&FaultControlsPass;
std::printf("[ScreenSpaceFaultInjection] lod=%d case=missing-fine-ring-surface cracks=%llu max_px=%.4f status=%s\n",
Lod,static_cast<unsigned long long>(MissingFineError.Cracks),
MissingFineError.Maximum,CrackRejected?"REJECTED_AS_REQUIRED":"GATE_FALSE_NEGATIVE");
@@ -851,170 +695,25 @@ namespace StandaloneScreenSpaceGate
const auto CheckNegative=[&](const char* Name,std::uint32_t Drop,std::uint32_t Stride)
{
FStandaloneCpuTile Bad=Streamer.GenerateDiagnostic(
CoarseTile.Key,Drop,Stride,true,nullptr,true);
CoarseTile.Key,Drop,Stride,true);
const FStandaloneCpuTile* BadPointer=&Bad;
const std::span<const FStandaloneCpuTile* const> BadSpan(&BadPointer,1);
const FHeightGrid BadGrid=Rasterize(BadSpan,Bad.Key,VoxelMeters);
const FMeshComparisonRow BadError=CompareMeshes(BaselineGrid,BadGrid,
CoarseTile.Key,VoxelMeters,Budgets[Lod],View);
const bool Rejected=BadError.Holes>0||BadError.Floating>0||BadError.Cracks>0
||BadError.Geometry.Samples<16||BadError.Geometry.Maximum>1.0
||BadError.ShadeMaximum>ShadeLimit;
const FErrorRow BadError=CompareToReference(BadGrid,ExactGrid,
CoarseTile.Key,VoxelMeters,Budgets[Lod],Assembly,View);
const bool Rejected=BadError.Missing>0||BadError.Floating>0
||BadError.Samples<16||BadError.Maximum>1.0;
NegativeControlsPass=NegativeControlsPass&&Rejected;
std::printf("[ScreenSpaceNegative] lod=%d case=%s p50_px=%.4f p99_px=%.4f max_px=%.4f shade_max=%.6f holes=%llu cracks=%llu floating=%llu status=%s\n",
Lod,Name,BadError.Geometry.P50,BadError.Geometry.P99,BadError.Geometry.Maximum,
BadError.ShadeMaximum,static_cast<unsigned long long>(BadError.Holes),
static_cast<unsigned long long>(BadError.Cracks),
std::printf("[ScreenSpaceNegative] lod=%d case=%s p50_px=%.4f p99_px=%.4f max_px=%.4f missing=%llu floating=%llu status=%s\n",
Lod,Name,BadError.P50,BadError.P99,BadError.Maximum,
static_cast<unsigned long long>(BadError.Missing),
static_cast<unsigned long long>(BadError.Floating),
Rejected?"REJECTED_AS_REQUIRED":"GATE_FALSE_NEGATIVE");
};
CheckNegative("s13-global-octave-drop",1,1);
CheckNegative("stride-2-column-interpolation",0,2);
GatePass=GatePass&&FaultControlsPass&&NegativeControlsPass;
GatePass=GatePass&&NegativeControlsPass;
}
struct FCoverageRow
{
std::uint64_t Tiles=0,Holes=0,Cracks=0,Floating=0,MaterialMismatches=0;
std::vector<double> GeometryPixels,ShadeValues,NormalAngles;
};
std::array<FCoverageRow,9> Coverage;
for(const FVoxelTileKey& Key:DesiredKeys)
{
const int Lod=Key.Level;
if(Lod<3||Lod>MaxLod||Lod>=9)continue;
FStandaloneCpuTile BaselineTile=Streamer.GenerateDiagnostic(
Key,0,1,true,&BaselineOptions,true);
FStandaloneCpuTile CandidateTile=Streamer.GenerateDiagnostic(
Key,0,1,true,&CandidateOptions,true);
const FStandaloneCpuTile* BaselinePointer=&BaselineTile;
const FStandaloneCpuTile* CandidatePointer=&CandidateTile;
const std::span<const FStandaloneCpuTile* const> BaselineSpan(&BaselinePointer,1);
const std::span<const FStandaloneCpuTile* const> CandidateSpan(&CandidatePointer,1);
const FHeightGrid BaselineGrid=Rasterize(BaselineSpan,Key,VoxelMeters);
const FHeightGrid CandidateGrid=Rasterize(CandidateSpan,Key,VoxelMeters);
const FMeshComparisonRow Delta=CompareMeshes(BaselineGrid,CandidateGrid,
Key,VoxelMeters,Budgets[Lod],View);
auto& Row=Coverage[Lod];
++Row.Tiles;
Row.Holes+=Delta.Holes;Row.Cracks+=Delta.Cracks;Row.Floating+=Delta.Floating;
Row.MaterialMismatches+=Delta.MaterialMismatches;
Row.GeometryPixels.insert(Row.GeometryPixels.end(),
Delta.GeometryPixels.begin(),Delta.GeometryPixels.end());
Row.ShadeValues.insert(Row.ShadeValues.end(),Delta.ShadeValues.begin(),Delta.ShadeValues.end());
Row.NormalAngles.insert(Row.NormalAngles.end(),Delta.NormalAngles.begin(),Delta.NormalAngles.end());
}
for(int Lod=3;Lod<=MaxLod&&Lod<9;++Lod)
{
auto& Row=Coverage[Lod];
const double GeometryP50=Percentile(Row.GeometryPixels,0.50);
const double GeometryP99=Percentile(Row.GeometryPixels,0.99);
const double GeometryMaximum=Row.GeometryPixels.empty()?0.0
:*std::max_element(Row.GeometryPixels.begin(),Row.GeometryPixels.end());
const double ShadeP50=Percentile(Row.ShadeValues,0.50);
const double ShadeP99=Percentile(Row.ShadeValues,0.99);
const double ShadeMaximum=Row.ShadeValues.empty()?0.0
:*std::max_element(Row.ShadeValues.begin(),Row.ShadeValues.end());
const double NormalP50=Percentile(Row.NormalAngles,0.50);
const double NormalP99=Percentile(Row.NormalAngles,0.99);
const double NormalMaximum=Row.NormalAngles.empty()?0.0
:*std::max_element(Row.NormalAngles.begin(),Row.NormalAngles.end());
const bool LodPass=Row.Tiles>0&&Row.GeometryPixels.size()>=16
&&GeometryMaximum<=1.0&&ShadeMaximum<=ShadeLimit
&&Row.Holes==0&&Row.Cracks==0&&Row.Floating==0;
GatePass=GatePass&&LodPass;
std::printf("[ScreenSpaceGateCoverageLOD] lod=%d tiles=%llu geometry_samples=%llu geometry_px_p50=%.4f p99=%.4f max=%.4f shading_delta_p50=%.6f p99=%.6f max=%.6f normal_deg_p50=%.4f p99=%.4f max=%.4f material_mismatch=%llu holes=%llu cracks=%llu floating=%llu status=%s\n",
Lod,static_cast<unsigned long long>(Row.Tiles),
static_cast<unsigned long long>(Row.GeometryPixels.size()),
GeometryP50,GeometryP99,GeometryMaximum,ShadeP50,ShadeP99,ShadeMaximum,
NormalP50,NormalP99,NormalMaximum,
static_cast<unsigned long long>(Row.MaterialMismatches),
static_cast<unsigned long long>(Row.Holes),
static_cast<unsigned long long>(Row.Cracks),
static_cast<unsigned long long>(Row.Floating),LodPass?"PASS":"REJECT");
}
std::uint64_t RepairOpportunities=0,BaselineWallHoles=0,BaselineWallFloating=0;
std::uint64_t CandidateWallRays=0,CandidateWallHoles=0,CandidateWallFloating=0;
std::vector<std::uint64_t> BaselineHoleIds,CandidateHoleIds;
std::vector<std::uint64_t> BaselineFloatingIds,CandidateFloatingIds;
std::vector<std::uint64_t> CandidatePanelRemovalHoleIds;
bool bRanPanelRemovalControl=false;
for(const FVoxelTileKey& Key:DesiredKeys)
{
if(Key.Level<6||Key.Level>8)continue;
VoxelForgeCore::TileGenerationOptions NoPanelBaseline=BaselineOptions;
NoPanelBaseline.diagnosticRemoveFarConnectorPanels=true;
NoPanelBaseline.diagnosticAuditFarConnectorCoverage=true;
const FStandaloneCpuTile BaseNoPanels=Streamer.GenerateDiagnostic(Key,0,1,true,&NoPanelBaseline);
RepairOpportunities+=BaseNoPanels.CoreDiagnostics.farConnectorAuditHoles;
VoxelForgeCore::TileGenerationOptions AuditedBaseline=BaselineOptions;
AuditedBaseline.diagnosticAuditFarConnectorCoverage=true;
const FStandaloneCpuTile BaseRepaired=Streamer.GenerateDiagnostic(Key,0,1,true,&AuditedBaseline);
BaselineWallHoles+=BaseRepaired.CoreDiagnostics.farConnectorAuditHoles;
BaselineWallFloating+=BaseRepaired.CoreDiagnostics.farConnectorAuditFloating;
BaselineHoleIds.insert(BaselineHoleIds.end(),
BaseRepaired.CoreDiagnostics.farConnectorAuditHoleIds.begin(),
BaseRepaired.CoreDiagnostics.farConnectorAuditHoleIds.end());
BaselineFloatingIds.insert(BaselineFloatingIds.end(),
BaseRepaired.CoreDiagnostics.farConnectorAuditFloatingIds.begin(),
BaseRepaired.CoreDiagnostics.farConnectorAuditFloatingIds.end());
VoxelForgeCore::TileGenerationOptions AuditedCandidate=CandidateOptions;
AuditedCandidate.diagnosticAuditFarConnectorCoverage=true;
const FStandaloneCpuTile CandidateRepaired=Streamer.GenerateDiagnostic(Key,0,1,true,&AuditedCandidate);
CandidateWallRays+=CandidateRepaired.CoreDiagnostics.farConnectorAuditRays;
CandidateWallHoles+=CandidateRepaired.CoreDiagnostics.farConnectorAuditHoles;
CandidateWallFloating+=CandidateRepaired.CoreDiagnostics.farConnectorAuditFloating;
CandidateHoleIds.insert(CandidateHoleIds.end(),
CandidateRepaired.CoreDiagnostics.farConnectorAuditHoleIds.begin(),
CandidateRepaired.CoreDiagnostics.farConnectorAuditHoleIds.end());
CandidateFloatingIds.insert(CandidateFloatingIds.end(),
CandidateRepaired.CoreDiagnostics.farConnectorAuditFloatingIds.begin(),
CandidateRepaired.CoreDiagnostics.farConnectorAuditFloatingIds.end());
if(!bRanPanelRemovalControl&&BaseNoPanels.CoreDiagnostics.farConnectorAuditHoles>0)
{
AuditedCandidate.diagnosticRemoveFarConnectorPanels=true;
const FStandaloneCpuTile CandidateNoPanels=Streamer.GenerateDiagnostic(
Key,0,1,true,&AuditedCandidate);
CandidatePanelRemovalHoleIds=CandidateNoPanels.CoreDiagnostics.farConnectorAuditHoleIds;
bRanPanelRemovalControl=true;
}
}
std::sort(BaselineHoleIds.begin(),BaselineHoleIds.end());
std::sort(CandidateHoleIds.begin(),CandidateHoleIds.end());
std::sort(BaselineFloatingIds.begin(),BaselineFloatingIds.end());
std::sort(CandidateFloatingIds.begin(),CandidateFloatingIds.end());
const auto IsSubset=[](const std::vector<std::uint64_t>& A,const std::vector<std::uint64_t>& B)
{return std::includes(B.begin(),B.end(),A.begin(),A.end());};
std::sort(CandidatePanelRemovalHoleIds.begin(),CandidatePanelRemovalHoleIds.end());
const bool bNoNewHoles=IsSubset(CandidateHoleIds,BaselineHoleIds);
const bool bNoNewFloating=IsSubset(CandidateFloatingIds,BaselineFloatingIds);
const bool bPanelRemovalDetected=bRanPanelRemovalControl
&&!IsSubset(CandidatePanelRemovalHoleIds,CandidateHoleIds);
std::vector<std::uint64_t> NewHoleIds,NewFloatingIds,PanelRemovalNewHoleIds;
std::set_difference(CandidateHoleIds.begin(),CandidateHoleIds.end(),
BaselineHoleIds.begin(),BaselineHoleIds.end(),std::back_inserter(NewHoleIds));
std::set_difference(CandidateFloatingIds.begin(),CandidateFloatingIds.end(),
BaselineFloatingIds.begin(),BaselineFloatingIds.end(),std::back_inserter(NewFloatingIds));
std::set_difference(CandidatePanelRemovalHoleIds.begin(),CandidatePanelRemovalHoleIds.end(),
CandidateHoleIds.begin(),CandidateHoleIds.end(),std::back_inserter(PanelRemovalNewHoleIds));
const bool bRepairRowsPass=RepairOpportunities>0&&bNoNewHoles&&bNoNewFloating
&&bPanelRemovalDetected;
GatePass=GatePass&&bRepairRowsPass;
std::printf("[ScreenSpaceConnectorGate] lods=6..8 baseline_missing_ray_stations=%llu candidate_audited_rays=%llu baseline_holes=%llu candidate_holes=%llu new_holes=%llu baseline_floating=%llu candidate_floating=%llu new_floating=%llu panel_removal_new_holes=%llu status=%s\n",
static_cast<unsigned long long>(RepairOpportunities),
static_cast<unsigned long long>(CandidateWallRays),
static_cast<unsigned long long>(BaselineWallHoles),
static_cast<unsigned long long>(CandidateWallHoles),
static_cast<unsigned long long>(NewHoleIds.size()),
static_cast<unsigned long long>(BaselineWallFloating),
static_cast<unsigned long long>(CandidateWallFloating),
static_cast<unsigned long long>(NewFloatingIds.size()),
static_cast<unsigned long long>(PanelRemovalNewHoleIds.size()),
bRepairRowsPass?"PASS":"REJECT");
std::printf("[ScreenSpaceGateResult] status=%s\n",GatePass?"PASS":"REJECT");
return GatePass;
}
+2 -65
View File
@@ -9,7 +9,6 @@
#include <chrono>
#include <cmath>
#include <cstdint>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <filesystem>
@@ -36,17 +35,9 @@ namespace
bool StreamPipeline=false;
bool StreamHash=false;
bool ProfileColumnOverlap=false;
bool UseSharedColumnCache=true;
bool ForceGenerate=false;
bool MeshCoverage=false;
bool ScreenSpaceGate=false;
bool AuditUniformBlockProofs=false;
bool ProfileLodWork=false;
bool AuditBasePageEquivalence=false;
bool AuditRouteParity=false;
bool RegionCrossing=false;
bool AuditTileShapeReadiness=false;
int DiagnosticSlowShapeCompileMs=0;
bool HasSeedOverride=false;
int SeedOverride=0;
bool HasRenderDistanceOverride=false;
@@ -56,10 +47,8 @@ namespace
int TlsProbeWorkers=0;
std::string TlsProbeTouch="none";
bool HasCamera=false;
bool HasCameraStep=false;
bool AutoSurfaceCamera=false;
FVector CameraMeters=FVector::ZeroVector;
FVector CameraStepMeters=FVector::ZeroVector;
float CameraYawDegrees=0.0f;
float CameraPitchDegrees=0.0f;
std::filesystem::path MeshExportPath;
@@ -88,15 +77,6 @@ namespace
return true;
}
bool ParseCameraStep(std::string_view text,FVector& meters)
{
const std::string values(text);
float x=0.0f,y=0.0f,z=0.0f;
if(std::sscanf(values.c_str(),"%f,%f,%f",&x,&y,&z)!=3)return false;
meters={x,y,z};
return true;
}
bool ParseOptions(int argc,char** argv,FOptions& options)
{
const std::filesystem::path executable=std::filesystem::absolute(argv[0]);
@@ -111,21 +91,12 @@ namespace
std::printf("Usage: %s [owner_world.json] --world-assembler-prototype --stream-benchmark --stream-pipeline [options]\n"
" --workers=N --clip-radius=N --max-clip-level=N --max-level=N\n"
" --camera=X,Y,Z,YAW,PITCH (position in metres) --stream-hash\n"
" --camera-step=X,Y,Z (optional second view step in metres)\n"
" --region-crossing (compile entering Core regions at the camera step)\n"
" --column-cache=shared|thread-local (default: shared)\n"
" --mesh-export=FILE (write the exact generated tile meshes for offline rendering)\n"
" --profile-column-overlap --far-horizon-lod8-step=N --force-generate\n"
" --seed=N --recipe=surface-world|floating-islands\n"
" --auto-surface-camera (place the 27-tile cube on this seed's surface)\n"
" --mesh-coverage (report non-empty tiles and indexed triangles)\n"
" --screen-space-gate (measure display error and historical negative controls)\n"
" --audit-uniform-block-proofs (fill and check every interval-certified block)\n"
" --profile-lod-work (report per-LOD density sample counts)\n"
" --audit-base-page-equivalence (hash one tile through both shape routes)\n"
" --audit-route-parity (compare page, native-only, exact-query and mesh routes)\n"
" --audit-tile-shape-readiness (run a deliberately mis-marked tile against the native-only guard)\n"
" --diagnostic-slow-shape-compile-ms=N (diagnostic overlap control; default 0)\n"
" --render-distance-chunks=N (0 disables the extra far ring)\n"
" --tls-probe=N (Linux worker TLS/stack measurement; N=0..12)\n"
" --tls-probe-touch=none|surface-world|floating-islands (first-use probe)\n"
@@ -141,12 +112,6 @@ namespace
else if(arg=="--force-generate")options.ForceGenerate=true;
else if(arg=="--mesh-coverage")options.MeshCoverage=true;
else if(arg=="--screen-space-gate")options.ScreenSpaceGate=true;
else if(arg=="--audit-uniform-block-proofs")options.AuditUniformBlockProofs=true;
else if(arg=="--profile-lod-work")options.ProfileLodWork=true;
else if(arg=="--audit-base-page-equivalence")options.AuditBasePageEquivalence=true;
else if(arg=="--audit-route-parity")options.AuditRouteParity=true;
else if(arg=="--region-crossing")options.RegionCrossing=true;
else if(arg=="--audit-tile-shape-readiness")options.AuditTileShapeReadiness=true;
else if(arg=="--auto-surface-camera")options.AutoSurfaceCamera=true;
else if(arg.starts_with("--recipe="))
{
@@ -184,20 +149,6 @@ namespace
{std::fprintf(stderr,"Invalid --camera value: %.*s\n",static_cast<int>(arg.size()),arg.data());return false;}
options.HasCamera=true;
}
else if(arg.starts_with("--camera-step="))
{
if(!ParseCameraStep(arg.substr(std::string_view("--camera-step=").size()),
options.CameraStepMeters))
{std::fprintf(stderr,"Invalid --camera-step value: %.*s\n",static_cast<int>(arg.size()),arg.data());return false;}
options.HasCameraStep=true;
}
else if(arg.starts_with("--column-cache="))
{
const std::string_view mode=arg.substr(std::string_view("--column-cache=").size());
if(mode=="shared")options.UseSharedColumnCache=true;
else if(mode=="thread-local")options.UseSharedColumnCache=false;
else {std::fprintf(stderr,"Invalid --column-cache value: %.*s\n",static_cast<int>(arg.size()),arg.data());return false;}
}
else if(arg.starts_with("--mesh-export="))
{
options.MeshExportPath=std::filesystem::path(arg.substr(14));
@@ -214,8 +165,6 @@ namespace
{if(!readInt("--max-level=",options.MaxLevel))return false;}
else if(arg.starts_with("--far-horizon-lod8-step="))
{if(!readInt("--far-horizon-lod8-step=",options.FarHorizonLOD8InteriorStepVoxels))return false;}
else if(arg.starts_with("--diagnostic-slow-shape-compile-ms="))
{if(!readInt("--diagnostic-slow-shape-compile-ms=",options.DiagnosticSlowShapeCompileMs))return false;}
else if(arg.starts_with("--process-affinity=")||arg.starts_with("--process-priority=")
||arg.starts_with("--frame-limit="))
{
@@ -230,11 +179,8 @@ namespace
options.ClipRadius=std::clamp(options.ClipRadius,1,64);
options.MaxClipLevel=std::clamp(options.MaxClipLevel,0,8);
options.FarHorizonLOD8InteriorStepVoxels=std::max(0,options.FarHorizonLOD8InteriorStepVoxels);
options.DiagnosticSlowShapeCompileMs=std::clamp(options.DiagnosticSlowShapeCompileMs,0,30000);
if(!options.TlsProbeRequested&&options.TlsProbeTouch!="none")
{std::fprintf(stderr,"--tls-probe-touch requires --tls-probe=N\n");return false;}
if(options.RegionCrossing&&!options.HasCameraStep)
{std::fprintf(stderr,"--region-crossing requires --camera-step=X,Y,Z\n");return false;}
if(options.TlsProbeRequested)return true;
if(!options.WorldAssemblerPrototype||!options.StreamBenchmark||!options.StreamPipeline)
{
@@ -253,12 +199,10 @@ int main(int argc,char** argv)
if(!ParseOptions(argc,argv,options))return 2;
if(options.TlsProbeRequested)
return StandaloneTlsProbe::Run(options.TlsProbeWorkers,options.TlsProbeTouch);
std::printf("[HeadlessConfig] data=%s workers=%d clip_radius=%d max_clip_level=%d max_level=%d hash=%s column_overlap=%s force_generate=%s recipe=%s shared_column_cache=%s camera_step_m=(%.3f,%.3f,%.3f) seed_override=%s render_distance_override=%s\n",
std::printf("[HeadlessConfig] data=%s workers=%d clip_radius=%d max_clip_level=%d max_level=%d hash=%s column_overlap=%s force_generate=%s recipe=%s seed_override=%s render_distance_override=%s\n",
options.DataPath.string().c_str(),options.WorkerCount,options.ClipRadius,options.MaxClipLevel,
options.MaxLevel,options.StreamHash?"on":"off",options.ProfileColumnOverlap?"on":"off",
options.ForceGenerate?"on":"off",options.FloatingIslandsRecipe?"floating-islands":"surface-world",
options.UseSharedColumnCache?"on":"off",options.CameraStepMeters.X,options.CameraStepMeters.Y,
options.CameraStepMeters.Z,
options.HasSeedOverride?"yes":"no",options.HasRenderDistanceOverride?"yes":"no");
std::printf("[ColdTimeline] stage=owner_data_load begin_ms=%.3f\n",
std::chrono::duration<double,std::milli>(Clock::now()-coldStart).count());
@@ -365,17 +309,10 @@ int main(int argc,char** argv)
{std::fprintf(stderr,"Shape interval build failed: %s\n",error.c_str());return 2;}
FStandaloneCoreScheduler scheduler;
const FVector cameraStepVoxels=options.HasCameraStep
?FVector(options.CameraStepMeters.X*4.0f,options.CameraStepMeters.Y*4.0f,
options.CameraStepMeters.Z*4.0f):FVector::ZeroVector;
return StandaloneStreamBenchmark::RunPipelinedStreamingBenchmark(ownerWorld,snapshot,
cameraVoxels,options.WorkerCount,options.MaxLevel,VoxelForgeCore::DetailVariant::coherent,
scheduler,options.StreamHash,false,false,false,false,coldStart,
options.ProfileColumnOverlap,options.FarHorizonLOD8InteriorStepVoxels,
options.MeshCoverage,options.MeshExportPath,options.CameraYawDegrees,
options.CameraPitchDegrees,options.ScreenSpaceGate,options.UseSharedColumnCache,
cameraStepVoxels,options.AuditUniformBlockProofs,options.ProfileLodWork,
options.RegionCrossing,options.AuditTileShapeReadiness,
options.DiagnosticSlowShapeCompileMs,options.AuditBasePageEquivalence,
options.AuditRouteParity);
options.CameraPitchDegrees,options.ScreenSpaceGate);
}
File diff suppressed because it is too large. Load diff
+4 -43
View File
@@ -43,11 +43,9 @@ struct FStandaloneCpuTile
FVoxelTileKey Key;
uint64 RequestedCrossing=0;
std::vector<FStandaloneCpuVertex> Vertices;
std::vector<std::array<uint8,4>> VertexColors;
std::vector<uint32> Indices;
std::vector<uint8> TriangleSkirtFaceMasks;
uint32 SurfaceVertexCount=0;
uint32 CeilingTriangleCount=0;
uint32 SkirtTriangleCount=0;
uint64 DensitySamples=0;
double WorkerSeconds=0.0;
@@ -62,7 +60,6 @@ struct FStandaloneCpuTile
bool bHasPayloadHash=false;
uint64 TopologyHash=14695981039346656037ull;
bool bHasTopologyHash=false;
bool bGenerationFailed=false;
uint64 MeshPayloadAllocatedBytes=0;
VoxelForgeCore::TileGenerationStats CoreDiagnostics{};
std::array<uint64,VoxelDensityProfile::BucketCount> ProfileCycles{};
@@ -431,14 +428,12 @@ public:
bool bInSkipColors=false,
VoxelForgeCore::World* InCoreWorld=nullptr,
bool bInCaptureColumnCoordinates=false,
int32 InLod8HorizonInteriorStepVoxels=0,
bool bInSharedColumnCache=true)
int32 InLod8HorizonInteriorStepVoxels=0)
:World(&InWorld),WorkerCount(FMath::Clamp(InWorkerCount,1,16)),bHashDensity(bInHashDensity),
MeshCache(InMeshCache),MaxLevelFilter(InMaxLevelFilter),
CoreWorld(InCoreWorld),bSkipUvAndColors(bInSkipUvAndColors),bSkipMaterialGroups(bInSkipMaterialGroups),
bSkipUV(bInSkipUV),bSkipColors(bInSkipColors),
bCaptureColumnCoordinates(bInCaptureColumnCoordinates),
bSharedColumnCache(bInSharedColumnCache),
Lod8HorizonInteriorStepVoxels(std::max(0,InLod8HorizonInteriorStepVoxels))
{
VoxelGenLOD::InitializeConsoleSwitches();
@@ -653,19 +648,12 @@ public:
void SetMesherStageProfilingEnabled(bool Enabled)
{bProfileMesherStages=Enabled;}
void SetUniformBlockProofAuditEnabled(bool Enabled)
{bAuditUniformBlockProofs=Enabled;}
void SetDisplayAttributeCaptureEnabled(bool Enabled)
{bCaptureDisplayAttributes=Enabled;}
FStandaloneCpuTile GenerateDiagnostic(const FVoxelTileKey& Key,
std::uint32_t GlobalOctaveDrop=0,std::uint32_t CellStride=1,
bool ForceGenerate=false,
const VoxelForgeCore::TileGenerationOptions* FarDisplayOverride=nullptr,
bool CaptureDisplayAttributes=false)
bool ForceGenerate=false)
{
FStandaloneTileJob Job;Job.Key=Key;Job.StartedAt=FClock::now();Job.QueuedAt=Job.StartedAt;
return Generate(Job,GlobalOctaveDrop,CellStride,ForceGenerate,FarDisplayOverride,
CaptureDisplayAttributes);
return Generate(Job,GlobalOctaveDrop,CellStride,ForceGenerate);
}
private:
@@ -785,9 +773,7 @@ private:
}
FStandaloneCpuTile Generate(const FStandaloneTileJob& Job,
std::uint32_t DiagnosticGlobalOctaveDrop=0,std::uint32_t DiagnosticCellStride=1,
bool ForceGenerate=false,
const VoxelForgeCore::TileGenerationOptions* FarDisplayOverride=nullptr,
bool CaptureDisplayAttributes=false)
bool ForceGenerate=false)
{
const auto StartTime=Job.StartedAt;
FStandaloneCpuTile Out;Out.Key=Job.Key;Out.RequestedCrossing=Job.RequestedCrossing;
@@ -830,40 +816,24 @@ private:
Options.skipUvAndColors=bSkipUvAndColors;
Options.skipMaterialGroups=bSkipMaterialGroups;Options.skipUv=bSkipUV;Options.skipColors=bSkipColors;
Options.captureColumnCoordinates=bCaptureColumnCoordinates;
Options.useSharedColumnCache=bSharedColumnCache;
Options.lod8HorizonInteriorStepVoxels=Lod8HorizonInteriorStepVoxels;
Options.profileMesherStages=bProfileMesherStages&&!ForceGenerate;
Options.auditUniformBlockProofs=bAuditUniformBlockProofs&&!ForceGenerate;
Options.diagnosticGlobalOctaveDrop=DiagnosticGlobalOctaveDrop;
Options.diagnosticCellStride=std::max<std::uint32_t>(1,DiagnosticCellStride);
Options.diagnosticColumnInterpolationStride=
std::max<std::uint32_t>(1,DiagnosticCellStride);
if(FarDisplayOverride)
{
Options.overrideFarDisplayMesh=FarDisplayOverride->overrideFarDisplayMesh;
Options.farDisplayGeometryBudgetMillipixels=FarDisplayOverride->farDisplayGeometryBudgetMillipixels;
Options.farRefinementGridScale=FarDisplayOverride->farRefinementGridScale;
Options.farRefinementLodMask=FarDisplayOverride->farRefinementLodMask;
Options.farConnectorStationScale=FarDisplayOverride->farConnectorStationScale;
Options.farConnectorRayMask=FarDisplayOverride->farConnectorRayMask;
Options.farConnectorReuseStationRadii=FarDisplayOverride->farConnectorReuseStationRadii;
Options.diagnosticRemoveFarConnectorPanels=FarDisplayOverride->diagnosticRemoveFarConnectorPanels;
Options.diagnosticAuditFarConnectorCoverage=FarDisplayOverride->diagnosticAuditFarConnectorCoverage;
}
std::string Error;
auto Result=CoreWorld->generateTile(
{{Job.Key.Coord.X,Job.Key.Coord.Y,Job.Key.Coord.Z},Job.Key.Level},Options,Error);
if(!Result)
{
std::fprintf(stderr,"[VoxelForgeCore] tile generation failed: %s\n",Error.c_str());
Out.bGenerationFailed=true;
Out.WorkerSeconds=std::chrono::duration<double>(FClock::now()-StartTime).count();
Out.CompletedAt=FClock::now();return Out;
}
Out.DensitySamples=Result->densitySampleCount;
Out.CoreDiagnostics=Result->diagnostics;
Out.SurfaceVertexCount=Result->groups.surfaceVertexCount;
Out.CeilingTriangleCount=Result->groups.ceilingTriangleCount;
Out.SkirtTriangleCount=Result->groups.skirtTriangleCount;
Out.MeshPayloadAllocatedBytes=Result->meshPayloadAllocatedBytes;
Out.DensityHash=Result->densityHash;Out.MeshHash=Result->meshHash;
@@ -871,18 +841,12 @@ private:
Out.bHasDensityHash=Result->hasDensityHash;Out.bHasMeshHash=Result->hasMeshHash;
Out.bHasPayloadHash=Result->hasPayloadHash;Out.bHasTopologyHash=Result->hasTopologyHash;
Out.Vertices.reserve(Result->vertices.size());
const bool bCaptureAttributes=CaptureDisplayAttributes||bCaptureDisplayAttributes;
if(bCaptureAttributes)Out.VertexColors.reserve(Result->vertices.size());
for(const auto& Vertex:Result->vertices)
{
Out.Vertices.push_back({
{static_cast<float>(Vertex.position.x*0.01),static_cast<float>(Vertex.position.y*0.01),
static_cast<float>(Vertex.position.z*0.01)},
{static_cast<float>(Vertex.normal.x),static_cast<float>(Vertex.normal.y),
static_cast<float>(Vertex.normal.z)}});
if(bCaptureAttributes)
Out.VertexColors.push_back({Vertex.color.r,Vertex.color.g,Vertex.color.b,Vertex.color.a});
}
Out.Indices=std::move(Result->indices);
Out.TriangleSkirtFaceMasks=std::move(Result->skirtFaceMasks);
if(bProfile)
@@ -1029,11 +993,8 @@ private:
bool bSkipUV=false;
bool bSkipColors=false;
bool bCaptureColumnCoordinates=false;
bool bCaptureDisplayAttributes=false;
bool bSharedColumnCache=true;
int32 Lod8HorizonInteriorStepVoxels=0;
bool bProfileMesherStages=false;
bool bAuditUniformBlockProofs=false;
std::atomic<uint64> CacheHitCount{0};
mutable std::mutex Mutex;
std::condition_variable Wake;
@@ -121,9 +121,7 @@ FVoxelMeshData UVoxelMarchingCubesMesher::GenerateMesh(FIntVector OriginVoxels,
FVoxelSharedDensityGrid* OutPreEditDensityGrid,
const FVoxelSharedDensityGrid* InSharedDensityGrid,
std::vector<float>* OutDebugDensitySamples,
FVoxelMarchingCubesStageTimings* OutStageTimings,
FVoxelUniformBlockProofAuditStats* OutBlockProofAudit,
bool bForceFullDensityCapture)
FVoxelMarchingCubesStageTimings* OutStageTimings)
{
TRACE_CPUPROFILER_EVENT_SCOPE(VoxelForge_MesherGenerateMesh);
const uint64 StageMesherStartCycles=OutStageTimings?FPlatformTime::Cycles64():0;
@@ -132,7 +130,6 @@ FVoxelMeshData UVoxelMarchingCubesMesher::GenerateMesh(FIntVector OriginVoxels,
if (OutPreEditDensityGrid) { OutPreEditDensityGrid->Reset(); }
if (OutDensitySampleCount) { *OutDensitySampleCount = 0; }
if (OutStageTimings) { *OutStageTimings = FVoxelMarchingCubesStageTimings{}; }
if (OutBlockProofAudit) { *OutBlockProofAudit = FVoxelUniformBlockProofAuditStats{}; }
if (OutDebugDensitySamples) { OutDebugDensitySamples->clear(); }
if (!Generator) return MeshData;
const bool bEmitUV = !bStandaloneSkipUvAndColors && !bStandaloneSkipUV;
@@ -553,19 +550,22 @@ FVoxelMeshData UVoxelMarchingCubesMesher::GenerateMesh(FIntVector OriginVoxels,
MesherSetupTimer.End();
// Optional 8x8x8-cell block proof. Mixed/Unknown blocks always fall back to exact density
// sampling. The Core SurfaceWorld column-range proof at Step 2 can also omit evaluations
// outside active blocks and their one-sample normal halo.
// Optional 8x8x8-cell block proof. The tile classifier has already returned Mixed, but
// that is a conservative answer over the whole tile. A tile can still be uniformly solid
// (or uniformly air) when its smaller blocks are each provable. Do this before allocating
// or filling the density grid: the grid is only needed when at least one block can contain
// a surface. A whole-tile early return is allowed only when every relevant block has the
// SAME verdict; adjacent uniform blocks with opposite signs can contain a surface between
// them. This is a proof-only optimization: ClassifyTile is conservative and no samples or
// resolution are removed from a tile that reaches the mesher.
TArray<uint8> BlockSkip;
int32 BlocksPerAxis = 0;
// Step 2 is enabled only for a tile wholly inside one native SurfaceWorld stratum. Steps
// 16/32 keep the historical gate off because their smaller grids do not amortize per-block queries.
const bool bNativeSurfaceTileProof = Step == 2 && ShapeWorldContext != nullptr
&& ShapeWorldContext->IsNativeSurfaceBox(OriginVoxels,Step,CellsPerAxis);
// LOD2's 16-cell tile is the remaining false-Mixed empty case in the streamed game path.
// Its step-8 lattice can use the same proof-only 8-cell block partition as LOD0. Keep the
// gate off for steps 2/16/32: their meshing work is already smaller than repeating a full
// tile classifier per block, and this preserves the established coarse-LOD latency profile.
const bool bUseProofBlocks = bUseBlockEarlyOut && !OutCaptureGrid
&& (Step == 1 || Step == 8 || (Step == 2
&& (bNativeSurfaceTileProof || OutBlockProofAudit != nullptr)));
bool bCanSkipProofBlockGrid = bNativeSurfaceTileProof;
&& (Step == 1 || Step == 8);
if (bUseProofBlocks)
{
constexpr int32 BlockCells = 8;
@@ -613,27 +613,18 @@ FVoxelMeshData UVoxelMarchingCubesMesher::GenerateMesh(FIntVector OriginVoxels,
VoxelDensityProfile::RecordClassifierCall(bSampleClassifier);
}
EVoxelTileClass Verdict;
bool bBlockUnknown = false;
bool bBlockNative = false;
if(ShapeWorldContext&&Step<=2)
{
const auto ShapeVerdict=ShapeWorldContext->ClassifyBoxDetailed(
BlockOrigin,Step,BlockCells,Step==2);
Verdict=ShapeVerdict.Verdict==EVoxelTileClass::AllSolid
const auto ShapeVerdict=ShapeWorldContext->ClassifyBox(
BlockOrigin,Step,BlockCells);
Verdict=ShapeVerdict==EVoxelTileClass::AllSolid
?EVoxelTileClass::AllSolid
:ShapeVerdict.Verdict==EVoxelTileClass::AllAir
:ShapeVerdict==EVoxelTileClass::AllAir
?EVoxelTileClass::AllAir:EVoxelTileClass::Mixed;
bBlockUnknown=ShapeVerdict.bUnknown;
bBlockNative=ShapeVerdict.bNativeSurface;
if(Step==2&&!ShapeVerdict.bNativeSurface)
bCanSkipProofBlockGrid=false;
}
else
{
if(Step==2)bCanSkipProofBlockGrid=false;
Verdict=Generator->ClassifyTile(BlockOrigin,Step,BlockCells,
bSampleClassifier ? &ClassifierStats : nullptr);
}
if (bSampleClassifier)
{
VoxelDensityProfile::AddSampledMeasurement(
@@ -708,70 +699,20 @@ FVoxelMeshData UVoxelMarchingCubesMesher::GenerateMesh(FIntVector OriginVoxels,
ClassifierStats.RoomTailCycles);
}
}
if (Verdict == EVoxelTileClass::AllSolid
|| Verdict == EVoxelTileClass::AllAir)
{
if(OutBlockProofAudit&&Step==2&&bBlockNative)
{
++OutBlockProofAudit->CheckedBlocks;
const int32 ProofMinX=BlockX*BlockCells-1;
const int32 ProofMinY=BlockY*BlockCells-1;
const int32 ProofMinZ=BlockZ*BlockCells-1;
const int32 ProofMaxX=BlockX*BlockCells+BlockCells+1;
const int32 ProofMaxY=BlockY*BlockCells+BlockCells+1;
const int32 ProofMaxZ=BlockZ*BlockCells+BlockCells+1;
bool bUniform=true;
for(int32 Z=ProofMinZ;Z<=ProofMaxZ&&bUniform;++Z)
for(int32 Y=ProofMinY;Y<=ProofMaxY&&bUniform;++Y)
for(int32 X=ProofMinX;X<=ProofMaxX;++X)
{
++OutBlockProofAudit->CheckedSamples;
const float Density=ShapeWorldContext
?ShapeWorldContext->DensityAtLattice(
OriginVoxels.X+X*Step,
OriginVoxels.Y+Y*Step,
OriginVoxels.Z+Z*Step)
:Generator->GetDensityAtLattice(
OriginVoxels.X+X*Step,
OriginVoxels.Y+Y*Step,
OriginVoxels.Z+Z*Step);
if(!VoxelMath::IsFinite(Density)||Density==0.0f
||(Verdict==EVoxelTileClass::AllSolid
?Density>=0.0f:Density<=0.0f))
{
std::printf("[UniformBlockProofViolation] tile_origin=(%d,%d,%d) step=%d cells=%d block=(%d,%d,%d) sample=(%d,%d,%d) expected=%s density=%.9g native=%d unknown=%d\n",
OriginVoxels.X,OriginVoxels.Y,OriginVoxels.Z,Step,
CellsPerAxis,BlockX,BlockY,BlockZ,
OriginVoxels.X+X*Step,OriginVoxels.Y+Y*Step,
OriginVoxels.Z+Z*Step,
Verdict==EVoxelTileClass::AllSolid?"solid":"air",
Density,bBlockNative?1:0,bBlockUnknown?1:0);
bUniform=false;
break;
}
}
if(!bUniform)
{
++OutBlockProofAudit->Violations;
Verdict=EVoxelTileClass::Mixed;
}
}
}
if (Verdict == EVoxelTileClass::Mixed)
{
if(OutBlockProofAudit&&Step==2)
{
++OutBlockProofAudit->FallbackBlocks;
if(bBlockUnknown)++OutBlockProofAudit->UnknownBlocks;
}
MixedBlockIndices.Add(
((BlockZ * BlocksPerAxis) + BlockY) * BlocksPerAxis + BlockX);
}
if (Verdict == EVoxelTileClass::AllSolid
|| Verdict == EVoxelTileClass::AllAir)
{
// In the ordinary path, candidates are checked against the filled grid.
// The Step-2 supremum interval path is itself the proof used to omit fills.
// Keep the classifier result as a candidate until the exact density grid
// used by this mesher has been filled. ClassifyTile is conservative by
// contract, but its proof and the mesher share worker-local caches; a
// cache replacement must never turn that contract into a cell skip by
// itself. The post-grid sign check below is the final proof consumed by
// the cell loop and clears any candidate whose actual MC vertices disagree.
BlockSkip[((BlockZ * BlocksPerAxis) + BlockY) * BlocksPerAxis + BlockX] =
Verdict == EVoxelTileClass::AllSolid ? 1 : 2;
if (!bHaveUniformBlock)
@@ -865,9 +806,7 @@ FVoxelMeshData UVoxelMarchingCubesMesher::GenerateMesh(FIntVector OriginVoxels,
// ClassifyTile path already relies on this same non-Mixed proof contract. Return before
// allocating the density grid; no samples are skipped for a tile that can contain
// geometry, and the final geometry remains byte-identical because this path emits none.
if (bHaveUniformBlock && bAllRelevantBlocksSame && bAllRelevantBlocksUniform
&& !(Step == 2 && OutDebugDensitySamples != nullptr)
&& !(bForceFullDensityCapture && OutDebugDensitySamples != nullptr))
if (bHaveUniformBlock && bAllRelevantBlocksSame && bAllRelevantBlocksUniform)
{
return MeshData;
}
@@ -902,43 +841,6 @@ FVoxelMeshData UVoxelMarchingCubesMesher::GenerateMesh(FIntVector OriginVoxels,
&& SharedDeltaX + GridDim < ReuseGrid->Dim
&& SharedDeltaY + GridDim < ReuseGrid->Dim
&& SharedDeltaZ + GridDim < ReuseGrid->Dim;
const bool bSkipProofBlockGrid = bUseProofBlocks && bCanSkipProofBlockGrid
&& OutBlockProofAudit == nullptr && OutPreEditDensityGrid == nullptr
&& !bUseSharedDensityGrid;
static thread_local TArray<uint8> RequiredGridSamples;
if(bSkipProofBlockGrid)
{
RequiredGridSamples.SetNumUninitialized(MDim*MDim*MDim);
FMemory::Memzero(RequiredGridSamples.GetData(),
static_cast<SIZE_T>(RequiredGridSamples.Num())*sizeof(uint8));
constexpr int32 BlockCells=8;
for(int32 BlockZ=0;BlockZ<BlocksPerAxis;++BlockZ)
{
const int32 BlockMinZ=BlockZ*BlockCells;
const int32 BlockMaxZ=FMath::Min(CellsPerAxis-1,BlockMinZ+BlockCells-1);
if(BlockMaxZ<CzLo||BlockMinZ>CzHi)continue;
for(int32 BlockY=0;BlockY<BlocksPerAxis;++BlockY)
for(int32 BlockX=0;BlockX<BlocksPerAxis;++BlockX)
{
const int32 BlockIndex=((BlockZ*BlocksPerAxis)+BlockY)*BlocksPerAxis+BlockX;
if(BlockSkip[BlockIndex]!=0)continue;
const int32 CellMinX=BlockX*BlockCells;
const int32 CellMinY=BlockY*BlockCells;
const int32 CellMaxX=FMath::Min(CellsPerAxis-1,CellMinX+BlockCells-1);
const int32 CellMaxY=FMath::Min(CellsPerAxis-1,CellMinY+BlockCells-1);
const int32 SampleMinX=FMath::Max(-1,CellMinX-1);
const int32 SampleMaxX=FMath::Min(GridDim,CellMaxX+2);
const int32 SampleMinY=FMath::Max(-1,CellMinY-1);
const int32 SampleMaxY=FMath::Min(GridDim,CellMaxY+2);
const int32 SampleMinZ=FMath::Max(GzLo,FMath::Max(CzLo,BlockMinZ)-1);
const int32 SampleMaxZ=FMath::Min(GzHi,FMath::Min(CzHi,BlockMaxZ)+2);
for(int32 Z=SampleMinZ;Z<=SampleMaxZ;++Z)
for(int32 Y=SampleMinY;Y<=SampleMaxY;++Y)
for(int32 X=SampleMinX;X<=SampleMaxX;++X)
RequiredGridSamples[((Z+1)*MDim+(Y+1))*MDim+(X+1)]=1;
}
}
}
const bool bCapturePreEditGrid = OutPreEditDensityGrid != nullptr
&& !bUseSharedDensityGrid
&& Step == 1 && CellsPerAxis == CHUNK_SIZE
@@ -1144,7 +1046,6 @@ FVoxelMeshData UVoxelMarchingCubesMesher::GenerateMesh(FIntVector OriginVoxels,
auto SampleGridPoint = [&](int32 gx, int32 gy, int32 gz)
{
const int32 LocalIndex = ((gz + 1) * MDim + (gy + 1)) * MDim + (gx + 1);
if(bSkipProofBlockGrid&&RequiredGridSamples[LocalIndex]==0)return;
if (bUseSharedDensityGrid)
{
const int32 SharedX = SharedDeltaX + gx;
@@ -1191,9 +1092,9 @@ FVoxelMeshData UVoxelMarchingCubesMesher::GenerateMesh(FIntVector OriginVoxels,
const FStandaloneShapeWorld* ActiveShapeWorld=ShapeWorldContext;
const bool bUseShapeWorldZBatch=ActiveShapeWorld!=nullptr
&&ActiveShapeWorld->IsAnalyticOnly()
&&!bUseSharedDensityGrid&&!bCapturePreEditGrid&&!bSkipProofBlockGrid;
&&!bUseSharedDensityGrid&&!bCapturePreEditGrid;
const bool bUseShapeWorldXBatch=ActiveShapeWorld!=nullptr
&&!bUseSharedDensityGrid&&!bCapturePreEditGrid&&!bSkipProofBlockGrid;
&&!bUseSharedDensityGrid&&!bCapturePreEditGrid;
if(bUseShapeWorldZBatch&&!bUseVerticalCacheTraversal)
{
for(const std::vector<int32>& YGroup:YGroups)
@@ -1341,34 +1242,6 @@ FVoxelMeshData UVoxelMarchingCubesMesher::GenerateMesh(FIntVector OriginVoxels,
}
if (OutDebugDensitySamples)
{
// Hash/debug runs need the complete reference density lattice. Let MC exercise the
// sparse block path, then evaluate omitted samples before exporting that lattice.
if(bSkipProofBlockGrid)
{
for(int32 gz=GzLo;gz<=GzHi;++gz)
for(int32 gy=-1;gy<=GridDim;++gy)
for(int32 gx=-1;gx<=GridDim;++gx)
{
const int32 LocalIndex=((gz+1)*MDim+(gy+1))*MDim+(gx+1);
if(RequiredGridSamples[LocalIndex]!=0)continue;
RequiredGridSamples[LocalIndex]=1;
const int32 ReachBlockX=FMath::Clamp(gx,0,CellsPerAxis-1)
/VoxelGenLOD::TileReachBlockCells;
const int32 ReachBlockY=FMath::Clamp(gy,0,CellsPerAxis-1)
/VoxelGenLOD::TileReachBlockCells;
const int32 ReachBlockZ=FMath::Clamp(gz,0,CellsPerAxis-1)
/VoxelGenLOD::TileReachBlockCells;
VoxelGenLOD::TileReachBlockIndex=
((ReachBlockZ*ReachBlocksPerAxis)+ReachBlockY)*ReachBlocksPerAxis+ReachBlockX;
const int32 SampleX=OriginVoxels.X+gx*Step;
const int32 SampleY=OriginVoxels.Y+gy*Step;
const int32 SampleZ=OriginVoxels.Z+gz*Step;
DensityGrid[LocalIndex]=ShapeWorldContext
?ShapeWorldContext->DensityAtLattice(SampleX,SampleY,SampleZ)
:Generator->GetDensityAtLattice(SampleX,SampleY,SampleZ);
if(OutDensitySampleCount)++(*OutDensitySampleCount);
}
}
const size_t SampleCount = static_cast<size_t>(GzHi - GzLo + 1)
* static_cast<size_t>(MDim) * static_cast<size_t>(MDim);
OutDebugDensitySamples->reserve(SampleCount);
@@ -1386,7 +1259,7 @@ FVoxelMeshData UVoxelMarchingCubesMesher::GenerateMesh(FIntVector OriginVoxels,
FPlatformTime::Cycles64()-StageDensityGridStartCycles)
*FPlatformTime::GetSecondsPerCycle64()*1000.0;
if (bUseProofBlocks&&(!bSkipProofBlockGrid||OutDebugDensitySamples!=nullptr))
if (bUseProofBlocks)
{
// Finalize every block candidate against the exact density samples that the marching-
// cubes loop will consume. This is intentionally redundant with ClassifyTile: it is a
@@ -57,17 +57,6 @@ struct FVoxelMarchingCubesStageTimings
uint64 GradientMemoHits = 0;
};
// Opt-in soundness audit for density blocks which the Core mesher would skip.
// Audit de justesse facultatif pour les blocs de densite que Core sauterait.
struct FVoxelUniformBlockProofAuditStats
{
uint64 CheckedBlocks = 0;
uint64 CheckedSamples = 0;
uint64 FallbackBlocks = 0;
uint64 UnknownBlocks = 0;
uint64 Violations = 0;
};
// Stable plan data copied onto one worker-owned mesher for hybrid LOD0 generation.
// Donnees stables du plan copiees dans un mailleur de worker pour le mode hybride LOD0.
struct FVoxelHybridSharpFeatureBox
@@ -119,9 +108,7 @@ public:
FVoxelSharedDensityGrid* OutPreEditDensityGrid = nullptr,
const FVoxelSharedDensityGrid* InSharedDensityGrid = nullptr,
std::vector<float>* OutDebugDensitySamples = nullptr,
FVoxelMarchingCubesStageTimings* OutStageTimings = nullptr,
FVoxelUniformBlockProofAuditStats* OutBlockProofAudit = nullptr,
bool bForceFullDensityCapture = false);
FVoxelMarchingCubesStageTimings* OutStageTimings = nullptr);
//=========================================================================
// SERVICES (injectés par AVoxelWorld)
@@ -30,34 +30,6 @@ namespace StandaloneWorldAssemblyPrototype
return std::max<std::int64_t>(1,WorldAssemblyFixed(wavelength));
}
inline bool ApplyFarDisplayMeshDeclaration(const VFJson::Value& root,
VoxelForgeCore::WorldAssemblyRecipeV1& recipe,std::string& error)
{
const VFJson::Value& declaration=root.Get("far_display_mesh");
if(std::holds_alternative<std::nullptr_t>(declaration.Data))return true;
if(!declaration.IsObject())
{error="far_display_mesh must be an object when declared";return false;}
const auto ReadUnsigned=[&](const char* key,std::uint32_t& output)
{
const VFJson::Value& value=declaration.Get(key);
if(!value.IsNumber()||!std::isfinite(value.Number())||value.Number()<0.0
||value.Number()>static_cast<double>(UINT32_MAX)
||std::floor(value.Number())!=value.Number())return false;
output=static_cast<std::uint32_t>(value.Number());return true;
};
if(!ReadUnsigned("geometry_budget_millipixels",recipe.farDisplayGeometryBudgetMillipixels)
||!ReadUnsigned("refinement_grid_scale",recipe.farRefinementGridScale)
||!ReadUnsigned("refinement_lod_mask",recipe.farRefinementLodMask)
||!ReadUnsigned("connector_station_scale",recipe.farConnectorStationScale)
||!ReadUnsigned("connector_ray_mask",recipe.farConnectorRayMask))
{error="far_display_mesh declaration has a missing or non-integer parameter";return false;}
const VFJson::Value& reuse=declaration.Get("connector_reuse_station_radii");
if(!std::holds_alternative<bool>(reuse.Data))
{error="far_display_mesh connector_reuse_station_radii must be boolean";return false;}
recipe.farConnectorReuseStationRadii=std::get<bool>(reuse.Data);
return true;
}
inline uint64 WorldAssemblyFeatureId(uint32 seed,int64 x,int64 y,uint32 kind)
{
uint64 hash=14695981039346656037ull;
@@ -251,7 +223,6 @@ namespace StandaloneWorldAssemblyPrototype
recipe.biomeClimateReliefWavelengthSubvoxels=WorldAssemblyWavelength(map.ReliefFrequency,3333.0);
recipe.biomeClimateMoistureWavelengthSubvoxels=WorldAssemblyWavelength(map.MoistureFrequency,2500.0);
recipe.biomeClimateReliefContrastQ16=WorldAssemblyQ16(map.ReliefContrast);
if(!ApplyFarDisplayMeshDeclaration(root,recipe,error))return false;
const auto makeProfile=[&](uint32 stableId,const FSurfaceGenerationParams& params,
const FBiomeResolved* climate)
{