t1k:playablelabs:optimize:mass-populations
| Field | Value |
|---|---|
| Module | optimize |
| Version | 1.16.2 |
| Effort | medium |
| Tools | — |
Keywords: cpu bound playable, data-oriented playable, gpu particles playable, instanced draw playable, low-end phone playable, mass population playable, vat instancing playable
How to invoke
Section titled “How to invoke”/t1k:playablelabs:optimize:mass-populations[population name | profile | cocos | three]Mass populations: runtime frame cost
Section titled “Mass populations: runtime frame cost”Scope: game-side CPU/GPU frame cost of anything that exists in the hundreds (crowd units, enemies,
bullets and tracers, debris and fracture pieces, pickups). Engine-agnostic rules here; the Cocos 3.8
and three.js (web host) recipes are in references/. Packed-size work is the passes skill
(link only). Changing shared engine code (not game code) must be proven not to change Cocos output:
change-proof.
The three patterns
Section titled “The three patterns”| # | Pattern | One line |
|---|---|---|
| 1 | Data-oriented population | State of one entity type lives in packed typed arrays, advanced by ONE system loop |
| 2 | One instanced draw per population | A population is one draw, never one scene object per member |
| 3 | GPU-side animation and effects | Pose and motion computed in the vertex shader from initial state plus time |
They stack: 1 makes the per-frame CPU cost flat, 2 makes the draw cost flat, 3 removes the CPU work for things gameplay never reads. Each is independent; adopt only what the profile asks for.
1. Data-oriented population
Section titled “1. Data-oriented population”- Struct-of-arrays: one
Float32Arrayper field (posX,posZ,velX,life…), pluscount. Capacity is preallocated for the worst case; nothing is allocated after load. - ONE loop per type updates every live entity:
for (let i = 0; i < count; i++). No per-entityNode,Componentlifecycle, closure,Vec3/Vector3temporary or Promise. - Despawn is swap-remove: copy the last live entity into slot
i,count--, and re-check sloti. Anything holding an index must be re-pointed (keep aUint32Arrayid table if outside code needs handles, never hold raw indices across frames). - Collision and picking run on the arrays (distance checks, a uniform grid if pairs explode), never through scene objects or physics bodies.
- Use when: more than about 50 similar entities, or anything spawned per shot. Do not use for: unique hero objects, anything that needs per-node editor wiring, animation-graph state, or a handful of entities (the arrays cost more clarity than they save).
2. One instanced draw per population
Section titled “2. One instanced draw per population”- The population renders through one instanced mesh and the typed arrays are copied into it once
per frame (Cocos: GPU instancing on a shared material; three:
InstancedMesh; varied static meshes: static batching /BatchedMesh). Zero per-member nodes. - Per-instance variation (tint, pose row, scale) goes in instanced attributes, never in a per-member material or material clone: a per-renderer material instance leaves the batch.
- Upload only what changed (dirty range); cull per population with one bounding volume.
3. GPU-side animation and effects
Section titled “3. GPU-side animation and effects”- Skinned crowds: baked animation (Cocos
useBakedAnimation) or a vertex animation texture (three). - Particles, debris and tracer motion: the vertex shader computes position from spawn state
(position, velocity,
spawnTime,seed) and one time uniform. The CPU writes an instance once at spawn and never again. - Use only where gameplay does not read the position back. Anything that collides, scores or gets picked stays in pattern 1 arrays; the GPU copy is cosmetic.
Step 0: decide CPU or GPU bound, then pick
Section titled “Step 0: decide CPU or GPU bound, then pick”A desktop CPU-throttle profile slows only the main thread; a CPU-side change that looks good on the
desktop can do nothing on a GPU-bound phone. Decide on the real device: references/device-probe-workflow.md
(probe table, the sync >= 2x JS -> GPU; &dpr=1 no-change -> vertex-bound; isolation-toggle decision
table). Calibration method and the desktop stand-in: references/cpu-first-checklist.md; probe build and
parameters also in PlaybleEngine .claude/skills/playable-engine/references/device-probes.md.
- Calibrate a desktop CDP CPU-throttle factor to the target phone, and ship the on-device probes
(
?perf=1overlay,&sync=1GPU-vs-JS verdict, per-kind isolation toggles) default-off. - Read the verdict on the phone. JS-bound: work the CPU checklist. GPU-bound: the vertex-budget
items only (
references/vertex-budget.md). - Entities per type, scene
Node/Object3Dcount, draws, triangles AND vertices per kind; per-frame JS self-time by system; repeat under the calibrated throttle. Recipe:references/profiling-and-proof.md. - Re-profile after each change; keep it only if the counter that justified it moved.
- In TimelineUp three CPU PRs (#42-#44) measured well on the desktop and gave no phone gain — the phone was vertex-bound. A desktop throttle ranks JS work; it never overrides the phone verdict.
Pooling alone is not this skill: a pool of 600 nodes is still 600 nodes walked every frame.
CPU checklist (what moves a CPU-bound phone)
Section titled “CPU checklist (what moves a CPU-bound phone)”Per-frame overhead that scales with entity count is what moved the phone. Each item has its measured
effect in references/cpu-first-checklist.md.
- Struct-of-arrays and one loop per population; one instanced draw per population (patterns 1, 2).
- Particles batched per material and on the update list only while playing.
- Adaptive culling that backs off when it removes little (a cull that removes about 0 % is pure cost).
- Cached world matrices, no-op same-value transform writes, no per-call allocation in hot paths.
- Skip unchanged subtrees in the scene walk; keep nodes that cannot draw out of the render graph.
- Close-out items (allocation-free argument shapes, reused input events,
checkShaderErrorsoff in shipped builds,material.needsUpdategated on the map, a ClockMixer for baked time):references/cpu-alloc-closeout.md.
GPU-geometry items: only when probes say GPU-bound
Section titled “GPU-geometry items: only when probes say GPU-bound”Vertex-cost work (per-instance frustum cull, shadow-geometry weld, fewer skin fetches, cheaper
tracer meshes) did not move a CPU-bound phone and read 2-4 % on a desktop GPU. Do it only after
&sync=1 reports GPU-bound on the target device: references/vertex-budget.md (low-tri projectiles,
planar-shadow LOD -69..-75 %, distance LOD at 280/360 design px with hysteresis, meshoptimizer
weld/transfer recipe, 3-texel VAT bone, drop-unread-varyings).
VISUAL-IDENTITY rule (hard)
Section titled “VISUAL-IDENTITY rule (hard)”These patterns change how pixels are produced, never which pixels. Before merging, prove it:
same scene, fixed seed, fixed dt, same frame index, before/after screenshots, pixel diff within a
stated tolerance (zero for the same draw order, antialiasing tolerance otherwise). A visible diff
(draw order of transparents, lost per-unit flash, blend-less crossfade) is a regression: fix it or
document the trade-off for the owner to accept. Recipe: references/profiling-and-proof.md.
Geometry-LOD exception (decision 2026-10-12, TimelineUp). A device-class-driven quality cut (resolution below the reference rule, fewer particles, shadows off, LOD keyed on device) stays forbidden, whatever the frame time. But a geometry LOD / simplification that is identical on every device is allowed after before/after shots are reviewed: record the differing-pixel count and the max channel delta and get the owner’s approval. The shipped tracer (512 -> 64 tris, SSIM 0.998) and crowd LOD went in this way. Never read DPR/canvas size/device to decide a level; a test should fail if the code does.
Prove a change BEFORE you claim “0 pixels”. This harness is not bit-reproducible across browser launches: measure the pixel-pair noise floor (A-vs-A, or main-vs-main) first, and only then compare A-vs-B; when a box is shared, use a same-page paired A/B (the change toggled in one build, one frame) so launch noise cannot hide or fake a diff. For a re-tessellation (tracer, LOD) the exact proof is the program/state itself (transform feedback, or a hashed state trace), not the pixels.
Every PR that touches these patterns also passes gate check F4 (t1k-playablelabs-optimize-gate,
references/visual-fidelity.md): fidelity gate plus asset lint, and no device-driven quality cuts.
Mesh simplification gotcha
Section titled “Mesh simplification gotcha”Simplify with position-only error, as the Cocos meshSimplify does. Attribute-weighted error (uv, normal,
colour terms) can collapse a layered shell through the surface under it. Layered meshes (helmets, armour,
clothing over a body) must not interpenetrate after simplification: check each one with a same-camera
pixel-crop before/after. Detail: t1k-playablelabs-optimize-gate/references/visual-fidelity.md.
For an offline meshoptimizer LOD of a seam-heavy skinned mesh: weld on
(position, skinIndex, skinWeight) first (a plain simplify stalls on a seam, ~92 %), then transfer each
moved corner’s UV from its source triangle (naive wedge pick gives a dark speckle). Keep a
rounded-helmet mesh out of the LOD when its facets show. Recipe: references/vertex-budget.md.
Mobile GPU precision gotcha
Section titled “Mobile GPU precision gotcha”mediump is real fp16 on Mali, Adreno and Apple GPUs; desktop GPUs run it as fp32 and hide the bug.
Use highp for world/instance positions, VAT texel fetch and matrix decode, depth and anything
accumulating time. Symptoms on a phone only: crowd jitter, shimmering at distance, stepped animation
after a minute of play. Details per engine in the references.
Measured gains per pattern, with config and n: references/cpu-first-checklist.md (Proof table).
Replace a row only with a measured value plus config and n.
References
Section titled “References”references/device-probe-workflow.md: on-device probes (?perf=1,&sync=1, isolation toggles) and the CPU/GPU/vertex-bound decision tablereferences/vertex-budget.md: GPU-bound geometry work — low-tri projectiles, shadow LOD, distance LOD (280/360 px), meshoptimizer weld/transfer, 3-texel VATreferences/cpu-alloc-closeout.md: allocation-free shapes, input-event reuse, shader-check stall, label redraw, ClockMixer, heap samplingreferences/cocos-recipes.md: Cocos 3.8 instancing, batching, baked animation, GPU particlesreferences/three-recipes.md: three.jsInstancedMesh,BatchedMesh, VAT, GPU particles, typed-array loopsreferences/profiling-and-proof.md: profiling recipe, paired screenshot diff, precision checksreferences/cpu-first-checklist.md: CPU-vs-GPU decision, CPU checklist with measured effects, Proof table