mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-17 08:42:21 +00:00
Base map through the globe port
Cesium switches the map stacks through its globe port, as any renderer does, rather than through a map engine of its own. Every route keeps its behaviour: - Google 3D turned off is kept hidden, and shown again without loading it anew; the key route's tiles take clamped marks, as the token routes' do. - Esri goes to its deepest level (23); its "Map data not yet available" picture is a missing tile, so the parent's imagery stays. - Cesium ion's world imagery is Bing over HTTPS on any page, with ion's credits; a token ion refuses refuses the switch, as before. - Keyless terrain that does not answer is the flat ellipsoid, tried again behind it; world terrain asks ion first, as before. - window.__godsEyeView.tileset is the Cesium photoreal tileset.
This commit is contained in:
1 parent
65480f2604
commit
8ff9a1fa29
12 files changed
+496
-81
No files matched your search
@@ -25,7 +25,7 @@ export function createDefaultMapSources({
|
||||
id: hasIon ? 'world' : 'keyless',
|
||||
create: hasIon
|
||||
? (request) => engineOf().terrain.world(ionToken, request)
|
||||
: () => engineOf().terrain.keyless(),
|
||||
: (request) => engineOf().terrain.keyless(request),
|
||||
};
|
||||
return {
|
||||
defaultId: googleTileset ? 'photoreal' : 'esri-imagery',
|
||||
|
||||
+123
-12
@@ -16,6 +16,15 @@ import { findFrame, findGlobe, rendererOf } from '../render/rendererOf.js';
|
||||
import { ESRI_IMAGERY_CREDIT, ESRI_TILES } from './attribution.js';
|
||||
import { KEYLESS_TERRAIN_URL } from './keylessTerrain.js';
|
||||
|
||||
/** Esri World Imagery's deepest level (its tile info lists levels 0–23). */
|
||||
const ESRI_MAX_LEVEL = 23;
|
||||
/**
|
||||
* A tile Esri has no imagery for: it answers every such tile with this one
|
||||
* "Map data not yet available" picture, the same bytes each time.
|
||||
*/
|
||||
const ESRI_MISSING_TILE =
|
||||
'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/23/0/0';
|
||||
const OSM_MAX_LEVEL = 19;
|
||||
const OSM_TILES = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
|
||||
const OSM_CREDIT = '© OpenStreetMap contributors';
|
||||
/** Cesium ion's world imagery assets (`MAP_STACKS`' `style`). */
|
||||
@@ -30,6 +39,90 @@ const shownGlobes = new WeakMap();
|
||||
|
||||
const credit = (text) => ({ text });
|
||||
|
||||
/** Esri's "no imagery here" picture's bytes, once read; null if unread. */
|
||||
let esriMissing = null;
|
||||
|
||||
/** Read Esri's "no imagery here" picture, once; null while it cannot be. */
|
||||
function esriMissingTile() {
|
||||
esriMissing ??= fetch(ESRI_MISSING_TILE)
|
||||
.then((response) => (response.ok ? response.arrayBuffer() : null))
|
||||
.then((buffer) => (buffer ? new Uint8Array(buffer) : null))
|
||||
.catch(() => null)
|
||||
.then((bytes) => {
|
||||
// Not read: asked for again with the next tile.
|
||||
if (!bytes) esriMissing = null;
|
||||
return bytes;
|
||||
});
|
||||
return esriMissing;
|
||||
}
|
||||
|
||||
const sameBytes = (a, b) =>
|
||||
a.length === b.length && a.every((byte, i) => byte === b[i]);
|
||||
|
||||
/**
|
||||
* An Esri tile, fetched. Esri's "no imagery here" picture is a missing tile,
|
||||
* drawn from its parent, as Cesium's own Esri provider discards it; a
|
||||
* refused tile is a failed one, which counts toward the Esri source's
|
||||
* fallback to OSM.
|
||||
*/
|
||||
async function fetchEsriTile({ url, signal }) {
|
||||
const [response, missing] = await Promise.all([
|
||||
fetch(url, { signal }),
|
||||
esriMissingTile(),
|
||||
]);
|
||||
if (!response.ok) {
|
||||
const error = new Error(`Esri tile answered ${response.status}`);
|
||||
error.statusCode = response.status;
|
||||
throw error;
|
||||
}
|
||||
const bytes = await response.arrayBuffer();
|
||||
if (missing && sameBytes(new Uint8Array(bytes), missing))
|
||||
return { missing: true };
|
||||
const contentType = response.headers.get('content-type');
|
||||
return { bytes, ...(contentType ? { contentType } : {}) };
|
||||
}
|
||||
|
||||
/** Cesium World Terrain's ion asset. */
|
||||
const ION_WORLD_TERRAIN = 1;
|
||||
|
||||
/**
|
||||
* Ask Cesium ion for an asset's endpoint, as Cesium does before it draws
|
||||
* one: a token ion refuses, or no answer, refuses the switch with ion's
|
||||
* message, so the map stack stays where it was and says why.
|
||||
* @param {number} asset
|
||||
* @param {string} token
|
||||
* @param {AbortSignal} [signal]
|
||||
*/
|
||||
async function ionEndpoint(asset, token, signal) {
|
||||
const response = await fetch(
|
||||
`https://api.cesium.com/v1/assets/${asset}/endpoint?access_token=${encodeURIComponent(token)}`,
|
||||
{ signal },
|
||||
);
|
||||
const body = await response.json().catch(() => null);
|
||||
if (!response.ok)
|
||||
throw new Error(
|
||||
body?.message ||
|
||||
`Cesium ion answered ${response.status} for asset ${asset}`,
|
||||
);
|
||||
return body;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the keyless terrain answers: its `layer.json`, read as any
|
||||
* quantized-mesh terrain is read before its first tile.
|
||||
*/
|
||||
async function keylessTerrainAnswers(signal) {
|
||||
try {
|
||||
const response = await fetch(`${KEYLESS_TERRAIN_URL}/layer.json`, {
|
||||
signal,
|
||||
});
|
||||
return response.ok;
|
||||
} catch (error) {
|
||||
if (signal?.aborted) throw error;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a photoreal handle's base on or off. Turning it on can fail (the
|
||||
* port answers route `none`, or rejects): the handle is then off again, so
|
||||
@@ -123,7 +216,7 @@ export const globeMapEngine = Object.freeze({
|
||||
kind: 'xyz',
|
||||
url: OSM_TILES,
|
||||
tiling: 'webMercator',
|
||||
maxLevel: 19,
|
||||
maxLevel: OSM_MAX_LEVEL,
|
||||
credit: credit(OSM_CREDIT),
|
||||
}),
|
||||
esri: () =>
|
||||
@@ -131,12 +224,18 @@ export const globeMapEngine = Object.freeze({
|
||||
kind: 'xyz',
|
||||
url: ESRI_TILES,
|
||||
tiling: 'webMercator',
|
||||
maxLevel: 19,
|
||||
maxLevel: ESRI_MAX_LEVEL,
|
||||
fetchTile: fetchEsriTile,
|
||||
credit: credit(ESRI_IMAGERY_CREDIT),
|
||||
}),
|
||||
ion(style, accessToken) {
|
||||
if (!String(accessToken || '').trim())
|
||||
throw new Error('Ion imagery requires an explicit token');
|
||||
async ion(style, accessToken, { signal } = {}) {
|
||||
const token = String(accessToken || '').trim();
|
||||
if (!token) throw new Error('Ion imagery requires an explicit token');
|
||||
const endpoint = await ionEndpoint(style, token, signal);
|
||||
if (endpoint?.type !== 'IMAGERY' || endpoint.externalType !== 'BING')
|
||||
throw new Error(
|
||||
'Ion world imagery did not return a Bing imagery endpoint',
|
||||
);
|
||||
return Object.freeze({
|
||||
kind: 'world',
|
||||
worldStyle: WORLD_STYLES[style] ?? 'aerial',
|
||||
@@ -144,19 +243,31 @@ export const globeMapEngine = Object.freeze({
|
||||
},
|
||||
}),
|
||||
terrain: Object.freeze({
|
||||
world: async (accessToken) => {
|
||||
if (!String(accessToken || '').trim())
|
||||
world: async (accessToken, { signal } = {}) => {
|
||||
const token = String(accessToken || '').trim();
|
||||
if (!token)
|
||||
throw new Error('World terrain requires an explicit ion token');
|
||||
await ionEndpoint(ION_WORLD_TERRAIN, token, signal);
|
||||
return {
|
||||
provider: null,
|
||||
spec: { kind: 'world', requestVertexNormals: true },
|
||||
};
|
||||
},
|
||||
// Re:Earth's keyless terrain, as the Cesium map engine draws it.
|
||||
keyless: async () => ({
|
||||
provider: null,
|
||||
spec: { kind: 'quantizedMesh', url: KEYLESS_TERRAIN_URL },
|
||||
}),
|
||||
/**
|
||||
* Re:Earth's keyless terrain. While it does not answer, the ellipsoid
|
||||
* stands in as a fallback the map stack tries the terrain again behind.
|
||||
*/
|
||||
keyless: async ({ signal } = {}) => {
|
||||
if (await keylessTerrainAnswers(signal))
|
||||
return {
|
||||
provider: null,
|
||||
spec: { kind: 'quantizedMesh', url: KEYLESS_TERRAIN_URL },
|
||||
};
|
||||
console.warn(
|
||||
'[MapStack] Re:Earth terrain unavailable, falling back to flat ellipsoid terrain',
|
||||
);
|
||||
return { provider: null, spec: { kind: 'ellipsoid' }, fallback: true };
|
||||
},
|
||||
}),
|
||||
createImageryLayer: (spec) => ({ spec, layer: null }),
|
||||
requestRender(host) {
|
||||
|
||||
@@ -70,6 +70,116 @@ test('the globe is shown and hidden through the port, read back without globe vi
|
||||
assert.equal(engine.globeShown(visible.host), false);
|
||||
});
|
||||
|
||||
/** Answer `fetch` from `answers` (url to response) while `run` runs. */
|
||||
async function withFetch(answers, run) {
|
||||
const real = globalThis.fetch;
|
||||
const asked = [];
|
||||
globalThis.fetch = async (url) => {
|
||||
asked.push(String(url));
|
||||
const answer = answers(String(url));
|
||||
if (answer instanceof Error) throw answer;
|
||||
return answer;
|
||||
};
|
||||
try {
|
||||
return await run(asked);
|
||||
} finally {
|
||||
globalThis.fetch = real;
|
||||
}
|
||||
}
|
||||
|
||||
const bytesResponse = (bytes, status = 200) => ({
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
headers: { get: (name) => (name === 'content-type' ? 'image/jpeg' : null) },
|
||||
arrayBuffer: async () => new Uint8Array(bytes).buffer,
|
||||
json: async () => JSON.parse(new TextDecoder().decode(new Uint8Array(bytes))),
|
||||
});
|
||||
|
||||
const jsonResponse = (body, status = 200) =>
|
||||
bytesResponse([...new TextEncoder().encode(JSON.stringify(body))], status);
|
||||
|
||||
/** Cesium ion's endpoints as a valid token is answered. */
|
||||
const ionAnswers = (url) =>
|
||||
/assets\/1\/endpoint/.test(url)
|
||||
? jsonResponse({ type: 'TERRAIN', url: 'https://assets.ion.invalid/1/' })
|
||||
: jsonResponse({ type: 'IMAGERY', externalType: 'BING', options: {} });
|
||||
|
||||
// Nothing here reaches the network: ion and the keyless terrain answer,
|
||||
// offline.
|
||||
globalThis.fetch = async (url) =>
|
||||
String(url).startsWith('https://api.cesium.com/')
|
||||
? ionAnswers(String(url))
|
||||
: bytesResponse([1]);
|
||||
|
||||
test('Esri goes to its deepest level, its no-imagery picture drawn from the parent', async () => {
|
||||
const spec = engine.imagery.esri();
|
||||
assert.equal(spec.maxLevel, 23);
|
||||
const placeholder = [9, 9, 9];
|
||||
await withFetch(
|
||||
(url) =>
|
||||
url.endsWith('/tile/23/0/0')
|
||||
? bytesResponse(placeholder)
|
||||
: url.endsWith('/5/1/2')
|
||||
? bytesResponse([1, 2, 3, 4])
|
||||
: url.endsWith('/22/7/7')
|
||||
? bytesResponse(placeholder)
|
||||
: bytesResponse([], 503),
|
||||
async (asked) => {
|
||||
const signal = new AbortController().signal;
|
||||
const tile = await spec.fetchTile({ url: `${'x'}/5/1/2`, signal });
|
||||
assert.deepEqual([...new Uint8Array(tile.bytes)], [1, 2, 3, 4]);
|
||||
assert.equal(tile.contentType, 'image/jpeg');
|
||||
assert.deepEqual(
|
||||
await spec.fetchTile({ url: 'x/22/7/7', signal }),
|
||||
{ missing: true },
|
||||
'the no-imagery picture is a missing tile',
|
||||
);
|
||||
await assert.rejects(
|
||||
spec.fetchTile({ url: 'x/1/1/1', signal }),
|
||||
(error) => error.statusCode === 503,
|
||||
'a refused tile is a failed one',
|
||||
);
|
||||
assert.equal(
|
||||
asked.filter((url) => url.endsWith('/tile/23/0/0')).length,
|
||||
1,
|
||||
'the no-imagery picture is read once',
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('keyless terrain that does not answer is the flat ellipsoid, marked a fallback', async () => {
|
||||
await withFetch(
|
||||
() => new TypeError('offline'),
|
||||
async (asked) => {
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
assert.deepEqual(await engine.terrain.keyless(), {
|
||||
provider: null,
|
||||
spec: { kind: 'ellipsoid' },
|
||||
fallback: true,
|
||||
});
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
}
|
||||
assert.deepEqual(asked, [`${KEYLESS_TERRAIN_URL}/layer.json`]);
|
||||
},
|
||||
);
|
||||
await withFetch(
|
||||
() => bytesResponse([], 503),
|
||||
async () => {
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
assert.equal((await engine.terrain.keyless()).fallback, true);
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('terrain is the port’s world terrain, or the keyless quantized mesh without a token', async () => {
|
||||
const { host, renderer } = scene(['terrain']);
|
||||
await assert.rejects(engine.terrain.world(''), /ion token/);
|
||||
@@ -78,20 +188,66 @@ test('terrain is the port’s world terrain, or the keyless quantized mesh witho
|
||||
assert.deepEqual(calls(renderer, 'setTerrain').at(-1).args, [
|
||||
{ kind: 'world', requestVertexNormals: true },
|
||||
]);
|
||||
engine.applyTerrain(host, await engine.terrain.keyless());
|
||||
engine.applyTerrain(
|
||||
host,
|
||||
await withFetch(
|
||||
() => bytesResponse([1]),
|
||||
() => engine.terrain.keyless(),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(calls(renderer, 'setTerrain').at(-1).args, [
|
||||
{ kind: 'quantizedMesh', url: KEYLESS_TERRAIN_URL },
|
||||
]);
|
||||
assert.throws(() => engine.imagery.ion(2, ''), /token/);
|
||||
assert.deepEqual(engine.imagery.ion(3, 'token'), {
|
||||
await assert.rejects(engine.imagery.ion(2, ''), /token/);
|
||||
assert.deepEqual(await engine.imagery.ion(3, 'token'), {
|
||||
kind: 'world',
|
||||
worldStyle: 'aerialLabels',
|
||||
});
|
||||
});
|
||||
|
||||
test('a token ion refuses refuses the switch with ion’s message, as Cesium’s own route did', async () => {
|
||||
await withFetch(
|
||||
() =>
|
||||
jsonResponse(
|
||||
{ code: 'InvalidCredentials', message: 'Invalid access token' },
|
||||
401,
|
||||
),
|
||||
async (asked) => {
|
||||
await assert.rejects(
|
||||
engine.imagery.ion(2, 'bad'),
|
||||
/Invalid access token/,
|
||||
);
|
||||
await assert.rejects(engine.terrain.world('bad'), /Invalid access token/);
|
||||
assert.match(asked[0], /\/v1\/assets\/2\/endpoint\?access_token=bad$/);
|
||||
assert.match(asked[1], /\/v1\/assets\/1\/endpoint\?access_token=bad$/);
|
||||
},
|
||||
);
|
||||
await withFetch(
|
||||
() => jsonResponse({ type: 'IMAGERY', externalType: 'GOOGLE_2D_MAPS' }),
|
||||
async () => {
|
||||
await assert.rejects(
|
||||
engine.imagery.ion(2, 'token'),
|
||||
/Bing imagery endpoint/,
|
||||
);
|
||||
},
|
||||
);
|
||||
await withFetch(
|
||||
() => new TypeError('offline'),
|
||||
async () => {
|
||||
await assert.rejects(engine.terrain.world('token'), /offline/);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('where the renderer draws no terrain the ellipsoid stays', async () => {
|
||||
const { host, renderer } = scene([]);
|
||||
engine.applyTerrain(host, await engine.terrain.keyless());
|
||||
engine.applyTerrain(
|
||||
host,
|
||||
await withFetch(
|
||||
() => bytesResponse([1]),
|
||||
() => engine.terrain.keyless(),
|
||||
),
|
||||
);
|
||||
assert.deepEqual(calls(renderer, 'setTerrain').at(-1).args, [null]);
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user