Skip to content

viewer: skip redundant chunk scans while stationary - #7164

Open
ibrahimmaq14 wants to merge 1 commit into
ItsNotRexed:mainfrom
ibrahimmaq14:fix/viewer-stationary-chunk-scan
Open

ibrahimmaq14 wants to merge 1 commit into
ItsNotRexed:mainfrom
ibrahimmaq14:fix/viewer-stationary-chunk-scan

Conversation

@ibrahimmaq14

Copy link
Copy Markdown

Claimed in the coordination issue as stationary chunk-manifest scans. Implements the map viewer finding.

What and why

With the camera still and download slots available, the viewer checked every unloaded chunk every frame. Skip the candidate scan at the same camera position until a load settles, a chunk is dropped, or an in-range retry becomes due. The existing per-frame pass still handles eviction and LOD visibility, and eligible requests use the same nearest-first order.

Tested

  • Windows 11, Node.js 24.20.0, CPU-only synthetic fixtures. Both new regression tests failed on the original scheduler and passed with this patch. They cover idle frames, vertical camera movement, and retry timing.
  • A synthetic 12,340-chunk manifest went from 1,480,680 unloaded-chunk bounds reads to zero over 120 stationary frames after the first scan.
  • 67 of 68 viewer tests passed. The keyboard fixture also fails on main with AbortController is not defined and is addressed by Fix/viewer horizontal wheel #6265. Applying Fix/viewer horizontal wheel #6265 to a temporary copy made all 61 streaming tests pass.
  • The no-game-data guard and git diff --check passed. The CPU translator suite ran 5,889 tests across 443 files. Three modules failed in unchanged translator code or tests (test_float_nan_fract, test_image_atomics_guard, test_image_store_d16).

AI-assisted: yes (OpenAI Codex).

Checklist

  • No game data, keys or decryption, including in tests or reports.
  • Translator contract update is inapplicable to this viewer change.

@tikD1337

Copy link
Copy Markdown
Contributor

Review: viewer: skip redundant chunk scans while stationary (#7164)

Environment: Windows 11 Pro, CPython 3.13, Node v24.19.0. No GPU or game files needed, since this only touches the viewer's streaming logic and its Node test harness.

What changed

stream() used to walk all of world.chunks on every animation frame whenever an inflight slot was free. It called range() (bounds/cell distance) on every manifest entry, even when the camera hadn't moved and nothing in the queue had changed. On a full-size world manifest that is O(N) work per frame for nothing.

The PR stores the result of the last scan as a small key, lastCandidateScan = { x, y, z, nextRetryAt }, and skips the scan when both of these hold:

  • camera.position matches the stored position exactly, and
  • now < nextRetryAt, where nextRetryAt is the earliest retryAt among entries that are in load range and still backing off.

Three places clear the key:

  1. drop(id): covers eviction, and the case where c.previous is put back into live right after a drop (the drop has already cleared it).
  2. loadChunk finally: covers success, failure (a new retryAt is set just before), and the stale-entry paths where live.get(def.id) !== entry returns early. finally runs on all of them, and it also frees the inflight slot.
  3. Camera movement: any change to x/y/z fails the equality check, so movement, #cam= hash teleports and Q/E vertical moves all trigger a rescan.

The backoff check moved below the range check. range() now runs for entries that are backing off, so that only in-range retries feed nextRetryAt. A retry for an out-of-range chunk can't make work eligible until the camera moves, and moving already invalidates the key. The only cost is one extra range() call per backing-off entry, and only on frames that actually scan. That's negligible.

Why the key is sufficient

I checked what the scan result depends on in viewer/index.html:

  • range(def, p) reads only def, p, the constants LOAD_R/UNLOAD_R/LOD_SLACK, and world.lod_bands. world is a const bound once from loadWorld() at line 225 and is never reassigned, so no reload path can leave the key stale.
  • The per-entry filters are entry.obj, entry.loading, entry.attempts and entry.retryAt. All of them change only inside loadChunk (which clears the key in finally), the scan loop itself, or the eviction path (drop, which clears the key).
  • Saturated queue: if the scan finds more wanted chunks than free slots, the loop breaks at MAX_INFLIGHT. The next frames return at the inflight >= MAX_INFLIGHT guard, which runs before the cache check, until a load finishes and its finally clears the key. The leftover candidates are picked up on that next scan.
  • world.test path: chunks are built synchronously inside the loop and come out with obj set, so they would be skipped on the next scan anyway. Caching after that loop can't hide pending work. inflight isn't incremented on this path, so it never saturates.
  • Floating-point drift: the main loop calls addScaledVector only when v.lengthSq() is non-zero (line 442). A stationary camera keeps bit-identical coordinates, so exact === is correct here and needs no epsilon. A NaN position would never compare equal and would just fall back to scanning every frame, which is safe.
  • Clock domain: retryAt is set from performance.now(), and stream(now = performance.now()) uses the same clock, so the deadline comparison is consistent.

Eviction and LOD-tier visibility still run every frame, before the early return. Only the candidate search is skipped, so this PR doesn't change unload behaviour or tier hand-off.

Nits (non-blocking)

  • drop() clears the key before the c.previous restore. That's correct, because the restore happens after the drop in the same call, but it's easy to break by reordering. A one-line comment at the restore would help (// key already invalidated by drop()).
  • lastCandidateScan sits next to live/inflight. Its only guard is the comment at the check. A short comment at the declaration, saying which state it summarises and who must clear it, would help the next person who adds a new way for a chunk to become eligible.

Tests

The two new tests cover the two skip conditions:

  • Settled stationary camera: a getter on bounds counts reads and shows no manifest reads across 60 stationary frames. A 1 m Y move then brings the far chunk (Y 1400–1401) inside LOAD_R and issues 1.glb. This checks that a skipped scan doesn't hide work once the position changes.
  • Backoff deadline: wrapping Symbol.iterator shows no scans at t=500 and t=999, then the retry of 0.glb at exactly t=1000 (the 1 s first backoff).

Verification (no game files)

Check Result
git diff --check PASS
python -m compileall -q make_game.py tools tests PASS
python -I scripts/check_no_game_data.py on changed files PASS
python -I make_game.py --help PASS
node --test tests/test_viewer_streaming.cjs 58/59 pass. Both new tests pass.

The one failure, "Shift speeds the camera up and Ctrl slows it down…" (ReferenceError: AbortController is not defined inside that test's own vm context), already fails on the parent commit: 56/57 there with the same error. This PR doesn't cause it. It's a fixture gap in that test (its context doesn't include AbortController) and is worth a separate finding:.

Adherence

  • No game data: the diff contains only viewer JS and a synthetic test fixture. The chunks are generated {id, url, bounds} stubs.
  • No keys, decryption or protection workarounds: not touched.
  • Nothing online: no new network targets. Fetches still go only to manifest-relative chunk URLs served by the local serve.py.
  • Fix, don't disable: this is a performance change with no change in behaviour. No streaming path is turned off or skipped; the scan only runs when its result could differ.

Verdict: approve. The invalidation points cover every change that can make a chunk eligible, the retry-deadline handling is correct, and the tests check both skip conditions. The nits are optional.

AI-assisted.

@overz4

overz4 commented Nov 23, 2026

Copy link
Copy Markdown

Thanks for this, the caching logic looks correct overall:

The camera position is copied by value (x/y/z), so it's safe even if the camera reuses the same Vector3.
The cache is cleared on eviction (drop()) and when a load finishes (inflight--), so a freed slot triggers a rescan.
nextRetryAt only tracks in-range chunks, which is correct because out-of-range chunks can't become eligible while the camera is still.
With no pending work, nextRetryAt = Infinity skips scans until the camera moves or the queue changes, as intended.
Main concern: stale cache / stalled loading

The cache is only cleared in drop() and on load completion. Any other state change that affects range() or the chunk list will leave a stale cache, and loading will stall for as long as the camera stays still. For example:

loading or replacing world / world.chunks
changing the load distance or any parameter read by range()
resetting attempts / retryAt on an entry (e.g. a manual "retry" action)
Could you make sure the cache is invalidated in those places too, if they exist?

Suggestions

Put the invalidation in a small helper instead of writing lastCandidateScan = undefined in several places, so future code paths are less likely to miss it:
// Cached result of the last candidate scan; any state change that can make a chunk eligible must clear it.let lastCandidateScan;function invalidateCandidates() { lastCandidateScan = undefined; }

@lucastayaralvarenga-ui lucastayaralvarenga-ui left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 729126f on Windows 11 Pro build 26300, Node.js 24.14.0, CPU only.

Both new stationary-camera regressions passed. I checked invalidation after drop and load completion, inclusion of vertical movement in the camera key, and the earliest in-range retry deadline.

The full viewer suite reports 58 passed and one failure. The failure is the existing keyboard-speed fixture with ReferenceError: AbortController is not defined. I ran the parent too, which reports the same error with 56 passed and one failure. Thus I verified the two added tests, with the full-suite limitation recorded here.

No blocking issue found in the changed scheduling logic. AI-assisted (Codex), synthetic loader and clock, no browser or GPU run.

@whattheflop

Copy link
Copy Markdown
Contributor

Independent browser verification, AI-assisted, on exact head 729126f and direct parent c25b9f2.

In the same eight-chunk synthetic world, both revisions issued the four nearest GLB requests first, then filled the freed slot with request five while the camera stayed still. A 3,000 m move evicted the original five chunks and requested both destination chunks. All seven requests per revision returned HTTP 200, parsed with GLTFLoader, and attached to the scene.

Across four matched 12-tick windows with pending and settled loads at both camera positions, the parent ran 48 candidate scans and the head ran zero. Neither issued new requests during those windows. Load completion and camera movement still triggered scans on the head.

T3 Preview Chromium, local Three.js r160, WebGL 2 through ANGLE/D3D11 on RTX 3080 (Windows driver 32.0.16.1664), Windows 11 build 26200. The preview tabs throttled animation while hidden, so scratch instrumentation invoked the stock callback once per controlled tick. Fetch, GLB parse and rendering ran normally. This measures scan counts per tick. Synthetic CPU-side fixtures, no game data.

Node.js 24.16.0 viewer suites: 67/68 head and 65/66 parent. Both fail the existing keyboard fixture with AbortController is not defined.

@desarrollo-jpg

Copy link
Copy Markdown

Tested 729126f on Windows 11 (10.0.26100), Node 24.22.3, CPU only, no game files.

@whattheflop

Copy link
Copy Markdown
Contributor

AI-assisted integration check on Windows with Node 24.16.0. Upstream dde82f27 + #3687 dfea56d8 conflicts with this head 729126fe in the candidate loop and adjacent test additions. The tested resolution keeps the indexed candidates and manifest-order tie-break (carry order through want.push and sort by distance, then order), while computing nextRetryAt only for candidates that pass the exact load-range test. Keep both PRs' test additions. With the missing camera-test globals supplied in both snapshots, the streaming and Studio tests passed 76/76 on the index tree and 78/78 on the combination.

Replayed a local saved map manifest (175 chunks, seven LOD tiers) through the Node viewer harness with synthetic loader completions. At eight camera positions, all load requests matched in order (215 requests summed across the eight independent starts). After each position settled, 120 stationary ticks issued no new loads on either tree. The index-only tree called the indexed candidate lookup 960 times during those windows. The combined tree called it zero times. This counts lookup calls, not elapsed time or GPU frames. No local asset data is included.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants