mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-18 01:02:23 +00:00
feat(firms): add Navara renderer checkpoint
This commit is contained in:
1 parent
a9b3125a99
commit
5dd05a4a81
33 files changed
+2112
-285
No files matched your search
@@ -2,15 +2,13 @@
|
||||
// Navara post-effect. Native ground colour blends in display space; doing
|
||||
// it explicitly preserves translucent colours and overlap order.
|
||||
import { Effect, EffectAttribute } from 'postprocessing';
|
||||
import { Uniform } from 'three';
|
||||
import {
|
||||
DataTexture,
|
||||
FloatType,
|
||||
RGBAFormat,
|
||||
NearestFilter,
|
||||
Matrix4,
|
||||
Uniform,
|
||||
RGBADepthPacking,
|
||||
} from 'three';
|
||||
createGroundTexture as texture,
|
||||
createGroundStorage as storage,
|
||||
groundSurfaceUniforms,
|
||||
updateGroundSurface,
|
||||
} from '../../shared/render/navaraGroundSurface.js';
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import {
|
||||
DISC_EDGES,
|
||||
@@ -103,19 +101,6 @@ void mainImage(const in vec4 inputColor,const in vec2 uv,out vec4 outputColor) {
|
||||
outputColor=vec4(toLinear(color),inputColor.a);
|
||||
}
|
||||
`;
|
||||
function texture(data, width, height) {
|
||||
const t = new DataTexture(data, width, height, RGBAFormat, FloatType);
|
||||
t.minFilter = NearestFilter;
|
||||
t.magFilter = NearestFilter;
|
||||
t.needsUpdate = true;
|
||||
return t;
|
||||
}
|
||||
function storage(texels) {
|
||||
const width = Math.min(1024, Math.max(1, texels));
|
||||
const height = Math.max(1, Math.ceil(texels / width));
|
||||
const data = new Float32Array(width * height * 4);
|
||||
return { data, width, height, texture: texture(data, width, height) };
|
||||
}
|
||||
function buildState(discs) {
|
||||
const frames = discs.map(discFrame);
|
||||
const edges = storage(discs.length * DISC_EDGES);
|
||||
@@ -225,8 +210,7 @@ function groundEffectClass(EffectDesc, NavaraEffect) {
|
||||
// Keep a separate pass: inputColor is the already tone-mapped frame.
|
||||
attributes: EffectAttribute.CONVOLUTION,
|
||||
uniforms: new Map([
|
||||
['tAllDepth', new Uniform(null)],
|
||||
['tSurfaceDepth', new Uniform(null)],
|
||||
...groundSurfaceUniforms(),
|
||||
['tEdges', new Uniform(null)],
|
||||
['tFrames', new Uniform(null)],
|
||||
['tGrid', new Uniform(null)],
|
||||
@@ -234,8 +218,6 @@ function groundEffectClass(EffectDesc, NavaraEffect) {
|
||||
['uEdgeSize', new Uniform([1, 1])],
|
||||
['uFrameSize', new Uniform([1, 1])],
|
||||
['uCandidateSize', new Uniform([1, 1])],
|
||||
['uInverseProjection', new Uniform(new Matrix4())],
|
||||
['uLogDepthFC', new Uniform(1)],
|
||||
]),
|
||||
});
|
||||
return new NavaraEffect(this.view.camera.raw, this.effect);
|
||||
@@ -245,14 +227,9 @@ function groundEffectClass(EffectDesc, NavaraEffect) {
|
||||
camera = this.view.camera.raw,
|
||||
mrt = this.find('mrt');
|
||||
if (!this.effect || !camera || !state) return;
|
||||
if (mrt?.depthBufferPacking !== RGBADepthPacking)
|
||||
throw new Error(
|
||||
'Earthquake classification requires packed scene depth',
|
||||
);
|
||||
updateGroundSurface(this.effect, camera, this.ctx, mrt);
|
||||
state.update(camera, this.ctx);
|
||||
const u = this.effect.uniforms;
|
||||
u.get('tAllDepth').value = mrt.depthBuffer;
|
||||
u.get('tSurfaceDepth').value = this.ctx.getRenderTarget().depthTexture;
|
||||
u.get('tEdges').value = state.edges.texture;
|
||||
u.get('uEdgeSize').value = [state.edges.width, state.edges.height];
|
||||
u.get('tFrames').value = state.packed.texture;
|
||||
@@ -263,8 +240,6 @@ function groundEffectClass(EffectDesc, NavaraEffect) {
|
||||
state.candidates.width,
|
||||
state.candidates.height,
|
||||
];
|
||||
u.get('uInverseProjection').value.copy(camera.projectionMatrixInverse);
|
||||
u.get('uLogDepthFC').value = 2 / Math.log2(camera.far + 1);
|
||||
}
|
||||
onDestroy() {
|
||||
this.effect?.dispose();
|
||||
|
||||
@@ -78,65 +78,7 @@ export function discFrame(disc) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Camera-relative transforms in JS float64; only nearby metres enter GLSL. */
|
||||
export function viewFrame(frame, matrix, out) {
|
||||
const m = matrix.elements;
|
||||
const transform = (p, offset, translate) => {
|
||||
out[offset] =
|
||||
m[0] * p.x + m[4] * p.y + m[8] * p.z + (translate ? m[12] : 0);
|
||||
out[offset + 1] =
|
||||
m[1] * p.x + m[5] * p.y + m[9] * p.z + (translate ? m[13] : 0);
|
||||
out[offset + 2] =
|
||||
m[2] * p.x + m[6] * p.y + m[10] * p.z + (translate ? m[14] : 0);
|
||||
};
|
||||
transform(frame.center, 0, true);
|
||||
transform(frame.east, 3, false);
|
||||
transform(frame.north, 6, false);
|
||||
transform(frame.up, 9, false);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Conservative clip bounds, including a camera inside/crossing the volume. */
|
||||
export function discClipBounds(frame, view, projection, out) {
|
||||
const p = projection.elements;
|
||||
let x0 = 1,
|
||||
y0 = 1,
|
||||
x1 = -1,
|
||||
y1 = -1,
|
||||
front = 0,
|
||||
behind = 0;
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const x = (i & 1 ? 1 : -1) * frame.radius;
|
||||
const y = (i & 2 ? 1 : -1) * frame.radius;
|
||||
const z = i & 4 ? frame.ceiling : frame.floor;
|
||||
const vx = view[0] + view[3] * x + view[6] * y + view[9] * z;
|
||||
const vy = view[1] + view[4] * x + view[7] * y + view[10] * z;
|
||||
const vz = view[2] + view[5] * x + view[8] * y + view[11] * z;
|
||||
const w = p[3] * vx + p[7] * vy + p[11] * vz + p[15];
|
||||
if (w <= 0) {
|
||||
behind++;
|
||||
continue;
|
||||
}
|
||||
front++;
|
||||
const cx = (p[0] * vx + p[4] * vy + p[8] * vz + p[12]) / w;
|
||||
const cy = (p[1] * vx + p[5] * vy + p[9] * vz + p[13]) / w;
|
||||
x0 = Math.min(x0, cx);
|
||||
y0 = Math.min(y0, cy);
|
||||
x1 = Math.max(x1, cx);
|
||||
y1 = Math.max(y1, cy);
|
||||
}
|
||||
if (front && behind) {
|
||||
x0 = -1;
|
||||
y0 = -1;
|
||||
x1 = 1;
|
||||
y1 = 1;
|
||||
}
|
||||
if (!front || x1 < -1 || y1 < -1 || x0 > 1 || y0 > 1) out.fill(2);
|
||||
else {
|
||||
out[0] = Math.max(-1, x0);
|
||||
out[1] = Math.max(-1, y0);
|
||||
out[2] = Math.min(1, x1);
|
||||
out[3] = Math.min(1, y1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
export {
|
||||
viewFrame,
|
||||
groundClipBounds as discClipBounds,
|
||||
} from '../../shared/render/navaraGroundGeometry.js';
|
||||
@@ -1,69 +1,5 @@
|
||||
// A screen grid of conservative projected volumes. Prefix-sum storage has
|
||||
// no feature/cell cap: overlapping discs retain their source order.
|
||||
export const GRID_COLS = 32;
|
||||
export const GRID_ROWS = 20;
|
||||
export function createDiscGrid(count) {
|
||||
const counts = new Uint32Array(GRID_COLS * GRID_ROWS);
|
||||
const offsets = new Uint32Array(counts.length);
|
||||
const cursor = new Uint32Array(counts.length);
|
||||
const bounds = new Float64Array(count * 4);
|
||||
const ranges = new Int32Array(count * 4);
|
||||
let indices = new Uint32Array(0);
|
||||
const clamp = (value, max) => Math.min(max - 1, Math.max(0, value));
|
||||
return {
|
||||
bounds,
|
||||
counts,
|
||||
offsets,
|
||||
get indices() {
|
||||
return indices;
|
||||
},
|
||||
pack() {
|
||||
counts.fill(0);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const b = i * 4;
|
||||
const valid =
|
||||
bounds[b] <= bounds[b + 2] &&
|
||||
bounds[b + 1] <= bounds[b + 3] &&
|
||||
bounds[b] <= 1 &&
|
||||
bounds[b + 1] <= 1 &&
|
||||
bounds[b + 2] >= -1 &&
|
||||
bounds[b + 3] >= -1;
|
||||
ranges[b] = valid
|
||||
? clamp(Math.floor((bounds[b] * 0.5 + 0.5) * GRID_COLS), GRID_COLS)
|
||||
: -1;
|
||||
ranges[b + 1] = clamp(
|
||||
Math.floor((bounds[b + 1] * 0.5 + 0.5) * GRID_ROWS),
|
||||
GRID_ROWS,
|
||||
);
|
||||
ranges[b + 2] = clamp(
|
||||
Math.floor((bounds[b + 2] * 0.5 + 0.5) * GRID_COLS),
|
||||
GRID_COLS,
|
||||
);
|
||||
ranges[b + 3] = clamp(
|
||||
Math.floor((bounds[b + 3] * 0.5 + 0.5) * GRID_ROWS),
|
||||
GRID_ROWS,
|
||||
);
|
||||
if (!valid) continue;
|
||||
for (let y = ranges[b + 1]; y <= ranges[b + 3]; y++)
|
||||
for (let x = ranges[b]; x <= ranges[b + 2]; x++)
|
||||
counts[y * GRID_COLS + x]++;
|
||||
}
|
||||
let total = 0;
|
||||
for (let i = 0; i < counts.length; i++) {
|
||||
offsets[i] = total;
|
||||
total += counts[i];
|
||||
cursor[i] = offsets[i];
|
||||
}
|
||||
if (indices.length < total)
|
||||
indices = new Uint32Array(Math.max(total, indices.length * 2));
|
||||
for (let i = 0; i < count; i++) {
|
||||
const b = i * 4;
|
||||
if (ranges[b] < 0) continue;
|
||||
for (let y = ranges[b + 1]; y <= ranges[b + 3]; y++)
|
||||
for (let x = ranges[b]; x <= ranges[b + 2]; x++)
|
||||
indices[cursor[y * GRID_COLS + x]++] = i;
|
||||
}
|
||||
return total;
|
||||
},
|
||||
};
|
||||
}
|
||||
export {
|
||||
GRID_COLS,
|
||||
GRID_ROWS,
|
||||
createGroundGrid as createDiscGrid,
|
||||
} from '../../shared/render/navaraGroundGrid.js';
|
||||
@@ -98,6 +98,7 @@ export function createLifecycle({
|
||||
layerState._fires = [];
|
||||
layerState._firesByFrp = [];
|
||||
layerState._cellCacheByGrid.clear();
|
||||
layerState.glowSpriteCache.clear();
|
||||
layerState._count = 0;
|
||||
layerState._cellCount = 0;
|
||||
layerState._lastUpdate = null;
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createFirmsState } from './state.js';
|
||||
import { createLifecycle } from './lifecycle.js';
|
||||
test('destroy releases the owned generated PNG cache even when the layer facade remains referenced', () => {
|
||||
const state = createFirmsState({ services: {}, config: {} });
|
||||
state.glowSpriteCache.set(
|
||||
'red:28',
|
||||
'data:image/png;base64,' + 'x'.repeat(65536),
|
||||
);
|
||||
const noop = () => {};
|
||||
const lifecycle = createLifecycle({
|
||||
layerState: state,
|
||||
services: {
|
||||
picking: { unregisterPickOwner: noop },
|
||||
context: { clearSelectedEntityContextForLayer: noop },
|
||||
},
|
||||
components: {
|
||||
viewport: { removeLodWatcher: noop, removeMoveEndWatcher: noop },
|
||||
selection: { removeClickHandler: noop, clearContextRegistrations: noop },
|
||||
rendering: { removeDetectionCollections: noop },
|
||||
},
|
||||
config: {
|
||||
id: 'firms-cache',
|
||||
overlayHost: { clearSource: noop, setVisible: noop },
|
||||
},
|
||||
});
|
||||
lifecycle.methods.destroy();
|
||||
assert.equal(state.glowSpriteCache.size, 0);
|
||||
lifecycle.methods.destroy();
|
||||
assert.equal(state.glowSpriteCache.size, 0);
|
||||
});
|
||||
@@ -0,0 +1,411 @@
|
||||
// FIRMS terrain/tiles classification and actual engine mover glows.
|
||||
import { Effect, EffectAttribute } from 'postprocessing';
|
||||
import { Matrix4, Uniform } from 'three';
|
||||
import { createEngineLayerView } from '../../shared/render/engineView.js';
|
||||
import { selectionDispatcherFor } from '../../../data/selectionDispatcher.js';
|
||||
import { LOD_LEVELS } from '../policy.js';
|
||||
import { createFirmsSpriteBank } from './navaraSprites.js';
|
||||
import { rectangleFrame } from './navaraGeometry.js';
|
||||
import {
|
||||
viewFrame,
|
||||
groundClipBounds,
|
||||
} from '../../shared/render/navaraGroundGeometry.js';
|
||||
import {
|
||||
createGroundGrid,
|
||||
GRID_COLS,
|
||||
GRID_ROWS,
|
||||
} from '../../shared/render/navaraGroundGrid.js';
|
||||
import {
|
||||
createGroundTexture,
|
||||
createGroundStorage,
|
||||
groundSurfaceUniforms,
|
||||
updateGroundSurface,
|
||||
} from '../../shared/render/navaraGroundSurface.js';
|
||||
const KEY = 'gevFirmsGround';
|
||||
const registeredViews = new WeakSet();
|
||||
const fragmentShader = /* glsl */ `
|
||||
uniform sampler2D tAllDepth;
|
||||
uniform sampler2D tSurfaceDepth;
|
||||
uniform sampler2D tCells;
|
||||
uniform sampler2D tGrid;
|
||||
uniform sampler2D tCandidates;
|
||||
uniform vec2 uCellSize;
|
||||
uniform vec2 uCandidateSize;
|
||||
uniform mat4 uInverseProjection;
|
||||
uniform mat4 uInverseView;
|
||||
uniform float uLogDepthFC;
|
||||
vec4 atSlot(sampler2D image,vec2 size,float slot) {
|
||||
return texture2D(image,(vec2(mod(slot,size.x),floor(slot/size.x))+0.5)/size);
|
||||
}
|
||||
vec3 toDisplay(vec3 c) {
|
||||
return mix(12.92*c,1.055*pow(max(c,vec3(0.0)),vec3(1.0/2.4))-0.055,step(vec3(0.0031308),c));
|
||||
}
|
||||
vec3 toLinear(vec3 c) {
|
||||
return mix(c/12.92,pow(max((c+0.055)/1.055,vec3(0.0)),vec3(2.4)),step(vec3(0.04045),c));
|
||||
}
|
||||
vec3 pixelPlane(float distance,vec3 normal,vec3 dx,vec3 dy) {
|
||||
return vec3(distance,dot(normal,dx),dot(normal,dy));
|
||||
}
|
||||
float rectangleCoverage(vec3 west,vec3 east,vec3 south,vec3 north) {
|
||||
vec3 edges[4];
|
||||
edges[0]=west;edges[1]=east;edges[2]=south;edges[3]=north;
|
||||
float coverage=1.0;
|
||||
int partial=0;
|
||||
for(int i=0;i<4;i++) {
|
||||
float width=abs(edges[i].y)+abs(edges[i].z);
|
||||
coverage=min(coverage,clamp(edges[i].x/max(width,0.001)+0.5,0.0,1.0));
|
||||
if(coverage<=0.0) return 0.0;
|
||||
if(edges[i].x<=width*0.5) partial++;
|
||||
}
|
||||
if(partial<2) return coverage;
|
||||
// Intersect the SAME pixel square with all sides. Minimum soft-edge
|
||||
// coverage creates long miter halos at acute/polar rectangle corners.
|
||||
vec2 polygon[8],clipped[8];
|
||||
polygon[0]=vec2(-0.5,-0.5);polygon[1]=vec2(0.5,-0.5);
|
||||
polygon[2]=vec2(0.5,0.5);polygon[3]=vec2(-0.5,0.5);
|
||||
int count=4;
|
||||
for(int side=0;side<4;side++) {
|
||||
int nextCount=0;
|
||||
vec2 previous=polygon[count-1];
|
||||
float before=edges[side].x+dot(edges[side].yz,previous);
|
||||
for(int i=0;i<8;i++) {
|
||||
if(i>=count) break;
|
||||
vec2 current=polygon[i];
|
||||
float after=edges[side].x+dot(edges[side].yz,current);
|
||||
if((before>0.0&&after<0.0)||(before<0.0&&after>0.0))
|
||||
clipped[nextCount++]=mix(previous,current,before/(before-after));
|
||||
if(after>=0.0) clipped[nextCount++]=current;
|
||||
previous=current;before=after;
|
||||
}
|
||||
count=nextCount;
|
||||
if(count<3) return 0.0;
|
||||
for(int i=0;i<8;i++) { if(i>=count) break;polygon[i]=clipped[i]; }
|
||||
}
|
||||
float area=0.0;
|
||||
vec2 previous=polygon[count-1];
|
||||
for(int i=0;i<8;i++) {
|
||||
if(i>=count) break;
|
||||
area+=previous.x*polygon[i].y-previous.y*polygon[i].x;
|
||||
previous=polygon[i];
|
||||
}
|
||||
return clamp(abs(area)*0.5,0.0,1.0);
|
||||
}
|
||||
void mainImage(const in vec4 inputColor,const in vec2 uv,out vec4 outputColor) {
|
||||
outputColor=inputColor;
|
||||
float depth=unpackRGBAToDepth(texture2D(tAllDepth,uv));
|
||||
float distance=exp2(2.0*depth/uLogDepthFC)-1.0;
|
||||
vec4 ray=uInverseProjection*vec4(uv*2.0-1.0,-1.0,1.0);
|
||||
vec3 point=ray.xyz*(distance/-ray.z);
|
||||
// Evaluate derivatives before divergent candidate branches, as in quakes.
|
||||
vec3 world=(uInverseView*vec4(point,1.0)).xyz;
|
||||
vec3 dx=(uInverseView*vec4(dFdx(point),0.0)).xyz;
|
||||
vec3 dy=(uInverseView*vec4(dFdy(point),0.0)).xyz;
|
||||
// A quad crossing the sky has no surface derivative. Keep exact halfspaces
|
||||
// there; otherwise its far-plane lane spreads cell AA along the globe limb.
|
||||
float onSurface=1.0-step(1.0,depth);
|
||||
float derivativeMask=1.0-step(0.5,abs(dFdx(onSurface))+abs(dFdy(onSurface)));
|
||||
dx*=derivativeMask;
|
||||
dy*=derivativeMask;
|
||||
if(depth>=1.0) return;
|
||||
vec2 tile=clamp(floor(uv*vec2(${GRID_COLS}.0,${GRID_ROWS}.0)),vec2(0.0),vec2(${GRID_COLS - 1}.0,${GRID_ROWS - 1}.0));
|
||||
vec2 range=texture2D(tGrid,(tile+0.5)/vec2(${GRID_COLS}.0,${GRID_ROWS}.0)).xy;
|
||||
if(range.y<0.5) return;
|
||||
float surface=texture2D(tSurfaceDepth,uv).r;
|
||||
if(depth<surface-2e-7) return;
|
||||
float rho=length(world.xy);
|
||||
vec2 radial=world.xy/max(rho,0.001);
|
||||
vec3 color=toDisplay(inputColor.rgb);
|
||||
for(int k=0;k<int(range.y);k++) {
|
||||
float id=atSlot(tCandidates,uCandidateSize,range.x+float(k)).x;
|
||||
vec4 longitude=atSlot(tCells,uCellSize,id*4.0);
|
||||
vec3 south=atSlot(tCells,uCellSize,id*4.0+1.0).xyz;
|
||||
vec3 north=atSlot(tCells,uCellSize,id*4.0+2.0).xyz;
|
||||
vec3 westNormal=vec3(-longitude.x,longitude.y,0.0);
|
||||
vec3 eastNormal=vec3(longitude.z,-longitude.w,0.0);
|
||||
float coverage=rectangleCoverage(
|
||||
pixelPlane(dot(westNormal,world),westNormal,dx,dy),
|
||||
pixelPlane(dot(eastNormal,world),eastNormal,dx,dy),
|
||||
pixelPlane(world.z*south.y-rho*south.x+south.z,vec3(-south.x*radial,south.y),dx,dy),
|
||||
pixelPlane(rho*north.x-world.z*north.y-north.z,vec3(north.x*radial,-north.y),dx,dy));
|
||||
if(coverage<=0.0) continue;
|
||||
vec4 fill=atSlot(tCells,uCellSize,id*4.0+3.0);
|
||||
color=mix(color,fill.rgb,fill.a*coverage);
|
||||
}
|
||||
outputColor=vec4(toLinear(color),inputColor.a);
|
||||
}
|
||||
`;
|
||||
function buildState(cells) {
|
||||
const frames = cells.map(rectangleFrame),
|
||||
packed = createGroundStorage(cells.length * 4);
|
||||
const grid = createGroundGrid(cells.length),
|
||||
gridData = new Float32Array(GRID_COLS * GRID_ROWS * 4);
|
||||
const gridTexture = createGroundTexture(gridData, GRID_COLS, GRID_ROWS);
|
||||
let candidates = createGroundStorage(1);
|
||||
const scratch = new Float64Array(12),
|
||||
bounds = new Float64Array(4);
|
||||
const lastView = new Float64Array(16).fill(NaN),
|
||||
lastProjection = new Float64Array(16).fill(NaN);
|
||||
let lastWidth = 0,
|
||||
lastHeight = 0;
|
||||
frames.forEach((frame, index) => {
|
||||
const offset = index * 16,
|
||||
color = cells[index].color;
|
||||
packed.data.set(frame.bounds.longitude, offset);
|
||||
packed.data.set(frame.bounds.south, offset + 4);
|
||||
packed.data.set(frame.bounds.north, offset + 8);
|
||||
packed.data.set(
|
||||
[color.red, color.green, color.blue, color.alpha],
|
||||
offset + 12,
|
||||
);
|
||||
});
|
||||
return {
|
||||
count: cells.length,
|
||||
packed,
|
||||
gridTexture,
|
||||
get candidates() {
|
||||
return candidates;
|
||||
},
|
||||
update(camera, context) {
|
||||
const input = context.getInputBuffer(),
|
||||
view = camera.matrixWorldInverse.elements,
|
||||
projection = camera.projectionMatrix.elements;
|
||||
let changed = input.width !== lastWidth || input.height !== lastHeight;
|
||||
for (let i = 0; i < 16 && !changed; i++)
|
||||
changed =
|
||||
view[i] !== lastView[i] || projection[i] !== lastProjection[i];
|
||||
if (!changed) return;
|
||||
lastView.set(view);
|
||||
lastProjection.set(projection);
|
||||
lastWidth = input.width;
|
||||
lastHeight = input.height;
|
||||
frames.forEach((frame, index) => {
|
||||
viewFrame(frame, camera.matrixWorldInverse, scratch);
|
||||
groundClipBounds(frame, scratch, camera.projectionMatrix, bounds);
|
||||
if (bounds[0] <= 1) {
|
||||
bounds[0] -= 2 / Math.max(1, input.width);
|
||||
bounds[2] += 2 / Math.max(1, input.width);
|
||||
bounds[1] -= 2 / Math.max(1, input.height);
|
||||
bounds[3] += 2 / Math.max(1, input.height);
|
||||
}
|
||||
grid.bounds.set(bounds, index * 4);
|
||||
});
|
||||
const total = grid.pack();
|
||||
if (candidates.data.length / 4 < total) {
|
||||
candidates.texture.dispose();
|
||||
candidates = createGroundStorage(
|
||||
Math.max(total, candidates.data.length / 2),
|
||||
);
|
||||
}
|
||||
for (let i = 0; i < total; i++) candidates.data[i * 4] = grid.indices[i];
|
||||
for (let i = 0; i < grid.counts.length; i++) {
|
||||
gridData[i * 4] = grid.offsets[i];
|
||||
gridData[i * 4 + 1] = grid.counts[i];
|
||||
}
|
||||
gridTexture.needsUpdate = true;
|
||||
candidates.texture.needsUpdate = true;
|
||||
},
|
||||
dispose() {
|
||||
packed.texture.dispose();
|
||||
gridTexture.dispose();
|
||||
candidates.texture.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
function groundEffectClass(EffectDesc, NavaraEffect) {
|
||||
return class FirmsGroundEffectDesc extends EffectDesc {
|
||||
static key = KEY;
|
||||
static insertAfter = ['toneMapping'];
|
||||
static insertBefore = [
|
||||
'gevSharpen',
|
||||
'smaa',
|
||||
'fxaa',
|
||||
'gevPreSharpenOverlay',
|
||||
'gevOverlay',
|
||||
'final',
|
||||
];
|
||||
constructor(view, context, config) {
|
||||
super(view, context, config);
|
||||
this.owner = config[KEY].owner;
|
||||
}
|
||||
createPass() {
|
||||
this.effect = new Effect('GevFirmsGround', fragmentShader, {
|
||||
attributes: EffectAttribute.CONVOLUTION,
|
||||
uniforms: new Map([
|
||||
...groundSurfaceUniforms(),
|
||||
['tCells', new Uniform(null)],
|
||||
['tGrid', new Uniform(null)],
|
||||
['tCandidates', new Uniform(null)],
|
||||
['uCellSize', new Uniform([1, 1])],
|
||||
['uCandidateSize', new Uniform([1, 1])],
|
||||
['uInverseView', new Uniform(new Matrix4())],
|
||||
]),
|
||||
});
|
||||
return new NavaraEffect(this.view.camera.raw, this.effect);
|
||||
}
|
||||
update() {
|
||||
const state = this.owner.state,
|
||||
camera = this.view.camera.raw;
|
||||
if (!this.effect || !state || !camera) return;
|
||||
updateGroundSurface(this.effect, camera, this.ctx, this.find('mrt'));
|
||||
state.update(camera, this.ctx);
|
||||
const u = this.effect.uniforms;
|
||||
u.get('tCells').value = state.packed.texture;
|
||||
u.get('uCellSize').value[0] = state.packed.width;
|
||||
u.get('uCellSize').value[1] = state.packed.height;
|
||||
u.get('tGrid').value = state.gridTexture;
|
||||
u.get('tCandidates').value = state.candidates.texture;
|
||||
u.get('uCandidateSize').value[0] = state.candidates.width;
|
||||
u.get('uCandidateSize').value[1] = state.candidates.height;
|
||||
u.get('uInverseView').value.copy(camera.matrixWorld);
|
||||
}
|
||||
onDestroy() {
|
||||
this.effect?.dispose();
|
||||
super.onDestroy();
|
||||
}
|
||||
};
|
||||
}
|
||||
export function createFirmsNavaraRenderer(
|
||||
engine,
|
||||
{ view: nativeView, EffectDesc, NavaraEffect, id = 'local-firms' } = {},
|
||||
) {
|
||||
if (!engine?.movers || !nativeView?.camera || !EffectDesc || !NavaraEffect)
|
||||
throw new TypeError('FIRMS requires a Navara view');
|
||||
if (!registeredViews.has(nativeView)) {
|
||||
nativeView.registerEffect(KEY, groundEffectClass(EffectDesc, NavaraEffect));
|
||||
registeredViews.add(nativeView);
|
||||
}
|
||||
let destroyed = false,
|
||||
visible = false,
|
||||
cells = [],
|
||||
queued = false,
|
||||
handle = null,
|
||||
sprites = null;
|
||||
const owner = { state: buildState([]) },
|
||||
dataSource = { show: false },
|
||||
handlers = new Set();
|
||||
const adapter = createEngineLayerView(engine, {
|
||||
layerId: id,
|
||||
isDestroyed: () => destroyed,
|
||||
});
|
||||
adapter.view.camera.moveEnd = engine.camera.moveEnd;
|
||||
adapter.view.scene.preRender = engine.frames.preRender;
|
||||
const sync = () => {
|
||||
const show = visible && owner.state.count > 0;
|
||||
if (show && !handle)
|
||||
handle = nativeView.addEffect({ [KEY]: { owner }, visible: true });
|
||||
else handle?.update({ visible: show });
|
||||
};
|
||||
const scheduleCells = () => {
|
||||
if (queued || destroyed) return;
|
||||
queued = true;
|
||||
queueMicrotask(() => {
|
||||
queued = false;
|
||||
if (destroyed) return;
|
||||
const next = buildState(cells),
|
||||
previous = owner.state;
|
||||
owner.state = next;
|
||||
sync();
|
||||
previous.dispose();
|
||||
if (visible) engine.render.request('firms-cells');
|
||||
});
|
||||
};
|
||||
const removeSprites = () => {
|
||||
sprites?.destroy();
|
||||
sprites = null;
|
||||
};
|
||||
return {
|
||||
kind: 'navara',
|
||||
view: adapter.view,
|
||||
dataSource,
|
||||
clickType: 'click',
|
||||
project: (position, result) =>
|
||||
engine.projector.worldToWindow(position, result),
|
||||
viewRectangle(result) {
|
||||
const rect = engine.camera.viewRectangle();
|
||||
return rect ? Object.assign(result ?? {}, rect) : null;
|
||||
},
|
||||
horizon: () => ({
|
||||
isPointVisible: (position) => engine.projector.horizonVisible(position),
|
||||
}),
|
||||
createInputHandler() {
|
||||
let remove = null;
|
||||
const handler = {
|
||||
setInputAction(callback) {
|
||||
remove?.();
|
||||
remove = selectionDispatcherFor(engine).register(id, {
|
||||
owns: (pickId) => {
|
||||
const collection = sprites?.collection;
|
||||
if (!collection) return false;
|
||||
for (let i = 0; i < collection.length; i++)
|
||||
if (collection.get(i).id === pickId) return true;
|
||||
return false;
|
||||
},
|
||||
onClick: (event) => {
|
||||
if (!destroyed && visible) callback(event);
|
||||
},
|
||||
});
|
||||
},
|
||||
destroy() {
|
||||
remove?.();
|
||||
remove = null;
|
||||
handlers.delete(handler);
|
||||
},
|
||||
};
|
||||
handlers.add(handler);
|
||||
return handler;
|
||||
},
|
||||
pick: (position, event) => event?.picked,
|
||||
setVisible(show) {
|
||||
if (destroyed) return;
|
||||
const next = show !== false;
|
||||
if (visible === next) return;
|
||||
visible = next;
|
||||
dataSource.show = next;
|
||||
sprites?.setVisible(next);
|
||||
sync();
|
||||
engine.render.request('firms-visibility');
|
||||
},
|
||||
clearCells() {
|
||||
if (destroyed) return;
|
||||
cells = [];
|
||||
scheduleCells();
|
||||
},
|
||||
addCell(cell) {
|
||||
if (destroyed) return null;
|
||||
cells.push(cell);
|
||||
scheduleCells();
|
||||
return cell;
|
||||
},
|
||||
ensureSprites() {
|
||||
if (destroyed) return null;
|
||||
if (!sprites) {
|
||||
sprites = createFirmsSpriteBank(engine, {
|
||||
id: `firms:${id}`,
|
||||
capacity: Math.max(
|
||||
...LOD_LEVELS.map((lod) => lod.maxDetections ?? 0),
|
||||
),
|
||||
});
|
||||
sprites.setVisible(visible);
|
||||
}
|
||||
return sprites.collection;
|
||||
},
|
||||
addSprite(description) {
|
||||
return destroyed ? null : sprites.add(description);
|
||||
},
|
||||
removeSprites,
|
||||
onEnable() {},
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
visible = false;
|
||||
dataSource.show = false;
|
||||
cells = [];
|
||||
for (const handler of [...handlers]) handler.destroy();
|
||||
removeSprites();
|
||||
handle?.delete();
|
||||
owner.state.dispose();
|
||||
adapter.destroy();
|
||||
engine.render.request('firms-destroy');
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createEngineEvent } from '../../../globe/contract.js';
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { createFirmsNavaraRenderer } from './navara.js';
|
||||
const settle = () => new Promise((resolve) => setImmediate(resolve));
|
||||
function harness() {
|
||||
const effects = [],
|
||||
registered = [],
|
||||
requests = [],
|
||||
input = new Map();
|
||||
const frames = {
|
||||
preUpdate: createEngineEvent(),
|
||||
preRender: createEngineEvent(),
|
||||
};
|
||||
const position = geo.cartesian3.fromDegrees(0, 0, 4000000);
|
||||
const engine = {
|
||||
frames,
|
||||
host: { size: () => ({ width: 1280, height: 800 }) },
|
||||
movers: {
|
||||
createSet() {
|
||||
throw new Error('cells do not allocate sprite movers');
|
||||
},
|
||||
},
|
||||
render: { request: (reason) => requests.push(reason) },
|
||||
camera: {
|
||||
livePosition: position,
|
||||
moveEnd: createEngineEvent(),
|
||||
viewRectangle: () => ({ west: -1, south: -0.5, east: 1, north: 0.5 }),
|
||||
pose: () => ({
|
||||
position,
|
||||
cartographic: { longitude: 0, latitude: 0, height: 4000000 },
|
||||
direction: { x: -1, y: 0, z: 0 },
|
||||
up: { x: 0, y: 0, z: 1 },
|
||||
right: { x: 0, y: 1, z: 0 },
|
||||
heading: 0,
|
||||
pitch: -Math.PI / 2,
|
||||
roll: 0,
|
||||
fovy: 1,
|
||||
}),
|
||||
},
|
||||
projector: {
|
||||
worldToWindow: (point, result) =>
|
||||
Object.assign(result ?? {}, { x: 10, y: 20 }),
|
||||
horizonVisible: () => true,
|
||||
},
|
||||
input: {
|
||||
on(type, listener) {
|
||||
input.set(type, listener);
|
||||
return () => input.delete(type);
|
||||
},
|
||||
},
|
||||
};
|
||||
const view = {
|
||||
camera: {},
|
||||
registerEffect: (key, desc) => registered.push([key, desc]),
|
||||
addEffect(config) {
|
||||
const handle = {
|
||||
config,
|
||||
updates: [],
|
||||
deleted: 0,
|
||||
update(value) {
|
||||
this.updates.push(value);
|
||||
},
|
||||
delete() {
|
||||
this.deleted++;
|
||||
},
|
||||
};
|
||||
effects.push(handle);
|
||||
return handle;
|
||||
},
|
||||
};
|
||||
const options = { view, EffectDesc: class {}, NavaraEffect: class {} };
|
||||
return {
|
||||
engine,
|
||||
options,
|
||||
effects,
|
||||
registered,
|
||||
requests,
|
||||
input,
|
||||
frames,
|
||||
renderer: createFirmsNavaraRenderer(engine, options),
|
||||
};
|
||||
}
|
||||
const cell = {
|
||||
west: 0,
|
||||
south: 0,
|
||||
east: 1,
|
||||
north: 1,
|
||||
color: { red: 1, green: 0, blue: 0, alpha: 0.3 },
|
||||
};
|
||||
test('ground changes are atomic, lazy and dispose replaced and destroyed GPU textures once', async () => {
|
||||
const h = harness(),
|
||||
r = h.renderer;
|
||||
r.setVisible(true);
|
||||
assert.equal(h.effects.length, 0);
|
||||
r.clearCells();
|
||||
r.addCell(cell);
|
||||
r.addCell({ ...cell, west: 1, east: 2 });
|
||||
assert.equal(h.effects.length, 0);
|
||||
await settle();
|
||||
assert.equal(h.effects.length, 1);
|
||||
const owner = h.effects[0].config.gevFirmsGround.owner;
|
||||
assert.equal(owner.state.count, 2);
|
||||
let disposed = 0;
|
||||
for (const t of [
|
||||
owner.state.packed.texture,
|
||||
owner.state.gridTexture,
|
||||
owner.state.candidates.texture,
|
||||
])
|
||||
t.addEventListener('dispose', () => disposed++);
|
||||
r.clearCells();
|
||||
r.addCell(cell);
|
||||
await settle();
|
||||
assert.equal(owner.state.count, 1);
|
||||
assert.equal(disposed, 3);
|
||||
r.setVisible(false);
|
||||
assert.equal(r.dataSource.show, false);
|
||||
assert.deepEqual(h.effects[0].updates.at(-1), { visible: false });
|
||||
r.clearCells();
|
||||
r.addCell(cell);
|
||||
r.destroy();
|
||||
r.destroy();
|
||||
const before = h.requests.length;
|
||||
await settle();
|
||||
assert.equal(h.requests.length, before);
|
||||
assert.equal(h.effects[0].deleted, 1);
|
||||
assert.equal(h.frames.preUpdate.numberOfListeners, 0);
|
||||
const second = createFirmsNavaraRenderer(h.engine, h.options);
|
||||
second.destroy();
|
||||
assert.equal(h.registered.length, 1);
|
||||
});
|
||||
test('FIRMS selection uses actual engine event picks and releases its dispatcher subscriptions', () => {
|
||||
const h = harness(),
|
||||
r = h.renderer;
|
||||
r.setVisible(true);
|
||||
const handler = r.createInputHandler();
|
||||
let event;
|
||||
handler.setInputAction((value) => (event = value), 'click');
|
||||
assert.equal(h.input.size, 4);
|
||||
const picked = { id: 'sibling-contact' };
|
||||
h.input.get('click')({ position: { x: 10, y: 20 }, picked, drilled: [] });
|
||||
assert.equal(r.pick(event.position, event), picked);
|
||||
assert.equal(r.view.camera.moveEnd, h.engine.camera.moveEnd);
|
||||
assert.equal(r.view.scene.preRender, h.engine.frames.preRender);
|
||||
assert.deepEqual(r.viewRectangle({}), {
|
||||
west: -1,
|
||||
south: -0.5,
|
||||
east: 1,
|
||||
north: 0.5,
|
||||
});
|
||||
assert.deepEqual(r.project({}, {}), { x: 10, y: 20 });
|
||||
event = null;
|
||||
r.setVisible(false);
|
||||
h.input.get('click')({ position: { x: 10, y: 20 }, picked, drilled: [] });
|
||||
assert.equal(event, null);
|
||||
handler.destroy();
|
||||
handler.destroy();
|
||||
assert.equal(h.input.size, 0);
|
||||
r.destroy();
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
// Exact geodetic rectangle sides, including latitude parallels at any height.
|
||||
import * as geo from '../../../geo/index.js';
|
||||
const ellipsoid = geo.ellipsoid.WGS84;
|
||||
const A = ellipsoid.radii.x,
|
||||
B = ellipsoid.radii.z;
|
||||
const E2 = 1 - (B * B) / (A * A);
|
||||
export function latitudeBoundary(degrees) {
|
||||
const angle = geo.math.toRadians(degrees),
|
||||
sin = Math.sin(angle),
|
||||
cos = Math.cos(angle);
|
||||
return [sin, cos, ((E2 * A) / Math.sqrt(1 - E2 * sin * sin)) * sin * cos, 0];
|
||||
}
|
||||
export function rectangleBoundaries({ west, south, east, north }) {
|
||||
const w = geo.math.toRadians(west),
|
||||
e = geo.math.toRadians(east);
|
||||
return {
|
||||
longitude: [Math.sin(w), Math.cos(w), Math.sin(e), Math.cos(e)],
|
||||
south: latitudeBoundary(south),
|
||||
north: latitudeBoundary(north),
|
||||
};
|
||||
}
|
||||
export function rectangleDistances(bounds, point) {
|
||||
const { x, y, z } = point,
|
||||
rho = Math.hypot(x, y),
|
||||
l = bounds.longitude;
|
||||
return [
|
||||
y * l[1] - x * l[0],
|
||||
x * l[2] - y * l[3],
|
||||
z * bounds.south[1] - rho * bounds.south[0] + bounds.south[2],
|
||||
rho * bounds.north[0] - z * bounds.north[1] - bounds.north[2],
|
||||
];
|
||||
}
|
||||
export function rectangleFrame(cell) {
|
||||
let eastBound = cell.east;
|
||||
if (eastBound < cell.west) eastBound += 360;
|
||||
const lon = (cell.west + eastBound) / 2,
|
||||
lat = (cell.south + cell.north) / 2;
|
||||
const center = geo.cartesian3.fromDegrees(lon, lat);
|
||||
const up = ellipsoid.geodeticSurfaceNormal(center, geo.cartesian3.create());
|
||||
const angle = geo.math.toRadians(lon);
|
||||
const east = geo.cartesian3.create(-Math.sin(angle), Math.cos(angle), 0);
|
||||
const north = geo.cartesian3.cross(up, east, geo.cartesian3.create());
|
||||
let radius = 0;
|
||||
for (const latitude of [cell.south, lat, cell.north])
|
||||
for (const longitude of [cell.west, lon, eastBound]) {
|
||||
const p = geo.cartesian3.fromDegrees(longitude, latitude);
|
||||
const dx = p.x - center.x,
|
||||
dy = p.y - center.y,
|
||||
dz = p.z - center.z;
|
||||
radius = Math.max(
|
||||
radius,
|
||||
Math.hypot(
|
||||
dx * east.x + dy * east.y + dz * east.z,
|
||||
dx * north.x + dy * north.y + dz * north.z,
|
||||
),
|
||||
);
|
||||
}
|
||||
radius = radius * (1 + 101000 / ellipsoid.minimumRadius) + 1;
|
||||
return {
|
||||
center,
|
||||
east,
|
||||
north,
|
||||
up,
|
||||
radius,
|
||||
floor: -100000 - ((radius * radius) / (2 * ellipsoid.minimumRadius)) * 1.1,
|
||||
ceiling: 12000,
|
||||
bounds: rectangleBoundaries(cell),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import {
|
||||
rectangleBoundaries,
|
||||
rectangleDistances,
|
||||
rectangleFrame,
|
||||
} from './navaraGeometry.js';
|
||||
const cases = [];
|
||||
for (const lat of [-90, -80, -45, 0, 45, 80, 88])
|
||||
for (const west of [-180, -123, 0, 178])
|
||||
for (const width of [1, 2])
|
||||
cases.push({
|
||||
west,
|
||||
south: lat,
|
||||
east: west + width,
|
||||
north: Math.min(90, lat + width),
|
||||
});
|
||||
test('geodetic cell sides contain public native rectangle vertices and retain exact parallels at every height', () => {
|
||||
let vertices = 0,
|
||||
heights = 0;
|
||||
for (const rect of cases) {
|
||||
const bounds = rectangleBoundaries(rect);
|
||||
const native = Cesium.RectangleGeometry.createGeometry(
|
||||
new Cesium.RectangleGeometry({
|
||||
rectangle: Cesium.Rectangle.fromDegrees(
|
||||
rect.west,
|
||||
rect.south,
|
||||
rect.east,
|
||||
rect.north,
|
||||
),
|
||||
vertexFormat: Cesium.VertexFormat.POSITION_ONLY,
|
||||
}),
|
||||
);
|
||||
const positions = native.attributes.position.values;
|
||||
for (let i = 0; i < positions.length; i += 3) {
|
||||
const distance = rectangleDistances(bounds, {
|
||||
x: positions[i],
|
||||
y: positions[i + 1],
|
||||
z: positions[i + 2],
|
||||
});
|
||||
assert.ok(Math.min(...distance) > -1e-6, JSON.stringify(rect));
|
||||
vertices++;
|
||||
}
|
||||
for (const h of [-100000, 0, 200, 12000])
|
||||
for (const t of [0.1, 0.5, 0.9]) {
|
||||
const lon = rect.west + (rect.east - rect.west) * t,
|
||||
lat = rect.south + (rect.north - rect.south) * t;
|
||||
for (const [x, y] of [
|
||||
[lon, rect.south],
|
||||
[lon, rect.north],
|
||||
[rect.west, lat],
|
||||
[rect.east, lat],
|
||||
]) {
|
||||
const d = rectangleDistances(
|
||||
bounds,
|
||||
geo.cartesian3.fromDegrees(x, y, h),
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs(Math.min(...d)) < 1e-6,
|
||||
`${JSON.stringify(rect)} height ${h}`,
|
||||
);
|
||||
heights++;
|
||||
}
|
||||
assert.ok(
|
||||
Math.min(
|
||||
...rectangleDistances(
|
||||
bounds,
|
||||
geo.cartesian3.fromDegrees(lon, lat, h),
|
||||
),
|
||||
) > 0,
|
||||
);
|
||||
assert.ok(
|
||||
Math.min(
|
||||
...rectangleDistances(
|
||||
bounds,
|
||||
geo.cartesian3.fromDegrees(rect.west - 0.01, lat, h),
|
||||
),
|
||||
) < 0,
|
||||
);
|
||||
assert.ok(
|
||||
Math.min(
|
||||
...rectangleDistances(
|
||||
bounds,
|
||||
geo.cartesian3.fromDegrees(rect.east + 0.01, lat, h),
|
||||
),
|
||||
) < 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
assert.equal(vertices, 562);
|
||||
assert.equal(heights, 2688);
|
||||
});
|
||||
test('candidate volumes enclose geodetic cells through their conservative terrain/roof height window', () => {
|
||||
for (const rect of cases) {
|
||||
const frame = rectangleFrame(rect);
|
||||
for (const lat of [rect.south, (rect.south + rect.north) / 2, rect.north])
|
||||
for (const lon of [rect.west, (rect.west + rect.east) / 2, rect.east])
|
||||
for (const h of [-100000, 0, 12000]) {
|
||||
const p = geo.cartesian3.fromDegrees(lon, lat, h),
|
||||
delta = {
|
||||
x: p.x - frame.center.x,
|
||||
y: p.y - frame.center.y,
|
||||
z: p.z - frame.center.z,
|
||||
};
|
||||
const x = geo.cartesian3.dot(delta, frame.east),
|
||||
y = geo.cartesian3.dot(delta, frame.north),
|
||||
z = geo.cartesian3.dot(delta, frame.up);
|
||||
assert.ok(
|
||||
Math.abs(x) <= frame.radius && Math.abs(y) <= frame.radius,
|
||||
JSON.stringify(rect),
|
||||
);
|
||||
assert.ok(
|
||||
z >= frame.floor - 1e-6 && z <= frame.ceiling + 1e-6,
|
||||
`${JSON.stringify(rect)} ${z}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,198 @@
|
||||
// The real FIRMS PNGs in one engine mover atlas.
|
||||
const WHITE = Object.freeze([1, 1, 1, 1]);
|
||||
const CELL = 60,
|
||||
PAD = 2,
|
||||
BASE_SIZE = 56;
|
||||
const imageFromUrl = (url) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const image = new Image();
|
||||
image.onload = () => {
|
||||
image.onload = image.onerror = null;
|
||||
resolve(image);
|
||||
};
|
||||
image.onerror = () => {
|
||||
image.onload = image.onerror = null;
|
||||
reject(new Error('FIRMS sprite decode failed'));
|
||||
};
|
||||
image.src = url;
|
||||
});
|
||||
export function createFirmsSpriteBank(
|
||||
engine,
|
||||
{
|
||||
id,
|
||||
capacity,
|
||||
loadImage = imageFromUrl,
|
||||
createCanvas = () => document.createElement('canvas'),
|
||||
} = {},
|
||||
) {
|
||||
let rows = [],
|
||||
visible = false,
|
||||
destroyed = false,
|
||||
generation = 0,
|
||||
queued = false,
|
||||
set = null,
|
||||
atlas = null;
|
||||
const images = new Map();
|
||||
const loaded = new Map();
|
||||
const getImage = (url) => {
|
||||
let task = images.get(url);
|
||||
if (!task) {
|
||||
task = Promise.resolve()
|
||||
.then(() => loadImage(url))
|
||||
.then((image) => {
|
||||
if (!destroyed) loaded.set(url, image);
|
||||
return image;
|
||||
})
|
||||
.catch((error) => {
|
||||
images.delete(url);
|
||||
throw error;
|
||||
});
|
||||
images.set(url, task);
|
||||
}
|
||||
return task;
|
||||
};
|
||||
const hide = () => {
|
||||
if (set && set.count() !== 0) {
|
||||
set.setCount(0);
|
||||
set.commit();
|
||||
}
|
||||
};
|
||||
function buildAtlas() {
|
||||
const entries = [...loaded],
|
||||
side = Math.ceil(Math.sqrt(entries.length));
|
||||
const canvas = createCanvas();
|
||||
canvas.width = side * CELL;
|
||||
canvas.height = Math.ceil(entries.length / side) * CELL;
|
||||
const context = canvas.getContext('2d');
|
||||
if (!context) throw new Error('FIRMS atlas requires a canvas');
|
||||
const cells = {},
|
||||
lookup = new Map();
|
||||
entries.forEach(([url, image], index) => {
|
||||
const width = image.naturalWidth ?? image.width,
|
||||
height = image.naturalHeight ?? image.height;
|
||||
if (!(width > 0 && width <= BASE_SIZE && height === width))
|
||||
throw new Error('FIRMS sprite dimensions are invalid');
|
||||
const x = (index % side) * CELL + PAD,
|
||||
y = Math.floor(index / side) * CELL + PAD;
|
||||
context.drawImage(image, x, y);
|
||||
const key = String(index);
|
||||
cells[key] = [
|
||||
x / canvas.width,
|
||||
y / canvas.height,
|
||||
(x + width) / canvas.width,
|
||||
(y + height) / canvas.height,
|
||||
];
|
||||
lookup.set(url, { key, scale: width / BASE_SIZE });
|
||||
});
|
||||
return { canvas, cells, lookup };
|
||||
}
|
||||
async function flush() {
|
||||
if (destroyed) return;
|
||||
if (!visible || !rows.length) {
|
||||
hide();
|
||||
return;
|
||||
}
|
||||
const version = generation,
|
||||
snapshot = rows.slice();
|
||||
const urls = [...new Set(snapshot.map((row) => row.image))];
|
||||
await Promise.all(urls.map(getImage));
|
||||
if (destroyed || !visible || version !== generation) return;
|
||||
if (!atlas || urls.some((url) => !atlas.lookup.has(url))) {
|
||||
const next = buildAtlas();
|
||||
set?.destroy();
|
||||
set = engine.movers.createSet({
|
||||
id,
|
||||
kind: 'sprite',
|
||||
capacity,
|
||||
depthTest: 'always',
|
||||
pickable: true,
|
||||
sharpen: true,
|
||||
sprite: {
|
||||
atlas: { canvas: next.canvas, cells: next.cells },
|
||||
sizePx: BASE_SIZE,
|
||||
},
|
||||
});
|
||||
atlas = next;
|
||||
}
|
||||
snapshot.forEach((row, index) => {
|
||||
const cell = atlas.lookup.get(row.image);
|
||||
set.set(index, {
|
||||
position: row.position,
|
||||
cell: cell.key,
|
||||
scale: cell.scale,
|
||||
color: WHITE,
|
||||
show: row.show,
|
||||
pickId: row.id,
|
||||
});
|
||||
});
|
||||
set.setCount(snapshot.length);
|
||||
set.commit();
|
||||
}
|
||||
function schedule() {
|
||||
generation++;
|
||||
if (queued || destroyed) return;
|
||||
queued = true;
|
||||
queueMicrotask(() => {
|
||||
queued = false;
|
||||
const version = generation;
|
||||
void flush().catch(() => {
|
||||
if (!destroyed && visible && version === generation)
|
||||
console.error('FIRMS sprite atlas failed');
|
||||
});
|
||||
});
|
||||
}
|
||||
const collection = {
|
||||
get length() {
|
||||
return rows.length;
|
||||
},
|
||||
get(index) {
|
||||
return rows[index];
|
||||
},
|
||||
removeAll() {
|
||||
if (destroyed) return;
|
||||
rows = [];
|
||||
schedule();
|
||||
},
|
||||
};
|
||||
return {
|
||||
collection,
|
||||
add(description) {
|
||||
if (destroyed) return null;
|
||||
if (rows.length >= capacity)
|
||||
throw new RangeError('FIRMS sprite capacity exceeded');
|
||||
let show = description.show !== false;
|
||||
const row = {
|
||||
...description,
|
||||
get show() {
|
||||
return show;
|
||||
},
|
||||
set show(value) {
|
||||
const next = Boolean(value);
|
||||
if (next === show || destroyed) return;
|
||||
show = next;
|
||||
schedule();
|
||||
},
|
||||
};
|
||||
rows.push(row);
|
||||
schedule();
|
||||
return row;
|
||||
},
|
||||
setVisible(value) {
|
||||
if (destroyed || visible === Boolean(value)) return;
|
||||
visible = Boolean(value);
|
||||
if (!visible) hide();
|
||||
schedule();
|
||||
},
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
destroyed = true;
|
||||
generation++;
|
||||
rows = [];
|
||||
images.clear();
|
||||
loaded.clear();
|
||||
set?.destroy();
|
||||
set = null;
|
||||
atlas = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createMoverRegistry } from '../../../globe/movers.js';
|
||||
import { createFirmsSpriteBank } from './navaraSprites.js';
|
||||
const settle = () => new Promise((resolve) => setImmediate(resolve));
|
||||
function harness(loadImage) {
|
||||
let commits = 0,
|
||||
disposals = 0;
|
||||
const draws = [],
|
||||
canvases = [];
|
||||
const registry = createMoverRegistry((options, store) => ({
|
||||
ready: () => true,
|
||||
commit() {
|
||||
commits++;
|
||||
},
|
||||
destroy() {
|
||||
disposals++;
|
||||
},
|
||||
}));
|
||||
const bank = createFirmsSpriteBank(
|
||||
{ movers: registry.movers },
|
||||
{
|
||||
id: 'firms-test',
|
||||
capacity: 3,
|
||||
loadImage,
|
||||
createCanvas() {
|
||||
const canvas = {
|
||||
getContext: () => ({ drawImage: (...args) => draws.push(args) }),
|
||||
};
|
||||
canvases.push(canvas);
|
||||
return canvas;
|
||||
},
|
||||
},
|
||||
);
|
||||
return {
|
||||
bank,
|
||||
registry,
|
||||
draws,
|
||||
canvases,
|
||||
get commits() {
|
||||
return commits;
|
||||
},
|
||||
get disposals() {
|
||||
return disposals;
|
||||
},
|
||||
};
|
||||
}
|
||||
test('actual image dimensions set both the atlas cell and visible/pickable quad, with batched horizon flips', async () => {
|
||||
const h = harness(async (url) => ({
|
||||
width: url === 'small' ? 16 : 56,
|
||||
height: url === 'small' ? 16 : 56,
|
||||
}));
|
||||
const first = h.bank.add({
|
||||
id: 'firms-0',
|
||||
position: { x: 1, y: 2, z: 3 },
|
||||
image: 'small',
|
||||
});
|
||||
const second = h.bank.add({
|
||||
id: 'firms-1',
|
||||
position: { x: 4, y: 5, z: 6 },
|
||||
image: 'large',
|
||||
});
|
||||
h.bank.setVisible(true);
|
||||
await settle();
|
||||
const entry = h.registry.sets.get('firms-test');
|
||||
assert.equal(h.registry.sets.size, 1);
|
||||
assert.equal(entry.options.sharpen, true);
|
||||
assert.equal(entry.options.depthTest, 'always');
|
||||
assert.equal(entry.options.pickable, true);
|
||||
assert.equal(entry.store.count, 2);
|
||||
assert.ok(Math.abs(entry.store.scales[0] - 16 / 56) < 1e-7);
|
||||
assert.equal(entry.store.scales[1], 1);
|
||||
assert.deepEqual(entry.store.pickIds.slice(0, 2), ['firms-0', 'firms-1']);
|
||||
assert.equal(h.draws.length, 2);
|
||||
assert.ok(
|
||||
h.draws.every((args) => args.length === 3),
|
||||
'atlas does not resize source PNGs',
|
||||
);
|
||||
const rect = entry.options.sprite.atlas.cells['0'];
|
||||
assert.ok(Math.abs((rect[2] - rect[0]) * h.canvases[0].width - 16) < 1e-10);
|
||||
assert.ok(
|
||||
rect[0] > 0 && rect[1] > 0,
|
||||
'transparent neighbor padding is retained',
|
||||
);
|
||||
const before = h.commits;
|
||||
first.show = false;
|
||||
second.show = false;
|
||||
await settle();
|
||||
assert.equal(h.commits, before + 1);
|
||||
assert.equal(h.canvases.length, 1);
|
||||
assert.deepEqual([...entry.store.shows.slice(0, 2)], [0, 0]);
|
||||
h.bank.setVisible(false);
|
||||
assert.equal(entry.store.count, 0);
|
||||
const hidden = h.commits;
|
||||
await settle();
|
||||
assert.equal(h.commits, hidden);
|
||||
h.bank.destroy();
|
||||
h.bank.destroy();
|
||||
assert.equal(h.registry.sets.size, 0);
|
||||
assert.equal(h.disposals, 1);
|
||||
});
|
||||
test('uncooperative image completion after disable or destroy cannot create movers or request a frame', async () => {
|
||||
let finish;
|
||||
const h = harness(() => new Promise((resolve) => (finish = resolve)));
|
||||
h.bank.add({ id: 'firms-0', position: { x: 1, y: 2, z: 3 }, image: 'late' });
|
||||
h.bank.setVisible(true);
|
||||
await settle();
|
||||
h.bank.setVisible(false);
|
||||
finish({ width: 16, height: 16 });
|
||||
await settle();
|
||||
assert.equal(h.registry.sets.size, 0);
|
||||
assert.equal(h.commits, 0);
|
||||
h.bank.collection.removeAll();
|
||||
h.bank.add({ id: 'firms-1', position: { x: 1, y: 2, z: 3 }, image: 'later' });
|
||||
h.bank.setVisible(true);
|
||||
await settle();
|
||||
h.bank.destroy();
|
||||
finish({ width: 56, height: 56 });
|
||||
await settle();
|
||||
assert.equal(h.registry.sets.size, 0);
|
||||
assert.equal(h.commits, 0);
|
||||
assert.equal(h.bank.collection.length, 0);
|
||||
});
|
||||
test('clearing rows during decode preserves the new generation and commits only the replacement', async () => {
|
||||
const complete = new Map(),
|
||||
h = harness((url) => new Promise((resolve) => complete.set(url, resolve)));
|
||||
h.bank.setVisible(true);
|
||||
h.bank.add({ id: 'old', position: { x: 1, y: 2, z: 3 }, image: 'old' });
|
||||
await settle();
|
||||
h.bank.collection.removeAll();
|
||||
h.bank.add({ id: 'new', position: { x: 4, y: 5, z: 6 }, image: 'new' });
|
||||
await settle();
|
||||
complete.get('old')({ width: 16, height: 16 });
|
||||
await settle();
|
||||
assert.equal(h.registry.sets.size, 0);
|
||||
complete.get('new')({ width: 56, height: 56 });
|
||||
await settle();
|
||||
const entry = h.registry.sets.get('firms-test');
|
||||
assert.equal(entry.store.count, 1);
|
||||
assert.equal(entry.store.pickIds[0], 'new');
|
||||
assert.equal(h.commits, 1);
|
||||
h.bank.destroy();
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
/** Camera-relative transforms in JS float64; only nearby metres enter GLSL. */
|
||||
export function viewFrame(frame, matrix, out) {
|
||||
const m = matrix.elements;
|
||||
const transform = (p, offset, translate) => {
|
||||
out[offset] =
|
||||
m[0] * p.x + m[4] * p.y + m[8] * p.z + (translate ? m[12] : 0);
|
||||
out[offset + 1] =
|
||||
m[1] * p.x + m[5] * p.y + m[9] * p.z + (translate ? m[13] : 0);
|
||||
out[offset + 2] =
|
||||
m[2] * p.x + m[6] * p.y + m[10] * p.z + (translate ? m[14] : 0);
|
||||
};
|
||||
transform(frame.center, 0, true);
|
||||
transform(frame.east, 3, false);
|
||||
transform(frame.north, 6, false);
|
||||
transform(frame.up, 9, false);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Conservative clip bounds, including a camera inside/crossing the volume. */
|
||||
export function groundClipBounds(frame, view, projection, out) {
|
||||
const p = projection.elements;
|
||||
let x0 = 1,
|
||||
y0 = 1,
|
||||
x1 = -1,
|
||||
y1 = -1,
|
||||
front = 0,
|
||||
behind = 0;
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const x = (i & 1 ? 1 : -1) * frame.radius;
|
||||
const y = (i & 2 ? 1 : -1) * frame.radius;
|
||||
const z = i & 4 ? frame.ceiling : frame.floor;
|
||||
const vx = view[0] + view[3] * x + view[6] * y + view[9] * z;
|
||||
const vy = view[1] + view[4] * x + view[7] * y + view[10] * z;
|
||||
const vz = view[2] + view[5] * x + view[8] * y + view[11] * z;
|
||||
const w = p[3] * vx + p[7] * vy + p[11] * vz + p[15];
|
||||
if (w <= 0) {
|
||||
behind++;
|
||||
continue;
|
||||
}
|
||||
front++;
|
||||
const cx = (p[0] * vx + p[4] * vy + p[8] * vz + p[12]) / w;
|
||||
const cy = (p[1] * vx + p[5] * vy + p[9] * vz + p[13]) / w;
|
||||
x0 = Math.min(x0, cx);
|
||||
y0 = Math.min(y0, cy);
|
||||
x1 = Math.max(x1, cx);
|
||||
y1 = Math.max(y1, cy);
|
||||
}
|
||||
if (front && behind) {
|
||||
x0 = -1;
|
||||
y0 = -1;
|
||||
x1 = 1;
|
||||
y1 = 1;
|
||||
}
|
||||
if (!front || x1 < -1 || y1 < -1 || x0 > 1 || y0 > 1) out.fill(2);
|
||||
else {
|
||||
out[0] = Math.max(-1, x0);
|
||||
out[1] = Math.max(-1, y0);
|
||||
out[2] = Math.min(1, x1);
|
||||
out[3] = Math.min(1, y1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// A screen grid of conservative projected volumes. Prefix-sum storage has
|
||||
// no feature/cell cap: overlapping shapes retain their source order.
|
||||
export const GRID_COLS = 64;
|
||||
export const GRID_ROWS = 40;
|
||||
export function createGroundGrid(count) {
|
||||
const counts = new Uint32Array(GRID_COLS * GRID_ROWS);
|
||||
const offsets = new Uint32Array(counts.length);
|
||||
const cursor = new Uint32Array(counts.length);
|
||||
const bounds = new Float64Array(count * 4);
|
||||
const ranges = new Int32Array(count * 4);
|
||||
let indices = new Uint32Array(0);
|
||||
const clamp = (value, max) => Math.min(max - 1, Math.max(0, value));
|
||||
return {
|
||||
bounds,
|
||||
counts,
|
||||
offsets,
|
||||
get indices() {
|
||||
return indices;
|
||||
},
|
||||
pack() {
|
||||
counts.fill(0);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const b = i * 4;
|
||||
const valid =
|
||||
bounds[b] <= bounds[b + 2] &&
|
||||
bounds[b + 1] <= bounds[b + 3] &&
|
||||
bounds[b] <= 1 &&
|
||||
bounds[b + 1] <= 1 &&
|
||||
bounds[b + 2] >= -1 &&
|
||||
bounds[b + 3] >= -1;
|
||||
ranges[b] = valid
|
||||
? clamp(Math.floor((bounds[b] * 0.5 + 0.5) * GRID_COLS), GRID_COLS)
|
||||
: -1;
|
||||
ranges[b + 1] = clamp(
|
||||
Math.floor((bounds[b + 1] * 0.5 + 0.5) * GRID_ROWS),
|
||||
GRID_ROWS,
|
||||
);
|
||||
ranges[b + 2] = clamp(
|
||||
Math.floor((bounds[b + 2] * 0.5 + 0.5) * GRID_COLS),
|
||||
GRID_COLS,
|
||||
);
|
||||
ranges[b + 3] = clamp(
|
||||
Math.floor((bounds[b + 3] * 0.5 + 0.5) * GRID_ROWS),
|
||||
GRID_ROWS,
|
||||
);
|
||||
if (!valid) continue;
|
||||
for (let y = ranges[b + 1]; y <= ranges[b + 3]; y++)
|
||||
for (let x = ranges[b]; x <= ranges[b + 2]; x++)
|
||||
counts[y * GRID_COLS + x]++;
|
||||
}
|
||||
let total = 0;
|
||||
for (let i = 0; i < counts.length; i++) {
|
||||
offsets[i] = total;
|
||||
total += counts[i];
|
||||
cursor[i] = offsets[i];
|
||||
}
|
||||
if (indices.length < total)
|
||||
indices = new Uint32Array(Math.max(total, indices.length * 2));
|
||||
for (let i = 0; i < count; i++) {
|
||||
const b = i * 4;
|
||||
if (ranges[b] < 0) continue;
|
||||
for (let y = ranges[b + 1]; y <= ranges[b + 3]; y++)
|
||||
for (let x = ranges[b]; x <= ranges[b + 2]; x++)
|
||||
indices[cursor[y * GRID_COLS + x]++] = i;
|
||||
}
|
||||
return total;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Public depth inputs shared by actual terrain/tiles classifiers.
|
||||
import {
|
||||
DataTexture,
|
||||
FloatType,
|
||||
RGBAFormat,
|
||||
NearestFilter,
|
||||
Matrix4,
|
||||
Uniform,
|
||||
RGBADepthPacking,
|
||||
} from 'three';
|
||||
export function createGroundTexture(data, width, height) {
|
||||
const texture = new DataTexture(data, width, height, RGBAFormat, FloatType);
|
||||
texture.minFilter = NearestFilter;
|
||||
texture.magFilter = NearestFilter;
|
||||
texture.needsUpdate = true;
|
||||
return texture;
|
||||
}
|
||||
export function createGroundStorage(texels) {
|
||||
const width = Math.min(1024, Math.max(1, texels));
|
||||
const height = Math.max(1, Math.ceil(texels / width));
|
||||
const data = new Float32Array(width * height * 4);
|
||||
return {
|
||||
data,
|
||||
width,
|
||||
height,
|
||||
texture: createGroundTexture(data, width, height),
|
||||
};
|
||||
}
|
||||
export function groundSurfaceUniforms() {
|
||||
return [
|
||||
['tAllDepth', new Uniform(null)],
|
||||
['tSurfaceDepth', new Uniform(null)],
|
||||
['uInverseProjection', new Uniform(new Matrix4())],
|
||||
['uLogDepthFC', new Uniform(1)],
|
||||
];
|
||||
}
|
||||
export function updateGroundSurface(effect, camera, context, mrt) {
|
||||
if (mrt?.depthBufferPacking !== RGBADepthPacking)
|
||||
throw new Error('Ground classification requires packed scene depth');
|
||||
const u = effect.uniforms;
|
||||
u.get('tAllDepth').value = mrt.depthBuffer;
|
||||
u.get('tSurfaceDepth').value = context.getRenderTarget().depthTexture;
|
||||
u.get('uInverseProjection').value.copy(camera.projectionMatrixInverse);
|
||||
u.get('uLogDepthFC').value = 2 / Math.log2(camera.far + 1);
|
||||
}
|
||||
Reference in new issue
Block a user