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

RD-459_reimplement-handling-webgl-context-loss #146

Open
wants to merge 4 commits into
base: v3.0.0
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
158 changes: 158 additions & 0 deletions demos/handling-webgl-errors.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
<html>

<head>
<title>MapTiler JS SDK example</title>
<style>
html {
height: 100%;
font-family: sans-serif;
font-size: 13px;
}

body {
height: 100%;
margin: 0;
display: grid;
grid-template: 1fr 1fr / 1fr 1fr;
gap: 16px;
box-sizing: border-box;
padding: 16px;
}

.map {
display: flex;
justify-content: center;
align-items: center;
box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.5);
}

#style-picker-container {
position: absolute;
z-index: 2;
margin: 10px;
}
</style>

<link rel="stylesheet" href="../build/maptiler-sdk.css">
</head>

<body>
<script src="../build/maptiler-sdk.umd.min.js"></script>

<script>
function getRandomMapStyle() {
const styles = Object.keys(maptilersdk.MapStyle);
const style = maptilersdk.MapStyle[styles[Math.floor(Math.random() * styles.length)]];
const variants = Object.keys(style.variants);
const variant = style[variants[Math.floor(Math.random() * variants.length)]];
return variant;
}

function createMap() {
const element = document.createElement("div");
element.className = "map";
document.body.appendChild(element);

const map = new maptilersdk.Map({
container: element,
style: getRandomMapStyle(),
hash: false,
geolocate: true,
terrain: true,
scaleControl: true,
fullscreenControl: true,
terrainControl: true,
});

return map;
}
</script>

<script>
maptilersdk.config.apiKey = "YOUR_API_KEY";

/*
* The mapLeftTop will lose the WebGL context because it is removed
* so the event will not be called.
*/
const mapLeftTop = createMap();

mapLeftTop.on("webglcontextlost", () => {
console.log("webglcontextlost", mapLeftTop); // Should not be called
});

mapLeftTop.on("load", () => {
setTimeout(() => {
mapLeftTop.remove();
mapLeftTop.getContainer().innerHTML = "Map removed successfully 🎉";
}, 1000);
});
/* *** */

/*
* The mapRightTop will lose the WebGL context and default warning will be displayed.
*/
const mapRightTop = createMap();

mapRightTop.on("webglcontextlost", () => {
maptilersdk.displayWebGLContextLostWarning(mapRightTop);
});

mapRightTop.on("load", () => {
setTimeout(() => {
mapRightTop.getCanvas().getContext("webgl2").getExtension("WEBGL_lose_context").loseContext();
}, 1000);
});
/* *** */

/*
* The mapLeftBottom will lose the WebGL context and custom warning will be displayed.
*/
const mapLeftBottom = createMap();

mapLeftBottom.on("webglcontextlost", () => {
const element = document.createElement("div");
element.style.position = "absolute";
element.style.top = "0";
element.style.left = "0";
element.style.right = "0";
element.style.bottom = "0";
element.style.margin = "auto";
element.style.height = "48px";
element.style.width = "256px";
element.style.display = "flex";
element.style.justifyContent = "center";
element.style.alignItems = "center";
element.style.transform = "rotate(-45deg)";
element.style.background = "peachpuff";
element.innerHTML = "WebGL context lost custom warning.";

mapLeftBottom.getContainer().appendChild(element);
});

mapLeftBottom.on("load", () => {
setTimeout(() => {
mapLeftBottom.getCanvas().getContext("webgl2").getExtension("WEBGL_lose_context").loseContext();
}, 1000);
});
/* *** */

/*
* The mapRightBottom will lose the WebGL context and the map will be recreated.
*/
const mapRightBottom = createMap();

mapRightBottom.on("webglContextLost", () => {
mapRightBottom.recreate();
});

mapRightBottom.on("load", () => {
setTimeout(() => {
mapRightBottom.getCanvas().getContext("webgl2").getExtension("WEBGL_lose_context").loseContext();
}, 1000);
});
/* *** */
</script>
</body>

</html>
42 changes: 37 additions & 5 deletions src/Map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import {
combineTransformRequest,
computeLabelsLocalizationMetrics,
displayNoWebGlWarning,
displayWebGLContextLostWarning,
replaceLanguage,
} from "./tools";
import { getBrowserLanguage, Language, type LanguageInfo } from "./language";
Expand Down Expand Up @@ -206,6 +205,7 @@ export type MapOptions = Omit<MapOptionsML, "style" | "maplibreLogo"> & {
// biome-ignore lint/suspicious/noShadowRestrictedNames: we want to keep consitency with MapLibre
export class Map extends maplibregl.Map {
public readonly telemetry: Telemetry;
private options: MapOptions;
private isTerrainEnabled = false;
private terrainExaggeration = 1;
private primaryLanguage: LanguageInfo;
Expand Down Expand Up @@ -272,6 +272,9 @@ export class Map extends maplibregl.Map {
// biome-ignore lint/performance/noDelete: <explanation>
delete superOptions.style;
super(superOptions);

this.options = options;

this.setStyle(style);

if (requiresUrlMonitoring) {
Expand Down Expand Up @@ -687,16 +690,45 @@ export class Map extends maplibregl.Map {

// Display a message if WebGL context is lost
this.once("load", () => {
this.getCanvas().addEventListener("webglcontextlost", (e) => {
console.warn(e);
displayWebGLContextLostWarning(options.container);
this.fire("webglContextLost", { error: e });
this.getCanvas().addEventListener("webglcontextlost", (event) => {
if (this._removed === true) {
/**
* https://github.com/maplibre/maplibre-gl-js/blob/main/src/ui/map.ts#L3334
*/
console.warn("[webglcontextlost]", "WebGL context lost after map removal. This is harmless.");
return;
}

console.warn("[webglcontextlost]", "Unexpected loss of WebGL context!");

this.fire("webglContextLost", event);
});
});

this.telemetry = new Telemetry(this);
}

/**
* Recreates the map instance with the same options.
* Useful for WebGL context loss.
*/
public recreate() {
const cameraOptions: maplibregl.CameraOptions = {
center: this.getCenter(),
zoom: this.getZoom(),
bearing: this.getBearing(),
pitch: this.getPitch(),
};

this.remove();

Object.assign(this, new Map({ ...this.options }));

this.once("load", () => {
this.jumpTo(cameraOptions);
});
}

/**
* Set the duration (millisec) of the terrain animation for growing or flattening.
* Must be positive. (Built-in default: `1000` milliseconds)
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ export {
getLanguageInfoFromKey,
} from "@maptiler/client";

export { getWebGLSupportError } from "./tools";
export { getWebGLSupportError, displayWebGLContextLostWarning } from "./tools";
export { config, SdkConfig } from "./config";
export * from "./language";
export { type Unit } from "./unit";
Expand Down
21 changes: 4 additions & 17 deletions src/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,28 +204,15 @@ export function displayNoWebGlWarning(container: HTMLElement | string) {
}

/**
* Display an error message in the Map div if WebGL2 is not supported
* Display a warning message in the Map div if the WebGL context was lost
*/
export function displayWebGLContextLostWarning(container: HTMLElement | string) {
export function displayWebGLContextLostWarning(map: MapSDK) {
const webglError = "The WebGL context was lost.";

let actualContainer: HTMLElement | null = null;

if (typeof container === "string") {
actualContainer = document.getElementById(container);
} else if (container instanceof HTMLElement) {
actualContainer = container;
}

if (!actualContainer) {
throw new Error("The Map container must be provided.");
}

const container: HTMLElement = map.getContainer();
const errorMessageDiv = document.createElement("div");
errorMessageDiv.innerHTML = webglError;
errorMessageDiv.classList.add("webgl-warning-div");
actualContainer.appendChild(errorMessageDiv);
// throw new Error(webglError);
container.appendChild(errorMessageDiv);
}

/**
Expand Down
Loading