Skip to content

Client: make a loc-only square rebuild cheaper (#6240) - #6624

Merged
UnhealthyKraken merged 1 commit into
RSPSApp:mainfrom
BeefBeefs:fix/6240-loc-only-rebuild
Nov 23, 2026
Merged

UnhealthyKraken merged 1 commit into
RSPSApp:mainfrom
BeefBeefs:fix/6240-loc-only-rebuild

Conversation

@BeefBeefs

Copy link
Copy Markdown
Collaborator

Addresses #6240. It does not close it: the first change to a square after it loads is still about 2 s (see "Not fixed").

What was wrong

The Varlamore tree and Baker's stall are not special. A loc change (tree felled, stall emptied) makes the client reload the map square's scenery in the worker, and that reload is not a delta. It runs the whole scene build (decode every loc, light the scene) and then repacks every non-door loc of the 64x64 square, near and far LOD. The cost follows how much scenery the square holds, so the same change shows about 0.2 s late in a sparse square and 2-3 s late in Varlamore.

Measured in the worker on the idle scene (browser pane, same machine, before this PR):

Square Rebuild Worker build
26,48 Varlamore (2.28M faces, 7274 models, 31 MB loc mesh) loc-only 2.2-2.5 s
26,48 whole square about 2.2 s
26,48 door-only 160 ms
48,55 (tree 1278 at 3098,3533, the issue's control) loc-only 197 ms

Inside the 26,48 loc-only build: scene build about 700 ms (scene.light about 620 of it), packing about 1450 ms, the rest about 120 ms. Keeping decoded models between builds on its own only saved about 10%.

What changed

  • ModelData.mergeNormals (client/rs/model/ModelData.ts): it built a string-keyed map of all of the second model's vertices for every neighbouring pair, then checked whether the models overlapped. It now returns early when no vertex can fall inside the other model's X, Z and Y ranges, and builds the map lazily with numeric keys. scene.light goes from about 660 ms to about 200 ms in square 26,48. This helps every build, not just loc-only ones.
  • Chunked packing (SdMapDataLoader.addSceneModelsByChunk, SceneChunkCache, SceneBuffer.toFragment / appendFragment, getModelSignature): a loc-only build packs the scenery per 8x8-tile chunk, which is how its models are already grouped, and keeps each chunk's packed fragment in a per-worker cache. A chunk is reused when a signature of its models (geometry, topology, alphas, priorities, UVs) and positions is unchanged, so a change repacks the chunk it touches and appends the rest. The cache keeps 4 squares or 128 MB per worker (1 square or 24 MB on low-end devices). Whole-square and door-only builds are unchanged.
  • Worker pinning (RenderDataWorkerPool.runPinned): loc-only builds of the main world run on the first worker, so they find that worker's cache. It is reserved the same way the NPC pose jobs reserve a worker (a placeholder in runningTasks, started after the builds already there), so it never interleaves with another build: a worker's scene builder holds one build's overrides at a time. Instances, boat decks and single-worker pools go through the pool as before.
  • RenderDataWorker: the decoded loc models stay after a loc-only build; the next whole build clears them as before.

Results

Worker build time for loc-only rebuilds of square 26,48, scene idle, after this PR:

Before After
First change after the square loaded (cold cache) 2.2-2.5 s about 2.0 s
Later changes (cache warm), 12 rebuilds 2.2-2.5 s 0.45-0.62 s

A real chop, tree delete packet to the stump being applied: about 2.9 s before, 0.7-1.0 s after (warm). Those include the test pane's 1.3 fps frame wait (0.4-0.9 s), so a normal client is faster.

Verification

  • cd client && npx tsc --noEmit -p tsconfig.json: no errors.
  • node scripts/run-tests.mjs <name> for scene-chunk-cache, model-merge-normals (2 files), scene-build-steps, geometry-buffer-memory, partial-loc-bridge-heights, map-square-cache (2 files), roof-underside, loc-animation-smoothing, loc-animation-submission, scenery-distance, hd-lights, map-loading-regression, minimap: all pass.
  • New model-merge-normals-equivalence.test.ts: 4000 random model pairs against a copy of the original algorithm, covering merges, skipped pairs and hidden faces. Making the early-out too aggressive makes it fail.
  • New scene-chunk-cache.test.ts: chunked packing draws what packing everything at once draws (cold and reused), an unchanged square packs nothing, one changed model repacks exactly one chunk, a recoloured model at the same place is not mistaken for the old one, and the square/byte limits evict. Breaking the offset rebasing in appendFragment makes it fail.
  • scene-build-steps.test.ts: the castle test used to require a loc-only reload's vertex and index bytes to equal a whole build's. Chunked packing numbers vertices differently, so it now compares the lit triangles (same intent: the rope reload keeps the castle's merged wall lighting). It passes on the real castle square, cold and on a second, reused reload. New test: loc-only builds are pinned to the first worker, wait for the builds ahead of them, run one at a time, release their reservation (also on abort), and everything else still goes through the pool.
  • Real data: whole-square builds of 37,48, 50,50, 26,48 and 48,55 are byte-identical (deepEqual of the whole result) with the original mergeNormals and the new one. This was a throwaway test and is not in the PR.
  • Live (agent MCP, browser pane, local server): chopped the Varlamore tree (loc 52823 at 1696,3102) cold, on respawn, and again; chopped and teleported away so streaming builds ran against the pinned worker (no hang, no console errors, nothing left pending); scene renders correctly with the stump and after returning.

Not fixed

  • The first change to a square after it loads packs the whole square (about 2 s here). Whole-square builds do not fill the cache, and they can run on any worker. Warming it when the player starts interacting with a loc, or packing whole builds by chunk on a pinned worker, would close that.
  • Warm rebuilds still spend about 150 ms decoding locs and about 200 ms lighting the whole scene.

Not verified

  • Only square 26,48 and the 48,55 control were timed. The Baker's stall theft goes through the same reload path but I did not run it.
  • No real phone or Safari; no single-worker pool run beyond the pool unit test (with one worker the pinning is a no-op).
  • Times are from one machine through the in-app browser pane at about 1.3 fps; absolute numbers will differ elsewhere, the ratios should hold.

Generated data untouched.

A loc-only reload (a tree felled, a stall emptied) ran the whole scene build and repacked every non-door loc in the 64x64 square, so in a dense square like Varlamore 26,48 (2.28M faces) the change showed 2-3 s late while a sparse square took 0.2 s.

Lighting: ModelData.mergeNormals built a string-keyed vertex map of the second model for every neighbouring pair, then checked whether they overlapped. It now skips pairs whose ranges cannot meet and builds the map lazily with numeric keys. scene.light drops from ~660 ms to ~200 ms in that square, for every build; real squares build byte-identically.

Packing: loc-only builds pack the scenery chunk by chunk (8x8 tiles, how the models are already grouped) and keep each chunk's packed fragment in a per-worker SceneChunkCache keyed by a signature of its models and positions. A change repacks the chunk it touches and appends the rest.

Workers: loc-only builds of the world run on the first worker (reserved like the NPC pose jobs, so they never interleave with another build) so they find that cache, and the worker keeps its decoded models after them.
@UnhealthyKraken
UnhealthyKraken self-requested a review November 23, 2026 18:10
@UnhealthyKraken

Copy link
Copy Markdown
Collaborator

Reviewing this now (review loop, head 837e674).

@UnhealthyKraken UnhealthyKraken left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed PR #6624 at 837e674 (main e7ec324, integration tree 572a7cf3633eed01398bbc39c685b3c2e155ebef).

What it does

Makes loc-only map square rebuilds cheaper, which is the rebuild that runs when a tree is felled or a stall is emptied (#6240).
ModelData.mergeNormals now returns early when two models' bounds cannot touch, and it builds its vertex map lazily with numeric keys.
A loc-only build now packs scenery one 8x8 chunk at a time. Each worker keeps the packed chunks in a cache (SceneChunkCache) and reuses a chunk when the signature of its models and positions is unchanged.
Loc-only builds of the main world are pinned to the first worker, so they find that cache.

What was checked

  • Behaviour: whether a chunked loc-only rebuild draws exactly what a whole build draws, cold and with reused chunks. Cases covered: loc add, remove and change; a 2x2 loc across a chunk edge; a 2x2 loc across the square edge; merged-normal walls (castle 37,48). Each case ran with minimizeDrawCalls true (WebGPU, and WebGL without multi-draw) and false (WebGL with multi-draw).
  • Parity: no OSRS counterpart. The PR cites no recordings or Wiki pages; the change is client render internals only.
  • Traced:
    • mergeNormals: the early-out is implied by the per-vertex X/Z/Y filters it replaces. It uses the same bounds: calculateBounds covers usedVertexCount and the contour Y. mergeModelNormalsCount still increments first. The numeric key x*2^31+z is exact for model coordinates.
    • addSceneModels: it already groups by 8x8 chunk (hash key and createModelGroups both carry the chunk), so chunked packing gives the same groups. appendFarScenery replaces the LOD lists per chunk, and the union is the same.
    • Packing inputs: every SceneBuffer.addModel/addModelGroup/getModelFaces* read is in getModelSignature or the per-model signature fields. The texture slot map is read-only and is hashed into the context.
    • toFragment bounds: they come from the same vertex bytes, and createDrawRange uses the final buffer's heightBounds.
    • Consumers: buildLocGeometryData, WebGLMapSquare.refreshLocGeometry, WebGPUMapSquare loc-only apply, HD lights (collectHdLights reads tile loc ids, not packed geometry), and HD normals (shader derivatives, so vertex sharing does not matter).
    • Pool: queueLoad callers in streaming2, WebGPURenderer loadSceneData (abort via signal, checked when the pinned task starts), instance.ts and worldEntity. None calls .cancel(), so the no-op cancel is harmless. loadNpcPose reservations and threads.js scheduleWork/runningTasks reassignment are compatible with the placeholder reservation.
    • RenderDataWorker: skipping clearCache after loc-only builds keeps shared cached models. mergeNormals locs are copy()'d with their own faceRenderTypes/mergedNormals, so no per-build mutation carries over. Sparse misses are not cached, and custom content still clears.
  • Rules: client only, no generated JSON, no docs, no plugin config. LF endings.

Findings

No defects found.

Scope

ordinary

Verified

  • Review-only real-cache equivalence test (temporary, deleted). It compares whole build vs loc-only on one shared worker state: every draw-range list, with its triangles, per-instance model texture data, planes, bounds, chunk and batch key. Squares 48,55 and 37,48, each with minimizeDrawCalls true and false.
    • 48,55: base; tree 1278 at 3098,3533 changed to stump 1342; tree removed; back to base; 2x2 tree added across a chunk edge; 2x2 tree added across the square edge; base again.
    • 37,48: base; rope added; base again.
    • All 20 cases are identical. Chunks repacked per change: 1 (2 when the added loc moved chunks), and 0 for an unchanged square.
    • In every case, all non-loc fields of the loc-only result (collision, tile loc ids, bridge flags, roofs/planes and the rest) are deepEqual to a cold loc-only build on a fresh state.
  • Tests from the PR description, one at a time, each passing: scene-chunk-cache, model-merge-normals-equivalence, model-merge-normals-tolerance, scene-build-steps (5/5, real cache, castle test included), geometry-buffer-memory, partial-loc-bridge-heights, map-square-cache, map-square-cache-format, roof-underside, loc-animation-smoothing, loc-animation-submission, scenery-distance, hd-lights, map-loading-regression.
  • Consumer tests, each passing: webgpu-loc-reload-batch, webgpu-scenery, webgpu-map-streaming, async-npc-pose, house-portal-pick, minimap-floors, minimap-chunk-retry, world-map-worker.
  • Revert check (main's RenderDataWorkerPool, ModelData, SdMapDataLoader, RenderDataWorker under the PR's tests):
    • scene-chunk-cache fails 4/4.
    • scene-build-steps fails the pinning test.
    • model-merge-normals-equivalence passes on main too, as expected: it checks equivalence with the original algorithm.
  • client tsc --noEmit -p tsconfig.json: no errors.
  • main+head merge tree: clean
  • generated JSON: none edited

Not verified

  • Timings (2.2-2.5 s down to 0.45-0.62 s warm) were not re-measured, and the client was not run live in a browser. The real-cache build test stands in for rendering; no visual WebGL/WebGPU/HD screenshot was taken.
  • Varlamore square 26,48 was not built (memory-heavy under the 2 GB test cap). 48,55 and the castle square were used instead.
  • No instance, boat-deck or single-worker run beyond the pool unit test. Instances and decks keep the old path.

Notes, not findings (none is a defect; each is a different/shared system or lacks a reproducible wrong result):

  • getModelSignature does not hash model.faceColors, which isHdLightSourceFace reads for HD lamp faces. Lit colours (hashed) derive from it, and textured faces are excluded, so a mismatch is not practically reachable.
  • SceneChunkCache byte accounting counts fragment bytes only. Instanced draw commands keep references to their SceneModel/Model objects, which stay alive uncounted while cached (first worker, up to 4 squares).
  • After a loc-only build, the first worker keeps its decoded type and model caches until a whole build runs on it. A player standing still keeps them longer than before.
  • Draw commands are ordered per chunk in loc-only builds and per kind in whole builds. Only translucent overlap across chunks could draw in a different order. That order was never depth-sorted.
  • Chunk reuse rests on a 32-bit content hash plus face and vertex counts.

Verdict

Merge

@UnhealthyKraken
UnhealthyKraken merged commit b79817e into RSPSApp:main Nov 23, 2026
3 checks passed
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.

3 participants