Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactored library to support custom web workers #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions .gitmodules

This file was deleted.

102 changes: 102 additions & 0 deletions examples/worker/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import "core-js/stable";
import "regenerator-runtime/runtime";
import "cesiumSource/Widgets/widgets.css";
import "./main.css";
const Cesium = require("cesiumSource/Cesium");
// Import @types/cesium to use along with CesiumJS
import { Viewer, Ion, IonResource, createWorldTerrain } from "cesium";
import { MartiniTerrainProvider } from "lib/terrain-provider";
import { DefaultHeightmapResource } from "lib/resources/heightmap-resource";
import { WorkerFarmTerrainDecoder } from "lib/worker/decoder";
import TerrariumWorker from "./mapzen.worker";

// Mapzen API discontinued, alternate source required
const terrainResource = new DefaultHeightmapResource({
//url: "https://tile.mapzen.com/mapzen/terrain/v1/terrarium/{z}/{x}/{y}.png?api_key=XXX",
//url: "http://localhost:8080/public/terrain1/{z}/{x}/{reverseY}.png",
url: "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png",
skipOddLevels: false,
maxZoom: 15,
});

// Terrarium format utilises a different encoding scheme to Mapbox Terrain-RGB
// @ts-ignore
const terrainDecoder = new WorkerFarmTerrainDecoder({
worker: new TerrariumWorker()
});

// Construct terrain provider with Mapzen datasource and custom RGB decoding
// @ts-ignore
const terrainProvider = new MartiniTerrainProvider({
resource: terrainResource,
decoder: terrainDecoder,
});

let satellite = new Cesium.MapboxImageryProvider({
mapId: "mapbox.satellite",
maximumLevel: 19,
accessToken: process.env.MAPBOX_API_TOKEN,
});

var opts = {
terrainProvider, //: createWorldTerrain(),
// imageryProvider: Cesium.createWorldImagery({
// style: Cesium.IonWorldImageryStyle.AERIAL,
// }),
// @ts-ignore
skyBox: false as false,
baseLayerPicker: false,
geocoder: false,
skyAtmosphere: false as false,
animation: false,
timeline: false,
// Makes cesium not render high fps all the time
requestRenderMode: true,
// Use full scene buffer (respecting pixel ratio) if this is false
useBrowserRecommendedResolution: false,
// We have a bug in the tile bounding box calculation somewhere.
terrainExaggeration: 1.0,
imageryProvider: satellite,
};

const domID = "cesium-container";
const g = document.createElement("div");
g.id = domID;
document.body.appendChild(g);

var clat = -21.133786;
var clon = 14.5481193;

const rect = Cesium.Rectangle.fromDegrees(
clon - 0.01,
clat - 0.01,
clon + 0.01,
clat + 0.01
);
//Cesium.Camera.DEFAULT_VIEW_RECTANGLE = rect;
//Cesium.Camera.DEFAULT_VIEW_FACTOR = 0.005;
//Cesium.Camera.DEFAULT_VIEW_OFFSET = new Cesium.HeadingPitchRange(0, Cesium.Math.toRadians(-10), 1)

var viewer = new Cesium.Viewer(domID, opts);
// Quadtree props: don't preload ancestors

//viewer.scene.globe.baseColor = Cesium.Color.AQUAMARINE
// @ts-ignore
//viewer.scene.globe._surface._tileProvider._debug.wireframe = true
// @ts-ignore
viewer.extend(Cesium.viewerCesiumInspectorMixin);
viewer.scene.debugShowFramesPerSecond = true;

var extent = Cesium.Cartesian3.fromDegrees(clon, clat - 0.3, 8000);
viewer.camera.setView({
destination: extent,
orientation: {
heading: Cesium.Math.toRadians(0), // east, default value is 0.0 (north)
pitch: Cesium.Math.toRadians(-15), // default value (looking down)
roll: 0.0, // default value
},
});

//viewer.resolutionScale = 2
//viewer.scene.globe.enableLighting = true
//viewer.canvas.style.imageRendering = false
11 changes: 11 additions & 0 deletions examples/worker/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
body,
#cesium-container {
width: 100vw;
height: 100vh;
margin: 0;
padding: 0;
}

.cesium-cesiumInspector {
transform: translate(0, 70px);
}
54 changes: 54 additions & 0 deletions examples/worker/mapzen.worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import {
rgbTerrainToGrid,
createQuantizedMeshData,
} from "lib/worker/worker-util";
import ndarray from "ndarray";
import Martini from "@mapbox/martini";

const ctx: Worker = self as any;

let martini = null;

const terrariumDecodeRgb = (r, g, b, a) => (r * 256) + g + (b / 256) - 32768;

function decodeTerrain(parameters) {
const { imageData, tileSize = 256, errorLevel } = parameters;

const pixels = ndarray(
new Uint8Array(imageData),
[tileSize, tileSize, 4],
[4, 4 * tileSize, 1],
0
);

// Tile size must be maintained through the life of the worker
martini = martini ?? new Martini(tileSize + 1);

const terrain = rgbTerrainToGrid(pixels, terrariumDecodeRgb);

const tile = martini.createTile(terrain);

// get a mesh (vertices and triangles indices) for a 10m error
const mesh = tile.getMesh(errorLevel, parameters.maxLength);
return createQuantizedMeshData(tile, mesh, tileSize);
}

ctx.addEventListener("message", (msg) => {
const { id, payload } = msg.data;
if (id == null) return;
let objects = [];
let res = null;
try {
res = decodeTerrain(payload);
objects.push(res.indices.buffer);
objects.push(res.quantizedVertices.buffer);
ctx.postMessage({ id, payload: res }, objects);
} catch (err) {
ctx.postMessage({ id, err: err.toString() });
} finally {
res = null;
objects = null;
}
});

export default null as any;
1 change: 0 additions & 1 deletion martini
Submodule martini deleted from b90ba2
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@
"watch": "rollup -c -w",
"dev": "npm run watch & webpack-dev-server examples/simple/index.ts",
"dev:react": "npm run watch & webpack-dev-server examples/react/index.ts",
"dev:worker": "npm run watch & webpack-dev-server examples/worker/index.ts",
"test": "echo \"Error: no test specified\" && exit 1",
"prepublish": "npm run build"
},
"author": "",
"license": "ISC",
"dependencies": {
"@mapbox/martini": "^0.2.0",
"@mapbox/martini": "git://github.com/davenquinn/martini.git",
"@types/ndarray": "^1.0.7",
"axios": "^0.21.1",
"cesium": "^1.81.0",
Expand Down Expand Up @@ -54,6 +55,7 @@
"typescript": "^3.8.3",
"webpack": "^4.42.1",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
"webpack-dev-server": "^3.10.3",
"worker-loader": "^3.0.8"
}
}
11 changes: 2 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,3 @@
import DefaultHeightmapResource from './heightmap-resource'
import MapboxTerrainResource from './mapbox-resource'
import MapboxTerrainProvider, { MartiniTerrainProvider } from './terrain-provider'
import MapboxTerrainProvider from './mapbox-terrain-provider'

export default MapboxTerrainProvider
export {
MartiniTerrainProvider,
DefaultHeightmapResource,
MapboxTerrainResource
}
export default MapboxTerrainProvider;
22 changes: 22 additions & 0 deletions src/mapbox-terrain-provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { TerrainProvider } from "cesium";
import MapboxTerrainResource, { MapboxTerrainResourceOpts } from "./resources/mapbox-resource";
import { MartiniTerrainOpts, MartiniTerrainProvider } from './terrain-provider';
import WorkerFarmTerrainDecoder from "./worker/decoder";
import MapboxTerrainWorker from "web-worker:./worker/mapbox-worker";

type MapboxTerrainOpts = Omit<MartiniTerrainOpts, 'resource'> & MapboxTerrainResourceOpts;

export default class MapboxTerrainProvider extends MartiniTerrainProvider<TerrainProvider> {
constructor(opts: MapboxTerrainOpts = {}) {
const resource = new MapboxTerrainResource(opts);
const decoder = new WorkerFarmTerrainDecoder({
worker: new MapboxTerrainWorker()
});

super({
...opts,
resource,
decoder,
});
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Resource } from "cesium";
import { TileCoordinates } from "./terrain-provider";
import { Resource, Credit } from "cesium";
import { TileCoordinates } from "../terrain-provider";

export interface HeightmapResource {
credit?: Credit;
tileSize: number;
getTilePixels: (coords: TileCoordinates) => Promise<ImageData>;
getTileDataAvailable: (coords: TileCoordinates) => boolean;
Expand All @@ -12,7 +13,7 @@ interface CanvasRef {
context: CanvasRenderingContext2D;
}

const loadImage: (url: string) => Promise<HTMLImageElement> = (url) =>
export const loadImage: (url: string) => Promise<HTMLImageElement> = (url) =>
new Promise((resolve, reject) => {
const img = new Image();
img.addEventListener("load", () => resolve(img));
Expand Down
3 changes: 2 additions & 1 deletion src/mapbox-resource.ts → src/resources/mapbox-resource.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Resource } from "cesium";
import Credit from "cesium/Source/Core/Credit";
import { DefaultHeightmapResource, DefaultHeightmapResourceOpts } from "./heightmap-resource";
import { TileCoordinates } from "./terrain-provider";

export enum ImageFormat {
WEBP = "webp",
Expand All @@ -16,6 +16,7 @@ export type MapboxTerrainResourceOpts = {

export class MapboxTerrainResource extends DefaultHeightmapResource {
resource: Resource = null;
credit = new Credit("Mapbox");

constructor(opts: MapboxTerrainResourceOpts = {}) {
super(opts);
Expand Down
Loading