WebGL map: simplify the coastlines for the zoom
On the card the land was most of a frame's work (the stencil fills twice, the sand, the edge), and it scales with vertices, not pixels. The land is now built per zoom level (powers of 2) with each coastline simplified (Douglas-Peucker) so that no point moves more than 0.25 px at the level's zoom; zooming in takes the finer level at once, zooming out keeps it until the zoom is 10 % under it. COAST, onLand() and the 2D map are unchanged.
This commit is contained in:
parent
eeeccc60d4
commit
3482142ae5
4 changed files with 108 additions and 12 deletions
|
|
@ -13,6 +13,7 @@ All notable changes to this project are documented here. The project follows
|
|||
- Cities, labels, building cones, ships, offer bubbles and money pop-ups are painted once and then reused, so the usual map also draws far fewer shapes each frame.
|
||||
- Long zooms stay on the graphics card: the pictures of cities and labels are painted on one shared canvas instead of each keeping its own, so the browser no longer runs out of room for them and switches to the slower drawing.
|
||||
- Zooming is smoother on big maps: while you zoom, cities and ships keep their picture and are only redrawn sharp once the zoom stops, instead of being repainted at every small step.
|
||||
- The graphics card draws the coastlines with fewer points when you zoom out, where the extra detail was smaller than a pixel, so the map costs it a lot less work, which helps phones most.
|
||||
|
||||
## [2.9.1] — 2026-11-04
|
||||
|
||||
|
|
|
|||
|
|
@ -18,15 +18,33 @@ void main(){float d=(length(vq/vr)-1.)*min(vr.x,vr.y),a=clamp(.5-d*uDpr,0.,1.);i
|
|||
const CIRC_VS=GL_HEAD+GL_CLIP+`layout(location=0) in vec4 aC;uniform vec2 uView;uniform vec3 uCam;out vec2 vq;flat out float vr;
|
||||
void main(){vec2 c=(aC.xy-uCam.xy)*uCam.z+uView*.5;float r=aC.z*uCam.z,m=r+1.;vq=vec2((gl_VertexID&1)==0?-m:m,(gl_VertexID&2)==0?-m:m);vr=r;gl_Position=clip(c+vq,uView,0.);}`;
|
||||
const CIRC_FS=GL_HEAD+`in vec2 vq;flat in float vr;out vec4 o;void main(){if(length(vq)>vr)discard;o=vec4(1.);}`;
|
||||
/* The land, built once per level of detail (the far view leaves out the islets as LANDP_FAR does): the fan for the
|
||||
fills, the coastlines as line segments (paintWorld()'s curves, four segments each) for the sand and the dark edge,
|
||||
and the hills. */
|
||||
function glLandGeo(gl,far){const key=far?'far':'all';let G=GLX.land[key];if(G)return G;
|
||||
const keep=far?new Set(LANDP_FAR):null,fan=[],sand=[],edge=[],SAND=glColor('#F8E6A8'),EDGE=glColor('#1E2640');
|
||||
COAST.forEach((ring,ri)=>{if(keep&&!keep.has(LANDP_ALL[ri]))return;const n=ring.length;if(n<3)return;
|
||||
// As smoothPath(): a quadratic curve from the middle of each side to the next, through the corner between them.
|
||||
const mid=(a,b)=>[(a[0]+b[0])/2,(a[1]+b[1])/2],P=[];let m=mid(ring[n-1],ring[0]);P.push(m);
|
||||
for(let i=0;i<n;i++){const c=ring[i],e=mid(c,ring[(i+1)%n]);for(let j=1;j<=4;j++){const t=j/4,u=1-t;P.push([u*u*m[0]+2*u*t*c[0]+t*t*e[0],u*u*m[1]+2*u*t*c[1]+t*t*e[1]]);}m=e;}
|
||||
/* The land, built once per level of detail (the far view leaves out the islets as LANDP_FAR does) and per zoom level
|
||||
lv (powers of 2): the fan for the fills, the coastlines as line segments (paintWorld()'s curves, four segments each)
|
||||
for the sand and the dark edge, and the hills. Zoomed out a coastline has far more points than pixels, and its
|
||||
vertices were most of the card's work: at level lv it is simplified so that no point moves more than COAST_TOL px at
|
||||
the level's zoom (Douglas-Peucker). Without lv, the whole coastline. COAST and onLand() are not touched. */
|
||||
const COAST_TOL=0.25,COASTP=[];
|
||||
// A coastline as paintWorld() draws it (smoothPath(): a quadratic curve from the middle of each side to the next,
|
||||
// through the corner between them), four segments per curve; the first point is repeated at the end.
|
||||
function coastPts(ri){let P=COASTP[ri];if(P)return P;const ring=COAST[ri],n=ring.length;P=[];
|
||||
const mid=(a,b)=>[(a[0]+b[0])/2,(a[1]+b[1])/2];let m=mid(ring[n-1],ring[0]);P.push(m);
|
||||
for(let i=0;i<n;i++){const c=ring[i],e=mid(c,ring[(i+1)%n]);for(let j=1;j<=4;j++){const t=j/4,u=1-t;P.push([u*u*m[0]+2*u*t*c[0]+t*t*e[0],u*u*m[1]+2*u*t*c[1]+t*t*e[1]]);}m=e;}
|
||||
return COASTP[ri]=P;}
|
||||
// The points of P to keep so that none of the others is further than tol from the line kept (Douglas-Peucker).
|
||||
function coastSimplify(P,tol){const n=P.length;if(n<4||!(tol>0))return P;const keep=new Uint8Array(n),st=[0,n-1],t2=tol*tol;keep[0]=keep[n-1]=1;
|
||||
while(st.length){const b=st.pop(),a=st.pop(),ax=P[a][0],ay=P[a][1],dx=P[b][0]-ax,dy=P[b][1]-ay,L=dx*dx+dy*dy||1e-12;let m=-1,md=t2;
|
||||
for(let i=a+1;i<b;i++){let t=((P[i][0]-ax)*dx+(P[i][1]-ay)*dy)/L;t=t<0?0:t>1?1:t;const ex=ax+t*dx-P[i][0],ey=ay+t*dy-P[i][1],d=ex*ex+ey*ey;if(d>md){md=d;m=i;}}
|
||||
if(m>=0){keep[m]=1;st.push(a,m,m,b);}}
|
||||
const o=[];for(let i=0;i<n;i++)if(keep[i])o.push(P[i]);return o;}
|
||||
// The zoom level the land is drawn at: 2^lv ≤ zoom < 2^(lv+1). Zooming in takes the finer level at once; zooming out
|
||||
// keeps the finer one (only more points, never less detail) until the zoom is 10 % under it, so a zoom that hovers
|
||||
// around a power of 2 does not switch back and forth.
|
||||
function coastLevel(z){const want=Math.floor(Math.log2(Math.max(z,1/64))),cur=GLX.coastLv;
|
||||
if(cur===undefined||want>cur||z<Math.pow(2,cur)/1.1)GLX.coastLv=want;return GLX.coastLv;}
|
||||
function glLandGeo(gl,far,lv){const key=(far?'far':'all')+(lv===undefined?'':'@'+lv);let G=GLX.land[key];if(G)return G;
|
||||
const keep=far?new Set(LANDP_FAR):null,tol=lv===undefined?0:COAST_TOL/Math.pow(2,lv),fan=[],sand=[],edge=[],SAND=glColor('#F8E6A8'),EDGE=glColor('#1E2640');
|
||||
COAST.forEach((ring,ri)=>{if(keep&&!keep.has(LANDP_ALL[ri]))return;if(ring.length<3)return;
|
||||
const P=coastSimplify(coastPts(ri),tol);if(P.length<4)return;
|
||||
for(let i=1;i+1<P.length;i++)fan.push(P[0][0],P[0][1],P[i][0],P[i][1],P[i+1][0],P[i+1][1]);
|
||||
// Round ends make the joins round, as lineJoin='round' does; both lines are opaque, so the overlaps do not show.
|
||||
for(let i=0;i+1<P.length;i++){glSeg(sand,P[i],P[i+1],0,10,0,LINE_ROUND,SAND);glSeg(edge,P[i],P[i+1],0,2.5,0,LINE_ROUND,EDGE);}});
|
||||
|
|
@ -45,7 +63,7 @@ function glLandFill(gl,G,ks,ox,oy,col){const P=GLX.fan;gl.enable(gl.STENCIL_TEST
|
|||
function glEllipses(gl,vao,n,ks,col){const P=GLX.ell;gl.useProgram(P.p);gl.bindVertexArray(vao);gl.uniform2f(P.u.uView,CW,CH);gl.uniform1f(P.u.uDpr,DPR);gl.uniform4fv(P.u.uCol,col);
|
||||
for(const k of ks){gl.uniform3f(P.u.uCam,cam.x-k*W,cam.y,cam.z);gl.drawArraysInstanced(gl.TRIANGLE_STRIP,0,4,n);}}
|
||||
// In paintWorld()'s order: the shadow (5, 7 px down and right), the sand, the grass, the hills, the coastline.
|
||||
function glLand(gl,ks){const G=glLandGeo(gl,lodFar());
|
||||
function glLand(gl,ks){const G=glLandGeo(gl,lodFar(),coastLevel(cam.z));
|
||||
glLandFill(gl,G,ks,5,7,LAND_SHADOW);
|
||||
glLines(gl,G.sand,G.nSeg,ks);
|
||||
glLandFill(gl,G,ks,0,0,LAND_GRASS);
|
||||
|
|
|
|||
76
tests/webgl-coast.test.js
Normal file
76
tests/webgl-coast.test.js
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
// The land on the card per zoom level (src/game/96-map/57-webgl-background.js): zoomed out, the coastlines are
|
||||
// simplified so that no point moves more than COAST_TOL px on screen at that level, which takes most of the card's
|
||||
// vertices away. The coastlines themselves (COAST, onLand()) and the 2D map stay as they were.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
|
||||
function open() {
|
||||
const h = load({ seed: 777 });
|
||||
h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`);
|
||||
return h;
|
||||
}
|
||||
|
||||
const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k;
|
||||
return (...a)=>{calls.push([k,...a]);return {};};}});
|
||||
const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');
|
||||
const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}});
|
||||
Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'});return gl;})()`;
|
||||
|
||||
test('a simplified coastline never strays more than the tolerance from the full one', () => {
|
||||
const { ev, errors } = open();
|
||||
const r = JSON.parse(ev(`(()=>{const out=[];let worst=0,rings=0,kept=0,all=0;
|
||||
for(const lv of [-2,-1,0,1,3]){const tol=COAST_TOL/Math.pow(2,lv);
|
||||
COAST.forEach((ring,ri)=>{if(ring.length<3)return;const P=coastPts(ri),Q=coastSimplify(P,tol),at=new Map(P.map((p,i)=>[p,i]));rings++;kept+=Q.length;all+=P.length;
|
||||
if(Q[0]!==P[0]||Q[Q.length-1]!==P[P.length-1])out.push('ends '+ri);
|
||||
for(let j=0;j+1<Q.length;j++){const a=at.get(Q[j]),b=at.get(Q[j+1]);if(!(b>a))out.push('order '+ri);
|
||||
const ax=P[a][0],ay=P[a][1],dx=P[b][0]-ax,dy=P[b][1]-ay,L=dx*dx+dy*dy||1e-12;
|
||||
for(let i=a+1;i<b;i++){let t=((P[i][0]-ax)*dx+(P[i][1]-ay)*dy)/L;t=Math.max(0,Math.min(1,t));const d=Math.hypot(ax+t*dx-P[i][0],ay+t*dy-P[i][1])/tol;if(d>worst)worst=d;}}});}
|
||||
return JSON.stringify({bad:out.slice(0,5),worst,rings,share:kept/all});})()`));
|
||||
assert.deepEqual(r.bad, [], 'each ring keeps its ends and its order');
|
||||
assert.ok(r.worst <= 1 + 1e-9, `no point further than the tolerance (worst ${r.worst.toFixed(3)} of it)`);
|
||||
assert.ok(r.rings > 50);
|
||||
assert.ok(r.share < 0.6, `points are left out (${(r.share * 100).toFixed(0)} % kept)`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('zoomed out the land has a few times fewer segments, and the closer the zoom the more it keeps', () => {
|
||||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
const r = JSON.parse(ev(`(()=>{const full=glLandGeo(GLX.gl,false),n=lv=>glLandGeo(GLX.gl,false,lv).nSeg;
|
||||
return JSON.stringify({full:full.nSeg,fullFan:full.nFan,l_1:n(-1),l0:n(0),l1:n(1),l3:n(3),far:glLandGeo(GLX.gl,true,-1).nSeg,once:glLandGeo(GLX.gl,false,0)===glLandGeo(GLX.gl,false,0),
|
||||
fan:glLandGeo(GLX.gl,false,-1).nFan});})()`));
|
||||
assert.ok(r.l_1 * 3 < r.full, `zoom 0.5–1: ${r.l_1} segments, ${r.full} in full`);
|
||||
assert.ok(r.l_1 < r.l0 && r.l0 < r.l1 && r.l1 <= r.l3 && r.l3 <= r.full, JSON.stringify(r));
|
||||
assert.ok(r.far < r.l_1, 'the far view still leaves out the islets');
|
||||
assert.ok(r.fan * 3 < r.fullFan, 'the fill’s fan shrinks as much');
|
||||
assert.equal(r.once, true, 'each level is built once');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the zoom level takes the finer level at once and keeps it a little while zooming out', () => {
|
||||
const { ev, errors } = open();
|
||||
const lv = JSON.parse(ev(`(()=>{delete GLX.coastLv;return JSON.stringify([1.5,2.1,1.95,1.85,1.8,0.9,0.95,0.4].map(coastLevel));})()`));
|
||||
assert.deepEqual(lv, [0, 1, 1, 1, 0, -1, -1, -2]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('each frame on the card fills the land from its zoom level’s geometry; the coastlines and the 2D map stay as they were', () => {
|
||||
const { ev, errors } = open();
|
||||
const coast = ev('JSON.stringify(COAST)');
|
||||
ev(STUB);
|
||||
const fans = JSON.parse(ev(`(()=>{const h=CITY[S.home];cam.x=h.x;cam.y=h.y;delete GLX.coastLv;const o=[];
|
||||
for(const z of [0.6,1.4,3.2]){cam.z=z;GLX.gl.calls.length=0;draw(1000);const want=glLandGeo(GLX.gl,lodFar(),coastLevel(z)).nFan;
|
||||
o.push(GLX.gl.calls.filter(c=>c[0]==='drawArrays'&&c[1]==='TRIANGLES').every(c=>c[3]===want));}return JSON.stringify(o);})()`));
|
||||
assert.deepEqual(fans, [true, true, true]);
|
||||
assert.equal(ev('JSON.stringify(COAST)'), coast, 'COAST is never changed (onLand() reads it)');
|
||||
let built = 0;
|
||||
ev(`mapGl(false);window.__lg=glLandGeo;glLandGeo=function(){__built++;return __lg.apply(this,arguments);};window.__built=0;cam.z=0.6;draw(1016);cam.z=3.2;draw(1032);`);
|
||||
built = ev('__built');
|
||||
assert.equal(built, 0, 'the 2D map does not use it');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -108,14 +108,15 @@ test('the land is geometry on the card: one fan per coastline, its outlines, its
|
|||
const pts=COAST.reduce((a,p)=>a+p.length,0);
|
||||
GLX.gl.calls.length=0;cam.z=1.4;draw(1000);
|
||||
const fans=GLX.gl.calls.filter(c=>c[0]==='drawArrays'&&c[1]==='TRIANGLES').map(c=>c[3]);
|
||||
return JSON.stringify({nFan:all.nFan,nSeg:all.nSeg,farSeg:far.nSeg,pts,hills:all.nHill,again:glLandGeo(GLX.gl,false)===all,fans,
|
||||
const lv=glLandGeo(GLX.gl,false,coastLevel(1.4));
|
||||
return JSON.stringify({nFan:all.nFan,nSeg:all.nSeg,farSeg:far.nSeg,pts,hills:all.nHill,again:glLandGeo(GLX.gl,false)===all,fans,lvFan:lv.nFan,
|
||||
wl:GLX.gl.calls.some(c=>c[0]==='texImage2D'&&c[6]===WL.cv)});})()`));
|
||||
assert.equal(r.nFan % 3, 0, 'whole triangles');
|
||||
assert.equal(r.nSeg, r.pts * 4, 'each curve of the coast in four segments');
|
||||
assert.ok(r.farSeg < r.nSeg, 'zoomed out, the islets are left out as in 2D');
|
||||
assert.equal(r.hills, ev('HILLS.length'));
|
||||
assert.ok(r.again, 'built once');
|
||||
assert.ok(r.fans.length >= 2 && r.fans.every(n => n === r.nFan), 'shadow and grass are filled each frame from the same fan');
|
||||
assert.ok(r.fans.length >= 2 && r.fans.every(n => n === r.lvFan), 'shadow and grass are filled each frame from the same fan (the zoom level’s)');
|
||||
assert.equal(r.wl, false, 'no picture of the land is uploaded');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue