mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 16:22:20 +00:00
feat(globe): instanced movers on both engines
engine.movers.createSet({ id, kind: sprite|point|model, capacity, order,
depthTest, sprite|point|model, pickable }) → a MoverSet: set(index,
fields) stores an instance (position, screen rotation, orientation, rgba,
scale, atlas cell, show, pickId) in flat arrays, commit() uploads the
changed range once and requests one render, positionsView() reads the
positions, destroy() removes it; movers.list() for QA. The options, the
store and the registry are engine-neutral (src/globe/movers.js); the fake
engine keeps them for layer tests.
- Cesium: one primitive per set in an engine-owned PrimitiveCollection
added with the first set, in `order`: sprites a BillboardCollection
(one image per atlas cell, NearFarScalar, disableDepthTestDistance),
points a PointPrimitiveCollection, models a Model per instance.
- Navara: a public MeshDesc per set. Sprites and points are one
InstancedMesh of a quad, faced to the screen and sized in CSS pixels in
the vertex shader from uniforms (the pick pass draws the same
footprint), atlas uv, rotation, colour and scale per instance, drawn in
the transparent pass unlit; offsets from an origin that follows the
camera past max(1 km, 10 % of its height). Models: the glTF once, one
InstancedMesh per mesh, minimumPixelSize/maximumScale on the CPU per
drawn frame, colorBlend in the shader. Pickable sets register a
PickableInstancedMeshWrapper; pickIds.js maps batch ids back to
instances (used by Task 4).
- The contract suite draws three 24 px sprites on both engines: centred
within 2 px of worldToWindow, hidden by show:false, recoloured, gone on
destroy, and no frames added once the commit has drawn.
- qa-engine-bench --scenario=movers: 10 000 synthetic aircraft
(src/bench/syntheticFlights.js, moved from the Navara spike with its
test), every instance moved and committed every frame. p95 Navara
(look=minimal) / Cesium: global 5.2/7.0 ms, city 5.6/9.9, orbit 6.0/7.4
(0.74, 0.57, 0.81; gate 1.1). Cesium is measured without its 60 fps cap.
Main chunk 2,860,302 bytes (+9,706, +0.34 %: the Cesium movers).
This commit is contained in:
1 parent
4623c8b616
commit
0109097440
24 files changed
+2735
-3
No files matched your search
@@ -23,6 +23,14 @@ import { createGroundFloor, GROUND_FLOOR } from './groundFloor.js';
|
||||
|
||||
const { cartesian3, math } = geo;
|
||||
|
||||
// engine.movers without the view's three runtime (Node tests of the engine).
|
||||
const NO_MOVERS = Object.freeze({
|
||||
createSet() {
|
||||
throw new Error("Navara movers need the view's three runtime (movers/)");
|
||||
},
|
||||
list: () => [],
|
||||
});
|
||||
|
||||
// Navara's drawn camera (view.camera.raw, a three PerspectiveCamera in
|
||||
// Earth-fixed metres): matrixWorld columns are right, up, back, position.
|
||||
function readCamera(raw) {
|
||||
@@ -75,6 +83,8 @@ function rayRaisedEllipsoid({ origin, direction }, height) {
|
||||
* canvas's parent; `sharpen` draws render.setSharpen (sharpen.js; without
|
||||
* it the engine only keeps the state) and the engine destroys it;
|
||||
* `appClock` (the engine clock's time) defaults to the page's app clock;
|
||||
* `movers` is engine.movers on the view's three runtime (movers/index.js;
|
||||
* without it createSet throws) and the engine destroys it;
|
||||
* `fetch` and `clock` (the camera model's timers) are test seams.
|
||||
* @returns {import('../contract.js').GlobeEngine}
|
||||
*/
|
||||
@@ -86,6 +96,7 @@ export function createNavaraEngine(
|
||||
fetch,
|
||||
clock,
|
||||
appClock,
|
||||
movers: moversPort = null,
|
||||
sharpen: sharpenPort = null,
|
||||
} = {},
|
||||
) {
|
||||
@@ -234,6 +245,7 @@ export function createNavaraEngine(
|
||||
credits: credits.credits,
|
||||
maps: maps.maps,
|
||||
clock: engineClock.clock,
|
||||
movers: moversPort?.movers ?? NO_MOVERS,
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
@@ -244,6 +256,7 @@ export function createNavaraEngine(
|
||||
credits.destroy();
|
||||
maps.destroy();
|
||||
sharpenPort?.destroy();
|
||||
moversPort?.destroy();
|
||||
},
|
||||
isDestroyed: () => destroyed,
|
||||
// Navara only, not contract: the ground the floor last sampled under
|
||||
|
||||
@@ -9,6 +9,7 @@ import { createNavaraEngine } from './createNavaraEngine.js';
|
||||
import { forEachLuminanceUniform, navaraHooks } from './internals.js';
|
||||
import { buildNavaraLook } from './look.js';
|
||||
import { createNavaraSharpen } from './sharpen.js';
|
||||
import { createNavaraMovers } from './movers/index.js';
|
||||
import {
|
||||
NAVARA_CONTEXT_ATTRIBUTES,
|
||||
navaraScenePlan,
|
||||
@@ -115,6 +116,7 @@ export async function createNavaraGlobe({
|
||||
container,
|
||||
...(appClock ? { appClock } : {}),
|
||||
sharpen: createNavaraSharpen(view),
|
||||
movers: createNavaraMovers(view),
|
||||
});
|
||||
const camera = engine.camera;
|
||||
let ground = Number.NaN;
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
// engine.movers on Navara: each set is one Navara mesh descriptor (public
|
||||
// MeshDesc API) holding its instanced meshes (moverMesh.js, modelMover.js).
|
||||
// Pickable sets register a PickableInstancedMeshWrapper so Navara's pick
|
||||
// pass sees each instance; pickIds.js turns its batch ids back into
|
||||
// instances. commit() uploads and asks for one frame (view.forceUpdate): a
|
||||
// descriptor's update() runs only on frames the view draws anyway (S5), so
|
||||
// an idle view stays idle.
|
||||
|
||||
import {
|
||||
MeshDesc,
|
||||
PickableInstancedMeshWrapper,
|
||||
createGltfLoader,
|
||||
} from '@navaramap/three';
|
||||
import { Group } from 'three';
|
||||
import { createMoverRegistry } from '../../movers.js';
|
||||
import { createModelMover } from './modelMover.js';
|
||||
import { createMoverMesh } from './moverMesh.js';
|
||||
import { createPickIndex } from './pickIds.js';
|
||||
|
||||
const DESC_NAME = 'gevMoverSet';
|
||||
const registered = new WeakSet();
|
||||
const EARTH_RADIUS_M = 6_371_000;
|
||||
|
||||
class GevMoverSetDesc extends MeshDesc {
|
||||
constructor(view, ctx, config) {
|
||||
super(view, ctx, config);
|
||||
this.gev = config[DESC_NAME];
|
||||
this.wrappers = [];
|
||||
}
|
||||
|
||||
// Sprites and points are screen overlays: the transparent pass, unlit.
|
||||
getPassKey() {
|
||||
return this.gev?.kind === 'model' ? super.getPassKey() : 'transparent';
|
||||
}
|
||||
|
||||
createMesh() {
|
||||
const { mover, pickable, onPickable, kind } = this.gev;
|
||||
const register = (mesh, key) => {
|
||||
if (!pickable) return;
|
||||
const wrapper = new PickableInstancedMeshWrapper(
|
||||
mesh,
|
||||
mesh.instanceMatrix.count,
|
||||
this.ctx,
|
||||
);
|
||||
this.ctx.registerPickableMesh(key, wrapper);
|
||||
this.wrappers.push(key);
|
||||
onPickable(wrapper);
|
||||
};
|
||||
if (kind !== 'model') {
|
||||
register(mover.mesh, this.id);
|
||||
return mover.mesh;
|
||||
}
|
||||
const group = new Group();
|
||||
group.frustumCulled = false;
|
||||
// Meshes arrive with the glTF; they join the group (and the pick pass).
|
||||
mover.group.ready.then(() => {
|
||||
if (this.destroyedByGev) return;
|
||||
mover.group.meshes.forEach((mesh, index) => {
|
||||
group.add(mesh);
|
||||
register(mesh, `${this.id}#${index}`);
|
||||
});
|
||||
this.view.forceUpdate();
|
||||
});
|
||||
return group;
|
||||
}
|
||||
|
||||
update() {
|
||||
const raw = this.view.camera.raw;
|
||||
const height = this.ctx.getRenderer().domElement.clientHeight;
|
||||
if (!raw || !(height > 0)) return;
|
||||
raw.updateMatrixWorld();
|
||||
const e = raw.matrixWorld.elements;
|
||||
const cameraPosition = { x: e[12], y: e[13], z: e[14] };
|
||||
const cameraHeight =
|
||||
Math.hypot(cameraPosition.x, cameraPosition.y, cameraPosition.z) -
|
||||
EARTH_RADIUS_M;
|
||||
this.gev.mover.update({
|
||||
cameraPosition,
|
||||
cameraHeight,
|
||||
fovDeg: raw.fov,
|
||||
viewportHeightPx: height,
|
||||
});
|
||||
}
|
||||
|
||||
onDestroy() {
|
||||
this.destroyedByGev = true;
|
||||
for (const key of this.wrappers) this.ctx.unregisterPickableMesh(key);
|
||||
this.gev.mover.dispose();
|
||||
super.onDestroy();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} view an initialised Navara ThreeView
|
||||
* @returns {{ movers: import('../../contract.js').GlobeMovers,
|
||||
* resolvePick: (batchId: number) => ({ set: string, instance: number, pickId: any } | null),
|
||||
* destroy: () => void }}
|
||||
*/
|
||||
export function createNavaraMovers(view) {
|
||||
if (!registered.has(view)) {
|
||||
view.registerMesh(DESC_NAME, GevMoverSetDesc);
|
||||
registered.add(view);
|
||||
}
|
||||
const pickIndex = createPickIndex();
|
||||
let loader = null;
|
||||
const loadGltf = (url) => {
|
||||
loader ??= createGltfLoader();
|
||||
return loader.loadAsync(url);
|
||||
};
|
||||
const request = () => view.forceUpdate();
|
||||
const registry = createMoverRegistry((options, store) => {
|
||||
const mover =
|
||||
options.kind === 'model'
|
||||
? createModelMover(options, store, { load: loadGltf, onLoad: request })
|
||||
: createMoverMesh(options, store, { onTextureLoad: request });
|
||||
const handle = view.addMesh({
|
||||
...(options.kind === 'model' ? {} : { lit: false }),
|
||||
[DESC_NAME]: {
|
||||
mover,
|
||||
kind: options.kind,
|
||||
pickable: options.pickable,
|
||||
onPickable: (wrapper) =>
|
||||
pickIndex.add(options.id, wrapper, (index) => store.pickIds[index]),
|
||||
},
|
||||
});
|
||||
return {
|
||||
commit() {
|
||||
mover.commit(store.dirty());
|
||||
request();
|
||||
},
|
||||
destroy() {
|
||||
pickIndex.remove(options.id);
|
||||
handle.delete();
|
||||
request();
|
||||
},
|
||||
};
|
||||
});
|
||||
return {
|
||||
movers: registry.movers,
|
||||
resolvePick: (batchId) => pickIndex.resolve(batchId),
|
||||
destroy: () => registry.destroyAll(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
// The three side of a Navara model set: the glTF loaded once, one
|
||||
// InstancedMesh per mesh in it (all instances share the model's meshes),
|
||||
// each instance placed by position, orientation and scale relative to an
|
||||
// origin near the camera. Cesium's minimumPixelSize/maximumScale are kept on
|
||||
// the CPU once per drawn frame (models are few: tracked and proximity
|
||||
// aircraft), and the instance colour is mixed into the surface colour
|
||||
// (colorBlend), or the model drawn unlit.
|
||||
|
||||
import {
|
||||
Box3,
|
||||
DynamicDrawUsage,
|
||||
InstancedBufferAttribute,
|
||||
InstancedMesh,
|
||||
Matrix4,
|
||||
MeshBasicMaterial,
|
||||
Quaternion,
|
||||
Sphere,
|
||||
Vector3,
|
||||
} from 'three';
|
||||
import { footprintPerDepth, originFor } from './pack.js';
|
||||
|
||||
const scratchMatrix = new Matrix4();
|
||||
const scratchQuaternion = new Quaternion();
|
||||
const scratchTranslation = new Vector3();
|
||||
const scratchScale = new Vector3();
|
||||
|
||||
/** Mixes the instance colour into the material's colour by uGevBlend × alpha. */
|
||||
function blendInstanceColor(material, uniforms) {
|
||||
material.onBeforeCompile = (shader) => {
|
||||
Object.assign(shader.uniforms, uniforms);
|
||||
shader.vertexShader = shader.vertexShader
|
||||
.replace(
|
||||
'void main() {',
|
||||
'attribute vec4 gevColor;\nvarying vec4 vGevColor;\nvoid main() {',
|
||||
)
|
||||
.replace(
|
||||
'#include <begin_vertex>',
|
||||
'#include <begin_vertex>\nvGevColor = gevColor;',
|
||||
);
|
||||
shader.fragmentShader = shader.fragmentShader
|
||||
.replace(
|
||||
'void main() {',
|
||||
'uniform float uGevBlend;\nvarying vec4 vGevColor;\nvoid main() {',
|
||||
)
|
||||
.replace(
|
||||
'#include <map_fragment>',
|
||||
'#include <map_fragment>\ndiffuseColor.rgb = mix(diffuseColor.rgb, vGevColor.rgb, uGevBlend * vGevColor.a);',
|
||||
);
|
||||
};
|
||||
material.customProgramCacheKey = () => 'gev-mover-model-blend';
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} options normalized model set options
|
||||
* @param {object} store the set's mover store
|
||||
* @param {{ load: (url: string) => Promise<{ scene: object }>, onLoad?: () => void }} ports
|
||||
*/
|
||||
export function createModelMover(options, store, { load, onLoad = () => {} }) {
|
||||
const { capacity, model } = options;
|
||||
const uniforms = {
|
||||
uGevBlend: {
|
||||
value: model.colorBlend
|
||||
? model.colorBlend.mode === 'replace'
|
||||
? 1
|
||||
: model.colorBlend.amount
|
||||
: 0,
|
||||
},
|
||||
};
|
||||
const parts = []; // { mesh, local: Matrix4 }
|
||||
let radius = 1;
|
||||
let origin = null;
|
||||
let footprint = 0;
|
||||
let cameraPosition = null;
|
||||
let loaded = false;
|
||||
let disposed = false;
|
||||
const colorAttributes = [];
|
||||
|
||||
const write = (from, to) => {
|
||||
if (!loaded || !origin) return;
|
||||
const { positions, orientations, scales, shows, colors } = store;
|
||||
for (let index = from; index < to; index++) {
|
||||
let scale = shows[index] === 1 ? scales[index] : 0;
|
||||
if (scale > 0 && cameraPosition && footprint > 0) {
|
||||
const dx = positions[index * 3] - cameraPosition.x;
|
||||
const dy = positions[index * 3 + 1] - cameraPosition.y;
|
||||
const dz = positions[index * 3 + 2] - cameraPosition.z;
|
||||
const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
|
||||
const pixels = (2 * radius * scale) / (footprint * distance);
|
||||
if (pixels < model.minimumPixelSize)
|
||||
scale *= model.minimumPixelSize / pixels;
|
||||
scale = Math.min(scale, model.maximumScale);
|
||||
}
|
||||
scratchTranslation.set(
|
||||
positions[index * 3] - origin.x,
|
||||
positions[index * 3 + 1] - origin.y,
|
||||
positions[index * 3 + 2] - origin.z,
|
||||
);
|
||||
scratchQuaternion.set(
|
||||
orientations[index * 4],
|
||||
orientations[index * 4 + 1],
|
||||
orientations[index * 4 + 2],
|
||||
orientations[index * 4 + 3],
|
||||
);
|
||||
scratchScale.setScalar(scale);
|
||||
for (const { mesh, local } of parts) {
|
||||
scratchMatrix
|
||||
.compose(scratchTranslation, scratchQuaternion, scratchScale)
|
||||
.multiply(local);
|
||||
mesh.setMatrixAt(index, scratchMatrix);
|
||||
}
|
||||
for (const attribute of colorAttributes)
|
||||
attribute.array.set(
|
||||
colors.subarray(index * 4, index * 4 + 4),
|
||||
index * 4,
|
||||
);
|
||||
}
|
||||
for (const { mesh } of parts) {
|
||||
mesh.count = store.count;
|
||||
mesh.instanceMatrix.needsUpdate = true;
|
||||
}
|
||||
for (const attribute of colorAttributes) attribute.needsUpdate = true;
|
||||
};
|
||||
|
||||
const group = { meshes: [], ready: null };
|
||||
group.ready = load(model.url).then((gltf) => {
|
||||
if (disposed) return;
|
||||
const root = gltf.scene;
|
||||
root.updateMatrixWorld(true);
|
||||
const sphere = new Box3()
|
||||
.setFromObject(root)
|
||||
.getBoundingSphere(new Sphere());
|
||||
radius = Math.max(sphere.radius, 1e-3);
|
||||
root.traverse((child) => {
|
||||
if (!child.isMesh) return;
|
||||
let material = child.material;
|
||||
if (model.unlit)
|
||||
material = new MeshBasicMaterial({
|
||||
map: material.map ?? null,
|
||||
color: material.color,
|
||||
});
|
||||
else material = material.clone();
|
||||
blendInstanceColor(material, uniforms);
|
||||
const geometry = child.geometry.clone();
|
||||
const color = new InstancedBufferAttribute(
|
||||
new Float32Array(capacity * 4).fill(1),
|
||||
4,
|
||||
);
|
||||
color.setUsage(DynamicDrawUsage);
|
||||
geometry.setAttribute('gevColor', color);
|
||||
colorAttributes.push(color);
|
||||
const mesh = new InstancedMesh(geometry, material, capacity);
|
||||
mesh.instanceMatrix.setUsage(DynamicDrawUsage);
|
||||
mesh.frustumCulled = false;
|
||||
mesh.renderOrder = options.order;
|
||||
mesh.count = 0;
|
||||
parts.push({ mesh, local: child.matrixWorld.clone() });
|
||||
group.meshes.push(mesh);
|
||||
});
|
||||
loaded = true;
|
||||
if (origin)
|
||||
for (const { mesh } of parts)
|
||||
mesh.position.set(origin.x, origin.y, origin.z);
|
||||
write(0, store.count);
|
||||
onLoad(group.meshes);
|
||||
});
|
||||
|
||||
const placeAt = (next) => {
|
||||
origin = { x: next.x, y: next.y, z: next.z };
|
||||
for (const { mesh } of parts) {
|
||||
mesh.position.set(origin.x, origin.y, origin.z);
|
||||
mesh.updateMatrix();
|
||||
mesh.updateMatrixWorld(true);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
group,
|
||||
uniforms,
|
||||
origin: () => origin,
|
||||
commit(range) {
|
||||
if (!origin && store.count > 0)
|
||||
placeAt({
|
||||
x: store.positions[0],
|
||||
y: store.positions[1],
|
||||
z: store.positions[2],
|
||||
});
|
||||
if (range) write(range.from, Math.min(range.to, store.count));
|
||||
for (const { mesh } of parts) mesh.count = store.count;
|
||||
},
|
||||
/** Each drawn frame: pixel limits need every instance rewritten. */
|
||||
update({ cameraPosition: camera, cameraHeight, fovDeg, viewportHeightPx }) {
|
||||
footprint = footprintPerDepth(fovDeg, viewportHeightPx);
|
||||
cameraPosition = camera;
|
||||
if (!origin || store.count === 0) return false;
|
||||
const next = originFor(camera, origin, cameraHeight);
|
||||
if (next !== origin) placeAt(next);
|
||||
write(0, store.count);
|
||||
return true;
|
||||
},
|
||||
dispose() {
|
||||
disposed = true;
|
||||
for (const { mesh } of parts) {
|
||||
mesh.geometry.dispose();
|
||||
mesh.material.dispose();
|
||||
mesh.dispose?.();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
BoxGeometry,
|
||||
Group,
|
||||
Matrix4,
|
||||
Mesh,
|
||||
MeshStandardMaterial,
|
||||
Vector3,
|
||||
} from 'three';
|
||||
import { createMoverStore, normalizeMoverSetOptions } from '../../movers.js';
|
||||
import { createModelMover } from './modelMover.js';
|
||||
|
||||
const options = normalizeMoverSetOptions({
|
||||
id: 'm',
|
||||
kind: 'model',
|
||||
capacity: 2,
|
||||
model: {
|
||||
url: '/models/box.glb',
|
||||
minimumPixelSize: 40,
|
||||
colorBlend: { mode: 'mix', amount: 0.3 },
|
||||
},
|
||||
});
|
||||
|
||||
function fakeGltf() {
|
||||
const scene = new Group();
|
||||
const box = new Mesh(new BoxGeometry(2, 2, 2), new MeshStandardMaterial());
|
||||
box.position.set(0, 1, 0);
|
||||
scene.add(box);
|
||||
return { scene };
|
||||
}
|
||||
|
||||
test('instances share the model meshes, placed from the origin', async () => {
|
||||
const store = createMoverStore(options);
|
||||
const mover = createModelMover(options, store, {
|
||||
load: async () => fakeGltf(),
|
||||
});
|
||||
store.set(0, { position: { x: 6_378_137, y: 0, z: 0 } });
|
||||
store.set(1, {
|
||||
position: { x: 6_378_147, y: 0, z: 0 },
|
||||
orientation: { x: 0, y: 0, z: Math.SQRT1_2, w: Math.SQRT1_2 },
|
||||
color: [1, 0, 0, 1],
|
||||
});
|
||||
store.setCount(2);
|
||||
mover.commit(store.dirty());
|
||||
await mover.group.ready;
|
||||
const [mesh] = mover.group.meshes;
|
||||
assert.equal(mesh.count, 2);
|
||||
assert.equal(mesh.position.x, 6_378_137);
|
||||
assert.equal(mover.uniforms.uGevBlend.value, 0.3);
|
||||
const matrix = new Matrix4();
|
||||
mesh.getMatrixAt(1, matrix);
|
||||
const translation = new Vector3().setFromMatrixPosition(matrix);
|
||||
// Offset 10 m east of the origin plus the box's local +1 y turned 90° about z.
|
||||
assert.ok(Math.abs(translation.x - 9) < 1e-9, translation.x);
|
||||
assert.ok(Math.abs(translation.y) < 1e-9);
|
||||
const color = mesh.geometry.getAttribute('gevColor');
|
||||
assert.deepEqual([...color.array.subarray(4, 8)], [1, 0, 0, 1]);
|
||||
});
|
||||
|
||||
test('a far model keeps its minimum pixel size', async () => {
|
||||
const store = createMoverStore(options);
|
||||
const mover = createModelMover(options, store, {
|
||||
load: async () => fakeGltf(),
|
||||
});
|
||||
store.set(0, { position: { x: 6_378_137, y: 0, z: 0 } });
|
||||
store.setCount(1);
|
||||
mover.commit(store.dirty());
|
||||
await mover.group.ready;
|
||||
mover.update({
|
||||
cameraPosition: { x: 6_378_137 + 100_000, y: 0, z: 0 },
|
||||
cameraHeight: 100_000,
|
||||
fovDeg: 60,
|
||||
viewportHeightPx: 800,
|
||||
});
|
||||
const matrix = new Matrix4();
|
||||
mover.group.meshes[0].getMatrixAt(0, matrix);
|
||||
const scale = new Vector3().setFromMatrixScale(matrix).x;
|
||||
// Box radius √3; 40 px at 100 km with a 60° fov over 800 px.
|
||||
const footprint = (2 * Math.tan(Math.PI / 6)) / 800;
|
||||
const expected = (40 * footprint * 100_000) / (2 * Math.sqrt(3));
|
||||
assert.ok(
|
||||
Math.abs(scale - expected) / expected < 1e-6,
|
||||
`${scale} vs ${expected}`,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,280 @@
|
||||
// The three side of a Navara sprite or point set: one InstancedMesh of a
|
||||
// unit quad, turned to face the screen and sized in CSS pixels in the
|
||||
// vertex shader (the size comes from uniforms, not the projection, so the
|
||||
// pick pass draws the same footprint), rotated by the instance's screen
|
||||
// angle, textured from the atlas cell (sprites) or drawn as a disc with an
|
||||
// outline (points), coloured per instance. Instance data lives in
|
||||
// InstancedBufferAttributes written on commit; hidden instances get scale 0.
|
||||
|
||||
import {
|
||||
CanvasTexture,
|
||||
DoubleSide,
|
||||
DynamicDrawUsage,
|
||||
InstancedBufferAttribute,
|
||||
InstancedMesh,
|
||||
MeshBasicMaterial,
|
||||
PlaneGeometry,
|
||||
SRGBColorSpace,
|
||||
Texture,
|
||||
} from 'three';
|
||||
import {
|
||||
atlasUvRects,
|
||||
footprintPerDepth,
|
||||
originFor,
|
||||
packInstances,
|
||||
} from './pack.js';
|
||||
|
||||
const VERTEX_HEAD = /* glsl */ `
|
||||
attribute vec4 gevStyle;
|
||||
attribute vec4 gevColor;
|
||||
attribute vec4 gevUv;
|
||||
uniform float uGevSizePx;
|
||||
uniform float uGevFootprint;
|
||||
uniform vec4 uGevScaleByDistance;
|
||||
uniform float uGevHasScaleByDistance;
|
||||
uniform float uGevDisableWithinM;
|
||||
uniform float uGevOutlinePx;
|
||||
varying vec4 vGevColor;
|
||||
varying vec2 vGevLocal;
|
||||
varying float vGevOutline;
|
||||
`;
|
||||
|
||||
const VERTEX_PROJECT = /* glsl */ `
|
||||
vec4 mvCenter = modelViewMatrix * instanceMatrix * vec4(0.0, 0.0, 0.0, 1.0);
|
||||
float gevScale = gevStyle.y;
|
||||
float gevDistance = length(mvCenter.xyz);
|
||||
if (uGevHasScaleByDistance > 0.5) {
|
||||
float t = clamp(
|
||||
(gevDistance - uGevScaleByDistance.x) /
|
||||
max(uGevScaleByDistance.z - uGevScaleByDistance.x, 1e-6),
|
||||
0.0,
|
||||
1.0
|
||||
);
|
||||
gevScale *= mix(uGevScaleByDistance.y, uGevScaleByDistance.w, t);
|
||||
}
|
||||
float gevSizePx = uGevSizePx * gevScale;
|
||||
float gevCos = cos(gevStyle.x);
|
||||
float gevSin = sin(gevStyle.x);
|
||||
vec2 gevCorner = position.xy;
|
||||
vec2 gevTurned = vec2(
|
||||
gevCorner.x * gevCos - gevCorner.y * gevSin,
|
||||
gevCorner.x * gevSin + gevCorner.y * gevCos
|
||||
);
|
||||
vec4 mvPosition = mvCenter;
|
||||
mvPosition.xy += gevTurned * gevSizePx * uGevFootprint * max(-mvCenter.z, 0.0);
|
||||
gl_Position = projectionMatrix * mvPosition;
|
||||
vGevColor = gevColor;
|
||||
vGevLocal = gevCorner;
|
||||
vGevOutline = uGevOutlinePx / max(gevSizePx, 1e-3);
|
||||
`;
|
||||
|
||||
const VERTEX_UV = /* glsl */ `
|
||||
#include <uv_vertex>
|
||||
#ifdef USE_MAP
|
||||
vMapUv = mix(gevUv.xy, gevUv.zw, uv);
|
||||
#endif
|
||||
`;
|
||||
|
||||
const VERTEX_DEPTH = /* glsl */ `
|
||||
#include <logdepthbuf_vertex>
|
||||
#ifdef USE_LOGARITHMIC_DEPTH_BUFFER
|
||||
if (gevDistance < uGevDisableWithinM) vFragDepth = 1.0;
|
||||
#endif
|
||||
`;
|
||||
|
||||
const FRAGMENT_HEAD = /* glsl */ `
|
||||
varying vec4 vGevColor;
|
||||
varying vec2 vGevLocal;
|
||||
varying float vGevOutline;
|
||||
`;
|
||||
|
||||
const fragmentColor = (point) =>
|
||||
point
|
||||
? /* glsl */ `
|
||||
#include <color_fragment>
|
||||
float gevRadius = length(vGevLocal) * 2.0;
|
||||
if (gevRadius > 1.0) discard;
|
||||
diffuseColor *= vGevColor;
|
||||
if (gevRadius > 1.0 - vGevOutline) diffuseColor.rgb = vec3(0.0);
|
||||
`
|
||||
: /* glsl */ `
|
||||
#include <color_fragment>
|
||||
diffuseColor *= vGevColor;
|
||||
`;
|
||||
|
||||
/** Patches three's MeshBasicMaterial shaders into the screen-space quad. */
|
||||
export function patchMoverShader(shader, uniforms, { point = false } = {}) {
|
||||
Object.assign(shader.uniforms, uniforms);
|
||||
const replace = (source, from, to) => {
|
||||
if (!source.includes(from))
|
||||
throw new Error(`Mover shader: three has no ${from}`);
|
||||
return source.replace(from, to);
|
||||
};
|
||||
let vertex = replace(
|
||||
shader.vertexShader,
|
||||
'void main() {',
|
||||
`${VERTEX_HEAD}\nvoid main() {`,
|
||||
);
|
||||
vertex = replace(vertex, '#include <project_vertex>', VERTEX_PROJECT);
|
||||
vertex = replace(vertex, '#include <uv_vertex>', VERTEX_UV);
|
||||
vertex = replace(vertex, '#include <logdepthbuf_vertex>', VERTEX_DEPTH);
|
||||
let fragment = replace(
|
||||
shader.fragmentShader,
|
||||
'void main() {',
|
||||
`${FRAGMENT_HEAD}\nvoid main() {`,
|
||||
);
|
||||
fragment = replace(
|
||||
fragment,
|
||||
'#include <color_fragment>',
|
||||
fragmentColor(point),
|
||||
);
|
||||
shader.vertexShader = vertex;
|
||||
shader.fragmentShader = fragment;
|
||||
return shader;
|
||||
}
|
||||
|
||||
/** The atlas as a three texture (a canvas at once, a URL once loaded). */
|
||||
function atlasTexture(atlas, onLoad) {
|
||||
if (atlas.canvas) {
|
||||
const texture = new CanvasTexture(atlas.canvas);
|
||||
texture.colorSpace = SRGBColorSpace;
|
||||
return texture;
|
||||
}
|
||||
const texture = new Texture();
|
||||
texture.colorSpace = SRGBColorSpace;
|
||||
const image = new Image();
|
||||
image.crossOrigin = 'anonymous';
|
||||
image.onload = () => {
|
||||
texture.image = image;
|
||||
texture.needsUpdate = true;
|
||||
onLoad();
|
||||
};
|
||||
image.src = atlas.url;
|
||||
return texture;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ReturnType<import('../../movers.js').normalizeMoverSetOptions>} options
|
||||
* @param {ReturnType<import('../../movers.js').createMoverStore>} store
|
||||
* @param {{ onTextureLoad?: () => void }} [hooks]
|
||||
*/
|
||||
export function createMoverMesh(
|
||||
options,
|
||||
store,
|
||||
{ onTextureLoad = () => {} } = {},
|
||||
) {
|
||||
const { capacity, kind, depthTest } = options;
|
||||
const point = kind === 'point';
|
||||
const style = point ? options.point : options.sprite;
|
||||
const geometry = new PlaneGeometry(1, 1);
|
||||
const attribute = (name, size) => {
|
||||
const value = new InstancedBufferAttribute(
|
||||
new Float32Array(capacity * size),
|
||||
size,
|
||||
);
|
||||
value.setUsage(DynamicDrawUsage);
|
||||
geometry.setAttribute(name, value);
|
||||
return value;
|
||||
};
|
||||
const styleAttribute = attribute('gevStyle', 4);
|
||||
const colorAttribute = attribute('gevColor', 4);
|
||||
const uvAttribute = attribute('gevUv', 4);
|
||||
const uvRects = point
|
||||
? null
|
||||
: atlasUvRects(options.sprite.atlas.cells, options.cellKeys);
|
||||
const sbd = style.scaleByDistance;
|
||||
const uniforms = {
|
||||
uGevSizePx: { value: style.sizePx },
|
||||
uGevFootprint: { value: 0 },
|
||||
uGevScaleByDistance: { value: sbd ? [...sbd] : [0, 1, 1, 1] },
|
||||
uGevHasScaleByDistance: { value: sbd ? 1 : 0 },
|
||||
uGevDisableWithinM: {
|
||||
value: typeof depthTest === 'object' ? depthTest.disableWithinM : -1,
|
||||
},
|
||||
uGevOutlinePx: { value: point ? options.point.outlinePx : 0 },
|
||||
};
|
||||
const material = new MeshBasicMaterial({
|
||||
map: point ? null : atlasTexture(options.sprite.atlas, onTextureLoad),
|
||||
transparent: true,
|
||||
alphaTest: 0.02,
|
||||
depthTest: depthTest !== 'always',
|
||||
depthWrite: false,
|
||||
side: DoubleSide,
|
||||
});
|
||||
material.onBeforeCompile = (shader) =>
|
||||
patchMoverShader(shader, uniforms, { point });
|
||||
material.customProgramCacheKey = () => `gev-mover-${kind}`;
|
||||
const mesh = new InstancedMesh(geometry, material, capacity);
|
||||
mesh.instanceMatrix.setUsage(DynamicDrawUsage);
|
||||
mesh.frustumCulled = false;
|
||||
mesh.renderOrder = options.order;
|
||||
mesh.count = 0;
|
||||
let origin = null;
|
||||
const out = {
|
||||
matrices: mesh.instanceMatrix.array,
|
||||
style: styleAttribute.array,
|
||||
colors: colorAttribute.array,
|
||||
uvs: uvAttribute.array,
|
||||
};
|
||||
const upload = (from, to) => {
|
||||
packInstances(store, from, to, origin, uvRects, out);
|
||||
for (const [value, size] of [
|
||||
[mesh.instanceMatrix, 16],
|
||||
[styleAttribute, 4],
|
||||
[colorAttribute, 4],
|
||||
[uvAttribute, 4],
|
||||
]) {
|
||||
value.clearUpdateRanges();
|
||||
value.addUpdateRange(from * size, (to - from) * size);
|
||||
value.needsUpdate = true;
|
||||
}
|
||||
};
|
||||
const placeAt = (next) => {
|
||||
origin = { x: next.x, y: next.y, z: next.z };
|
||||
mesh.position.set(origin.x, origin.y, origin.z);
|
||||
mesh.updateMatrix();
|
||||
mesh.updateMatrixWorld(true);
|
||||
};
|
||||
return {
|
||||
mesh,
|
||||
uniforms,
|
||||
origin: () => origin,
|
||||
/** Writes the changed instances; the origin starts at the first one. */
|
||||
commit(range) {
|
||||
if (!origin && store.count > 0)
|
||||
placeAt({
|
||||
x: store.positions[0],
|
||||
y: store.positions[1],
|
||||
z: store.positions[2],
|
||||
});
|
||||
mesh.count = store.count;
|
||||
if (range && origin) {
|
||||
const to = Math.min(range.to, store.count);
|
||||
if (to > range.from) upload(range.from, to);
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Once per drawn frame: the pixel footprint from the camera, and the
|
||||
* origin moved to the camera when it has gone too far (a full rewrite).
|
||||
* Returns true when it rewrote the instances.
|
||||
*/
|
||||
update({ cameraPosition, cameraHeight, fovDeg, viewportHeightPx }) {
|
||||
uniforms.uGevFootprint.value = footprintPerDepth(
|
||||
fovDeg,
|
||||
viewportHeightPx,
|
||||
);
|
||||
if (!origin || store.count === 0) return false;
|
||||
const next = originFor(cameraPosition, origin, cameraHeight);
|
||||
if (next === origin) return false;
|
||||
placeAt(next);
|
||||
upload(0, store.count);
|
||||
return true;
|
||||
},
|
||||
dispose() {
|
||||
geometry.dispose();
|
||||
material.map?.dispose();
|
||||
material.dispose();
|
||||
mesh.dispose?.();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { ShaderLib, UniformsUtils } from 'three';
|
||||
import { createMoverStore, normalizeMoverSetOptions } from '../../movers.js';
|
||||
import { createMoverMesh, patchMoverShader } from './moverMesh.js';
|
||||
|
||||
const spriteOptions = normalizeMoverSetOptions({
|
||||
id: 'flights',
|
||||
kind: 'sprite',
|
||||
capacity: 4,
|
||||
order: 3,
|
||||
depthTest: { disableWithinM: 2000 },
|
||||
sprite: {
|
||||
atlas: { canvas: { width: 8, height: 8 }, cells: { a: [0, 0, 1, 1] } },
|
||||
sizePx: 24,
|
||||
scaleByDistance: [1000, 1, 100000, 0.5],
|
||||
},
|
||||
});
|
||||
|
||||
const basicShader = () => ({
|
||||
uniforms: UniformsUtils.clone(ShaderLib.basic.uniforms),
|
||||
vertexShader: ShaderLib.basic.vertexShader,
|
||||
fragmentShader: ShaderLib.basic.fragmentShader,
|
||||
});
|
||||
|
||||
test('the shader patch sizes the quad in pixels and colours it per instance', () => {
|
||||
const shader = patchMoverShader(basicShader(), { uGevSizePx: { value: 9 } });
|
||||
assert.equal(shader.uniforms.uGevSizePx.value, 9);
|
||||
assert.match(shader.vertexShader, /attribute vec4 gevStyle;/);
|
||||
assert.match(
|
||||
shader.vertexShader,
|
||||
/uGevFootprint \* max\(-mvCenter\.z, 0\.0\)/,
|
||||
);
|
||||
assert.match(shader.vertexShader, /vMapUv = mix\(gevUv\.xy, gevUv\.zw, uv\)/);
|
||||
assert.match(shader.vertexShader, /vFragDepth = 1\.0;/);
|
||||
assert.doesNotMatch(shader.vertexShader, /#include <project_vertex>/);
|
||||
assert.match(shader.fragmentShader, /diffuseColor \*= vGevColor;/);
|
||||
assert.doesNotMatch(shader.fragmentShader, /discard/);
|
||||
const point = patchMoverShader(basicShader(), {}, { point: true });
|
||||
assert.match(point.fragmentShader, /if \(gevRadius > 1\.0\) discard;/);
|
||||
});
|
||||
|
||||
test('a sprite mesh uploads committed instances relative to its origin', () => {
|
||||
const store = createMoverStore(spriteOptions);
|
||||
const mover = createMoverMesh(spriteOptions, store);
|
||||
const { mesh, uniforms } = mover;
|
||||
assert.equal(mesh.renderOrder, 3);
|
||||
assert.equal(mesh.count, 0);
|
||||
assert.equal(mesh.material.depthTest, true);
|
||||
assert.equal(uniforms.uGevDisableWithinM.value, 2000);
|
||||
assert.deepEqual(uniforms.uGevScaleByDistance.value, [1000, 1, 100000, 0.5]);
|
||||
store.set(0, { position: { x: 6_378_137, y: 10, z: 20 } });
|
||||
store.set(1, {
|
||||
position: { x: 6_378_147, y: 10, z: 20 },
|
||||
color: [1, 0, 0, 1],
|
||||
});
|
||||
store.setCount(2);
|
||||
mover.commit(store.dirty());
|
||||
assert.equal(mesh.count, 2);
|
||||
assert.deepEqual(mover.origin(), { x: 6_378_137, y: 10, z: 20 });
|
||||
assert.equal(mesh.position.x, 6_378_137);
|
||||
assert.deepEqual([...mesh.instanceMatrix.array.subarray(28, 31)], [10, 0, 0]);
|
||||
const color = mesh.geometry.getAttribute('gevColor');
|
||||
assert.deepEqual([...color.array.subarray(4, 8)], [1, 0, 0, 1]);
|
||||
assert.ok(color.version > 0);
|
||||
});
|
||||
|
||||
test('update sets the pixel footprint and moves the origin to a far camera', () => {
|
||||
const store = createMoverStore(spriteOptions);
|
||||
const mover = createMoverMesh(spriteOptions, store);
|
||||
store.set(0, { position: { x: 6_378_137, y: 0, z: 0 } });
|
||||
store.setCount(1);
|
||||
mover.commit(store.dirty());
|
||||
const camera = {
|
||||
cameraPosition: { x: 6_378_137 + 300, y: 0, z: 0 },
|
||||
cameraHeight: 300,
|
||||
fovDeg: 90,
|
||||
viewportHeightPx: 800,
|
||||
};
|
||||
assert.equal(mover.update(camera), false, 'close: the origin stays');
|
||||
assert.ok(Math.abs(mover.uniforms.uGevFootprint.value - 2 / 800) < 1e-12);
|
||||
camera.cameraPosition = { x: 6_378_137 + 5_000, y: 0, z: 0 };
|
||||
assert.equal(mover.update(camera), true);
|
||||
assert.equal(mover.origin().x, 6_378_137 + 5_000);
|
||||
assert.equal(mesh(mover).instanceMatrix.array[12], -5_000);
|
||||
});
|
||||
|
||||
const mesh = (mover) => mover.mesh;
|
||||
|
||||
test('points have no atlas and draw a disc', () => {
|
||||
const options = normalizeMoverSetOptions({
|
||||
id: 'p',
|
||||
kind: 'point',
|
||||
capacity: 1,
|
||||
depthTest: 'always',
|
||||
point: { sizePx: 6, outlinePx: 1 },
|
||||
});
|
||||
const mover = createMoverMesh(options, createMoverStore(options));
|
||||
assert.equal(mover.mesh.material.map, null);
|
||||
assert.equal(mover.mesh.material.depthTest, false);
|
||||
assert.equal(mover.uniforms.uGevOutlinePx.value, 1);
|
||||
mover.dispose();
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
// Pure parts of Navara movers: what the instanced meshes upload. Offsets are
|
||||
// relative to an origin near the camera (the mesh sits at the origin, which
|
||||
// three keeps in doubles), so float32 instance data keeps centimetres where
|
||||
// it matters; the origin follows the camera past a distance that grows with
|
||||
// height (no jitter close in, few rewrites from space).
|
||||
|
||||
const RADIANS = Math.PI / 180;
|
||||
|
||||
/** Metres one CSS pixel spans per metre of view depth. */
|
||||
export function footprintPerDepth(verticalFovDeg, viewportHeightPx) {
|
||||
if (!(viewportHeightPx > 0)) return 0;
|
||||
return (2 * Math.tan((verticalFovDeg * RADIANS) / 2)) / viewportHeightPx;
|
||||
}
|
||||
|
||||
/** Atlas cells [u0, v0, u1, v1] (v down from the image top) as three uvs (v up). */
|
||||
export function atlasUvRects(cells, keys) {
|
||||
const rects = new Float32Array(keys.length * 4);
|
||||
keys.forEach((key, index) => {
|
||||
const [u0, v0, u1, v1] = cells[key];
|
||||
rects.set([u0, 1 - v1, u1, 1 - v0], index * 4);
|
||||
});
|
||||
return rects;
|
||||
}
|
||||
|
||||
/** The camera distance from the origin past which the origin moves. */
|
||||
export const recentreDistance = (cameraHeight) =>
|
||||
Math.max(1_000, 0.1 * Math.abs(cameraHeight));
|
||||
|
||||
/**
|
||||
* The origin to draw from: the current one while the camera stays within
|
||||
* recentreDistance(height) of it, else the camera position.
|
||||
*/
|
||||
export function originFor(cameraPosition, origin, cameraHeight) {
|
||||
if (!origin) return cameraPosition;
|
||||
const dx = cameraPosition.x - origin.x;
|
||||
const dy = cameraPosition.y - origin.y;
|
||||
const dz = cameraPosition.z - origin.z;
|
||||
const limit = recentreDistance(cameraHeight);
|
||||
return dx * dx + dy * dy + dz * dz > limit * limit ? cameraPosition : origin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes instances [from, to) of a mover store into the upload arrays:
|
||||
* `matrices` (identity with the offset from `origin` as translation),
|
||||
* `style` (rotation, scale or 0 when hidden, two spare lanes), `colors`
|
||||
* (rgba) and `uvs` (the instance's atlas rect, from `uvRects`).
|
||||
*/
|
||||
export function packInstances(store, from, to, origin, uvRects, out) {
|
||||
const { positions, rotations, scales, shows, colors, cells } = store;
|
||||
const { matrices, style, colors: colorOut, uvs } = out;
|
||||
for (let index = from; index < to; index++) {
|
||||
const m = index * 16;
|
||||
matrices[m] = 1;
|
||||
matrices[m + 1] = 0;
|
||||
matrices[m + 2] = 0;
|
||||
matrices[m + 3] = 0;
|
||||
matrices[m + 4] = 0;
|
||||
matrices[m + 5] = 1;
|
||||
matrices[m + 6] = 0;
|
||||
matrices[m + 7] = 0;
|
||||
matrices[m + 8] = 0;
|
||||
matrices[m + 9] = 0;
|
||||
matrices[m + 10] = 1;
|
||||
matrices[m + 11] = 0;
|
||||
matrices[m + 12] = positions[index * 3] - origin.x;
|
||||
matrices[m + 13] = positions[index * 3 + 1] - origin.y;
|
||||
matrices[m + 14] = positions[index * 3 + 2] - origin.z;
|
||||
matrices[m + 15] = 1;
|
||||
const s = index * 4;
|
||||
style[s] = rotations[index];
|
||||
style[s + 1] = shows[index] === 1 ? scales[index] : 0;
|
||||
style[s + 2] = 0;
|
||||
style[s + 3] = 0;
|
||||
colorOut[s] = colors[s];
|
||||
colorOut[s + 1] = colors[s + 1];
|
||||
colorOut[s + 2] = colors[s + 2];
|
||||
colorOut[s + 3] = colors[s + 3];
|
||||
if (uvs && uvRects) {
|
||||
const r = cells[index] * 4;
|
||||
uvs[s] = uvRects[r];
|
||||
uvs[s + 1] = uvRects[r + 1];
|
||||
uvs[s + 2] = uvRects[r + 2];
|
||||
uvs[s + 3] = uvRects[r + 3];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createMoverStore, normalizeMoverSetOptions } from '../../movers.js';
|
||||
import {
|
||||
atlasUvRects,
|
||||
footprintPerDepth,
|
||||
originFor,
|
||||
packInstances,
|
||||
} from './pack.js';
|
||||
|
||||
test('the footprint of a CSS pixel per metre of depth follows the vertical fov', () => {
|
||||
// 90° fov over 800 px: 2·tan(45°)/800.
|
||||
assert.ok(Math.abs(footprintPerDepth(90, 800) - 2 / 800) < 1e-12);
|
||||
assert.equal(footprintPerDepth(60, 0), 0);
|
||||
});
|
||||
|
||||
test('atlas cells become three uv rects (v up from the image bottom)', () => {
|
||||
const rects = atlasUvRects({ a: [0, 0, 0.5, 0.25], b: [0.5, 0.5, 1, 1] }, [
|
||||
'a',
|
||||
'b',
|
||||
]);
|
||||
assert.deepEqual([...rects], [0, 0.75, 0.5, 1, 0.5, 0, 1, 0.5]);
|
||||
});
|
||||
|
||||
test('the origin follows the camera only past a distance that grows with height', () => {
|
||||
const origin = { x: 6_378_137, y: 0, z: 0 };
|
||||
const near = { x: 6_378_137 + 500, y: 0, z: 0 };
|
||||
assert.equal(originFor(near, origin, 150), origin, 'within 1 km at 150 m');
|
||||
const far = { x: 6_378_137 + 2_000, y: 0, z: 0 };
|
||||
assert.deepEqual(originFor(far, origin, 150), far);
|
||||
assert.equal(originFor(far, origin, 1e6), origin, 'within 100 km at 1000 km');
|
||||
assert.deepEqual(originFor(far, null, 1e6), far, 'no origin yet');
|
||||
});
|
||||
|
||||
test('instances pack as offsets from the origin, style, colour and uv', () => {
|
||||
const options = normalizeMoverSetOptions({
|
||||
id: 's',
|
||||
kind: 'sprite',
|
||||
capacity: 3,
|
||||
sprite: {
|
||||
atlas: { canvas: {}, cells: { a: [0, 0, 1, 1], b: [0, 0, 0.5, 0.5] } },
|
||||
sizePx: 10,
|
||||
},
|
||||
});
|
||||
const store = createMoverStore(options);
|
||||
store.set(0, {
|
||||
position: { x: 1000.5, y: 2000, z: 3000 },
|
||||
rotation: 1,
|
||||
scale: 2,
|
||||
});
|
||||
store.set(1, {
|
||||
position: { x: 1001, y: 2001, z: 3001 },
|
||||
show: false,
|
||||
cell: 'b',
|
||||
color: [1, 0, 0, 0.5],
|
||||
});
|
||||
store.setCount(2);
|
||||
const out = {
|
||||
matrices: new Float32Array(48),
|
||||
style: new Float32Array(12),
|
||||
colors: new Float32Array(12),
|
||||
uvs: new Float32Array(12),
|
||||
};
|
||||
const uvRects = atlasUvRects(options.sprite.atlas.cells, options.cellKeys);
|
||||
packInstances(store, 0, 2, { x: 1000, y: 2000, z: 3000 }, uvRects, out);
|
||||
// Identity matrix with the offset as translation.
|
||||
assert.deepEqual(
|
||||
[...out.matrices.subarray(0, 16)],
|
||||
[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0.5, 0, 0, 1],
|
||||
);
|
||||
assert.deepEqual([...out.matrices.subarray(28, 31)], [1, 1, 1]);
|
||||
// rotation, scale (0 when hidden), and two spare lanes.
|
||||
assert.deepEqual([...out.style.subarray(0, 4)], [1, 2, 0, 0]);
|
||||
assert.deepEqual([...out.style.subarray(4, 8)], [0, 0, 0, 0]);
|
||||
assert.deepEqual([...out.colors.subarray(4, 8)], [1, 0, 0, 0.5]);
|
||||
assert.deepEqual([...out.uvs.subarray(0, 4)], [0, 0, 1, 1]);
|
||||
assert.deepEqual([...out.uvs.subarray(4, 8)], [0, 0.5, 0.5, 1]);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
// Navara picks report a batchId (PickableInstancedMeshWrapper, one per
|
||||
// instance); this resolves it to the mover set, the instance and the pickId
|
||||
// the layer gave it. Pure: wrappers are anything with a batchIds array.
|
||||
|
||||
export function createPickIndex() {
|
||||
const entries = new Map();
|
||||
return {
|
||||
/** `wrapper.batchIds[i]` is instance i's batch id. */
|
||||
add(set, wrapper, pickIdOf) {
|
||||
const list = entries.get(set) ?? [];
|
||||
list.push({ wrapper, pickIdOf });
|
||||
entries.set(set, list);
|
||||
},
|
||||
remove(set) {
|
||||
entries.delete(set);
|
||||
},
|
||||
/** { set, instance, pickId } for a batch id, or null. */
|
||||
resolve(batchId) {
|
||||
for (const [set, list] of entries)
|
||||
for (const { wrapper, pickIdOf } of list) {
|
||||
const instance = wrapper.batchIds.indexOf(batchId);
|
||||
if (instance >= 0)
|
||||
return { set, instance, pickId: pickIdOf(instance) };
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createPickIndex } from './pickIds.js';
|
||||
|
||||
test('a batch id resolves to its set, instance and pick id', () => {
|
||||
const index = createPickIndex();
|
||||
const pickIds = ['a', 'b', 'c'];
|
||||
index.add('flights', { batchIds: [11, 12, 13] }, (i) => pickIds[i]);
|
||||
index.add('sats', { batchIds: [21] }, () => 99);
|
||||
assert.deepEqual(index.resolve(12), {
|
||||
set: 'flights',
|
||||
instance: 1,
|
||||
pickId: 'b',
|
||||
});
|
||||
assert.deepEqual(index.resolve(21), { set: 'sats', instance: 0, pickId: 99 });
|
||||
assert.equal(index.resolve(5), null);
|
||||
index.remove('flights');
|
||||
assert.equal(index.resolve(12), null);
|
||||
});
|
||||
Reference in new issue
Block a user