maplibre-gl
Version:
BSD licensed community fork of mapbox-gl, a WebGL interactive maps library
28,832 lines • 1.18 MB
JavaScript
/**
* MapLibre GL JS
* @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v6.5.0/LICENSE.txt
*/
import { $ as tileCoordinatesToMercatorCoordinates, $n as deepEqual, $r as mul, $t as TRANSITION_SUFFIX, A as evaluateSizeForFeature, Ai as perspective, An as getVideo, Ar as remapSaturate, At as toEvaluationFeature, Bi as invert, Br as wrap, Bt as SegmentVector, C as isCustomStyleLayer, Ci as equals, Cn as Event, Cr as nextPowerOfTwo, Ct as HEATMAP_FULL_RENDER_FBO_KEY, D as SymbolBucket, Di as invert$1, Dn as getArrayBuffer, Dr as radiansToDegrees, Dt as RGBAImage, E as isSymbolStyleLayer, Ei as identity, En as GLOBAL_DISPATCHER_ID, Er as pointPlaneSignedDistance, Et as AlphaImage, F as ImagePosition, Fi as translate, Fn as removeProtocol, Fr as subscribe, Ft as Uniform4f, G as isFillExtrusionStyleLayer, Gn as bezier, Gr as length, Gt as PosArray, H as isLineStyleLayer, Hi as isOffscreenCanvasDistorted, Hn as angleToRotateBetweenVectors2D, Hr as pixelsToTileUnits, Ht as CollisionCircleLayoutArray, I as potpack, Ii as create$4, In as config, Ir as threePlaneIntersection, It as UniformColor, J as cameraDirectionFromPitchBearing, Jn as createIdentityMat4f32, Jr as zero, Jt as TriangleIndexArray, Kn as clamp, Kr as scale$1, Kt as QuadTriangleArray, L as isStyleImageWebGLData, Li as fromRotation, Ln as AbortError, Lr as translatePosition, Lt as UniformColorArray, Mi as rotateY$1, Mn as sameOrigin, Mr as rollPitchBearingToQuat, Mt as Uniform1i, N as getAnchorAlignment, Ni as rotateZ, Nn as addProtocol, Nr as scaleZoom, Nt as Uniform2f, O as addDynamicAttributes, Oi as multiply, On as getJSON, Or as rayPlaneIntersection, Ot as isCircleStyleLayer, Pi as scale, Pn as getProtocol, Pr as sphericalToCartesian, Pt as Uniform3f, Q as projectToWorldCoordinates, Qn as createVec4f64, Qr as slerp, Qt as Properties, R as renderStyleImage, Ri as create$2, Rn as isAbortError, Rr as uniqueId, Rt as UniformFloatArray, S as createStyleLayer, Si as create$1, Sn as ErrorEvent, Sr as mod, St as isHillshadeStyleLayer, T as isBackgroundStyleLayer, Ti as fromScaling, Tn as AJAXError, Tr as pick, Tt as renderColorRamp, Ui as offscreenCanvasSupported, Un as arrayBufferToImage, Ur as EXTENT, Ut as LineStripIndexArray, V as collisionCircleLayout, Vi as rotate, Vn as MAX_VALID_LATITUDE, Vr as zoomScale, Vt as CollisionBoxArray, Wi as Point, Wn as arrayBufferToImageBitmap, Wr as create$3, Wt as Pos3dArray, X as getMercatorHorizon, Xn as createMat4f64, Xr as fromValues, Xt as isRasterStyleLayer, Y as cameraMercatorCoordinateFromCenterAndRotation, Yn as createIdentityMat4f64, Yr as fromEuler, Yt as createLayout, Z as maxMercatorHorizonAngle, Zn as createVec3f64, Zr as multiply$1, Zt as DataConstantProperty, _ as UnwrappedTileID, _i as transformMat4$1, _n as emptyStyle, _r as isTouchableEvent, _t as SubdivisionGranularityExpression, a as clipLine, ai as dot, ar as evaluateZoomSnap, at as mercatorXfromLng, b as isInBoundsForZoomLngLat, bi as clone$1, bn as interpolateFactory, br as lerp, ci as negate, cn as validateAndEmit, cr as findLineIntersection, ct as LngLat, di as rotateY, dn as Color, dr as getEdgeTiles, dt as EXTENT_BOUNDS, ei as scale$3, en as Transitionable, er as defaultEasing, et as unprojectFromWorldCoordinates, f as GEOJSON_TILE_LAYER_NAME, fi as rotateZ$1, fn as ProjectionDefinition, ft as Bounds, g as OverscaledTileID, gi as transformMat3, gn as diff, gr as isSafari, gt as SOUTH_POLE_Y, h as CanonicalTileID, hi as sub, hn as derefLayers, hr as isPointableEvent, ht as NORTH_POLE_Y, ii as cross, in as ZoomHistory, ir as ensureError, it as lngFromMercatorX, j as evaluateSizeForZoom, ji as rotateX, jn as makeRequest, jr as rollPitchBearingEqual, jt as Uniform1f, k as getOverlapMode, ki as ortho, kn as getReferrer, kr as readImageUsingVideoFrame, kt as polygonIntersectsPolygon, li as normalize, ln as validateStyle, lr as getAABB, lt as earthRadius, mi as scaleAndAdd, mr as isImageBitmap, ni as add, nr as differenceOfAnglesDegrees, nt as altitudeFromMercatorZ, oi as len, on as SPEC_SOURCE_TYPES, or as extend, ot as mercatorYfromLat, pi as scale$2, pn as ValidationError, pr as getRollPitchBearing, pt as isFillStyleLayer, q as calculateTileMatrix, qn as clone$2, qr as sqrLen, qt as RasterBoundsArray, r as TextAnchorEnum, ri as clone, rn as codePointUsesLocalIdeographFontFamily, rr as distanceOfAnglesRadians, rt as latFromMercatorY, s as TileCache, si as length$1, sn as emitValidationErrors, sr as filterObject, st as mercatorZfromAltitude, t as getAnchorJustification, ti as transformMat4, tn as EvaluationParameters, tr as degreesToRadians, tt as MercatorCoordinate, u as GeoJSONFeature, ui as rotateX$1, un as validateStyleAndEmit, ur as getAngleDelta, v as calculateTileKey, vi as transformQuat, vn as featureFilter, vr as isTouchableOrPointableType, vt as SubdivisionGranularitySetting, w as validateCustomStyleLayer, wi as exactEquals, wn as Evented, wr as parseCacheControl, wt as isHeatmapStyleLayer, x as Actor, xi as copy, xn as latest, xr as mapObject, xt as Texture, y as compareTileId, yi as zero$1, yr as isWorker, yt as isColorReliefStyleLayer, z as parseGlyphPbf, zi as determinant, zn as throwIfAborted, zr as warnOnce, zt as UniformMatrix4f } from "./maplibre-gl-shared-dev.mjs";
//#region package.json
var version$2 = "6.5.0";
//#endregion
//#region src/util/browser.ts
let linkEl;
let reducedMotionQuery;
let reducedMotionOverride;
/** */
const browser = {
/**
* Schedules a callback to be invoked on the next animation frame.
* @param abortController - Controller to abort the scheduled frame.
* @param fn - Callback to invoke with the paint start timestamp.
* @param reject - Callback to invoke if the frame is aborted.
* @param targetWindow - Optional window to use for requestAnimationFrame.
* When the map is rendered in a popup window or iframe, pass the owning
* window to ensure animation frames continue even when the main window
* is not focused.
*/
frame(abortController, fn, reject, targetWindow) {
const win = targetWindow || window;
const frameId = win.requestAnimationFrame((paintStartTimestamp) => {
unsubscribe();
fn(paintStartTimestamp);
});
const { unsubscribe } = subscribe(abortController.signal, "abort", () => {
unsubscribe();
win.cancelAnimationFrame(frameId);
reject(new AbortError(abortController.signal.reason));
}, false);
},
/**
* Returns a promise that resolves on the next animation frame.
* @param abortController - Controller to abort the scheduled frame.
* @param targetWindow - Optional window to use for requestAnimationFrame.
* @see {@link browser.frame}
*/
frameAsync(abortController, targetWindow) {
return new Promise((resolve, reject) => {
this.frame(abortController, resolve, reject, targetWindow);
});
},
getImageData(img, padding = 0) {
return this.getImageCanvasContext(img).getImageData(-padding, -padding, img.width + 2 * padding, img.height + 2 * padding);
},
getImageCanvasContext(img) {
const canvas = window.document.createElement("canvas");
const context = canvas.getContext("2d", { willReadFrequently: true });
if (!context) throw new Error("failed to create canvas 2d context");
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img, 0, 0, img.width, img.height);
return context;
},
resolveURL(path) {
linkEl ||= document.createElement("a");
linkEl.href = path;
return linkEl.href;
},
get hardwareConcurrency() {
return typeof navigator !== "undefined" && navigator.hardwareConcurrency || 4;
},
get prefersReducedMotion() {
if (reducedMotionOverride !== void 0) return reducedMotionOverride;
if (!matchMedia) return false;
reducedMotionQuery ??= matchMedia("(prefers-reduced-motion: reduce)");
return reducedMotionQuery.matches;
},
set prefersReducedMotion(value) {
reducedMotionOverride = value;
}
};
//#endregion
//#region src/util/time_control.ts
/**
* Manages time flow with optional freezing capability for deterministic rendering.
*/
var TimeManager = class {
constructor() {
this._frozenAt = null;
}
/**
* Gets the current time, either real or frozen.
* @returns Current time in milliseconds
*/
getCurrentTime() {
return this._frozenAt !== null ? this._frozenAt : performance.now();
}
/**
* Sets time at a specific timestamp.
* @param timestamp - Time in milliseconds to set
*/
setNow(timestamp) {
this._frozenAt = timestamp;
}
/**
* Restores normal time flow.
*/
restoreNow() {
this._frozenAt = null;
}
/**
* Returns whether time is currently frozen.
* @returns True if time is frozen, false otherwise
*/
isFrozen() {
return this._frozenAt !== null;
}
};
const timeManager = new TimeManager();
/**
* Returns the current time in milliseconds.
* When time is frozen via setNow(), returns the frozen timestamp.
* Otherwise returns real browser time via performance.now().
*
* @returns Current time in milliseconds
* @example
* ```ts
* // Measure elapsed time
* const start = maplibregl.now();
* // ... later ...
* const elapsed = maplibregl.now() - start;
*
* // During frozen time
* maplibregl.setNow(16.67);
* console.log(maplibregl.now()); // 16.67
* maplibregl.restoreNow();
* console.log(maplibregl.now()); // real time
* ```
*/
function now() {
return timeManager.getCurrentTime();
}
/**
* Freezes time at a specific timestamp for deterministic rendering.
* Useful for frame-by-frame video capture where each frame needs
* a consistent time value.
*
* @param timestamp - Time in milliseconds to freeze at
* @example
* ```ts
* // Freeze time for video export at 60fps
* setNow(0); // First frame
* // ... render frame ...
* setNow(16.67); // Second frame
* // ... render frame ...
* setNow(33.34); // Third frame
* // ... done ...
* restoreNow(); // Resume normal time
* ```
*/
function setNow(timestamp) {
timeManager.setNow(timestamp);
}
/**
* Restores normal time flow after freezing with setNow().
* Call this after finishing deterministic rendering operations.
*
* @example
* ```ts
* // After video export, resume normal time
* setNow(0);
* // ... export frames ...
* restoreNow(); // Map animations resume normally
* ```
*/
function restoreNow() {
timeManager.restoreNow();
}
/**
* Returns whether time is currently frozen.
* @returns True if time is frozen via setNow(), false otherwise
* @example
* ```ts
* setNow(1000);
* console.log(isTimeFrozen()); // true
* restoreNow();
* console.log(isTimeFrozen()); // false
* ```
*/
function isTimeFrozen() {
return timeManager.isFrozen();
}
//#endregion
//#region src/util/dom.ts
var DOM = class DOM {
static {
this.docStyle = typeof window !== "undefined" && window.document?.documentElement.style;
}
static {
this.selectProp = !DOM.docStyle || "userSelect" in DOM.docStyle ? "userSelect" : "webkitUserSelect";
}
static create(tagName, className, container) {
const el = window.document.createElement(tagName);
if (className !== void 0) el.className = className;
if (container) container.appendChild(el);
return el;
}
static createNS(namespaceURI, tagName) {
return window.document.createElementNS(namespaceURI, tagName);
}
static disableDrag() {
if (DOM.docStyle && DOM.selectProp) {
DOM.userSelect = DOM.docStyle[DOM.selectProp];
DOM.docStyle[DOM.selectProp] = "none";
}
}
static enableDrag() {
if (DOM.docStyle && DOM.selectProp) DOM.docStyle[DOM.selectProp] = DOM.userSelect;
}
static suppressClickInternal(e) {
e.preventDefault();
e.stopPropagation();
window.removeEventListener("click", DOM.suppressClickInternal, true);
}
static suppressClick() {
window.addEventListener("click", DOM.suppressClickInternal, true);
window.setTimeout(() => {
window.removeEventListener("click", DOM.suppressClickInternal, true);
}, 0);
}
static getScale(element) {
const rect = element.getBoundingClientRect();
return {
x: rect.width / element.offsetWidth || 1,
y: rect.height / element.offsetHeight || 1,
boundingClientRect: rect
};
}
static getPoint(el, scale, e) {
const rect = scale.boundingClientRect;
return new Point((e.clientX - rect.left) / scale.x - el.clientLeft, (e.clientY - rect.top) / scale.y - el.clientTop);
}
static mousePos(el, e) {
const scale = DOM.getScale(el);
return DOM.getPoint(el, scale, e);
}
static touchPos(el, touches) {
const points = [];
const scale = DOM.getScale(el);
for (const touch of touches) points.push(DOM.getPoint(el, scale, touch));
return points;
}
/**
* Sanitize an HTML string - this might not be enough to prevent all XSS attacks
* Base on https://javascriptsource.com/sanitize-an-html-string-to-reduce-the-risk-of-xss-attacks/
* (c) 2021 Chris Ferdinandi, MIT License, https://gomakethings.com
*/
static sanitize(str) {
const html = new DOMParser().parseFromString(str, "text/html").body || document.createElement("body");
const scripts = html.querySelectorAll("script");
for (const script of scripts) script.remove();
DOM.clean(html);
return html.innerHTML;
}
/**
* Check if the attribute is potentially dangerous
*/
static isPossiblyDangerous(name, value) {
const val = value.replace(/\s+/g, "").toLowerCase();
if ([
"src",
"href",
"xlink:href"
].includes(name)) {
if (val.includes("javascript:") || val.includes("data:")) return true;
}
if (name.startsWith("on")) return true;
}
/**
* Remove dangerous stuff from the HTML document's nodes
* @param html - The HTML document
*/
static clean(html) {
const nodes = html.children;
for (const node of nodes) {
DOM.removeAttributes(node);
DOM.clean(node);
}
}
/**
* Remove potentially dangerous attributes from an element
* @param elem - The element
*/
static removeAttributes(elem) {
for (const { name, value } of Array.from(elem.attributes)) {
if (!DOM.isPossiblyDangerous(name, value)) continue;
elem.removeAttribute(name);
}
}
};
//#endregion
//#region src/util/image_request.ts
let ImageRequest;
(function(_ImageRequest) {
let imageRequestQueue;
let currentParallelImageRequests;
let throttleControlCallbackHandleCounter;
let throttleControlCallbacks;
_ImageRequest.resetRequestQueue = () => {
imageRequestQueue = [];
currentParallelImageRequests = 0;
throttleControlCallbackHandleCounter = 0;
throttleControlCallbacks = {};
};
_ImageRequest.addThrottleControl = (callback) => {
const handle = throttleControlCallbackHandleCounter++;
throttleControlCallbacks[handle] = callback;
return handle;
};
_ImageRequest.removeThrottleControl = (callbackHandle) => {
delete throttleControlCallbacks[callbackHandle];
processQueue();
};
/**
* Check to see if any of the installed callbacks are requesting the queue
* to be throttled.
* @returns `true` if any callback is causing the queue to be throttled.
*/
const isThrottled = () => {
for (const key of Object.keys(throttleControlCallbacks)) if (throttleControlCallbacks[key]()) return true;
return false;
};
async function transformAndGetImage(requestManager, url, resourceType, abortController, supportImageRefresh = true, imageBitmapOptions) {
const requestParameters = await requestManager.transformRequest(url, resourceType);
throwIfAborted(abortController.signal);
return ImageRequest.getImage(requestParameters, abortController, supportImageRefresh, imageBitmapOptions);
}
_ImageRequest.transformAndGetImage = transformAndGetImage;
_ImageRequest.getImage = (requestParameters, abortController, supportImageRefresh = true, imageBitmapOptions) => {
return new Promise((resolve, reject) => {
requestParameters.headers ||= {};
requestParameters.headers.accept = "image/webp,*/*";
extend(requestParameters, { type: "image" });
const request = {
abortController,
requestParameters,
supportImageRefresh,
imageBitmapOptions,
state: "queued",
onError: (error) => {
reject(error);
},
onSuccess: (response) => {
resolve(response);
}
};
imageRequestQueue.push(request);
processQueue();
});
};
const arrayBufferToCanvasImageSource = (data, imageBitmapOptions) => {
if (typeof createImageBitmap === "function") return arrayBufferToImageBitmap(data, imageBitmapOptions);
else return arrayBufferToImage(data);
};
const doImageRequest = async (itemInQueue) => {
itemInQueue.state = "running";
const { requestParameters, supportImageRefresh, imageBitmapOptions, onError, onSuccess, abortController } = itemInQueue;
const canUseHTMLImageElement = supportImageRefresh === false && !imageBitmapOptions && !isWorker(self) && !getProtocol(requestParameters.url) && (!requestParameters.headers || Object.keys(requestParameters.headers).reduce((acc, item) => acc && item === "accept", true));
currentParallelImageRequests++;
const getImagePromise = canUseHTMLImageElement ? getImageUsingHtmlImage(requestParameters, abortController) : makeRequest(requestParameters, abortController);
try {
const response = await getImagePromise;
delete itemInQueue.abortController;
itemInQueue.state = "completed";
if (response.data instanceof HTMLImageElement || isImageBitmap(response.data)) onSuccess(response);
else if (response.data) onSuccess({
data: await arrayBufferToCanvasImageSource(response.data, imageBitmapOptions),
cacheControl: response.cacheControl,
expires: response.expires
});
} catch (err) {
delete itemInQueue.abortController;
onError(ensureError(err));
} finally {
currentParallelImageRequests--;
processQueue();
}
};
/**
* Process some number of items in the image request queue.
*/
const processQueue = () => {
const maxImageRequests = isThrottled() ? config.MAX_PARALLEL_IMAGE_REQUESTS_PER_FRAME : config.MAX_PARALLEL_IMAGE_REQUESTS;
for (let numImageRequests = currentParallelImageRequests; numImageRequests < maxImageRequests && imageRequestQueue.length > 0; numImageRequests++) {
const topItemInQueue = imageRequestQueue.shift();
if (topItemInQueue.abortController.signal.aborted) {
numImageRequests--;
continue;
}
doImageRequest(topItemInQueue);
}
};
const getImageUsingHtmlImage = (requestParameters, abortController) => {
return new Promise((resolve, reject) => {
const image = new Image();
const url = requestParameters.url;
const credentials = requestParameters.credentials;
if (credentials && credentials === "include") image.crossOrigin = "use-credentials";
else if (credentials && credentials === "same-origin" || !sameOrigin(url)) image.crossOrigin = "anonymous";
abortController.signal.addEventListener("abort", () => {
image.src = "";
reject(new AbortError(abortController.signal.reason));
});
image.fetchPriority = "high";
image.onload = () => {
image.onerror = image.onload = null;
resolve({ data: image });
};
image.onerror = () => {
image.onerror = image.onload = null;
if (abortController.signal.aborted) return;
reject(/* @__PURE__ */ new Error("Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported."));
};
image.src = url;
});
};
})(ImageRequest || (ImageRequest = {}));
ImageRequest.resetRequestQueue();
var RequestManager = class {
constructor(transformRequestFn) {
this._transformRequestFn = transformRequestFn ?? null;
}
transformRequest(url, type) {
if (this._transformRequestFn) return this._transformRequestFn(url, type) || { url };
return { url };
}
setTransformRequest(transformRequest) {
this._transformRequestFn = transformRequest;
}
};
//#endregion
//#region src/ui/events.ts
/**
* The base event for MapLibre
*
* @group Event Related
*/
var MapLibreEvent = class extends Event {};
/**
* `MapMovementEvent` is the event type for the camera-transition map events:
* `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `rotatestart`, `rotate`, `rotateend`,
* `dragstart`, `drag`, `dragend`, `pitchstart`, `pitch`, `pitchend`, `rollstart`, `roll` and `rollend`.
* These are fired as the map's view changes, as a result of either user interaction or methods such
* as {@link Map.jumpTo} / {@link Map.flyTo}.
*
* @group Event Related
*/
var MapMovementEvent = class extends MapLibreEvent {};
/**
* The `style.load` event, fired once the map's style has fully loaded or changed.
*
* @group Event Related
*/
var MapStyleLoadEvent = class extends MapLibreEvent {
constructor(data = {}) {
super("style.load", data);
}
};
/**
* The style data event
*
* @group Event Related
*/
var MapStyleDataEvent = class extends MapLibreEvent {
constructor(type, data = {}) {
super(type, data);
this.dataType = "style";
}
};
/**
* A `MapSourceDataEvent` is emitted with the source-related `data`, `dataloading`, `dataabort`,
* `sourcedata`, `sourcedataloading` and `sourcedataabort` events. Its `dataType` is always `'source'`.
*
* Possible values for `sourceDataType`s are:
*
* - `'metadata'`: indicates that any necessary source metadata has been loaded (such as TileJSON) and it is ok to start loading tiles
* - `'content'`: indicates the source data has changed (such as when source.setData() has been called on GeoJSONSource)
* - `'visibility'`: send when the source becomes used when at least one of its layers becomes visible in style sense (inside the layer's zoom range and with layout.visibility set to 'visible')
* - `'idle'`: indicates that no new source data has been fetched (but the source has done loading)
*
* @group Event Related
*
* @example
* ```ts
* // The sourcedata event is an example of a MapSourceDataEvent.
* // Set up an event listener on the map.
* map.on('sourcedata', (e) => {
* if (e.isSourceLoaded) {
* // Do something when the source has finished loading
* }
* });
* ```
*/
var MapSourceDataEvent = class extends MapLibreEvent {
constructor(type, data = {}) {
super(type, data);
this.dataType = "source";
}
};
/**
* `MapMouseEvent` is the event type for mouse-related map events.
*
* @group Event Related
*
* @example
* ```ts
* // The `click` event is an example of a `MapMouseEvent`.
* // Set up an event listener on the map.
* map.on('click', (e) => {
* // The event object (e) contains information like the
* // coordinates of the point on the map that was clicked.
* console.log('A click event has occurred at ' + e.lngLat);
* });
* ```
*/
var MapMouseEvent = class extends MapLibreEvent {
/**
* Prevents subsequent default processing of the event by the map.
*
* Calling this method will prevent the following default map behaviors:
*
* * On `mousedown` events, the behavior of {@link DragPanHandler}
* * On `mousedown` events, the behavior of {@link DragRotateHandler}
* * On `mousedown` events, the behavior of {@link BoxZoomHandler}
* * On `dblclick` events, the behavior of {@link DoubleClickZoomHandler}
*
*/
preventDefault() {
this._defaultPrevented = true;
}
/**
* `true` if `preventDefault` has been called.
*/
get defaultPrevented() {
return this._defaultPrevented;
}
constructor(type, map, originalEvent, data = {}) {
originalEvent = originalEvent instanceof MouseEvent ? originalEvent : new MouseEvent(type, originalEvent);
const point = DOM.mousePos(map.getCanvas(), originalEvent);
const lngLat = map.unproject(point);
super(type, extend({
point,
lngLat,
originalEvent
}, data));
this._defaultPrevented = false;
this.target = map;
}
};
/**
* `MapTouchEvent` is the event type for touch-related map events.
*
* @group Event Related
*/
var MapTouchEvent = class extends MapLibreEvent {
/**
* Prevents subsequent default processing of the event by the map.
*
* Calling this method will prevent the following default map behaviors:
*
* * On `touchstart` events, the behavior of {@link DragPanHandler}
* * On `touchstart` events, the behavior of {@link TwoFingersTouchZoomRotateHandler}
*
*/
preventDefault() {
this._defaultPrevented = true;
}
/**
* `true` if `preventDefault` has been called.
*/
get defaultPrevented() {
return this._defaultPrevented;
}
constructor(type, map, originalEvent) {
const touches = type === "touchend" ? originalEvent.changedTouches : originalEvent.touches;
const points = DOM.touchPos(map.getCanvasContainer(), touches);
const lngLats = points.map((t) => map.unproject(t));
const point = points.reduce((prev, curr, i, arr) => {
return prev.add(curr.div(arr.length));
}, new Point(0, 0));
const lngLat = map.unproject(point);
super(type, {
points,
point,
lngLats,
lngLat,
originalEvent
});
this._defaultPrevented = false;
}
};
/**
* `MapWheelEvent` is the event type for the `wheel` map event.
*
* @group Event Related
*/
var MapWheelEvent = class extends MapLibreEvent {
/**
* Prevents subsequent default processing of the event by the map.
*
* Calling this method will prevent the behavior of {@link ScrollZoomHandler}.
*/
preventDefault() {
this._defaultPrevented = true;
}
/**
* `true` if `preventDefault` has been called.
*/
get defaultPrevented() {
return this._defaultPrevented;
}
/** */
constructor(map, originalEvent) {
super("wheel", { originalEvent });
this._defaultPrevented = false;
}
};
/**
* A `MapBoxZoomEvent` is the event type for the boxzoom-related map events emitted by the {@link BoxZoomHandler}.
*
* @group Event Related
*/
var MapBoxZoomEvent = class extends MapLibreEvent {};
/**
* The terrain event
*
* @group Event Related
*/
var MapTerrainEvent = class extends MapLibreEvent {
constructor(data = {}) {
super("terrain", data);
}
};
/**
* The map projection event
*
* @group Event Related
*/
var MapProjectionEvent = class extends MapLibreEvent {
constructor(data = {}) {
super("projectiontransition", data);
}
};
/**
* An event related to the web gl context
*
* @group Event Related
*/
var MapContextEvent = class extends MapLibreEvent {};
/**
* The style image missing event, fired when an image is still missing after the missing style image
* resolver has been given a chance to supply it. To load or generate images on demand,
* use {@link Map.setMissingStyleImageResolver}.
* Event listeners cannot resolve the missing image for the current request.
*
* @group Event Related
*
* @see [Generate and add a missing icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/generate-and-add-a-missing-icon-to-the-map/)
*/
var MapStyleImageMissingEvent = class extends MapLibreEvent {
constructor(data = {}) {
super("styleimagemissing", data);
}
};
//#endregion
//#region src/util/style.ts
/**
* Takes a SpriteSpecification value and returns it in its array form. If `undefined` is passed as an input value, an
* empty array is returned.
* duplicated entries with identical id/url will be removed in returned array
* @param sprite - optional sprite to coerce
* @returns an empty array in case `undefined` is passed; id-url pairs otherwise
*/
function coerceSpriteToArray(sprite) {
const resultArray = [];
if (typeof sprite === "string") resultArray.push({
id: "default",
url: sprite
});
else if (sprite && sprite.length > 0) {
const dedupArray = [];
for (const { id, url } of sprite) {
const key = `${id}${url}`;
if (!dedupArray.includes(key)) {
dedupArray.push(key);
resultArray.push({
id,
url
});
}
}
}
return resultArray;
}
//#endregion
//#region src/style/load_sprite.ts
function normalizeSpriteURL(url, format, extension) {
try {
const parsed = new URL(url);
parsed.pathname += `${format}${extension}`;
return parsed.toString();
} catch {
throw new Error(`Invalid sprite URL "${url}", must be absolute. Modify style specification directly or use TransformStyleFunction to correct the issue dynamically`);
}
}
async function loadSprite(originalSprite, requestManager, pixelRatio, abortController) {
const spriteArray = coerceSpriteToArray(originalSprite);
const format = pixelRatio > 1 ? "@2x" : "";
const jsonsMap = {};
const imagesMap = {};
for (const { id, url } of spriteArray) {
const jsonRequestParameters = await requestManager.transformRequest(normalizeSpriteURL(url, format, ".json"), "SpriteJSON");
jsonsMap[id] = getJSON(jsonRequestParameters, abortController);
const imageRequestParameters = await requestManager.transformRequest(normalizeSpriteURL(url, format, ".png"), "SpriteImage");
imagesMap[id] = ImageRequest.getImage(imageRequestParameters, abortController);
}
await Promise.all([...Object.values(jsonsMap), ...Object.values(imagesMap)]);
return doOnceCompleted(jsonsMap, imagesMap);
}
/**
* @param jsonsMap - JSON data map
* @param imagesMap - image data map
*/
async function doOnceCompleted(jsonsMap, imagesMap) {
const result = {};
for (const spriteName in jsonsMap) {
result[spriteName] = {};
const context = browser.getImageCanvasContext((await imagesMap[spriteName]).data);
const json = (await jsonsMap[spriteName]).data;
for (const id in json) {
const { width, height, x, y, sdf, pixelRatio, stretchX, stretchY, content, textFitWidth, textFitHeight } = json[id];
const spriteData = {
width,
height,
x,
y,
context
};
result[spriteName][id] = {
data: null,
pixelRatio,
sdf,
stretchX,
stretchY,
content,
textFitWidth,
textFitHeight,
spriteData
};
}
}
return result;
}
//#endregion
//#region src/render/image_manager.ts
/**
* Owns every image of the style - the ones the sprites bring in as well as the ones added at
* runtime - and tracks requests for them from the tile workers, sending responses when the
* requests are fulfilled.
*/
var ImageManager = class extends Evented {
constructor() {
super();
this.images = {};
this.updateVersion = 0;
this.loaded = false;
this.requestors = [];
this.missingImageResolver = null;
this._spriteImagesIds = {};
this._imagesIds = null;
this._renderCallbacksDispatchedThisFrame = {};
}
destroy() {
for (const id of Object.keys(this.images)) this.removeImage(id);
this._spriteImagesIds = {};
}
isLoaded() {
return this.loaded;
}
setLoaded(loaded) {
if (this.loaded === loaded) return;
this.loaded = loaded;
if (loaded) {
for (const { ids, promiseResolve } of this.requestors) promiseResolve(this._getImagesForIds(ids));
this.requestors = [];
}
}
getImage(id) {
const image = this.images[id];
if (image && !image.data && image.spriteData) {
const spriteData = image.spriteData;
image.data = new RGBAImage({
width: spriteData.width,
height: spriteData.height
}, spriteData.context.getImageData(spriteData.x, spriteData.y, spriteData.width, spriteData.height).data);
image.spriteData = null;
}
return image;
}
addImage(id, image) {
if (this.images[id]) throw new Error(`Image id ${id} already exist, use updateImage instead`);
if (this._validate(id, image)) {
this.images[id] = image;
this._imagesIds = null;
if (image.isWebGLImage) this.updateImage(id, image, false);
}
}
_validate(id, image) {
let valid = true;
const data = image.data || image.spriteData;
if (!this._validateStretch(image.stretchX, data?.width)) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`Image "${id}" has invalid "stretchX" value`)));
valid = false;
}
if (!this._validateStretch(image.stretchY, data?.height)) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`Image "${id}" has invalid "stretchY" value`)));
valid = false;
}
if (!this._validateContent(image.content, image)) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`Image "${id}" has invalid "content" value`)));
valid = false;
}
return valid;
}
_validateStretch(stretch, size) {
if (!stretch) return true;
let last = 0;
for (const part of stretch) {
if (part[0] < last || part[1] < part[0] || size < part[1]) return false;
last = part[1];
}
return true;
}
_validateContent(content, image) {
if (!content) return true;
if (content.length !== 4) return false;
const spriteData = image.spriteData;
const width = spriteData?.width || image.data.width;
const height = spriteData?.height || image.data.height;
if (content[0] < 0 || width < content[0]) return false;
if (content[1] < 0 || height < content[1]) return false;
if (content[2] < 0 || width < content[2]) return false;
if (content[3] < 0 || height < content[3]) return false;
if (content[2] < content[0]) return false;
return content[3] >= content[1];
}
/**
* Replaces an image that is already known under this id, bumping its version so that the
* atlases holding it notice.
*
* The old record is read directly rather than through {@link ImageManager.getImage}, which
* would force a synchronous decode of the sprite data of the very image being replaced. Its
* size therefore comes from whichever of the two the pixels are still in, since an image that
* came from a sprite and was never rendered has not been decoded yet, and its version is
* defaulted, since images start out without one.
*
* @param validate - whether to reject an image of a different size than the one it replaces
*/
updateImage(id, image, validate = true) {
const oldImage = this.images[id];
if (validate) {
const oldData = oldImage.data || oldImage.spriteData;
if (oldData.width !== image.data.width || oldData.height !== image.data.height) throw new Error(`size mismatch between old image (${oldData.width}x${oldData.height}) and new image (${image.data.width}x${image.data.height}).`);
}
image.version = (oldImage.version ?? 0) + 1;
this.images[id] = image;
this.updateVersion++;
}
removeImage(id) {
const image = this.images[id];
if (!image) return;
delete this.images[id];
this._imagesIds = null;
if (image.userImage?.onRemove) image.userImage.onRemove();
}
/**
* @returns the ids of every image currently held, sprite images and runtime ones alike. The
* returned array is shared between callers and must not be modified.
*/
listImages() {
this._imagesIds ??= Object.keys(this.images);
return this._imagesIds;
}
/**
* Images of the `default` sprite keep their plain id, the ones of any other sprite are
* namespaced by their sprite's id.
*/
_getSpriteImageId(spriteId, imageId) {
return spriteId === "default" ? imageId : `${spriteId}:${imageId}`;
}
/**
* Takes over the images of a single sprite: adds the new ones, updates the ones that are
* already known, and removes the ones that a previous load of this same sprite had brought in
* but that are not part of it anymore.
*
* @param spriteId - the id of the sprite the images belong to
* @param images - the sprite's images, keyed by their id within the sprite
* @returns the ids of the images that this sprite now provides, and the ids of the ones that
* were removed because they are no longer part of it
*/
setSpriteImages(spriteId, images) {
const previousIds = this._spriteImagesIds[spriteId] ?? [];
const loaded = [];
for (const id in images) {
const imageId = this._getSpriteImageId(spriteId, id);
loaded.push(imageId);
if (imageId in this.images) this.updateImage(imageId, images[id], false);
else this.addImage(imageId, images[id]);
}
const loadedIds = new Set(loaded);
const removed = previousIds.filter((imageId) => !loadedIds.has(imageId));
for (const imageId of removed) this.removeImage(imageId);
this._spriteImagesIds[spriteId] = loaded;
return {
loaded,
removed
};
}
/**
* Removes all the images a single sprite has brought in.
* @returns the ids of the removed images
*/
removeSpriteImages(spriteId) {
const removed = this._spriteImagesIds[spriteId] ?? [];
for (const imageId of removed) this.removeImage(imageId);
delete this._spriteImagesIds[spriteId];
return removed;
}
/**
* Removes the images of every sprite, leaving the images added at runtime alone.
* @returns the ids of the removed images
*/
removeAllSpriteImages() {
const removed = Object.values(this._spriteImagesIds).flat();
for (const imageId of removed) this.removeImage(imageId);
this._spriteImagesIds = {};
return removed;
}
setMissingImageResolver(resolver) {
this.missingImageResolver = resolver;
}
getImages(ids) {
return new Promise((resolve, _reject) => {
let hasAllDependencies = true;
if (!this.isLoaded()) {
for (const id of ids) if (!this.images[id]) hasAllDependencies = false;
}
if (this.isLoaded() || hasAllDependencies) resolve(this._getImagesForIds(ids));
else this.requestors.push({
ids,
promiseResolve: resolve
});
});
}
async _getImagesForIds(ids) {
const unresolvedIds = new Set(ids.filter((id) => !this.getImage(id)));
const resolver = this.missingImageResolver;
if (resolver) await Promise.allSettled(Array.from(unresolvedIds, (id) => resolver(id)));
const response = {};
for (const id of ids) {
const image = this.getImage(id);
if (image) {
unresolvedIds.delete(id);
response[id] = {
data: image.data.clone(),
pixelRatio: image.pixelRatio,
sdf: image.sdf,
version: image.version,
stretchX: image.stretchX,
stretchY: image.stretchY,
content: image.content,
textFitWidth: image.textFitWidth,
textFitHeight: image.textFitHeight,
hasRenderCallback: Boolean(image.userImage?.render),
isWebGLImage: image.isWebGLImage
};
}
}
for (const id of unresolvedIds) {
this.fire(new MapStyleImageMissingEvent({ id }));
warnOnce(`Image "${id}" could not be loaded. Please make sure you have added the image before it is needed with map.addImage(), resolved it with map.setMissingStyleImageResolver(), or included it in a "sprite" property in your style.`);
}
return response;
}
beginFrame() {
this._renderCallbacksDispatchedThisFrame = {};
}
/**
* Re-renders the images among `ids` that were added with a `render` callback (see
* `StyleImageInterface`), at most once per frame each.
*/
dispatchRenderCallbacks(ids) {
for (const id of ids) {
if (this._renderCallbacksDispatchedThisFrame[id]) continue;
this._renderCallbacksDispatchedThisFrame[id] = true;
const image = this.getImage(id);
if (!image) warnOnce(`Image with ID: "${id}" was not found`);
if (renderStyleImage(image)) this.updateImage(id, image);
}
}
cloneImages() {
const clonedImages = {};
for (const id in this.images) {
const image = this.images[id];
clonedImages[id] = {
...image,
data: image.data ? image.data.clone() : null
};
}
return clonedImages;
}
};
//#endregion
//#region src/render/pattern_atlas.ts
/**
* When copied into the atlas texture, pattern images are padded by one pixel on each side with a
* copy of the image data wrapped from the opposite side. This ensures the correct behavior of
* GL_LINEAR texture sampling mode.
*/
const PADDING = 1;
/**
* A texture atlas of the pattern images that are drawn without a tile's own {@link ImageAtlas},
* i.e. `background-pattern`. Entries are packed on demand and re-packed whenever one of them is
* added or changes, which is rare enough for the repacking cost not to matter.
*/
var PatternAtlas = class {
constructor(imageManager) {
this._imageManager = imageManager;
this._entries = {};
this._image = new RGBAImage({
width: 1,
height: 1
});
this._dirty = true;
}
destroy() {
if (this._texture) {
this._texture.destroy();
this._texture = null;
}
this._entries = {};
this._image = new RGBAImage({
width: 1,
height: 1
});
this._dirty = true;
}
getPixelSize() {
const { width, height } = this._image;
return {
width,
height
};
}
/**
* @returns the position of the pattern within the atlas, or `null` if there is no such image
*/
getPattern(id) {
const image = this._imageManager.getImage(id);
if (!image) return null;
const entry = this._entries[id];
if (entry?.image !== image) {
const bin = {
w: image.data.width + 2,
h: image.data.height + 2,
x: 0,
y: 0
};
this._entries[id] = {
bin,
position: new ImagePosition(bin, image),
image
};
} else if (entry.position.version !== image.version) entry.position.version = image.version;
else return entry.position;
this._update();
return this._entries[id].position;
}
bind(context) {
const gl = context.gl;
if (!this._texture) {
this._texture = new Texture(context, this._image, gl.RGBA);
this._dirty = false;
} else if (this._dirty) {
this._texture.update(this._image);
this._dirty = false;
}
this._texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
}
_update() {
for (const id in this._entries) if (!this._imageManager.getImage(id)) delete this._entries[id];
const bins = [];
for (const id in this._entries) bins.push(this._entries[id].bin);
const { w, h } = potpack(bins);
const dst = this._image;
dst.resize({
width: w || 1,
height: h || 1
});
for (const id in this._entries) {
const { bin } = this._entries[id];
const x = bin.x + PADDING;
const y = bin.y + PADDING;
const src = this._entries[id].image.data;
const w = src.width;
const h = src.height;
RGBAImage.copy(src, dst, {
x: 0,
y: 0
}, {
x,
y
}, {
width: w,
height: h
});
RGBAImage.copy(src, dst, {
x: 0,
y: h - 1
}, {
x,
y: y - 1
}, {
width: w,
height: 1
});
RGBAImage.copy(src, dst, {
x: 0,
y: 0
}, {
x,
y: y + h
}, {
width: w,
height: 1
});
RGBAImage.copy(src, dst, {
x: w - 1,
y: 0
}, {
x: x - 1,
y
}, {
width: 1,
height: h
});
RGBAImage.copy(src, dst, {
x: 0,
y: 0
}, {
x: x + w,
y
}, {
width: 1,
height: h
});
}
this._dirty = true;
}
};
//#endregion
//#region src/style/load_glyph_range.ts
async function loadGlyphRange(fontstack, range, urlTemplate, requestManager) {
const begin = range * 256;
const end = begin + 255;
const request = await requestManager.transformRequest(urlTemplate.replace("{fontstack}", fontstack).replace("{range}", `${begin}-${end}`), "Glyphs");
const response = await getArrayBuffer(request, new AbortController());
if (!response?.data) throw new Error(`Could not load glyph range. range: ${range}, ${begin}-${end}`);
const glyphs = {};
for (const glyph of parseGlyphPbf(response.data)) glyphs[glyph.id] = glyph;
return glyphs;
}
//#endregion
//#region node_modules/@mapbox/tiny-sdf/index.js
const INF = 0x56bc75e2d63100000;
const alphaTable = /* @__PURE__ */ new Float64Array(256);
for (let i = 0; i < 256; i++) {
const d = .5 - Math.pow(i / 255, 1 / 2.2);
alphaTable[i] = d * Math.abs(d);
}
alphaTable[255] = -0x56bc75e2d63100000;
var TinySDF = class {
constructor({ fontSize = 24, buffer = 3, radius = 8, cutoff = .25, fontFamily = "sans-serif", fontWeight = "normal", fontStyle = "normal", lang = null } = {}) {
this.buffer = buffer;
this.radius = radius;
this.cutoff = cutoff;
this.lang = lang;
const size = this.size = fontSize + buffer * 4;
const canvas = this._createCanvas(size);
const ctx = this.ctx = canvas.getContext("2d", { willReadFrequently: true });
ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px ${fontFamily}`;
ctx.textBaseline = "alphabetic";
ctx.textAlign = "left";
ctx.fillStyle = "black";
this.gridOuter = new Float64Array(size * size);
this.gridInner = new Float64Array(size * size);
this.f = new Float64Array(size);
this.z = new Float64Array(size + 1);
this.v = new Uint16Array(size);
}
_createCanvas(size) {
if (typeof OffscreenCanvas !== "undefined") return new OffscreenCanvas(size, size);
const canvas = document.createElement("canvas");
canvas.width = canvas.height = size;
return canvas;
}
draw(char) {
const { width: glyphAdvance, actualBoundingBoxAscent, actualBoundingBoxDescent, actualBoundingBoxLeft, actualBoundingBoxRight } = this.ctx.measureText(char);
const glyphTop = Math.ceil(actualBoundingBoxAscent);
const glyphLeft = Math.floor(-actualBoundingBoxLeft);
const glyphWidth = Math.max(0, Math.min(this.size - this.buffer, Math.ceil(actualBoundingBoxRight) - glyphLeft));
const glyphHeight = Math.max(0, Math.min(this.size - this.buffer, glyphTop + Math.ceil(actualBoundingBoxDescent)));
const width = glyphWidth + 2 * this.buffer;
const height = glyphHeight + 2 * this.buffer;
const len = Math.max(width * height, 0);
const data = new Uint8ClampedArray(len);
const glyph = {
data,
width,
height,
glyphWidth,
glyphHeight,
glyphTop,
glyphLeft,
glyphAdvance
};
if (glyphWidth === 0 || glyphHeight === 0) return glyph;
const { ctx, buffer, gridInner, gridOuter } = this;
if (this.lang) ctx.lang = this.lang;
ctx.clearRect(buffer, buffer, glyphWidth, glyphHeight);
ctx.fillText(char, buffer - glyphLeft, buffer + glyphTop);
const imgData = ctx.getImageData(buffer, buffer, glyphWidth, glyphHeight);
gridOuter.fill(INF, 0, len);
gridInner.fill(0, 0, len);
let imgIdx = 3;
for (let y = 0; y < glyphHeight; y++) {
let j = (y + buffer) * width + buffer;
for (let x = 0; x < glyphWidth; x++, imgIdx += 4, j++) {
const a = imgData.data[imgIdx];
if (a === 0) continue;
const t = alphaTable[a];
gridOuter[j] = Math.max(0, t);
gridInner[j] = Math.max(0, -t);
}
}
edt(gridOuter, 0, 0, width, height, width, this.f, this.v, this.z);
const pad = Math.min(buffer, 1);
edt(gridInner, buffer - pad, buffer - pad, glyphWidth + 2 * pad, glyphHeight + 2 * pad, width, this.f, this.v, this.z);
const scale = 255 / this.radius;
const base = 255 * (1 - this.cutoff);
for (let i = 0; i < len; i++) {
const d = Math.sqrt(gridOuter[i]) - Math.sqrt(gridInner[i]);
data[i] = Math.round(base - scale * d);
}
return glyph;
}
};
function edt(data, x0, y0, width, height, gridSize, f, v, z) {
for (let x = x0; x < x0 + width; x++) edt1d(data, y0 * gridSize + x, gridSize, height, f, v, z);
for (let y = y0; y < y0 + height; y++) edt1d(data, y * gridSize + x0, 1, width, f, v, z);
}
function edt1d(grid, offset, stride, length, f, v, z) {
v[0] = 0;
z[0] = -0x56bc75e2d63100000;
z[1] = INF;
f[0] = grid[offset];
for (let q = 1, k = 0, s = 0; q < length; q++) {
f[q] = grid[offset + q * stride];
const q2 = q * q;
do {
const r = v[k];
s = (f[q] - f[r] + q2 - r * r) / (q - r) / 2;
} while (s <= z[k] && --k > -1);
k++;
v[k] = q;
z[k] = s;
z[k + 1] = INF;
}
for (let q = 0, k = 0; q < length; q++) {
while (z[k + 1] < q) k++;
const r = v[k];
const qr = q - r;
grid[offset + q * stride] = f[r] + qr * qr;
}
}
//#endregion
//#region src/render/glyph_manager.ts
/**
* The style specification hard-codes some last resort fonts as a default fontstack.
*/
const defaultStack = latest.layout_symbol["text-font"].default.join(",");
/**
* The CSS generic font family closest to `defaultStack`.
*/
const defaultGenericFontFamily = "sans-serif";
/**
* Scale factor for client-generated glyphs.
*
* Client-generated glyphs are rendered at 2× because CJK glyphs are more detailed than others.
*/
const textureScale = 2;
var GlyphManager = class GlyphManager {
static {
this.loadGlyphRange = loadGlyphRange;
}
static {
this.TinySDF = TinySDF;
}
constructor(requestManager, localIdeographFontFamily, lang) {
this.requestManager = requestManager;
this.localIdeographFontFamily = localIdeographFontFamily;
this.entries = {};
this.lang = lang;
}
setURL(url) {
this.url = url;
}
async getGlyphs(glyphs) {
const glyphsPromises = [];
for (const stack in glyphs) for (const id of glyphs[stack]) glyphsPromises.push(this._getAndCacheGlyphsPromise(stack, id));
const updatedGlyphs = await Promise.all(glyphsPromises);
const result = {};
for (const { stack, id, glyph } of updatedGlyphs) {
result[stack] ||= {};
result[stack][id] = glyph && {
id: glyph.id,
bitmap: glyph.bitmap.clone(),
metrics: glyph.metrics
};
}
return result;
}
async _getAndCacheGlyphsPromise(stack, id) {
this.entries[stack] ??= {
glyphs: {},
requests: {},
ranges: {}
};
const entry = this.entries[stack];
let glyph = entry.glyphs[id];
if (glyph !== void 0) return {
stack,
id,
glyph
};
if (!this.url || this._charUsesLocalIdeographFontFamily(id)) {
glyph = entry.glyphs[id] = await this._drawGlyph(entry, stack, id);
return {
stack,
id,
glyph
};
}
return await this._downloadAndCacheRangePromise(stack, id);
}
async _downloadAndCacheRangePromise(stack, id) {
const entry = this.entries[stack];
const range = Math.floor(id / 256);
if (entry.ranges[range]) return {
stack,
id,
glyph: null
};
entry.requests[range] ||= GlyphManager.loadGlyphRange(stack, range, this.url, this.requestManager);
try {
const response = await entry.requests[range];
for (const id in response) entry.glyphs[+id] = response[+id];
entry.ranges[range] = true;
return {
stack,
id,
glyph: response[id] || null
};
} catch (e) {
const glyph = entry.glyphs[id] = await this._drawGlyph(entry, stack, id);
this._warnOnMissingGlyphRange(glyph, range, id, ensureError(e));
return {
stack,
id,
glyph
};
}
}
_warnOnMissingGlyphRange(glyph, range, id, err) {
const begin = range * 256;
const end = begin + 255;
const codePoint = id.toString(16).padStart(4, "0").toUpperCase();
warnOnce(`Unable to load glyph range ${range}, ${begin}-${end}. Rendering codepoint U+${codePoint} locally instead. ${err}`);
}
/**
* Returns whether the given codepoint should be rendered locally.
*/
_charUsesLocalIdeographFontFamily(id) {
return !!this.localIdeographFontFamily && codePointUsesLocalIdeographFontFamily(id);
}
/**
* Draws a glyph offscreen using TinySDF, creating a TinySDF instance lazily.
*/
async _drawGlyph(entry, stack, id) {
const usesLocalIdeographFontFamily = stack === defaultStack && this.localIdeographFontFamily !== "" && this._charUsesLocalIdeographFontFamily(id);
const tinySDFKey = usesLocalIdeographFontFamily ? "ideographTinySDF" : "tinySDF";
entry[tinySDFKey] ||= this._createTinySDF(usesLocalIdeographFontFamily ? this.localIdeographFontFamily : stack);
const char = (await entry[tinySDFKey]).draw(String.fromCodePoint(id));
/**
* TinySDF's "top" is the distance from the alphabetic baseline to the top of the glyph.
* Server-generated fonts specify "top" relative to an origin above the em box (the origin
* comes from FreeType, but I'm unclear on exactly how it's derived)
* ref: https://github.com/mapbox/sdf-glyph-foundry
*
* Server fonts don't yet include baseline information, so we can't line up exactly with them
* (and they don't line up with each other)
* ref: https://github.com/mapbox/node-fontnik/pull/160
*
* To approximately align TinySDF glyphs with server-provided glyphs, we use this baseline adjustment
* factor calibrated to be in between DIN Pro and Arial Unicode (but closer to Arial Unicode)
*/
const topAdjustment = 27.5;
const leftAdjustment = .5;
const isControl = /^\p{gc=Cf}+$/u.test(String.fromCodePoint(id));
return {
id,
bitmap: new AlphaImage({
width: char.width || 60,
height: char.height || 60
}, char.data),
metrics: {
width: isControl ? 0 : char.glyphWidth / textureScale || 24,
height: char.glyphHeight / textureScale || 24,
left: char.glyphLeft / textureScale + leftAdjustment || 0,
top: char.glyphTop / textureScale - topAdjustment || -8,
advance: isControl ? 0 : char.glyphAdvance / textureScale || 24,
isDoubleResolution: true
}
};
}
async _createTinySDF(stack) {
const fontFamilies = stack ? stack.split(",") : [];
fontFamilies.push(defaultGenericFontFamily);
const fontFamily = fontFamilies.map((fontName) => /[-\w]+/.test(fontName) ? fontName : `'${CSS.escape(fontName)}'`).join(",");
const fontSize = 48;
const fontWeight = this._fontWeight(fontFamilies[0]);
const fontStyle = this._fontStyle(fontFamilies[0]);
if (typeof document !== "undefined" && document.fonts?.load) try {
await document.fonts.load(`${fontStyle} ${fontWeight || "normal"} ${fontSize}px ${fontFamily}`);
} catch (e) {
warnOnce(`Failed to load font "${fontFamily}": ${ensureError(e).message}`);
}
return new GlyphManager.TinySDF({
fontSize,
buffer: 6,
radius: 16,
cutoff: .25,
fontFamily,
fontWeight,
fontStyle,
lang: this.lang
});
}
/**
* Sniffs the font style out of a font family name.
*/
_fontStyle(fontFamily) {
if (/italic/i.test(fontFamily)) return "italic";
else if (/oblique/i.test(fontFamily)) return "oblique";
return "normal";
}
/**
* Sniffs the font weight out of a font family name.
*/
_fontWeight(fontFamily) {
const weightsByName = {
thin: 100,
hairline: 100,
"extra light": 200,
"ultra light": 200,
light: 300,
normal: 400,
regular: 400,
medium: 500,
semibold: 600,
demibold: 600,
bold: 700,
"extra bold": 800,
"ultra bold": 800,
black: 900,
heavy: 900,
"extra black": 950,
"ultra black": 950
};
let match;
for (const [name, weight] of Object.entries(weightsByName)) if (new RegExp(`\\b${name}\\b`, "i").test(fontFamily)) match = `${weight}`;
return match;
}
destroy() {
for (const stack in this.entries) {
const entry = this.entries[stack];
entry.tinySDF = null;
entry.ideographTinySDF = null;
entry.glyphs = {};
entry.requests = {};
entry.ranges = {};
}
this.entries = {};
}
};
//#endregion
//#region src/style/light_properties.g.ts
let properties$2;
const getProperties$2 = () => properties$2 = properties$2 || new Properties({
"anchor": new DataConstantProperty(latest["light"]["anchor"], "anchor"),
"position": new DataConstantProperty(latest["light"]["position"], "position"),
"color": new DataConstantProperty(latest["light"]["color"], "color"),
"intensity": new DataConstantProperty(latest["light"]["intensity"], "intensity")
});
//#endregion
//#region src/style/light.ts
var Light = class extends Evented {
constructor(lightOptions, globalState) {
super();
this._transitionable = new Transitionable(getProperties$2(), "light", globalState);
this.setLight(lightOptions);
this._transitioning = this._transitionable.untransitioned();
}
getLight() {
return this._transitionable.serialize();
}
/**
* Gets the light position in cartesian coordinates.
*/
getCartesianPosition() {
return sphericalToCartesian(this.properties.get("position"));
}
setLight(light, options = {}) {
if (this._validate(validateStyle.light, light, options)) return;
for (const name in light) {
const value = light[name];
if (name.endsWith("-transition")) this._transitionable.setTransition(name.slice(0, -TRANSITION_SUFFIX.length), value);
else this._transitionable.setValue(name, value);
}
}
updateTransitions(parameters) {
this._transitioning = this._transitionable.transitioned(parameters, this._transitioning);
}
hasTransition() {
return this._transitioning.hasTransition();
}
recalculate(parameters) {
this.properties = this._transitioning.possiblyEvaluate(parameters);
}
_validate(validate, value, options) {
return validateAndEmit(this, validate, { value }, options);
}
};
//#endregion
//#region src/style/sky_properties.g.ts
let properties$1;
const getProperties$1 = () => properties$1 = properties$1 || new Properties({
"sky-color": new DataConstantProperty(latest["sky"]["sky-color"], "sky-color"),
"horizon-color": new DataConstantProperty(latest["sky"]["horizon-color"], "horizon-color"),
"fog-color": new DataConstantProperty(latest["sky"]["fog-color"], "fog-color"),
"fog-ground-blend": new DataConstantProperty(latest["sky"]["fog-ground-blend"], "fog-ground-blend"),
"horizon-fog-blend": new DataConstantProperty(latest["sky"]["horizon-fog-blend"], "horizon-fog-blend"),
"sky-horizon-blend": new DataConstantProperty(latest["sky"]["sky-horizon-blend"], "sky-horizon-blend"),
"atmosphere-blend": new DataConstantProperty(latest["sky"]["atmosphere-blend"], "atmosphere-blend")
});
//#endregion
//#region src/style/sky.ts
var Sky = class extends Evented {
constructor(sky, globalState) {
super();
this._transitionable = new Transitionable(getProperties$1(), "sky", globalState);
this.setSky(sky);
this._transitioning = this._transitionable.untransitioned();
this.recalculate(new EvaluationParameters(0));
}
setSky(sky, options = {}) {
if (this._validate(validateStyle.sky, sky, options)) return;
sky ||= {
"sky-color": "transparent",
"horizon-color": "transparent",
"fog-color": "transparent",
"fog-ground-blend": 1,
"atmosphere-blend": 0
};
for (const name in sky) {
const value = sky[name];
if (name.endsWith("-transition")) this._transitionable.setTransition(name.slice(0, -TRANSITION_SUFFIX.length), value);
else this._transitionable.setValue(name, value);
}
}
getSky() {
return this._transitionable.serialize();
}
updateTransitions(parameters) {
this._transitioning = this._transitionable.transitioned(parameters, this._transitioning);
}
hasTransition() {
return this._transitioning.hasTransition();
}
recalculate(parameters) {
this.properties = this._transitioning.possiblyEvaluate(parameters);
}
_validate(validate, value, options = {}) {
return validateAndEmit(this, validate, { value }, options);
}
/**
* Currently fog is a very simple implementation, and should only used
* to create an atmosphere near the horizon.
* But because the fog is drawn from the far-clipping-plane to
* map-center, and because the fog does nothing know about the horizon,
* this method does a fadeout in respect of pitch. So, when the horizon
* gets out of view, which is at about pitch 70, this methods calculates
* the corresponding opacity values. Below pitch 60 the fog is completely
* invisible.
*/
calculateFogBlendOpacity(pitch) {
if (pitch < 60) return 0;
if (pitch < 70) return (pitch - 60) / 10;
return 1;
}
};
//#endregion
//#region src/render/line_atlas.ts
/**
* @internal
* A LineAtlas lets us reuse rendered dashed lines
* by writing many of them to a texture and then fetching their positions
* using {@link LineAtlas.getDash}.
*
* @param width - the width
* @param height - the height
*/
var LineAtlas = class {
constructor(width, height) {
this.width = width;
this.height = height;
this.nextRow = 0;
this.data = new Uint8Array(this.width * this.height);
this.dashEntry = {};
}
/**
* Get or create a dash line pattern.
*
* @param dasharray - the key (represented by numbers) to get the dash texture
* @param round - whether to add circle caps in between dash segments
* @returns position of dash texture in {@link DashEntry}
*/
getDash(dasharray, round) {
const key = dasharray.join(",") + String(round);
this.dashEntry[key] ||= this.addDash(dasharray, round);
return this.dashEntry[key];
}
getDashRanges(dasharray, lineAtlasWidth, stretch) {
const oddDashArray = dasharray.length % 2 === 1;
const ranges = [];
let left = oddDashArray ? -dasharray[dasharray.length - 1] * stretch : 0;
let right = dasharray[0] * stretch;
let isDash = true;
ranges.push({
left,
right,
isDash,
zeroLength: dasharray[0] === 0
});
let currentDashLength = dasharray[0];
for (let i = 1; i < dasharray.length; i++) {
isDash = !isDash;
const dashLength = dasharray[i];
left = currentDashLength * stretch;
currentDashLength += dashLength;
right = currentDashLength * stretch;
ranges.push({
left,
right,
isDash,
zeroLength: dashLength === 0
});
}
return ranges;
}
addRoundDash(ranges, stretch, n) {
const halfStretch = stretch / 2;
for (let y = -n; y <= n; y++) {
const row = this.nextRow + n + y;
const index = this.width * row;
let currIndex = 0;
let range = ranges[currIndex];
for (let x = 0; x < this.width; x++) {
if (x / range.right > 1) range = ranges[++currIndex];
const distLeft = Math.abs(x - range.left);
const distRight = Math.abs(x - range.right);
const minDist = Math.min(distLeft, distRight);
let signedDistance;
const distMiddle = y / n * (halfStretch + 1);
if (range.isDash) {
const distEdge = halfStretch - Math.abs(distMiddle);
signedDistance = Math.sqrt(minDist * minDist + distEdge * distEdge);
} else signedDistance = halfStretch - Math.sqrt(minDist * minDist + distMiddle * distMiddle);
this.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128));
}
}
}
addRegularDash(ranges) {
for (let i = ranges.length - 1; i >= 0; --i) {
const part = ranges[i];
const next = ranges[i + 1];
if (part.zeroLength) ranges.splice(i, 1);
else if (next?.isDash === part.isDash) {
next.left = part.left;
ranges.splice(i, 1);
}
}
const first = ranges[0];
const last = ranges[ranges.length - 1];
if (first.isDash === last.isDash) {
first.left = last.left - this.width;
last.right = first.right + this.width;
}
const index = this.width * this.nextRow;
let currIndex = 0;
let range = ranges[currIndex];
for (let x = 0; x < this.width; x++) {
if (x / range.right > 1) range = ranges[++currIndex];
const distLeft = Math.abs(x - range.left);
const distRight = Math.abs(x - range.right);
const minDist = Math.min(distLeft, distRight);
const signedDistance = range.isDash ? minDist : -minDist;
this.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128));
}
}
addDash(dasharray, round) {
const n = round ? 7 : 0;
const height = 2 * n + 1;
if (this.nextRow + height > this.height) {
warnOnce("LineAtlas out of space");
return null;
}
let length = 0;
for (const dash of dasharray) length += dash;
if (length !== 0) {
const stretch = this.width / length;
const ranges = this.getDashRanges(dasharray, this.width, stretch);
if (round) this.addRoundDash(ranges, stretch, n);
else this.addRegularDash(ranges);
}
const dashEntry = {
y: this.nextRow + n,
height: 2 * n,
width: length
};
this.nextRow += height;
this.dirty = true;
return dashEntry;
}
bind(context) {
const gl = context.gl;
if (!this.texture) {
this.texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, this.texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, this.width, this.height, 0, gl.ALPHA, gl.UNSIGNED_BYTE, this.data);
} else {
gl.bindTexture(gl.TEXTURE_2D, this.texture);
if (this.dirty) {
this.dirty = false;
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.width, this.height, gl.ALPHA, gl.UNSIGNED_BYTE, this.data);
}
}
}
};
//#endregion
//#region src/util/web_worker.ts
function isCrossOrigin(url) {
if (!url) return false;
const loc = globalThis.location;
if (!loc) return false;
try {
return new URL(url, loc.href).origin !== loc.origin;
} catch {
return false;
}
}
function defaultWorkerUrl() {
const moduleUrl = import.meta.url;
if (!/^https?:/.test(moduleUrl)) return "";
const workerName = moduleUrl.endsWith("-dev.mjs") ? "maplibre-gl-worker-dev.mjs" : "maplibre-gl-worker.mjs";
return new URL(`./${workerName}`, moduleUrl).href;
}
function createWorker(url, asModule) {
if (asModule) try {
return new Worker(url, { type: "module" });
} catch (e) {
console.warn("Module worker not supported, falling back to classic worker", e);
}
return new Worker(url);
}
async function fetchAsBlobUrl(url) {
const response = await fetch(url);
if (!response.ok) throw new Error(`Failed to fetch worker script (${response.status}): ${url}`);
const code = await response.text();
const blob = new Blob([code], { type: "text/javascript" });
return URL.createObjectURL(blob);
}
function importAsBlobUrl(url) {
const blob = new Blob([`import ${JSON.stringify(new URL(url, import.meta.url).href)}`], { type: "text/javascript" });
return URL.createObjectURL(blob);
}
async function workerFactory() {
const url = config.WORKER_URL || defaultWorkerUrl();
const asModule = url?.endsWith(".cjs") ? false : true;
if (!isCrossOrigin(url)) return createWorker(url, asModule);
if (asModule) {
const blobUrl = importAsBlobUrl(url);
try {
return createWorker(blobUrl, asModule);
} finally {
URL.revokeObjectURL(blobUrl);
}
}
const blobUrl = await fetchAsBlobUrl(url);
try {
return createWorker(blobUrl, asModule);
} finally {
URL.revokeObjectURL(blobUrl);
}
}
//#endregion
//#region src/util/worker_pool.ts
const PRELOAD_POOL_ID = "maplibre_preloaded_worker_pool";
/**
* Constructs a worker pool.
*/
var WorkerPool = class WorkerPool {
constructor() {
this.active = {};
this.workersPromise = null;
}
async acquire(mapId) {
this.active[mapId] = true;
if (!this.workersPromise) {
const promises = [];
while (promises.length < WorkerPool.workerCount) promises.push(workerFactory());
this.workersPromise = Promise.all(promises);
}
return (await this.workersPromise).slice();
}
release(mapId) {
delete this.active[mapId];
if (this.numActive() === 0 && this.workersPromise) {
const promise = this.workersPromise;
this.workersPromise = null;
promise.then((workers) => {
for (const w of workers) w.terminate();
});
}
}
isPreloaded() {
return !!this.active[PRELOAD_POOL_ID];
}
numActive() {
return Object.keys(this.active).length;
}
};
const availableLogicalProcessors = Math.floor(browser.hardwareConcurrency / 2);
WorkerPool.workerCount = isSafari(globalThis) ? Math.max(Math.min(availableLogicalProcessors, 3), 1) : 1;
//#endregion
//#region src/util/global_worker_pool.ts
let globalWorkerPool;
/**
* Creates (if necessary) and returns the single, global WorkerPool instance
* to be shared across each Map
*/
function getGlobalWorkerPool() {
globalWorkerPool ||= new WorkerPool();
return globalWorkerPool;
}
/**
* Initializes resources like WebWorkers that can be shared across maps to lower load
* times in some situations. `setWorkerUrl()` and `setWorkerCount()`, if being
* used, must be set before `prewarm()` is called to have an effect.
*
* By default, the lifecycle of these resources is managed automatically, and they are
* lazily initialized when a Map is first created. By invoking `prewarm()`, these
* resources will be created ahead of time, and will not be cleared when the last Map
* is removed from the page. This allows them to be re-used by new Map instances that
* are created later. They can be manually cleared by calling
* `clearPrewarmedResources()`. This is only necessary if your web page remains
* active but stops using maps altogether.
*
* This is primarily useful when using GL-JS maps in a single page app, wherein a user
* would navigate between various views that can cause Map instances to constantly be
* created and destroyed.
*
* @example
* ```ts
* prewarm()
* ```
*/
function prewarm() {
getGlobalWorkerPool().acquire(PRELOAD_POOL_ID);
}
/**
* Clears up resources that have previously been created by `prewarm()`.
* Note that this is typically not necessary. You should only call this function
* if you expect the user of your app to not return to a Map view at any point
* in your application.
*
* @example
* ```ts
* clearPrewarmedResources()
* ```
*/
function clearPrewarmedResources() {
const pool = globalWorkerPool;
if (pool) {
if (pool.isPreloaded() && pool.numActive() === 1) {
pool.release(PRELOAD_POOL_ID);
globalWorkerPool = null;
} else console.warn("Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()");
}
}
//#endregion
//#region src/util/dispatcher.ts
/**
* Responsible for sending messages from a {@link Source} to an associated worker source (usually with the same name).
*/
var Dispatcher = class {
constructor(workerPool, mapId) {
this.workerPool = workerPool;
this.actors = [];
this.currentActor = 0;
this.id = mapId;
this.removed = false;
this.actorsPromise = this.initActors(mapId);
}
async initActors(mapId) {
const workers = await this.workerPool.acquire(mapId);
if (this.removed) return [];
this.actors = workers.map((worker, i) => {
const actor = new Actor(worker, mapId);
actor.name = `Worker ${i}`;
return actor;
});
if (!this.actors.length) throw new Error("No actors found");
return this.actors;
}
/**
* Broadcast a message to all Workers.
*/
async broadcast(type, data) {
const actors = await this.actorsPromise;
return Promise.all(actors.map((actor) => actor.sendAsync({
type,
data
})));
}
/**
* Acquires an actor to dispatch messages to. The actors are distributed in round-robin fashion.
* @returns An actor object backed by a web worker for processing messages.
*/
async getActor() {
const actors = await this.actorsPromise;
this.currentActor = (this.currentActor + 1) % actors.length;
return actors[this.currentActor];
}
async waitForInitComplete() {
if (this.actors.length === 0) await this.actorsPromise;
}
getReadyActor() {
this.currentActor = (this.currentActor + 1) % this.actors.length;
return this.actors[this.currentActor];
}
remove(mapRemoved = true) {
this.removed = true;
for (const actor of this.actors) actor.remove();
this.actors = [];
if (mapRemoved) this.workerPool.release(this.id);
}
async registerMessageHandler(type, handler) {
const actors = await this.actorsPromise;
for (const actor of actors) actor.registerMessageHandler(type, handler);
}
async unregisterMessageHandler(type) {
const actors = await this.actorsPromise;
for (const actor of actors) actor.unregisterMessageHandler(type);
}
};
let globalDispatcher;
/**
* This function is used to get the global dispatcher that is shared across all maps instances.
* It is used by the main thread to send messages to the workers, and by the workers to send messages back to the main thread.
* If you import a script into the worker and need to send a message to the workers to pass some parameters for example,
* you can use this function to get the global dispatcher and send a message to the workers.
* @returns The global dispatcher instance.
*/
function getGlobalDispatcher() {
if (!globalDispatcher) {
globalDispatcher = new Dispatcher(getGlobalWorkerPool(), GLOBAL_DISPATCHER_ID);
globalDispatcher.registerMessageHandler("GR", (_mapId, params, abortController) => {
return makeRequest(params, abortController);
});
}
return globalDispatcher;
}
//#endregion
//#region src/source/query_features.ts
function getPixelPosMatrix(transform, tileID) {
const t = create$1();
translate(t, t, [
1,
1,
0
]);
scale(t, t, [
transform.width * .5,
transform.height * .5,
1
]);
if (transform.calculatePosMatrix) return multiply(t, t, transform.calculatePosMatrix(tileID.toUnwrapped()));
else return t;
}
function queryIncludes3DLayer(layers, styleLayers, sourceID) {
if (layers) for (const layerID of layers) {
const layer = styleLayers[layerID];
if (layer?.source === sourceID && layer.type === "fill-extrusion") return true;
}
else for (const key in styleLayers) {
const layer = styleLayers[key];
if (layer.source === sourceID && layer.type === "fill-extrusion") return true;
}
return false;
}
function queryRenderedFeatures(tileManager, styleLayers, serializedLayers, queryGeometry, params, transform, getElevation) {
const has3DLayer = queryIncludes3DLayer(params?.layers ?? null, styleLayers, tileManager.id);
const maxPitchScaleFactor = transform.maxPitchScaleFactor();
const tilesIn = tileManager.tilesIn(queryGeometry, maxPitchScaleFactor, has3DLayer);
tilesIn.sort(sortTilesIn);
const renderedFeatureLayers = [];
for (const tileIn of tilesIn) renderedFeatureLayers.push({
wrappedTileID: tileIn.tileID.wrapped().key,
queryResults: tileIn.tile.queryRenderedFeatures(styleLayers, serializedLayers, tileManager.getState(), tileIn.queryGeometry, tileIn.cameraQueryGeometry, tileIn.scale, params, transform, maxPitchScaleFactor, getPixelPosMatrix(transform, tileIn.tileID), getElevation ? (x, y) => getElevation(tileIn.tileID, x, y) : void 0)
});
return convertFeaturesToMapFeatures(mergeRenderedFeatureLayers(renderedFeatureLayers), tileManager);
}
function queryRenderedSymbols(styleLayers, serializedLayers, tileManagers, queryGeometry, params, collisionIndex, retainedQueryData) {
const result = {};
const renderedSymbols = collisionIndex.queryRenderedSymbols(queryGeometry);
const bucketQueryData = [];
for (const bucketInstanceId of Object.keys(renderedSymbols).map(Number)) bucketQueryData.push(retainedQueryData[bucketInstanceId]);
bucketQueryData.sort(sortTilesIn);
for (const queryData of bucketQueryData) {
const bucketSymbols = queryData.featureIndex.lookupSymbolFeatures(renderedSymbols[queryData.bucketInstanceId], serializedLayers, queryData.bucketIndex, queryData.sourceLayerIndex, {
filterSpec: params.filter,
globalState: params.globalState
}, params.layers, params.availableImages, styleLayers);
for (const layerID in bucketSymbols) {
result[layerID] ||= [];
const layerSymbols = bucketSymbols[layerID];
layerSymbols.sort((a, b) => {
const featureSortOrder = queryData.featureSortOrder;
if (featureSortOrder) {
const sortedA = featureSortOrder.indexOf(a.featureIndex);
return featureSortOrder.indexOf(b.featureIndex) - sortedA;
} else return b.featureIndex - a.featureIndex;
});
for (const symbolFeature of layerSymbols) result[layerID].push(symbolFeature);
}
}
return convertFeaturesToMapFeaturesMultiple(result, styleLayers, tileManagers);
}
function querySourceFeatures(tileManager, params) {
const tiles = tileManager.getRenderableIds().map((id) => {
return tileManager.getTileByID(id);
});
const result = [];
const dataTiles = {};
for (const tile of tiles) {
const dataID = tile.tileID.canonical.key;
if (!dataTiles[dataID]) {
dataTiles[dataID] = true;
tile.querySourceFeatures(result, params);
}
}
return result;
}
function sortTilesIn(a, b) {
const idA = a.tileID;
const idB = b.tileID;
return idA.overscaledZ - idB.overscaledZ || idA.canonical.y - idB.canonical.y || idA.wrap - idB.wrap || idA.canonical.x - idB.canonical.x;
}
function mergeRenderedFeatureLayers(tiles) {
const result = {};
const wrappedIDLayerMap = {};
for (const { queryResults, wrappedTileID } of tiles) {
wrappedIDLayerMap[wrappedTileID] ||= {};
const wrappedIDLayers = wrappedIDLayerMap[wrappedTileID];
for (const layerID in queryResults) {
const tileFeatures = queryResults[layerID];
wrappedIDLayers[layerID] ||= {};
const wrappedIDFeatures = wrappedIDLayers[layerID];
result[layerID] ||= [];
for (const tileFeature of tileFeatures) if (!wrappedIDFeatures[tileFeature.featureIndex]) {
wrappedIDFeatures[tileFeature.featureIndex] = true;
result[layerID].push(tileFeature);
}
}
}
return result;
}
function convertFeaturesToMapFeatures(result, tileManager) {
for (const layerID in result) for (const featureWrapper of result[layerID]) convertFeatureToMapFeature(featureWrapper, tileManager);
return result;
}
function convertFeaturesToMapFeaturesMultiple(result, styleLayers, tileManagers) {
for (const layerName in result) for (const featureWrapper of result[layerName]) {
const tileManager = tileManagers[styleLayers[layerName].source];
convertFeatureToMapFeature(featureWrapper, tileManager);
}
return result;
}
function convertFeatureToMapFeature(featureWrapper, tileManager) {
const feature = featureWrapper.feature;
const state = tileManager.getFeatureState(feature.layer["source-layer"], feature.id);
feature.source = feature.layer.source;
if (feature.layer["source-layer"]) feature.sourceLayer = feature.layer["source-layer"];
feature.state = state;
}
//#endregion
//#region src/source/load_tilejson.ts
async function loadTileJson(options, requestManager, abortController, targetWindow) {
let tileJSON = options;
if (options.url) tileJSON = (await getJSON(await requestManager.transformRequest(options.url, "Source"), abortController)).data;
else await browser.frameAsync(abortController, targetWindow);
if (!tileJSON) return null;
const result = pick(extend(tileJSON, options), [
"tiles",
"minzoom",
"maxzoom",
"attribution",
"bounds",
"scheme",
"tileSize",
"encoding"
]);
if ("vector_layers" in tileJSON && tileJSON.vector_layers) result.vectorLayerIds = tileJSON.vector_layers.map((layer) => layer.id);
return result;
}
//#endregion
//#region src/geo/lng_lat_bounds.ts
/**
* A `LngLatBounds` object represents a geographical bounding box,
* defined by its southwest and northeast points in longitude and latitude.
*
* If no arguments are provided to the constructor, a `null` bounding box is created.
*
* Note that any MapLibre GL method that accepts a `LngLatBounds` object as an argument or option
* can also accept an `Array` of two {@link LngLatLike} constructs and will perform an implicit conversion.
* This flexible type is documented as {@link LngLatBoundsLike}.
*
* @group Geography and Geometry
*
* @example
* ```ts
* let sw = new LngLat(-73.9876, 40.7661);
* let ne = new LngLat(-73.9397, 40.8002);
* let llb = new LngLatBounds(sw, ne);
* ```
* @see [Fit to the bounds of a LineString](https://maplibre.org/maplibre-gl-js/docs/examples/fit-to-the-bounds-of-a-linestring/)
*/
var LngLatBounds = class LngLatBounds {
/**
* @param sw - The southwest corner of the bounding box.
* OR array of 4 numbers in the order of west, south, east, north
* OR array of 2 LngLatLike: `[sw, ne]`
* @param ne - The northeast corner of the bounding box.
* @example
* ```ts
* let sw = new LngLat(-73.9876, 40.7661);
* let ne = new LngLat(-73.9397, 40.8002);
* let llb = new LngLatBounds(sw, ne);
* ```
* OR
* ```ts
* let llb = new LngLatBounds([-73.9876, 40.7661, -73.9397, 40.8002]);
* ```
* OR
* ```ts
* let llb = new LngLatBounds([sw, ne]);
* ```
*/
constructor(sw, ne) {
if (!sw) {} else if (ne) this.setSouthWest(sw).setNorthEast(ne);
else if (Array.isArray(sw)) {
if (sw.length === 4) this.setSouthWest([sw[0], sw[1]]).setNorthEast([sw[2], sw[3]]);
else this.setSouthWest(sw[0]).setNorthEast(sw[1]);
}
}
/**
* Set the northeast corner of the bounding box
*
* @param ne - a {@link LngLatLike} object describing the northeast corner of the bounding box.
*/
setNorthEast(ne) {
this._ne = ne instanceof LngLat ? new LngLat(ne.lng, ne.lat) : LngLat.convert(ne);
return this;
}
/**
* Set the southwest corner of the bounding box
*
* @param sw - a {@link LngLatLike} object describing the southwest corner of the bounding box.
*/
setSouthWest(sw) {
this._sw = sw instanceof LngLat ? new LngLat(sw.lng, sw.lat) : LngLat.convert(sw);
return this;
}
/**
* Extend the bounds to include a given LngLatLike or LngLatBoundsLike.
*
* @param obj - object to extend to
*/
extend(obj) {
const sw = this._sw, ne = this._ne;
let sw2, ne2;
if (obj instanceof LngLat) {
sw2 = obj;
ne2 = obj;
} else if (obj instanceof LngLatBounds) {
sw2 = obj._sw;
ne2 = obj._ne;
if (!sw2 || !ne2) return this;
} else {
if (Array.isArray(obj)) {
if (obj.length === 4 || obj.every(Array.isArray)) {
const lngLatBoundsObj = obj;
return this.extend(LngLatBounds.convert(lngLatBoundsObj));
} else {
const lngLatObj = obj;
return this.extend(LngLat.convert(lngLatObj));
}
} else if (obj && ("lng" in obj || "lon" in obj) && "lat" in obj) return this.extend(LngLat.convert(obj));
return this;
}
if (!sw && !ne) {
this._sw = new LngLat(sw2.lng, sw2.lat);
this._ne = new LngLat(ne2.lng, ne2.lat);
} else {
sw.lng = Math.min(sw2.lng, sw.lng);
sw.lat = Math.min(sw2.lat, sw.lat);
ne.lng = Math.max(ne2.lng, ne.lng);
ne.lat = Math.max(ne2.lat, ne.lat);
}
return this;
}
/**
* Returns the geographical coordinate equidistant from the bounding box's corners.
*
* @returns The bounding box's center.
* @example
* ```ts
* let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
* llb.getCenter(); // = LngLat {lng: -73.96365, lat: 40.78315}
* ```
*/
getCenter() {
return new LngLat((this._sw.lng + this._ne.lng) / 2, (this._sw.lat + this._ne.lat) / 2);
}
/**
* Returns the southwest corner of the bounding box.
*
* @returns The southwest corner of the bounding box.
*/
getSouthWest() {
return this._sw;
}
/**
* Returns the northeast corner of the bounding box.
*
* @returns The northeast corner of the bounding box.
*/
getNorthEast() {
return this._ne;
}
/**
* Returns the northwest corner of the bounding box.
*
* @returns The northwest corner of the bounding box.
*/
getNorthWest() {
return new LngLat(this.getWest(), this.getNorth());
}
/**
* Returns the southeast corner of the bounding box.
*
* @returns The southeast corner of the bounding box.
*/
getSouthEast() {
return new LngLat(this.getEast(), this.getSouth());
}
/**
* Returns the west edge of the bounding box.
*
* @returns The west edge of the bounding box.
*/
getWest() {
return this._sw.lng;
}
/**
* Returns the south edge of the bounding box.
*
* @returns The south edge of the bounding box.
*/
getSouth() {
return this._sw.lat;
}
/**
* Returns the east edge of the bounding box.
*
* @returns The east edge of the bounding box.
*/
getEast() {
return this._ne.lng;
}
/**
* Returns the north edge of the bounding box.
*
* @returns The north edge of the bounding box.
*/
getNorth() {
return this._ne.lat;
}
/**
* Returns the bounding box represented as an array.
*
* @returns The bounding box represented as an array, consisting of the
* southwest and northeast coordinates of the bounding represented as arrays of numbers.
* @example
* ```ts
* let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
* llb.toArray(); // = [[-73.9876, 40.7661], [-73.9397, 40.8002]]
* ```
*/
toArray() {
return [this._sw.toArray(), this._ne.toArray()];
}
/**
* Return the bounding box represented as a string.
*
* @returns The bounding box represents as a string of the format
* `'LngLatBounds(LngLat(lng, lat), LngLat(lng, lat))'`.
* @example
* ```ts
* let llb = new LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);
* llb.toString(); // = "LngLatBounds(LngLat(-73.9876, 40.7661), LngLat(-73.9397, 40.8002))"
* ```
*/
toString() {
return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`;
}
/**
* Check if the bounding box is an empty/`null`-type box.
*
* @returns True if bounds have been defined, otherwise false.
*/
isEmpty() {
return !(this._sw && this._ne);
}
/**
* Check if the point is within the bounding box.
*
* @param lnglat - geographic point to check against.
* @returns `true` if the point is within the bounding box.
* @example
* ```ts
* let llb = new LngLatBounds(
* new LngLat(-73.9876, 40.7661),
* new LngLat(-73.9397, 40.8002)
* );
*
* let ll = new LngLat(-73.9567, 40.7789);
*
* console.log(llb.contains(ll)); // = true
* ```
*/
contains(lnglat) {
const { lng, lat } = LngLat.convert(lnglat);
const containsLatitude = this._sw.lat <= lat && lat <= this._ne.lat;
let containsLongitude = this._sw.lng <= lng && lng <= this._ne.lng;
if (this._sw.lng > this._ne.lng) containsLongitude = this._sw.lng >= lng && lng >= this._ne.lng;
return containsLatitude && containsLongitude;
}
/**
* Checks if this bounding box intersects with another bounding box.
*
* Returns true if the bounding boxes share any area, including cases where
* they only touch along an edge or at a corner.
*
* This method properly handles cases where either or both bounding boxes cross
* the antimeridian (date line).
*/
intersects(other) {
other = LngLatBounds.convert(other);
if (!(other.getNorth() >= this.getSouth() && other.getSouth() <= this.getNorth())) return false;
const thisSpan = Math.abs(this.getEast() - this.getWest());
const otherSpan = Math.abs(other.getEast() - other.getWest());
if (thisSpan >= 360 || otherSpan >= 360) return true;
const thisWest = wrap(this.getWest(), -180, 180);
const thisEast = wrap(this.getEast(), -180, 180);
const otherWest = wrap(other.getWest(), -180, 180);
const otherEast = wrap(other.getEast(), -180, 180);
const thisWraps = thisWest > thisEast;
const otherWraps = otherWest > otherEast;
if (thisWraps && otherWraps) return true;
if (thisWraps) return otherEast >= thisWest || otherWest <= thisEast;
if (otherWraps) return thisEast >= otherWest || thisWest <= otherEast;
return otherWest <= thisEast && otherEast >= thisWest;
}
/**
* Converts an array to a `LngLatBounds` object.
*
* If a `LngLatBounds` object is passed in, the function returns it unchanged.
*
* Internally, the function calls {@link LngLat.convert} to convert arrays to `LngLat` values.
*
* @param input - An array of two coordinates to convert, or a `LngLatBounds` object to return.
* @returns A new `LngLatBounds` object, if a conversion occurred, or the original `LngLatBounds` object.
* @example
* ```ts
* let arr = [[-73.9876, 40.7661], [-73.9397, 40.8002]];
* let llb = LngLatBounds.convert(arr); // = LngLatBounds {_sw: LngLat {lng: -73.9876, lat: 40.7661}, _ne: LngLat {lng: -73.9397, lat: 40.8002}}
* ```
*/
static convert(input) {
if (input instanceof LngLatBounds) return input;
if (!input) return input;
return new LngLatBounds(input);
}
/**
* Returns a `LngLatBounds` from the coordinates extended by a given `radius`. The returned `LngLatBounds` completely contains the `radius`.
*
* @param center - center coordinates of the new bounds.
* @param radius - Distance in meters from the coordinates to extend the bounds.
* @returns A new `LngLatBounds` object representing the coordinates extended by the `radius`.
* @example
* ```ts
* let center = new LngLat(-73.9749, 40.7736);
* LngLatBounds.fromLngLat(100).toArray(); // = [[-73.97501862141328, 40.77351016847229], [-73.97478137858673, 40.77368983152771]]
* ```
*/
static fromLngLat(center, radius = 0) {
const latAccuracy = 360 * radius / 40075017, lngAccuracy = latAccuracy / Math.cos(Math.PI / 180 * center.lat);
return new LngLatBounds(new LngLat(center.lng - lngAccuracy, center.lat - latAccuracy), new LngLat(center.lng + lngAccuracy, center.lat + latAccuracy));
}
/**
* Adjusts the given bounds to handle the case where the bounds cross the 180th meridian (antimeridian).
*
* @returns The adjusted LngLatBounds
* @example
* ```ts
* let bounds = new LngLatBounds([175.813127, -20.157768], [-178. 340903, -15.449124]);
* let adjustedBounds = bounds.adjustAntiMeridian();
* // adjustedBounds will be: [[175.813127, -20.157768], [181.659097, -15.449124]]
* ```
*/
adjustAntiMeridian() {
const sw = new LngLat(this._sw.lng, this._sw.lat);
const ne = new LngLat(this._ne.lng, this._ne.lat);
if (sw.lng > ne.lng) return new LngLatBounds(sw, new LngLat(ne.lng + 360, ne.lat));
return new LngLatBounds(sw, ne);
}
};
//#endregion
//#region src/tile/tile_bounds.ts
var TileBounds = class {
constructor(bounds, minzoom, maxzoom) {
this.bounds = LngLatBounds.convert(this.validateBounds(bounds));
this.minzoom = minzoom || 0;
this.maxzoom = maxzoom || 24;
}
validateBounds(bounds) {
if (!Array.isArray(bounds) || bounds.length !== 4) return [
-180,
-90,
180,
90
];
return [
Math.max(-180, bounds[0]),
Math.max(-90, bounds[1]),
Math.min(180, bounds[2]),
Math.min(90, bounds[3])
];
}
contains(tileID) {
const worldSize = Math.pow(2, tileID.z);
const level = {
minX: Math.floor(mercatorXfromLng(this.bounds.getWest()) * worldSize),
minY: Math.floor(mercatorYfromLat(this.bounds.getNorth()) * worldSize),
maxX: Math.ceil(mercatorXfromLng(this.bounds.getEast()) * worldSize),
maxY: Math.ceil(mercatorYfromLat(this.bounds.getSouth()) * worldSize)
};
return tileID.x >= level.minX && tileID.x < level.maxX && tileID.y >= level.minY && tileID.y < level.maxY;
}
};
//#endregion
//#region src/source/vector_tile_source.ts
/**
* A source containing vector tiles in [Maplibre Vector Tile format](https://maplibre.org/maplibre-tile-spec/) or [Mapbox Vector Tile format](https://docs.mapbox.com/vector-tiles/reference/).
* (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.)
*
* @group Sources
*
* @example
* ```ts
* map.addSource('some id', {
* type: 'vector',
* url: 'https://demotiles.maplibre.org/tiles/tiles.json'
* });
* ```
*
* @example
* ```ts
* map.addSource('some id', {
* type: 'vector',
* tiles: ['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt'],
* minzoom: 6,
* maxzoom: 14
* });
* ```
*
* @example
* ```ts
* map.getSource('some id').setUrl("https://demotiles.maplibre.org/tiles/tiles.json");
* ```
*
* @example
* ```ts
* map.getSource('some id').setTiles(['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt']);
* ```
* @see [Add a vector tile source](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-vector-tile-source/)
*/
var VectorTileSource = class extends Evented {
constructor(id, options, dispatcher, eventedParent) {
super();
this.id = id;
this.dispatcher = dispatcher;
this.type = "vector";
this.minzoom = 0;
this.maxzoom = 22;
this.scheme = "xyz";
this.tileSize = 512;
this.reparseOverscaled = true;
this.isTileClipped = true;
this._loaded = false;
extend(this, pick(options, [
"url",
"scheme",
"tileSize",
"promoteId",
"encoding"
]));
this._options = extend({ type: "vector" }, options);
this._collectResourceTiming = options.collectResourceTiming;
if (this.tileSize !== 512) throw new Error("vector tile sources must have a tileSize of 512");
this.setEventedParent(eventedParent);
}
async load(sourceDataChanged = false) {
this._loaded = false;
this.fire(new MapSourceDataEvent("dataloading"));
this._tileJSONRequest = new AbortController();
try {
const tileJSON = await loadTileJson(this._options, this.map._requestManager, this._tileJSONRequest, this.map._ownerWindow);
this._tileJSONRequest = null;
this._loaded = true;
if (tileJSON) {
extend(this, tileJSON);
if (tileJSON.bounds) this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom);
this.fire(new MapSourceDataEvent("data", { sourceDataType: "metadata" }));
this.fire(new MapSourceDataEvent("data", {
sourceDataType: "content",
sourceDataChanged
}));
}
} catch (err) {
this._tileJSONRequest = null;
this._loaded = true;
if (!isAbortError(err)) this.fire(new ErrorEvent(ensureError(err)));
}
}
loaded() {
return this._loaded;
}
hasTile(tileID) {
return !this.tileBounds || this.tileBounds.contains(tileID.canonical);
}
onAdd(map) {
this.map = map;
this.load();
}
setSourceProperty(callback) {
if (this._tileJSONRequest) this._tileJSONRequest.abort();
callback();
this.load(true);
}
/**
* Sets the source `tiles` property and re-renders the map.
*
* @param tiles - An array of one or more tile source URLs, as in the TileJSON spec.
*/
setTiles(tiles) {
this.setSourceProperty(() => {
this._options.tiles = tiles;
});
return this;
}
/**
* Sets the source `url` property and re-renders the map.
*
* @param url - A URL to a TileJSON resource. Supported protocols are `http:` and `https:`.
*/
setUrl(url) {
this.setSourceProperty(() => {
this.url = url;
this._options.url = url;
});
return this;
}
onRemove() {
if (this._tileJSONRequest) {
this._tileJSONRequest.abort();
this._tileJSONRequest = null;
}
}
serialize() {
return extend({}, this._options);
}
async loadTile(tile) {
const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme);
const params = {
request: await this.map._requestManager.transformRequest(url, "Tile"),
uid: tile.uid,
tileID: tile.tileID,
zoom: tile.tileID.overscaledZ,
tileSize: this.tileSize * tile.tileID.overscaleFactor(),
type: this.type,
source: this.id,
pixelRatio: this.map.getPixelRatio(),
showCollisionBoxes: this.map.showCollisionBoxes,
promoteId: this.promoteId,
subdivisionGranularity: this.map.style.projection.subdivisionGranularity,
encoding: this.encoding,
overzoomParameters: await this._getOverzoomParameters(tile),
etag: tile.etag
};
params.request.collectResourceTiming = this._collectResourceTiming;
await this.dispatcher.waitForInitComplete();
let messageType = "RT";
if (!tile.actor || tile.state === "expired") {
tile.actor = this.dispatcher.getReadyActor();
messageType = "LT";
} else if (tile.state === "loading") return new Promise((resolve, reject) => {
tile.reloadPromise = {
resolve,
reject
};
});
tile.abortController = new AbortController();
try {
const data = await tile.actor.sendAsync({
type: messageType,
data: params
}, tile.abortController);
delete tile.abortController;
if (tile.aborted) return;
this._afterTileLoadWorkerResponse(tile, data);
const result = {};
if (data?.etagUnmodified) result.unmodified = true;
return result;
} catch (err) {
delete tile.abortController;
if (tile.aborted || isAbortError(err)) return;
if (err && err.status !== 404) throw err;
this._afterTileLoadWorkerResponse(tile, null);
}
}
/**
* When the requested tile has a higher canonical Z than source maxzoom, pass overzoom parameters so worker can load the
* deepest tile at source max zoom to generate sub tiles using geojsonvt for highest performance on vector overscaling
*/
async _getOverzoomParameters(tile) {
if (tile.tileID.canonical.z <= this.maxzoom) return;
if (this.map._zoomLevelsToOverscale === void 0) return;
const maxZoomTileID = tile.tileID.scaledTo(this.maxzoom).canonical;
const maxZoomTileUrl = maxZoomTileID.url(this.tiles, this.map.getPixelRatio(), this.scheme);
return {
maxZoomTileID,
overzoomRequest: await this.map._requestManager.transformRequest(maxZoomTileUrl, "Tile")
};
}
_afterTileLoadWorkerResponse(tile, data) {
if (data?.resourceTiming) tile.resourceTiming = data.resourceTiming;
if (data && this.map._refreshExpiredTiles) tile.setExpiryData(data);
tile.etag = data?.etag;
tile.loadVectorData(data, this.map.painter);
if (tile.reloadPromise) {
const reloadPromise = tile.reloadPromise;
tile.reloadPromise = null;
this.loadTile(tile).then(reloadPromise.resolve).catch(reloadPromise.reject);
}
}
async abortTile(tile) {
if (tile.abortController) {
tile.abortController.abort();
delete tile.abortController;
}
if (tile.actor) await tile.actor.sendAsync({
type: "AT",
data: {
uid: tile.uid,
type: this.type,
source: this.id
}
});
}
async unloadTile(tile) {
tile.unloadVectorData();
if (tile.actor) await tile.actor.sendAsync({
type: "RMT",
data: {
uid: tile.uid,
type: this.type,
source: this.id
}
});
}
hasTransition() {
return false;
}
};
//#endregion
//#region src/source/raster_tile_source.ts
/**
* A source containing raster tiles (See the [raster source documentation](https://maplibre.org/maplibre-style-spec/sources/#raster) for detailed documentation of options.)
*
* @group Sources
*
* \> ℹ️ **Note:** The default `tileSize` is `512`. If your tile provider (such as OpenStreetMap or Stadia Maps) serves 256px tiles, set `tileSize: 256` manually to avoid blurry rendering due to upscaling.
*
* @example
* ```ts
* map.addSource('raster-source', {
* 'type': 'raster',
* 'tiles': ['https://tiles.stadiamaps.com/tiles/stamen_watercolor/{z}/{x}/{y}.jpg'],
* 'tileSize': 256, // Set this to match tile server output to avoid blurry rendering
* });
* ```
*
* @example
* ```ts
* map.addSource('wms-test-source', {
* 'type': 'raster',
* // use the tiles option to specify a WMS tile source URL
* 'tiles': [
* 'https://img.nj.gov/imagerywms/Natural2015?bbox={bbox-epsg-3857}&format=image/png&service=WMS&version=1.1.1&request=GetMap&srs=EPSG:3857&transparent=true&width=256&height=256&layers=Natural2015'
* ],
* 'tileSize': 256 // Important for WMS if tiles are 256px
* });
* ```
* @see [Add a raster tile source](https://maplibre.org/maplibre-gl-js/docs/examples/map-tiles/)
* @see [Add a WMS source](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-wms-source/)
* @see [Display a satellite map](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-satellite-map/)
*/
var RasterTileSource = class extends Evented {
constructor(id, options, dispatcher, eventedParent) {
super();
this.id = id;
this.dispatcher = dispatcher;
this.setEventedParent(eventedParent);
this.type = "raster";
this.minzoom = 0;
this.maxzoom = 22;
this.roundZoom = true;
this.scheme = "xyz";
this.tileSize = 512;
this._loaded = false;
this._premultiplyAlpha = true;
this._options = extend({ type: "raster" }, options);
extend(this, pick(options, [
"url",
"scheme",
"tileSize"
]));
}
async load(sourceDataChanged = false) {
this._loaded = false;
this.fire(new MapSourceDataEvent("dataloading"));
this._tileJSONRequest = new AbortController();
try {
const tileJSON = await loadTileJson(this._options, this.map._requestManager, this._tileJSONRequest, this.map._ownerWindow);
this._tileJSONRequest = null;
this._loaded = true;
if (tileJSON) {
extend(this, tileJSON);
if (tileJSON.bounds) this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom);
this.fire(new MapSourceDataEvent("data", { sourceDataType: "metadata" }));
this.fire(new MapSourceDataEvent("data", {
sourceDataType: "content",
sourceDataChanged
}));
}
} catch (err) {
this._tileJSONRequest = null;
this._loaded = true;
if (!isAbortError(err)) this.fire(new ErrorEvent(ensureError(err)));
}
}
loaded() {
return this._loaded;
}
onAdd(map) {
this.map = map;
this.load();
}
onRemove() {
if (this._tileJSONRequest) {
this._tileJSONRequest.abort();
this._tileJSONRequest = null;
}
}
setSourceProperty(callback) {
if (this._tileJSONRequest) {
this._tileJSONRequest.abort();
this._tileJSONRequest = null;
}
callback();
this.load(true);
}
/**
* Sets the source `tiles` property and re-renders the map.
*
* @param tiles - An array of one or more tile source URLs, as in the raster tiles spec (See the [Style Specification](https://maplibre.org/maplibre-style-spec/)
*/
setTiles(tiles) {
this.setSourceProperty(() => {
this._options.tiles = tiles;
});
return this;
}
/**
* Sets the source `url` property and re-renders the map.
*
* @param url - A URL to a TileJSON resource. Supported protocols are `http:` and `https:`.
*/
setUrl(url) {
this.setSourceProperty(() => {
this.url = url;
this._options.url = url;
});
return this;
}
serialize() {
return extend({}, this._options);
}
/**
* Sets whether alpha premultiplication is applied to raster tile images.
* Set to `false` to preserve exact RGBA byte values when alpha carries data instead of opacity.
*
* @param premultiplyAlpha - If `false`, disables alpha premultiplication for raster tile image decode and texture upload.
* @example
* ```ts
* map.getSource<RasterTileSource>('raster-source').setPremultiplyAlpha(false);
* ```
*/
setPremultiplyAlpha(premultiplyAlpha) {
if (this._premultiplyAlpha === premultiplyAlpha) return this;
this.setSourceProperty(() => {
this._premultiplyAlpha = premultiplyAlpha;
});
return this;
}
hasTile(tileID) {
return !this.tileBounds || this.tileBounds.contains(tileID.canonical);
}
async loadTile(tile) {
const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme);
const premultiply = this._premultiplyAlpha;
const imageBitmapOptions = premultiply ? void 0 : { premultiplyAlpha: "none" };
tile.abortController = new AbortController();
try {
const response = await ImageRequest.transformAndGetImage(this.map._requestManager, url, "Tile", tile.abortController, this.map._refreshExpiredTiles, imageBitmapOptions);
delete tile.abortController;
if (tile.aborted) {
tile.state = "unloaded";
return;
}
if (response?.data) {
if (this.map._refreshExpiredTiles && (response.cacheControl || response.expires)) tile.setExpiryData({
cacheControl: response.cacheControl,
expires: response.expires
});
const context = this.map.painter.context;
const gl = context.gl;
const img = response.data;
tile.texture = this.map.painter.getTileTexture(img.width);
if (tile.texture) tile.texture.update(img, {
useMipmap: true,
premultiply
});
else {
tile.texture = new Texture(context, img, gl.RGBA, {
useMipmap: true,
premultiply
});
tile.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);
}
tile.state = "loaded";
}
} catch (err) {
delete tile.abortController;
if (tile.aborted) tile.state = "unloaded";
else if (err) {
tile.state = "errored";
throw err;
}
}
}
async abortTile(tile) {
if (tile.abortController) {
tile.abortController.abort();
delete tile.abortController;
}
}
async unloadTile(tile) {
if (tile.texture) this.map.painter.saveTileTexture(tile.texture);
}
hasTransition() {
return false;
}
};
//#endregion
//#region src/source/raster_dem_tile_source.ts
/**
* A source containing raster DEM tiles (See the [Style Specification](https://maplibre.org/maplibre-style-spec/) for detailed documentation of options.)
* This source can be used to show hillshading and 3D terrain
*
* @group Sources
*
* @example
* ```ts
* map.addSource('raster-dem-source', {
* type: 'raster-dem',
* url: 'https://demotiles.maplibre.org/terrain-tiles/tiles.json',
* tileSize: 256
* });
* ```
* @see [3D Terrain](https://maplibre.org/maplibre-gl-js/docs/examples/3d-terrain/)
*/
var RasterDEMTileSource = class extends RasterTileSource {
constructor(id, options, dispatcher, eventedParent) {
super(id, options, dispatcher, eventedParent);
this.type = "raster-dem";
this.maxzoom = 22;
this._options = extend({ type: "raster-dem" }, options);
this.encoding = options.encoding || "mapbox";
this.redFactor = options.redFactor;
this.greenFactor = options.greenFactor;
this.blueFactor = options.blueFactor;
this.baseShift = options.baseShift;
}
async loadTile(tile) {
const url = tile.tileID.canonical.url(this.tiles, this.map.getPixelRatio(), this.scheme);
tile.neighboringTiles = this._getNeighboringTiles(tile.tileID);
tile.abortController = new AbortController();
try {
const response = await ImageRequest.transformAndGetImage(this.map._requestManager, url, "Tile", tile.abortController, this.map._refreshExpiredTiles, { colorSpaceConversion: "none" });
delete tile.abortController;
if (tile.aborted) {
tile.state = "unloaded";
return;
}
if (response?.data) {
const img = response.data;
if (this.map._refreshExpiredTiles && (response.cacheControl || response.expires)) tile.setExpiryData({
cacheControl: response.cacheControl,
expires: response.expires
});
const rawImageData = isImageBitmap(img) && offscreenCanvasSupported() ? img : await this.readImageNow(img);
const params = {
type: this.type,
uid: tile.uid,
source: this.id,
rawImageData,
encoding: this.encoding,
redFactor: this.redFactor,
greenFactor: this.greenFactor,
blueFactor: this.blueFactor,
baseShift: this.baseShift
};
if (tile.actor && tile.state !== "expired" && tile.state !== "reloading") return;
await this.dispatcher.waitForInitComplete();
if (!tile.actor || tile.state === "expired") tile.actor = this.dispatcher.getReadyActor();
tile.dem = await tile.actor.sendAsync({
type: "LDT",
data: params
});
tile.needsHillshadePrepare = true;
tile.needsTerrainPrepare = true;
tile.state = "loaded";
}
} catch (err) {
delete tile.abortController;
if (tile.aborted) tile.state = "unloaded";
else if (err) {
tile.state = "errored";
throw err;
}
}
}
async readImageNow(img) {
if (typeof VideoFrame !== "undefined" && isOffscreenCanvasDistorted()) {
const width = img.width + 2;
const height = img.height + 2;
try {
return new RGBAImage({
width,
height
}, await readImageUsingVideoFrame(img, -1, -1, width, height));
} catch {}
}
return browser.getImageData(img, 1);
}
_getNeighboringTiles(tileID) {
const canonical = tileID.canonical;
const dim = Math.pow(2, canonical.z);
const px = (canonical.x - 1 + dim) % dim;
const pxw = canonical.x === 0 ? tileID.wrap - 1 : tileID.wrap;
const nx = (canonical.x + 1 + dim) % dim;
const nxw = canonical.x + 1 === dim ? tileID.wrap + 1 : tileID.wrap;
const neighboringTiles = {};
neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y).key] = { backfilled: false };
neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y).key] = { backfilled: false };
if (canonical.y > 0) {
neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y - 1).key] = { backfilled: false };
neighboringTiles[new OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y - 1).key] = { backfilled: false };
neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y - 1).key] = { backfilled: false };
}
if (canonical.y + 1 < dim) {
neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y + 1).key] = { backfilled: false };
neighboringTiles[new OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y + 1).key] = { backfilled: false };
neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y + 1).key] = { backfilled: false };
}
return neighboringTiles;
}
async unloadTile(tile) {
if (tile.demTexture) this.map.painter.saveTileTexture(tile.demTexture);
if (tile.fbo) {
tile.fbo.destroy();
delete tile.fbo;
}
if (tile.dem) delete tile.dem;
delete tile.neighboringTiles;
tile.state = "unloaded";
if (tile.actor) await tile.actor.sendAsync({
type: "RDT",
data: {
type: this.type,
uid: tile.uid,
source: this.id
}
});
}
};
//#endregion
//#region src/source/geojson_source_diff.ts
function getFeatureId(feature, promoteId) {
return promoteId ? feature.properties[promoteId] : feature.id;
}
/**
* Converts a GeoJSON object into a map of feature IDs to GeoJSON features.
* @param data - The GeoJSON object to convert.
* @param promoteId - If set, the feature id will be set to the promoteId property value.
* @returns A map of feature IDs to GeoJSON features, or `undefined` if the GeoJSON object is not a valid updateable object.
*
* Features must have unique identifiers to be updateable. IDs can come from:
* - The feature's `id` property (standard GeoJSON)
* - A promoted property specified by `promoteId` (e.g., a "name" property)
*/
function toUpdateable(data, promoteId) {
const updateable = /* @__PURE__ */ new Map();
if (data == null) return updateable;
if (data.type == null) return updateable;
if (data.type === "Feature") {
const id = getFeatureId(data, promoteId);
if (id == null) return void 0;
updateable.set(id, data);
return updateable;
}
if (data.type === "FeatureCollection") {
const seenIds = /* @__PURE__ */ new Set();
for (const feature of data.features) {
const id = getFeatureId(feature, promoteId);
if (id == null) return void 0;
if (seenIds.has(id)) return void 0;
seenIds.add(id);
updateable.set(id, feature);
}
return updateable;
}
}
/**
* Mutates updateable and applies a {@link GeoJSONSourceDiff}. Operations are processed in a specific order to ensure predictable behavior:
* 1. Remove operations (removeAll, remove)
* 2. Add operations (add)
* 3. Update operations (update)
* @returns an array of geometries that were affected by the diff - with the exception of removeAll which does not track any affected geometries.
*/
function applySourceDiff(updateable, diff, promoteId) {
const affectedGeometries = [];
if (diff.removeAll) updateable.clear();
else if (diff.remove) for (const id of diff.remove) {
const existing = updateable.get(id);
if (!existing) continue;
affectedGeometries.push(existing.geometry);
updateable.delete(id);
}
if (diff.add) for (const feature of diff.add) {
const id = getFeatureId(feature, promoteId);
if (id == null) continue;
const existing = updateable.get(id);
if (existing) affectedGeometries.push(existing.geometry);
affectedGeometries.push(feature.geometry);
updateable.set(id, feature);
}
if (diff.update) for (const update of diff.update) {
const existing = updateable.get(update.id);
if (!existing) continue;
const changeGeometry = !!update.newGeometry;
const changeProps = update.removeAllProperties || update.removeProperties?.length > 0 || update.addOrUpdateProperties?.length > 0;
if (!changeGeometry && !changeProps) continue;
affectedGeometries.push(existing.geometry);
const feature = { ...existing };
updateable.set(update.id, feature);
if (changeGeometry) {
affectedGeometries.push(update.newGeometry);
feature.geometry = update.newGeometry;
}
if (changeProps) {
if (update.removeAllProperties) feature.properties = {};
else feature.properties = { ...feature.properties || {} };
if (update.removeProperties) for (const key of update.removeProperties) delete feature.properties[key];
if (update.addOrUpdateProperties) for (const { key, value } of update.addOrUpdateProperties) feature.properties[key] = value;
}
}
return affectedGeometries;
}
/**
* Merge two GeoJSONSourceDiffs, considering the order of operations as specified above (remove, add, update).
*
* For `add` features that use promoteId, the feature id will be set to the promoteId value temporarily so that
* the merge can be completed, then reverted to the original promoteId state after the merge.
*/
function mergeSourceDiffs(prevDiff, nextDiff, promoteId) {
if (!prevDiff) return nextDiff || {};
if (!nextDiff) return prevDiff || {};
if (promoteId) {
promoteFeatureIds(prevDiff.add, promoteId);
promoteFeatureIds(nextDiff.add, promoteId);
}
const prev = diffToHashed(prevDiff);
const next = diffToHashed(nextDiff);
resolveMergeConflicts(prev, next);
const merged = {};
if (prev.removeAll || next.removeAll) merged.removeAll = true;
merged.remove = /* @__PURE__ */ new Set([...prev.remove, ...next.remove]);
merged.add = new Map([...prev.add, ...next.add]);
merged.update = new Map([...prev.update, ...next.update]);
if (merged.remove.size && merged.add.size) for (const id of merged.add.keys()) merged.remove.delete(id);
const mergedDiff = hashedToDiff(merged);
if (promoteId) demoteFeatureIds(mergedDiff.add, promoteId);
return mergedDiff;
}
/**
* Resolve merge conflicts between two GeoJSONSourceDiffs considering the ordering above (remove/add/update).
*
* - If you `removeAll` and then `add` features in the same diff, the added features will be kept.
* - Updates only apply to features that exist after removes and adds have been processed.
*/
function resolveMergeConflicts(prev, next) {
if (next.removeAll) {
prev.add.clear();
prev.update.clear();
prev.remove.clear();
next.remove.clear();
}
for (const id of next.remove) {
prev.add.delete(id);
prev.update.delete(id);
}
for (const [id, nextUpdate] of next.update) {
const prevUpdate = prev.update.get(id);
if (!prevUpdate) continue;
next.update.set(id, mergeFeatureDiffs(prevUpdate, nextUpdate));
prev.update.delete(id);
}
}
/**
* Merge two feature diffs for the same feature id, considering the order of operations as specified above (remove, add/update).
*/
function mergeFeatureDiffs(prev, next) {
const merged = { id: prev.id };
if (next.removeAllProperties) {
delete prev.removeProperties;
delete prev.addOrUpdateProperties;
delete next.removeProperties;
}
if (next.removeProperties) for (const key of next.removeProperties) {
const index = prev.addOrUpdateProperties.findIndex((prop) => prop.key === key);
if (index > -1) prev.addOrUpdateProperties.splice(index, 1);
}
if (prev.removeAllProperties || next.removeAllProperties) merged.removeAllProperties = true;
if (prev.removeProperties || next.removeProperties) merged.removeProperties = [...prev.removeProperties || [], ...next.removeProperties || []];
if (prev.addOrUpdateProperties || next.addOrUpdateProperties) merged.addOrUpdateProperties = [...prev.addOrUpdateProperties || [], ...next.addOrUpdateProperties || []];
if (prev.newGeometry || next.newGeometry) merged.newGeometry = next.newGeometry || prev.newGeometry;
return merged;
}
/**
* Mutates diff.add and applies a feature id using the promoteId property
*/
function promoteFeatureIds(add, promoteId) {
if (!add) return;
for (const feature of add) {
const id = getFeatureId(feature, promoteId);
if (id != null) feature.id = id;
}
}
/**
* Mutates diff.add and removes the feature id if using the promoteId property
*/
function demoteFeatureIds(add, promoteId) {
if (!add) return;
for (const feature of add) if (getFeatureId(feature, promoteId) != null) delete feature.id;
}
/**
* @internal
* Convert a GeoJSONSourceDiff to an idempotent hashed representation using Sets and Maps
*/
function diffToHashed(diff) {
if (!diff) return {};
const hashed = {};
hashed.removeAll = diff.removeAll;
hashed.remove = new Set(diff.remove || []);
hashed.add = new Map(diff.add?.map((feature) => [feature.id, feature]));
hashed.update = new Map(diff.update?.map((update) => [update.id, update]));
return hashed;
}
/**
* @internal
* Convert a hashed GeoJSONSourceDiff back to the array-based representation
*/
function hashedToDiff(hashed) {
const diff = {};
if (hashed.removeAll) diff.removeAll = hashed.removeAll;
if (hashed.remove) diff.remove = Array.from(hashed.remove);
if (hashed.add) diff.add = Array.from(hashed.add.values());
if (hashed.update) diff.update = Array.from(hashed.update.values());
return diff;
}
//#endregion
//#region src/util/geojson_bounds.ts
function extractCoordinates(coords) {
if (!coords || coords.length === 0) return [];
if (typeof coords[0] === "number") return [coords];
return coords.flatMap((c) => extractCoordinates(c));
}
function getCoordinatesFromGeometry(geometry) {
if (geometry.type === "GeometryCollection") return geometry.geometries.flatMap((g) => getCoordinatesFromGeometry(g));
return extractCoordinates(geometry.coordinates);
}
/**
* Calculates the bounding box of GeoJSON data.
* @param data - The GeoJSON data to calculate bounds for
* @returns The bounding box of the GeoJSON data
*/
function getGeoJSONBounds(data) {
const bounds = new LngLatBounds();
let coordinates;
switch (data.type) {
case "FeatureCollection":
coordinates = data.features.flatMap((f) => getCoordinatesFromGeometry(f.geometry));
break;
case "Feature":
coordinates = getCoordinatesFromGeometry(data.geometry);
break;
default: coordinates = getCoordinatesFromGeometry(data);
}
if (coordinates.length === 0) return bounds;
for (const coordinate of coordinates) {
const [lng, lat] = coordinate;
bounds.extend([lng, lat]);
}
return bounds;
}
//#endregion
//#region src/tile/tile_id_to_lng_lat_bounds.ts
function tileIdToLngLatBounds({ x, y, z }, buffer = 0) {
const lngMin = lngFromMercatorX((x - buffer) / Math.pow(2, z));
const latMin = latFromMercatorY((y + 1 + buffer) / Math.pow(2, z));
const lngMax = lngFromMercatorX((x + 1 + buffer) / Math.pow(2, z));
const latMax = latFromMercatorY((y - buffer) / Math.pow(2, z));
return new LngLatBounds([lngMin, latMin], [lngMax, latMax]);
}
//#endregion
//#region src/source/geojson_source.ts
/**
* A source containing GeoJSON.
* (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-geojson) for detailed documentation of options.)
*
* @group Sources
*
* @example
* ```ts
* map.addSource('some id', {
* type: 'geojson',
* data: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson'
* });
* ```
*
* @example
* ```ts
* map.addSource('some id', {
* type: 'geojson',
* data: {
* "type": "FeatureCollection",
* "features": [{
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "Point",
* "coordinates": [
* -76.53063297271729,
* 39.18174077994108
* ]
* }
* }]
* }
* });
* ```
*
* @example
* ```ts
* map.getSource('some id').setData({
* "type": "FeatureCollection",
* "features": [{
* "type": "Feature",
* "properties": { "name": "Null Island" },
* "geometry": {
* "type": "Point",
* "coordinates": [ 0, 0 ]
* }
* }]
* });
* ```
* @see [Draw GeoJSON points](https://maplibre.org/maplibre-gl-js/docs/examples/draw-geojson-points/)
* @see [Add a GeoJSON line](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-geojson-line/)
* @see [Create a heatmap from points](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-heatmap-layer/)
* @see [Create and style clusters](https://maplibre.org/maplibre-gl-js/docs/examples/create-and-style-clusters/)
*/
var GeoJSONSource = class extends Evented {
/** @internal */
constructor(id, options, dispatcher, eventedParent) {
super();
this.id = id;
this.type = "geojson";
this.minzoom = 0;
this.maxzoom = 18;
this.tileSize = 512;
this.isTileClipped = true;
this.reparseOverscaled = true;
this._removed = false;
this._isUpdatingWorker = false;
this._pendingWorkerUpdate = { data: options.data };
this.actorPromise = dispatcher.getActor();
this.setEventedParent(eventedParent);
this._data = typeof options.data === "string" ? { url: options.data } : { geojson: options.data };
this._options = extend({}, options);
this._collectResourceTiming = options.collectResourceTiming;
if (options.maxzoom !== void 0) this.maxzoom = options.maxzoom;
if (options.type) this.type = options.type;
if (options.attribution) this.attribution = options.attribution;
this.promoteId = options.promoteId;
if (options.clusterMaxZoom !== void 0 && this.maxzoom <= options.clusterMaxZoom) warnOnce(`The maxzoom value "${this.maxzoom}" is expected to be greater than the clusterMaxZoom value "${options.clusterMaxZoom}".`);
this.workerOptions = extend({
source: this.id,
geojsonVtOptions: {
buffer: this._pixelsToTileUnits(options.buffer !== void 0 ? options.buffer : 128),
tolerance: this._pixelsToTileUnits(options.tolerance !== void 0 ? options.tolerance : .375),
extent: EXTENT,
maxZoom: this.maxzoom,
lineMetrics: options.lineMetrics || false,
generateId: options.generateId || false,
promoteId: typeof options.promoteId === "string" ? options.promoteId : void 0,
cluster: options.cluster || false,
clusterOptions: {
maxZoom: this._getClusterMaxZoom(options.clusterMaxZoom),
minPoints: Math.max(2, options.clusterMinPoints || 2),
extent: EXTENT,
radius: this._pixelsToTileUnits(options.clusterRadius || 50),
log: false,
generateId: options.generateId || false
}
},
clusterProperties: options.clusterProperties,
filter: options.filter
}, options.workerOptions);
}
_hasPendingWorkerUpdate() {
return this._pendingWorkerUpdate.data !== void 0 || this._pendingWorkerUpdate.diff !== void 0 || this._pendingWorkerUpdate.updateCluster;
}
_pixelsToTileUnits(pixelValue) {
return pixelValue * (EXTENT / this.tileSize);
}
_tileUnitsToPixels(tileUnitValue) {
return tileUnitValue / (EXTENT / this.tileSize);
}
_getClusterMaxZoom(clusterMaxZoom) {
const effectiveClusterMaxZoom = clusterMaxZoom ? Math.round(clusterMaxZoom) : this.maxzoom - 1;
if (!(Number.isInteger(clusterMaxZoom) || clusterMaxZoom === void 0)) warnOnce(`Integer expected for option 'clusterMaxZoom': provided value "${clusterMaxZoom}" rounded to "${effectiveClusterMaxZoom}"`);
return effectiveClusterMaxZoom;
}
async load() {
await this._updateWorkerData();
}
onAdd(map) {
this.map = map;
this.load();
}
/**
* Sets the GeoJSON data and re-renders the map.
*
* @param data - A GeoJSON data object or a URL to one. The latter is preferable in the case of large GeoJSON files.
*/
setData(data) {
this._data = typeof data === "string" ? { url: data } : { geojson: data };
this._pendingWorkerUpdate = { data };
return this._updateWorkerData();
}
/**
* Updates the source's GeoJSON, and re-renders the map.
*
* For sources with lots of features, this method can be used to make updates more quickly.
*
* This approach requires unique IDs for every feature in the source. The IDs can either be specified on the feature,
* or by using the promoteId option to specify which property should be used as the ID.
*
* It is an error to call updateData on a source that did not have unique IDs for each of its features already.
*
* Updates are applied on a best-effort basis, updating an ID that does not exist will not result in an error.
*
* @param diff - The changes that need to be applied.
*/
updateData(diff) {
this._pendingWorkerUpdate.diff = mergeSourceDiffs(this._pendingWorkerUpdate.diff, diff);
return this._updateWorkerData();
}
/**
* Allows to get the source's actual GeoJSON data.
*
* @returns a promise which resolves to the source's actual GeoJSON data
*/
async getData() {
if (this._data.url) await this.once("data");
if (this._data.geojson) return this._data.geojson;
return {
type: "FeatureCollection",
features: Array.from(this._data.updateable.values())
};
}
/**
* Allows getting the source's boundaries.
* If there's a problem with the source's data, it will return an empty {@link LngLatBounds}.
* @returns a promise which resolves to the source's boundaries
*/
async getBounds() {
return getGeoJSONBounds(await this.getData());
}
/**
* To disable/enable clustering on the source options
* @param options - The options to set
* @example
* ```ts
* map.getSource('some id').setClusterOptions({cluster: false});
* map.getSource('some id').setClusterOptions({cluster: false, clusterRadius: 50, clusterMaxZoom: 14});
* ```
*/
setClusterOptions(options) {
this.workerOptions.geojsonVtOptions.cluster = options.cluster;
if (options.clusterRadius !== void 0) this.workerOptions.geojsonVtOptions.clusterOptions.radius = this._pixelsToTileUnits(options.clusterRadius);
if (options.clusterMaxZoom !== void 0) this.workerOptions.geojsonVtOptions.clusterOptions.maxZoom = this._getClusterMaxZoom(options.clusterMaxZoom);
this._pendingWorkerUpdate.updateCluster = true;
return this._updateWorkerData();
}
/**
* Gets the cluster options currently configured on the source.
* The returned values mirror the options accepted by `setClusterOptions`.
*
* @returns the source's current cluster options
* @example
* ```ts
* const {cluster, clusterMaxZoom, clusterRadius} = map.getSource('some id').getClusterOptions();
* ```
*/
getClusterOptions() {
const { cluster, clusterOptions } = this.workerOptions.geojsonVtOptions;
return {
cluster,
clusterMaxZoom: clusterOptions.maxZoom,
clusterRadius: this._tileUnitsToPixels(clusterOptions.radius)
};
}
/**
* For clustered sources, fetches the zoom at which the given cluster expands.
*
* @param clusterId - The value of the cluster's `cluster_id` property.
* @returns a promise that is resolved with the zoom number
*/
async getClusterExpansionZoom(clusterId) {
return (await this.actorPromise).sendAsync({
type: "GCEZ",
data: {
type: this.type,
clusterId,
source: this.id
}
});
}
/**
* For clustered sources, fetches the children of the given cluster on the next zoom level (as an array of GeoJSON features).
*
* @param clusterId - The value of the cluster's `cluster_id` property.
* @returns a promise that is resolved when the features are retrieved
*/
async getClusterChildren(clusterId) {
return (await this.actorPromise).sendAsync({
type: "GCC",
data: {
type: this.type,
clusterId,
source: this.id
}
});
}
/**
* For clustered sources, fetches the original points that belong to the cluster (as an array of GeoJSON features).
*
* @param clusterId - The value of the cluster's `cluster_id` property.
* @param limit - The maximum number of features to return.
* @param offset - The number of features to skip (e.g. for pagination).
* @returns a promise that is resolved when the features are retrieved
* @example
* Retrieve cluster leaves on click
* ```ts
* map.on('click', 'clusters', (e) => {
* let features = map.queryRenderedFeatures(e.point, {
* layers: ['clusters']
* });
*
* let clusterId = features[0].properties.cluster_id;
* let pointCount = features[0].properties.point_count;
* let clusterSource = map.getSource('clusters');
*
* const features = await clusterSource.getClusterLeaves(clusterId, pointCount);
* // Print cluster leaves in the console
* console.log('Cluster leaves:', features);
* });
* ```
*/
async getClusterLeaves(clusterId, limit, offset) {
return (await this.actorPromise).sendAsync({
type: "GCL",
data: {
type: this.type,
source: this.id,
clusterId,
limit,
offset
}
});
}
/**
* Responsible for invoking WorkerSource's geojson.loadData target, which
* handles loading the geojson data and preparing to serve it up as tiles,
* using geojson-vt or supercluster as appropriate.
*/
async _updateWorkerData() {
if (this._isUpdatingWorker) return this._updatePromise;
if (!this._hasPendingWorkerUpdate()) {
warnOnce(`No pending worker updates for GeoJSONSource ${this.id}.`);
return;
}
const { data, diff, updateCluster } = this._pendingWorkerUpdate;
const params = this._getLoadGeoJSONParameters(data, diff, updateCluster);
if (data !== void 0) this._pendingWorkerUpdate.data = void 0;
else if (diff) this._pendingWorkerUpdate.diff = void 0;
else if (updateCluster) this._pendingWorkerUpdate.updateCluster = void 0;
this._updatePromise = this._dispatchWorkerUpdate(params);
await this._updatePromise;
}
/**
* Create the parameters object that will be sent to the worker and used to load GeoJSON.
*/
async _getLoadGeoJSONParameters(data, diff, updateCluster) {
const params = extend({
type: this.type,
source: this.id
}, this.workerOptions);
if (typeof data === "string") {
params.request = await this.map._requestManager.transformRequest(browser.resolveURL(data), "Source");
params.request.collectResourceTiming = this._collectResourceTiming;
return params;
}
if (data !== void 0) {
params.data = data;
return params;
}
if (diff) {
params.dataDiff = diff;
return params;
}
if (updateCluster) {
params.updateCluster = true;
return params;
}
}
/**
* Send the worker update data from the main thread to the worker
*/
async _dispatchWorkerUpdate(optionsPromise) {
this._isUpdatingWorker = true;
this.fire(new MapSourceDataEvent("dataloading"));
try {
const options = await optionsPromise;
const result = await (await this.actorPromise).sendAsync({
type: "LD",
data: options
});
this._isUpdatingWorker = false;
if (this._removed || result.abandoned) {
this.fire(new MapSourceDataEvent("dataabort"));
return;
}
if (result.data) this._data = { geojson: result.data };
const affectedGeometries = this._applyDiffToSource(options.dataDiff);
const shouldReloadTileOptions = this._getShouldReloadTileOptions(affectedGeometries);
const eventData = {};
this._applyResourceTiming(eventData, result);
this.fire(new MapSourceDataEvent("data", {
...eventData,
sourceDataType: "metadata"
}));
this.fire(new MapSourceDataEvent("data", {
...eventData,
sourceDataType: "content",
shouldReloadTileOptions
}));
} catch (err) {
this._isUpdatingWorker = false;
if (this._removed) {
this.fire(new MapSourceDataEvent("dataabort"));
return;
}
this.fire(new ErrorEvent(ensureError(err)));
} finally {
if (this._hasPendingWorkerUpdate()) await this._updateWorkerData();
}
}
/**
* Apply resource timing data to the event object.
*/
_applyResourceTiming(eventData, result) {
if (!this._collectResourceTiming) return;
const timingData = result.resourceTiming?.[this.id];
if (!timingData) return;
const resourceTiming = timingData.slice(0);
if (!resourceTiming?.length) return;
extend(eventData, { resourceTiming });
}
/**
* Apply a diff to this source's data and return the affected feature geometries.
* @param diff - The {@link GeoJSONSourceDiff} to apply.
* @returns The affected geometries, or undefined if the diff is not applicable or all geometries are affected.
*/
_applyDiffToSource(diff) {
if (!diff) return;
const promoteId = typeof this.promoteId === "string" ? this.promoteId : void 0;
if (!this._data.url && !this._data.updateable) {
const updateable = toUpdateable(this._data.geojson, promoteId);
if (!updateable) throw new Error(`GeoJSONSource "${this.id}": GeoJSON data is not compatible with updateData`);
this._data = { updateable };
}
if (!this._data.updateable) return;
const affectedGeometries = applySourceDiff(this._data.updateable, diff, promoteId);
if (diff.removeAll || this._options.cluster) return;
return affectedGeometries;
}
/**
* Get options for use in determining whether to reload a tile based on the modified features.
* @param affectedGeometries - The feature geometries affected by the update.
* @returns A {@link GeoJSONSourceShouldReloadTileOptions} object which contains an array of affected bounds caused by the update.
*/
_getShouldReloadTileOptions(affectedGeometries) {
if (!affectedGeometries) return void 0;
return { affectedBounds: affectedGeometries.filter(Boolean).map((g) => getGeoJSONBounds(g)) };
}
/**
* Determine whether a tile should be reloaded based on a set of options associated with a {@link MapSourceDataChangedEvent}.
* @internal
*/
shouldReloadTile(tile, { affectedBounds }) {
if (tile.state === "loading") return true;
if (tile.state === "unloaded") return false;
const { buffer, extent } = this.workerOptions.geojsonVtOptions;
const tileBounds = tileIdToLngLatBounds(tile.tileID.canonical, buffer / extent);
for (const bounds of affectedBounds) if (tileBounds.intersects(bounds)) return true;
return false;
}
loaded() {
return !this._isUpdatingWorker && !this._hasPendingWorkerUpdate();
}
async loadTile(tile) {
const message = !tile.actor ? "LT" : "RT";
tile.actor = await this.actorPromise;
const params = {
type: this.type,
uid: tile.uid,
tileID: tile.tileID,
zoom: tile.tileID.overscaledZ,
maxZoom: this.maxzoom,
tileSize: this.tileSize,
source: this.id,
pixelRatio: this.map.getPixelRatio(),
showCollisionBoxes: this.map.showCollisionBoxes,
promoteId: this.promoteId,
subdivisionGranularity: this.map.style.projection.subdivisionGranularity
};
tile.abortController = new AbortController();
try {
const data = await (await this.actorPromise).sendAsync({
type: message,
data: params
}, tile.abortController);
delete tile.abortController;
tile.unloadVectorData();
if (!tile.aborted) tile.loadVectorData(data, this.map.painter, message === "RT");
} catch (err) {
delete tile.abortController;
if (tile.aborted || isAbortError(err)) return;
throw err;
}
}
async abortTile(tile) {
if (tile.abortController) {
tile.abortController.abort();
delete tile.abortController;
}
tile.aborted = true;
}
async unloadTile(tile) {
tile.unloadVectorData();
await (await this.actorPromise).sendAsync({
type: "RMT",
data: {
uid: tile.uid,
type: this.type,
source: this.id
}
});
}
onRemove() {
this._removed = true;
this.actorPromise.then((actor) => actor.sendAsync({
type: "RS",
data: {
type: this.type,
source: this.id
}
}));
}
serialize() {
return extend({}, this._options, {
type: this.type,
data: this._data.updateable ? {
type: "FeatureCollection",
features: Array.from(this._data.updateable.values())
} : this._data.url || this._data.geojson
});
}
hasTransition() {
return false;
}
};
//#endregion
//#region src/webgl/program/raster_program.ts
/** The bilinear warp, which is also the affine one that a rectangle or a parallelogram needs. */
const bilinearImageWarp = [
0,
0,
1
];
const rasterUniforms = (context, locations) => ({
"u_tl_parent": new Uniform2f(context, locations.u_tl_parent),
"u_scale_parent": new Uniform1f(context, locations.u_scale_parent),
"u_buffer_scale": new Uniform1f(context, locations.u_buffer_scale),
"u_image_warp": new Uniform3f(context, locations.u_image_warp),
"u_fade_t": new Uniform1f(context, locations.u_fade_t),
"u_opacity": new Uniform1f(context, locations.u_opacity),
"u_image0": new Uniform1i(context, locations.u_image0),
"u_image1": new Uniform1i(context, locations.u_image1),
"u_brightness_low": new Uniform1f(context, locations.u_brightness_low),
"u_brightness_high": new Uniform1f(context, locations.u_brightness_high),
"u_saturation_factor": new Uniform1f(context, locations.u_saturation_factor),
"u_contrast_factor": new Uniform1f(context, locations.u_contrast_factor),
"u_spin_weights": new Uniform3f(context, locations.u_spin_weights),
"u_coords_top": new Uniform4f(context, locations.u_coords_top),
"u_coords_bottom": new Uniform4f(context, locations.u_coords_bottom)
});
const rasterUniformValues = (parentTL, parentScaleBy, fade, layer, cornerCoords, imageWarp) => ({
"u_tl_parent": parentTL,
"u_scale_parent": parentScaleBy,
"u_buffer_scale": 1,
"u_image_warp": imageWarp,
"u_fade_t": fade.mix,
"u_opacity": fade.opacity * layer.paint.get("raster-opacity"),
"u_image0": 0,
"u_image1": 1,
"u_brightness_low": layer.paint.get("raster-brightness-min"),
"u_brightness_high": layer.paint.get("raster-brightness-max"),
"u_saturation_factor": saturationFactor(layer.paint.get("raster-saturation")),
"u_contrast_factor": contrastFactor(layer.paint.get("raster-contrast")),
"u_spin_weights": spinWeights(layer.paint.get("raster-hue-rotate")),
"u_coords_top": [
cornerCoords[0].x,
cornerCoords[0].y,
cornerCoords[1].x,
cornerCoords[1].y
],
"u_coords_bottom": [
cornerCoords[3].x,
cornerCoords[3].y,
cornerCoords[2].x,
cornerCoords[2].y
]
});
function spinWeights(angle) {
angle *= Math.PI / 180;
const s = Math.sin(angle);
const c = Math.cos(angle);
return [
(2 * c + 1) / 3,
(-Math.sqrt(3) * s - c + 1) / 3,
(Math.sqrt(3) * s - c + 1) / 3
];
}
function contrastFactor(contrast) {
return contrast > 0 ? 1 / (1 - contrast) : 1 + contrast;
}
function saturationFactor(saturation) {
return saturation > 0 ? 1 - 1 / (1.001 - saturation) : -saturation;
}
//#endregion
//#region src/render/mesh.ts
var Mesh = class {
constructor(vertexBuffer, indexBuffer, segments) {
this.vertexBuffer = vertexBuffer;
this.indexBuffer = indexBuffer;
this.segments = segments;
}
destroy() {
this.vertexBuffer.destroy();
this.indexBuffer.destroy();
this.segments.destroy();
this.vertexBuffer = null;
this.indexBuffer = null;
this.segments = null;
}
};
//#endregion
//#region src/data/pos_attributes.ts
const posAttributes = createLayout([{
name: "a_pos",
type: "Int16",
components: 2
}]);
//#endregion
//#region src/util/create_tile_mesh.ts
/**
* The size of border region for stencil masks, in internal tile coordinates.
* Used for globe rendering.
*/
const EXTENT_STENCIL_BORDER = EXTENT / 128;
/**
* @internal
* Creates a mesh of a quad that covers the entire tile (covering positions in range 0..EXTENT),
* is optionally subdivided into finer quads, optionally includes a border
* and optionally extends to the north and/or special pole vertices.
* Also allocates and populates WebGL buffers for the mesh.
* Forces 16 bit indices that are used throughout MapLibre.
* @param context - The WebGL context wrapper.
* @param options - Specify options for tile mesh creation such as granularity or border.
* @returns The mesh vertices and indices, already allocated and uploaded into WebGL buffers.
*/
function createTileMeshWithBuffers(context, options) {
const tileMesh = createTileMesh(options, "16bit");
const vertices = PosArray.deserialize({
arrayBuffer: tileMesh.vertices,
length: tileMesh.vertices.byteLength / 2 / 2
});
const indices = TriangleIndexArray.deserialize({
arrayBuffer: tileMesh.indices,
length: tileMesh.indices.byteLength / 2 / 3
});
return new Mesh(context.createVertexBuffer(vertices, posAttributes.members), context.createIndexBuffer(indices), SegmentVector.simpleSegment(0, 0, vertices.length, indices.length));
}
/**
* Creates a mesh of a quad that covers the entire tile (covering positions in range 0..EXTENT),
* is optionally subdivided into finer quads, optionally includes a border
* and optionally extends to the north and/or special pole vertices.
* Additionally the resulting mesh indices type can be specified using `forceIndicesSize`.
* @example
* ```
* // Creating a mesh for a tile that can be used for raster layers, hillshade, etc.
* const meshBuffers = createTileMesh({
* granularity: map.style.projection.subdivisionGranularity.tile.getGranularityForZoomLevel(tileID.z),
* generateBorders: true,
* extendToNorthPole: tileID.y === 0,
* extendToSouthPole: tileID.y === (1 << tileID.z) - 1,
* }, '16bit');
* ```
* @see [Add a custom layer with tiles to a globe](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-custom-layer-with-tiles-to-a-globe/)
* @param options - Specify options for tile mesh creation such as granularity or border.
* @param forceIndicesSize - Specifies what indices type to use. The values '32bit' and '16bit' force their respective indices size. If undefined, the mesh may use either size, and will pick 16 bit indices if possible. If '16bit' is specified and the mesh exceeds 65536 vertices, an exception is thrown.
* @returns Typed arrays of the mesh vertices and indices.
*/
function createTileMesh(options, forceIndicesSize) {
const granularity = options.granularity !== void 0 ? Math.max(options.granularity, 1) : 1;
const quadsPerAxisX = granularity + (options.generateBorders ? 2 : 0);
const quadsPerAxisY = granularity + (options.extendToNorthPole || options.generateBorders ? 1 : 0) + (options.extendToSouthPole || options.generateBorders ? 1 : 0);
const verticesPerAxisX = quadsPerAxisX + 1;
const verticesPerAxisY = quadsPerAxisY + 1;
const offsetX = options.generateBorders ? -1 : 0;
const offsetY = options.generateBorders || options.extendToNorthPole ? -1 : 0;
const endX = granularity + (options.generateBorders ? 1 : 0);
const endY = granularity + (options.generateBorders || options.extendToSouthPole ? 1 : 0);
const vertexCount = verticesPerAxisX * verticesPerAxisY;
const indexCount = quadsPerAxisX * quadsPerAxisY * 6;
const overflows16bitIndices = verticesPerAxisX * verticesPerAxisY > 65536;
if (overflows16bitIndices && forceIndicesSize === "16bit") throw new Error("Granularity is too large and meshes would not fit inside 16 bit vertex indices.");
const use32bitIndices = overflows16bitIndices || forceIndicesSize === "32bit";
const vertices = new Int16Array(vertexCount * 2);
let vertexId = 0;
for (let y = offsetY; y <= endY; y++) for (let x = offsetX; x <= endX; x++) {
let vx = x / granularity * EXTENT;
if (x === -1) vx = -EXTENT_STENCIL_BORDER;
if (x === granularity + 1) vx = EXTENT + EXTENT_STENCIL_BORDER;
let vy = y / granularity * EXTENT;
if (y === -1) vy = options.extendToNorthPole ? NORTH_POLE_Y : -EXTENT_STENCIL_BORDER;
if (y === granularity + 1) vy = options.extendToSouthPole ? SOUTH_POLE_Y : EXTENT + EXTENT_STENCIL_BORDER;
vertices[vertexId++] = vx;
vertices[vertexId++] = vy;
}
const indices = use32bitIndices ? new Uint32Array(indexCount) : new Uint16Array(indexCount);
let indexId = 0;
for (let y = 0; y < quadsPerAxisY; y++) for (let x = 0; x < quadsPerAxisX; x++) {
const v0 = x + y * verticesPerAxisX;
const v1 = x + 1 + y * verticesPerAxisX;
const v2 = x + (y + 1) * verticesPerAxisX;
const v3 = x + 1 + (y + 1) * verticesPerAxisX;
indices[indexId++] = v0;
indices[indexId++] = v2;
indices[indexId++] = v1;
indices[indexId++] = v1;
indices[indexId++] = v2;
indices[indexId++] = v3;
}
return {
vertices: vertices.buffer.slice(0),
indices: indices.buffer.slice(0),
uses32bitIndices: use32bitIndices
};
}
//#endregion
//#region src/source/image_source.ts
/**
* How many grid cells per axis the mesh of a subdivided quad has. Within a cell the bilinear warp
* is still approximated by one mapping per triangle, so the error falls off with the cell size.
*/
const SUBDIVIDED_QUAD_GRANULARITY = 16;
/**
* How much a warp may foreshorten the image, as the ratio between the largest and the smallest
* homogeneous denominator over the quad, while staying purely projective. Ordinary oblique imagery
* stays well below it.
*/
const PROJECTIVE_FORESHORTENING = 4;
/**
* The foreshortening at which a warp is taken to be purely bilinear.
*
* The denominator vanishes on the warp's vanishing line, and that line touches the quad exactly when
* the quad degenerates into a triangle, so foreshortening grows without bound as a corner approaches
* the diagonal between its neighbours. Left alone, such a quad keeps a valid but wildly lopsided
* warp, squeezing nearly the whole image into a sliver along one edge and magnifying a handful of
* texels over the rest of the quad.
*/
const BILINEAR_FORESHORTENING = 512;
/**
* A data source containing an image.
* (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-image) for detailed documentation of options.)
*
* @group Sources
*
* @example
* ```ts
* // add to map
* map.addSource('some id', {
* type: 'image',
* url: 'https://www.maplibre.org/images/foo.png',
* coordinates: [
* [-76.54, 39.18],
* [-76.52, 39.18],
* [-76.52, 39.17],
* [-76.54, 39.17]
* ]
* });
*
* // update coordinates
* let mySource = map.getSource('some id');
* mySource.setCoordinates([
* [-76.54335737228394, 39.18579907229748],
* [-76.52803659439087, 39.1838364847587],
* [-76.5295386314392, 39.17683392507606],
* [-76.54520273208618, 39.17876344106642]
* ]);
*
* // update url and coordinates simultaneously
* mySource.updateImage({
* url: 'https://www.maplibre.org/images/bar.png',
* coordinates: [
* [-76.54335737228394, 39.18579907229748],
* [-76.52803659439087, 39.1838364847587],
* [-76.5295386314392, 39.17683392507606],
* [-76.54520273208618, 39.17876344106642]
* ]
* })
*
* // update with an already-decoded image (no network request)
* const bitmap = await createImageBitmap(myCanvas);
* mySource.updateImage({image: bitmap});
*
* map.removeSource('some id'); // remove
* ```
*/
var ImageSource = class extends Evented {
/** @internal */
constructor(id, options, dispatcher, eventedParent) {
super();
this.imageWarp = bilinearImageWarp;
this.flippedWindingOrder = false;
this._warp = "auto";
this._imageDirty = false;
this._subdividedQuad = false;
this._subdividedMesh = null;
this.id = id;
this.dispatcher = dispatcher;
this.coordinates = options.coordinates;
this.type = "image";
this.minzoom = 0;
this.maxzoom = 22;
this.tileSize = 512;
this.tiles = {};
this._loaded = false;
this.setEventedParent(eventedParent);
this.options = options;
}
async load(newCoordinates) {
this._loaded = false;
this.fire(new MapSourceDataEvent("dataloading"));
this.url = this.options.url;
this._abortController = new AbortController();
try {
const image = await ImageRequest.transformAndGetImage(this.map._requestManager, this.url, "Image", this._abortController);
this._abortController = null;
this._loaded = true;
if (image?.data) {
this._setImage(image.data);
if (newCoordinates) this.coordinates = newCoordinates;
this._finishLoading();
}
} catch (err) {
if (isAbortError(err)) return;
this._abortController = null;
this._loaded = true;
this.fire(new ErrorEvent(ensureError(err)));
}
}
loaded() {
return this._loaded;
}
/**
* Updates the image and, optionally, the coordinates. To avoid having the image flash after changing,
* set the `raster-fade-duration` paint property on the raster layer to 0.
*
* Provide exactly one of `url` (to fetch a new image over the network) or `image` (an
* already-decoded `HTMLImageElement`, `HTMLCanvasElement`, `ImageBitmap` or `ImageData` to
* display directly, without a network request).
*
* @param options - The options object.
*/
updateImage(options) {
if (this._abortController) {
this._abortController.abort();
this._abortController = null;
}
if ("image" in options) {
this._loaded = true;
this._setImage(options.image);
if (options.coordinates) this.coordinates = options.coordinates;
this._finishLoading();
return this;
}
if (!options.url) return this;
this.options.url = options.url;
this.load(options.coordinates);
return this;
}
/** Loaded tiles hold `this.texture`, so the wrapper has to outlive the images in it. */
_setImage(image) {
this.image = image;
this._imageDirty = true;
}
/**
* @internal
* The mesh the image is drawn with, or null to use the tile mesh of the current projection.
*
* The raster vertex shader evaluates {@link imageWarp} per vertex, so a pair of triangles only
* samples it at the four corners. That is enough for the affine mapping of a parallelogram, and
* for a purely projective mapping, whose straight lines survive linear interpolation across the
* diagonal. Anything in between is neither, and would be textured as two independently warped
* halves with a visible seam along that diagonal, so it needs the warp evaluated per grid cell.
*
* A projection that subdivides its own tile meshes already does this, so it keeps them.
*/
getMesh(context, projectionSubdividesTiles) {
if (!this._subdividedQuad || projectionSubdividesTiles) return null;
this._subdividedMesh ??= createTileMeshWithBuffers(context, { granularity: SUBDIVIDED_QUAD_GRANULARITY });
return this._subdividedMesh;
}
/** Teardown only: dropping the reference alone leaves the allocation to the GC. */
_disposeTexture() {
this.texture?.destroy();
this.texture = null;
}
_finishLoading() {
if (this.map) {
this.setCoordinates(this.coordinates);
this.fire(new MapSourceDataEvent("data", { sourceDataType: "metadata" }));
}
}
onAdd(map) {
this.map = map;
this.load();
}
onRemove() {
if (this._abortController) {
this._abortController.abort();
this._abortController = null;
}
this._disposeTexture();
this._subdividedMesh?.destroy();
this._subdividedMesh = null;
this.image = null;
this.tiles = {};
}
/**
* @experimental
* Sets how the image is warped onto its coordinates and re-renders the map.
*
* This only has an effect while the coordinates do not form a rectangle, and it is not part of
* the style specification, so it does not survive `map.setStyle`.
*
* @param warp - The warp to use, see {@link ImageSourceWarp}.
*
* @example
* ```ts
* // Keep the image pinned to its corners while the user drags them around.
* map.getSource('some id').setWarp('flat');
* ```
*/
setWarp(warp) {
if (this._warp === warp) return this;
this._warp = warp;
if (this.tileCoords) this.setCoordinates(this.coordinates);
return this;
}
/**
* @experimental
* Returns how the image is warped onto its coordinates.
*
* @returns The warp in use, see {@link ImageSourceWarp}.
*/
getWarp() {
return this._warp;
}
/**
* Sets the image's coordinates and re-renders the map.
*
* @param coordinates - Four geographical coordinates,
* represented as arrays of longitude and latitude numbers, which define the corners of the image.
* The coordinates start at the top left corner of the image and proceed in clockwise order.
* They do not have to represent a rectangle.
*/
setCoordinates(coordinates) {
this.coordinates = coordinates;
const cornerCoords = coordinates.map(MercatorCoordinate.fromLngLat);
this.tileID = getCoordinatesCenterTileID(cornerCoords);
this.terrainTileRanges = this._getOverlappingTileRanges(cornerCoords);
this.minzoom = this.maxzoom = this.tileID.z;
this.tileCoords = cornerCoords.map((coord) => this.tileID.getTilePoint(coord)._round());
this.imageWarp = calculateImageWarp(this.tileCoords, this._warp);
this._subdividedQuad = this.imageWarp[2] > 0 && !isParallelogram(this.tileCoords);
this.flippedWindingOrder = hasWrongWindingOrder(this.tileCoords);
this.fire(new MapSourceDataEvent("data", { sourceDataType: "content" }));
return this;
}
prepare() {
if (Object.keys(this.tiles).length === 0 || !this.image) return;
const context = this.map.painter.context;
const gl = context.gl;
if (!this.texture) {
this.texture = new Texture(context, this.image, gl.RGBA);
this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
} else if (this._imageDirty) {
this.texture.update(this.image);
this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
}
this._imageDirty = false;
let newTilesLoaded = false;
for (const w in this.tiles) {
const tile = this.tiles[w];
if (tile.state !== "loaded") {
tile.state = "loaded";
tile.texture = this.texture;
newTilesLoaded = true;
}
}
if (newTilesLoaded) this.fire(new MapSourceDataEvent("data", {
sourceDataType: "idle",
sourceId: this.id
}));
}
async loadTile(tile) {
if (this.tileID?.equals(tile.tileID.canonical)) {
this.tiles[String(tile.tileID.wrap)] = tile;
tile.buckets = {};
} else tile.state = "errored";
}
serialize() {
return {
type: "image",
url: this.options.url,
coordinates: this.coordinates
};
}
hasTransition() {
return false;
}
/**
* Given a list of coordinates, determine overlapping tile ranges for all zoom levels.
*
* @returns Overlapping tile ranges for all zoom levels.
* @internal
*/
_getOverlappingTileRanges(coords) {
const { minX, minY, maxX, maxY } = Bounds.fromPoints(coords);
const ranges = {};
for (let z = 0; z <= 25; z++) {
const tilesAtZoom = Math.pow(2, z);
const minTileX = Math.floor(minX * tilesAtZoom);
const minTileY = Math.floor(minY * tilesAtZoom);
const maxTileX = Math.floor(maxX * tilesAtZoom);
const maxTileY = Math.floor(maxY * tilesAtZoom);
const minTileXWrapped = (minTileX % tilesAtZoom + tilesAtZoom) % tilesAtZoom;
const maxTileXWrapped = maxTileX % tilesAtZoom;
const minWrap = Math.floor(minTileX / tilesAtZoom);
const maxWrap = Math.floor(maxTileX / tilesAtZoom);
ranges[z] = {
minWrap,
maxWrap,
minTileXWrapped,
maxTileXWrapped,
minTileY,
maxTileY
};
}
return ranges;
}
};
/**
* Given a list of coordinates, get their center as a coordinate.
*
* @returns centerpoint
* @internal
*/
function getCoordinatesCenterTileID(coords) {
const bounds = Bounds.fromPoints(coords);
const dx = bounds.width();
const dy = bounds.height();
const zoom = Math.max(0, Math.floor(-Math.log(Math.max(dx, dy)) / Math.LN2));
const tilesAtZoom = Math.pow(2, zoom);
return new CanonicalTileID(zoom, Math.floor((bounds.minX + bounds.maxX) / 2 * tilesAtZoom), Math.floor((bounds.minY + bounds.maxY) / 2 * tilesAtZoom));
}
function hasWrongWindingOrder(coords) {
const e0x = coords[1].x - coords[0].x;
const e0y = coords[1].y - coords[0].y;
const e1x = coords[2].x - coords[0].x;
return e0x * (coords[2].y - coords[0].y) - e0y * e1x < 0;
}
/**
* How the image is warped onto its coordinates, given the corners in tile space and what the user
* asked for. The projective warp is the perspective view of a plane, so it is the one a photograph
* wants; the bilinear warp is a rubber sheet pinned at the corners, and is the only one left once
* the corners stop describing a perspective view at all.
*
* Based on Paul S. Heckbert, "Fundamentals of Texture Mapping and Image
* Warping", UCB/CSD-89-516, 1989, section 2.2.3 and appendix A.2.
*
* @see https://www2.eecs.berkeley.edu/Pubs/TechRpts/1989/5504.html
* @see https://www.cs.cmu.edu/~ph/texfund/texfund.pdf
*/
function calculateImageWarp(cornerCoords, warp) {
if (warp === "flat" || isParallelogram(cornerCoords)) return bilinearImageWarp;
const [topLeft, topRight, bottomRight, bottomLeft] = cornerCoords;
const sumX = topLeft.x - topRight.x + bottomRight.x - bottomLeft.x;
const sumY = topLeft.y - topRight.y + bottomRight.y - bottomLeft.y;
const basis = [
topRight.x - bottomRight.x,
topRight.y - bottomRight.y,
bottomLeft.x - bottomRight.x,
bottomLeft.y - bottomRight.y
];
const [rightX, rightY, downX, downY] = basis;
const determinant$1 = determinant(basis);
const perspectiveX = (sumX * downY - downX * sumY) / determinant$1;
const perspectiveY = (rightX * sumY - sumX * rightY) / determinant$1;
const denominators = [
1,
1 + perspectiveX,
1 + perspectiveX + perspectiveY,
1 + perspectiveY
];
const foreshortening = Math.max(...denominators) / Math.min(...denominators);
const blend = warp === "perspective" ? 0 : bilinearBlend(foreshortening);
if (!(foreshortening >= 1 && foreshortening <= BILINEAR_FORESHORTENING) || blend >= 1) return bilinearImageWarp;
return [
perspectiveX,
perspectiveY,
blend
];
}
/**
* How far a warp of the given foreshortening is blended towards the bilinear one, ramping from
* purely projective at {@link PROJECTIVE_FORESHORTENING} to purely bilinear at
* {@link BILINEAR_FORESHORTENING}. Blending rather than switching keeps the image continuous as the
* quad is reshaped: the two warps only agree for a parallelogram, and diverge by roughly a tenth of
* the quad per unit of foreshortening, so a switch would visibly displace the image.
*/
function bilinearBlend(foreshortening) {
const ramp = (1 - PROJECTIVE_FORESHORTENING / foreshortening) / (1 - PROJECTIVE_FORESHORTENING / BILINEAR_FORESHORTENING);
return Math.max(0, ramp);
}
function isParallelogram(cornerCoords) {
const [topLeft, topRight, bottomRight, bottomLeft] = cornerCoords;
return topLeft.x + bottomRight.x === topRight.x + bottomLeft.x && topLeft.y + bottomRight.y === topRight.y + bottomLeft.y;
}
//#endregion
//#region src/source/video_source.ts
/**
* A data source containing video.
* (See the [Style Specification](https://maplibre.org/maplibre-style-spec/#sources-video) for detailed documentation of options.)
*
* @group Sources
*
* @example
* ```ts
* // add to map
* map.addSource('some id', {
* type: 'video',
* url: [
* 'https://www.mapbox.com/blog/assets/baltimore-smoke.mp4',
* 'https://www.mapbox.com/blog/assets/baltimore-smoke.webm'
* ],
* coordinates: [
* [-76.54, 39.18],
* [-76.52, 39.18],
* [-76.52, 39.17],
* [-76.54, 39.17]
* ]
* });
*
* // update
* let mySource = map.getSource('some id');
* mySource.setCoordinates([
* [-76.54335737228394, 39.18579907229748],
* [-76.52803659439087, 39.1838364847587],
* [-76.5295386314392, 39.17683392507606],
* [-76.54520273208618, 39.17876344106642]
* ]);
*
* map.removeSource('some id'); // remove
* ```
* @see [Add a video](https://maplibre.org/maplibre-gl-js/docs/examples/video-on-a-map/)
*
* Note that when rendered as a raster layer, the layer's `raster-fade-duration` property will cause the video to fade in.
* This happens when playback is started, paused and resumed, or when the video's coordinates are updated. To avoid this behavior,
* set the layer's `raster-fade-duration` property to `0`.
*/
var VideoSource = class extends ImageSource {
constructor(id, options, dispatcher, eventedParent) {
super(id, options, dispatcher, eventedParent);
this._onPlayingHandler = () => {
this.map?.triggerRepaint();
};
this.roundZoom = true;
this.type = "video";
this.options = options;
}
async load() {
this._loaded = false;
const options = this.options;
this.urls = [];
for (const url of options.urls) this.urls.push((await this.map._requestManager.transformRequest(url, "Source")).url);
try {
const video = await getVideo(this.urls);
this._loaded = true;
if (!video) return;
this.video = video;
this.video.loop = true;
this.video.addEventListener("playing", this._onPlayingHandler);
if (this.map) this.video.play();
this._finishLoading();
} catch (err) {
this.fire(new ErrorEvent(ensureError(err)));
}
}
/**
* Pauses the video.
*/
pause() {
if (this.video) this.video.pause();
}
/**
* Plays the video.
*/
play() {
if (this.video) this.video.play();
}
/**
* Sets playback to a timestamp, in seconds.
*/
seek(seconds) {
if (this.video) {
const seekableRange = this.video.seekable;
if (seconds < seekableRange.start(0) || seconds > seekableRange.end(0)) this.fire(new ErrorEvent(new ValidationError(`sources.${this.id}`, null, `Playback for this video can be set only between the ${seekableRange.start(0)} and ${seekableRange.end(0)}-second mark.`)));
else this.video.currentTime = seconds;
}
}
/**
* Returns the HTML `video` element.
*
* @returns The HTML `video` element.
*/
getVideo() {
return this.video;
}
onAdd(map) {
if (this.map) return;
this.map = map;
this.load();
if (this.video) {
this.video.play();
this.setCoordinates(this.coordinates);
}
}
onRemove() {
super.onRemove();
if (this.video) {
this.video.removeEventListener("playing", this._onPlayingHandler);
this.video.pause();
}
}
/**
* Sets the video's coordinates and re-renders the map.
*/
prepare() {
if (Object.keys(this.tiles).length === 0 || this.video.readyState < 2) return;
const context = this.map.painter.context;
const gl = context.gl;
if (!this.texture) {
this.texture = new Texture(context, this.video, gl.RGBA);
this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
} else if (!this.video.paused) {
this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, this.video);
}
let newTilesLoaded = false;
for (const w in this.tiles) {
const tile = this.tiles[w];
if (tile.state !== "loaded") {
tile.state = "loaded";
tile.texture = this.texture;
newTilesLoaded = true;
}
}
if (newTilesLoaded) this.fire(new MapSourceDataEvent("data", {
sourceDataType: "idle",
sourceId: this.id
}));
}
serialize() {
return {
type: "video",
urls: this.urls,
coordinates: this.coordinates
};
}
hasTransition() {
return this.video && !this.video.paused;
}
};
//#endregion
//#region src/source/canvas_source.ts
/**
* A data source containing the contents of an HTML canvas. See {@link CanvasSourceSpecification} for detailed documentation of options.
*
* @group Sources
*
* @example
* ```ts
* // add to map
* map.addSource('some id', {
* type: 'canvas',
* canvas: 'idOfMyHTMLCanvas',
* animate: true,
* coordinates: [
* [-76.54, 39.18],
* [-76.52, 39.18],
* [-76.52, 39.17],
* [-76.54, 39.17]
* ]
* });
*
* // update
* let mySource = map.getSource('some id');
* mySource.setCoordinates([
* [-76.54335737228394, 39.18579907229748],
* [-76.52803659439087, 39.1838364847587],
* [-76.5295386314392, 39.17683392507606],
* [-76.54520273208618, 39.17876344106642]
* ]);
*
* map.removeSource('some id'); // remove
* ```
*/
var CanvasSource = class extends ImageSource {
/** @internal */
constructor(id, options, dispatcher, eventedParent) {
super(id, options, dispatcher, eventedParent);
if (!options.coordinates) this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, "missing required property \"coordinates\"")));
else if (!Array.isArray(options.coordinates) || options.coordinates.length !== 4 || options.coordinates.some((c) => !Array.isArray(c) || c.length !== 2 || c.some((l) => typeof l !== "number"))) this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, "\"coordinates\" property must be an array of 4 longitude/latitude array pairs")));
if (options.animate && typeof options.animate !== "boolean") this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, "optional \"animate\" property must be a boolean value")));
if (!options.canvas) this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, "missing required property \"canvas\"")));
else if (typeof options.canvas !== "string" && !(options.canvas instanceof HTMLCanvasElement)) this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, "\"canvas\" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance")));
this.options = options;
this.animate = options.animate !== void 0 ? options.animate : true;
}
async load() {
this._loaded = true;
this.canvas ||= this.options.canvas instanceof HTMLCanvasElement ? this.options.canvas : document.getElementById(this.options.canvas);
this.width = this.canvas.width;
this.height = this.canvas.height;
if (this._hasInvalidDimensions()) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error("Canvas dimensions cannot be less than or equal to zero.")));
return;
}
this.play = function() {
this._playing = true;
this.map.triggerRepaint();
};
this.pause = function() {
if (this._playing) {
this.prepare();
this._playing = false;
}
};
this._finishLoading();
}
/**
* Returns the HTML `canvas` element.
*
* @returns The HTML `canvas` element.
*/
getCanvas() {
return this.canvas;
}
onAdd(map) {
this.map = map;
this.load();
if (this.canvas) {
if (this.animate) this.play();
}
}
onRemove() {
this._playing = false;
super.onRemove();
}
prepare() {
let resize = false;
if (this.canvas.width !== this.width) {
this.width = this.canvas.width;
resize = true;
}
if (this.canvas.height !== this.height) {
this.height = this.canvas.height;
resize = true;
}
if (this._hasInvalidDimensions()) return;
if (Object.keys(this.tiles).length === 0) return;
const context = this.map.painter.context;
const gl = context.gl;
if (!this.texture) {
this.texture = new Texture(context, this.canvas, gl.RGBA, { premultiply: true });
this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
} else if (resize || this._playing) this.texture.update(this.canvas, { premultiply: true });
let newTilesLoaded = false;
for (const w in this.tiles) {
const tile = this.tiles[w];
if (tile.state !== "loaded") {
tile.state = "loaded";
tile.texture = this.texture;
newTilesLoaded = true;
}
}
if (newTilesLoaded) this.fire(new MapSourceDataEvent("data", {
sourceDataType: "idle",
sourceId: this.id
}));
}
serialize() {
return {
type: "canvas",
animate: this.animate,
canvas: this.options.canvas,
coordinates: this.coordinates
};
}
hasTransition() {
return this._playing;
}
_hasInvalidDimensions() {
for (const x of [this.canvas.width, this.canvas.height]) if (isNaN(x) || x <= 0) return true;
return false;
}
};
//#endregion
//#region src/source/source.ts
const registeredSources = {};
/**
* Creates a tiled data source instance given an options object.
*
* @param id - The id for the source. Must not be used by any existing source.
* @param specification - Source options, specific to the source type (except for `options.type`, which is always required).
* @param source - A source definition object compliant with
* [`maplibre-gl-style-spec`](https://maplibre.org/maplibre-style-spec/#sources) or, for a third-party source type,
* with that type's requirements.
* @param dispatcher - A {@link Dispatcher} instance, which can be used to send messages to the workers.
* @returns a newly created source
*/
const create = (id, specification, dispatcher, eventedParent) => {
const source = new (getSourceType(specification.type))(id, specification, dispatcher, eventedParent);
if (source.id !== id) throw new Error(`Expected Source id to be ${id} instead of ${source.id}`);
return source;
};
const getSourceType = (name) => {
switch (name) {
case "geojson": return GeoJSONSource;
case "image": return ImageSource;
case "raster": return RasterTileSource;
case "raster-dem": return RasterDEMTileSource;
case "vector": return VectorTileSource;
case "video": return VideoSource;
case "canvas": return CanvasSource;
}
return registeredSources[name];
};
const setSourceType = (name, type) => {
registeredSources[name] = type;
};
/**
* Adds a custom source type, making it available for use with {@link Map.addSource}.
* @param name - The name of the source type; source definition objects use this name in the `{type: ...}` field.
* @param SourceType - A {@link SourceClass} - which is a constructor for the `Source` interface.
* @returns a promise that is resolved when the source type is ready or rejected with an error.
*/
const addSourceType = async (name, SourceType) => {
if (getSourceType(name)) throw new Error(`A source type called "${name}" already exists.`);
setSourceType(name, SourceType);
};
//#endregion
//#region src/data/bucket.ts
function deserialize(input, style) {
const output = {};
if (!style) return output;
for (const bucket of input) {
const layers = bucket.layerIds.map((id) => style.getLayer(id)).filter(Boolean);
if (layers.length === 0) continue;
bucket.layers = layers;
if (bucket.stateDependentLayerIds) bucket.stateDependentLayers = bucket.stateDependentLayerIds.map((lId) => layers.filter((l) => l.id === lId)[0]);
for (const layer of layers) output[layer.id] = bucket;
}
return output;
}
//#endregion
//#region src/source/rtl_text_plugin_status.ts
const RTLPluginLoadedEventName = "RTLPluginLoaded";
//#endregion
//#region src/source/rtl_text_plugin_main_thread.ts
var RTLMainThreadPlugin = class extends Evented {
constructor(..._args) {
super(..._args);
this.status = "unavailable";
this.url = null;
this.dispatcher = getGlobalDispatcher();
}
/** Sync RTL plugin state by broadcasting a message to the worker */
_syncState(statusToSend) {
this.status = statusToSend;
return this.dispatcher.broadcast("SRPS", {
pluginStatus: statusToSend,
pluginURL: this.url
}).catch((e) => {
this.status = "error";
throw e;
});
}
/** This one is exposed to outside */
getRTLTextPluginStatus() {
return this.status;
}
clearRTLTextPlugin() {
this.status = "unavailable";
this.url = null;
}
async setRTLTextPlugin(url, deferred = false) {
if (this.url) throw new Error("setRTLTextPlugin cannot be called multiple times.");
this.url = browser.resolveURL(url);
if (!this.url) throw new Error(`requested url ${url} is invalid`);
if (this.status === "unavailable") {
if (deferred) {
this.status = "deferred";
this._syncState(this.status);
} else return this._requestImport();
} else if (this.status === "requested") return this._requestImport();
}
/** Send a message to worker which will import the RTL plugin script */
async _requestImport() {
await this._syncState("loading");
this.status = "loaded";
this.fire(new Event(RTLPluginLoadedEventName));
}
/** Start a lazy loading process of RTL plugin */
lazyLoad() {
if (this.status === "unavailable") this.status = "requested";
else if (this.status === "deferred") this._requestImport();
}
};
let rtlMainThreadPlugin = null;
function rtlMainThreadPluginFactory() {
rtlMainThreadPlugin ||= new RTLMainThreadPlugin();
return rtlMainThreadPlugin;
}
//#endregion
//#region src/tile/tile.ts
const CLOCK_SKEW_RETRY_TIMEOUT = 3e4;
/**
* A tile object is the combination of a Coordinate, which defines
* its place, as well as a unique ID and data tracking for its content
*/
var Tile = class {
/**
* @param tileID - the tile ID
* @param size - The tile size
*/
constructor(tileID, size) {
this.timeAdded = 0;
this.fadeEndTime = 0;
this.fadeOpacity = 1;
this.tileID = tileID;
this.uid = uniqueId();
this.uses = 0;
this.tileSize = size;
this.buckets = {};
this.expirationTime = null;
this.queryPadding = 0;
this.hasSymbolBuckets = false;
this.hasRTLText = false;
this.dependencies = {};
this.rttObjects = [];
this.rttFingerprint = {};
this.expiredRequestCount = 0;
this.state = "loading";
this.featureStateRevision = -1;
}
isRenderable(symbolLayer) {
return this.hasData() && (!this.fadeEndTime || this.fadeOpacity > 0) && (symbolLayer || !this.holdingForSymbolFade());
}
/**
* @internal
* Many-to-one crossfade between a base tile and parent/ancestor tile (when zooming)
*/
setCrossFadeLogic({ fadingRole, fadingDirection, fadingParentID, fadeEndTime }) {
this.resetFadeLogic();
this.fadingRole = fadingRole;
this.fadingDirection = fadingDirection;
this.fadingParentID = fadingParentID;
this.fadeEndTime = fadeEndTime;
}
/**
* Self fading for edge tiles (when panning map)
*/
setSelfFadeLogic(fadeEndTime) {
this.resetFadeLogic();
this.selfFading = true;
this.fadeEndTime = fadeEndTime;
}
resetFadeLogic() {
this.fadingRole = null;
this.fadingDirection = null;
this.fadingParentID = null;
this.selfFading = false;
this.timeAdded = now();
this.fadeEndTime = 0;
this.fadeOpacity = 1;
}
wasRequested() {
return this.state === "errored" || this.state === "loaded" || this.state === "reloading";
}
clearTextures(painter) {
if (this.demTexture) painter.saveTileTexture(this.demTexture);
this.demTexture = null;
}
/**
* @internal
* Returns the cached RTT object for this stack, or undefined on a cache miss.
*/
getRTT(stack) {
return this.rttObjects[stack];
}
/**
* @internal
* Allocates a fresh RTT object from the painter's pool and stores it at the
* given stack slot. Callers should check {@link getRTT} first; calling this
* over an existing slot leaks the previous object.
*/
acquireRTT(painter, stack, size) {
return this.rttObjects[stack] = painter.acquireRTT(size);
}
/**
* @internal
* Returns all cached RTT slots to the painter's pool.
*/
releaseRTT(painter) {
if (this.rttObjects.length === 0) return;
for (const obj of this.rttObjects) if (obj) painter.releaseRTT(obj);
this.rttObjects.length = 0;
}
/**
* Given a data object with a 'buffers' property, load it into
* this tile's elementGroups and buffers properties and set loaded
* to true. If the data is null, like in the case of an empty
* GeoJSON tile, no-op but still set loaded to true.
* @param data - The data from the worker
* @param painter - the painter
* @param justReloaded - `true` to just reload
*/
loadVectorData(data, painter, justReloaded) {
if (data?.etagUnmodified === true) {
this.state = "loaded";
return;
}
if (this.hasData()) this.unloadVectorData();
this.state = "loaded";
if (!data) {
this.collisionBoxArray = new CollisionBoxArray();
return;
}
if (data.featureIndex) {
this.latestFeatureIndex = data.featureIndex;
if (data.rawTileData) {
this.latestRawTileData = data.rawTileData;
this.latestEncoding = data.encoding;
this.latestFeatureIndex.rawTileData = data.rawTileData;
this.latestFeatureIndex.encoding = data.encoding;
} else if (this.latestRawTileData) {
this.latestFeatureIndex.rawTileData = this.latestRawTileData;
this.latestFeatureIndex.encoding = this.latestEncoding;
}
}
this.collisionBoxArray = data.collisionBoxArray;
this.buckets = deserialize(data.buckets, painter?.style);
this.hasSymbolBuckets = false;
for (const id in this.buckets) {
const bucket = this.buckets[id];
if (bucket instanceof SymbolBucket) {
this.hasSymbolBuckets = true;
if (justReloaded) bucket.justReloaded = true;
else break;
}
}
this.hasRTLText = false;
if (this.hasSymbolBuckets) for (const id in this.buckets) {
const bucket = this.buckets[id];
if (bucket instanceof SymbolBucket) {
if (bucket.hasRTLText) {
this.hasRTLText = true;
rtlMainThreadPluginFactory().lazyLoad();
break;
}
}
}
this.queryPadding = 0;
for (const id in this.buckets) {
const bucket = this.buckets[id];
this.queryPadding = Math.max(this.queryPadding, painter.style.getLayer(id).queryRadius(bucket));
}
if (data.imageAtlas) this.imageAtlas = data.imageAtlas;
if (data.glyphAtlasImage) this.glyphAtlasImage = data.glyphAtlasImage;
this.dashPositions = data.dashPositions;
}
/**
* Release any data or WebGL resources referenced by this tile.
*/
unloadVectorData() {
for (const id in this.buckets) this.buckets[id].destroy();
this.buckets = {};
if (this.imageAtlasTexture) this.imageAtlasTexture.destroy();
if (this.glyphAtlasTexture) this.glyphAtlasTexture.destroy();
this.imageAtlas = null;
this.dashPositions = null;
this.latestFeatureIndex = null;
this.state = "unloaded";
}
getBucket(layer) {
return this.buckets[layer.id];
}
upload(context) {
for (const id in this.buckets) {
const bucket = this.buckets[id];
if (bucket.uploadPending()) bucket.upload(context);
}
const gl = context.gl;
if (this.imageAtlas && !this.imageAtlas.uploaded) {
this.imageAtlasTexture = new Texture(context, this.imageAtlas.image, gl.RGBA);
this.imageAtlas.uploaded = true;
}
if (this.glyphAtlasImage) {
this.glyphAtlasTexture = new Texture(context, this.glyphAtlasImage, gl.ALPHA);
this.glyphAtlasImage = null;
}
}
prepare(imageManager) {
if (this.imageAtlas) this.imageAtlas.patchUpdatedImages(imageManager, this.imageAtlasTexture);
}
queryRenderedFeatures(layers, serializedLayers, sourceFeatureState, queryGeometry, cameraQueryGeometry, scale, params, transform, maxPitchScaleFactor, pixelPosMatrix, getElevation) {
if (!this.latestFeatureIndex?.rawTileData) return {};
return this.latestFeatureIndex.query({
queryGeometry,
cameraQueryGeometry,
scale,
tileSize: this.tileSize,
pixelPosMatrix,
transform,
params,
queryPadding: this.queryPadding * maxPitchScaleFactor,
getElevation
}, layers, serializedLayers, sourceFeatureState);
}
querySourceFeatures(result, params) {
const featureIndex = this.latestFeatureIndex;
if (!featureIndex?.rawTileData) return;
const vtLayers = featureIndex.loadVTLayers();
const sourceLayer = params?.sourceLayer ? params.sourceLayer : "";
const layer = vtLayers["_geojsonTileLayer"] || vtLayers[sourceLayer];
if (!layer) return;
const filter = featureFilter(params?.filter, `querySourceFeatures[${sourceLayer}].filter`, params?.globalState);
const { z, x, y } = this.tileID.canonical;
const coord = {
z,
x,
y
};
for (let i = 0; i < layer.length; i++) {
const feature = layer.feature(i);
if (filter.needGeometry) {
const evaluationFeature = toEvaluationFeature(feature, true);
if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) continue;
} else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) continue;
const id = featureIndex.getId(feature, sourceLayer);
const geojsonFeature = new GeoJSONFeature(feature, z, x, y, id);
geojsonFeature.tile = coord;
result.push(geojsonFeature);
}
}
hasData() {
return this.state === "loaded" || this.state === "reloading" || this.state === "expired";
}
patternsLoaded() {
return this.imageAtlas && !!Object.keys(this.imageAtlas.patternPositions).length;
}
setExpiryData(data) {
const prior = this.expirationTime;
if (data.cacheControl) {
const parsedCC = parseCacheControl(data.cacheControl);
if (parsedCC["max-age"]) this.expirationTime = Date.now() + parsedCC["max-age"] * 1e3;
} else if (data.expires) this.expirationTime = new Date(data.expires).getTime();
if (this.expirationTime) {
const now = Date.now();
let isExpired = false;
if (this.expirationTime > now) isExpired = false;
else if (!prior) isExpired = true;
else if (this.expirationTime < prior) isExpired = true;
else {
const delta = this.expirationTime - prior;
if (!delta) isExpired = true;
else this.expirationTime = now + Math.max(delta, CLOCK_SKEW_RETRY_TIMEOUT);
}
if (isExpired) {
this.expiredRequestCount++;
this.state = "expired";
} else this.expiredRequestCount = 0;
}
}
getExpiryTimeout() {
if (this.expirationTime) {
if (this.expiredRequestCount) return 1e3 * (1 << Math.min(this.expiredRequestCount - 1, 31));
else return Math.min(this.expirationTime - (/* @__PURE__ */ new Date()).getTime(), Math.pow(2, 31) - 1);
}
}
setFeatureState(states, painter, revision) {
if (!this.latestFeatureIndex?.rawTileData || Object.keys(states).length === 0) return;
if (this.featureStateRevision === revision) return;
this.featureStateRevision = revision;
const vtLayers = this.latestFeatureIndex.loadVTLayers();
for (const id in this.buckets) {
if (!painter.style.hasLayer(id)) continue;
const bucket = this.buckets[id];
const sourceLayerId = bucket.layers[0]["sourceLayer"] || "_geojsonTileLayer";
const sourceLayer = vtLayers[sourceLayerId];
const sourceLayerStates = states[sourceLayerId];
if (!sourceLayer || !sourceLayerStates || sourceLayerStates.length === 0) continue;
bucket.update(sourceLayerStates, sourceLayer, this.imageAtlas?.patternPositions || {}, this.dashPositions || {});
const layer = painter?.style?.getLayer(id);
if (layer) this.queryPadding = Math.max(this.queryPadding, layer.queryRadius(bucket));
}
}
holdingForSymbolFade() {
return this.symbolFadeHoldUntil !== void 0;
}
symbolFadeFinished() {
return !this.symbolFadeHoldUntil || this.symbolFadeHoldUntil < now();
}
clearSymbolFadeHold() {
this.symbolFadeHoldUntil = void 0;
}
setSymbolHoldDuration(duration) {
this.symbolFadeHoldUntil = now() + duration;
}
setDependencies(namespace, dependencies) {
const index = {};
for (const dep of dependencies) index[dep] = true;
this.dependencies[namespace] = index;
}
hasDependency(namespaces, keys) {
for (const namespace of namespaces) {
const dependencies = this.dependencies[namespace];
if (dependencies) {
for (const key of keys) if (dependencies[key]) return true;
}
}
return false;
}
};
//#endregion
//#region src/source/source_state.ts
function featureStatesMapToArray(map) {
const result = [];
for (const id in map) result.push({
id,
state: map[id]
});
return result;
}
/**
* @internal
* SourceFeatureState manages the state and pending changes
* to features in a source, separated by source layer.
* stateChanges and deletedStates batch all changes to the tile (updates and removes, respectively)
* between coalesce() events. addFeatureState() and removeFeatureState() also update their counterpart's
* list of changes, such that coalesce() can apply the proper state changes while agnostic to the order of operations.
* In deletedStates, all null's denote complete removal of state at that scope
*/
var SourceFeatureState = class {
constructor() {
this.state = {};
this.stateChanges = {};
this.deletedStates = {};
this.revision = 0;
}
updateState(sourceLayer, featureId, newState) {
const feature = String(featureId);
this.stateChanges[sourceLayer] ||= {};
this.stateChanges[sourceLayer][feature] ||= {};
extend(this.stateChanges[sourceLayer][feature], newState);
if (this.deletedStates[sourceLayer] === null) {
this.deletedStates[sourceLayer] = {};
for (const ft in this.state[sourceLayer]) if (ft === feature) {
this.deletedStates[sourceLayer][feature] = {};
for (const prop in this.state[sourceLayer][ft]) if (newState[prop] === void 0) this.deletedStates[sourceLayer][feature][prop] = null;
} else this.deletedStates[sourceLayer][ft] = null;
} else if (this.deletedStates[sourceLayer]?.[feature] === null) {
this.deletedStates[sourceLayer][feature] = {};
for (const prop in this.state[sourceLayer][feature]) if (newState[prop] === void 0) this.deletedStates[sourceLayer][feature][prop] = null;
} else for (const key in newState) if (this.deletedStates[sourceLayer]?.[feature]?.[key] === null) delete this.deletedStates[sourceLayer][feature][key];
}
removeFeatureState(sourceLayer, featureId, key) {
if (this.deletedStates[sourceLayer] === null) return;
const feature = String(featureId);
this.deletedStates[sourceLayer] ||= {};
if (key && featureId !== void 0) {
if (this.deletedStates[sourceLayer][feature] !== null) {
this.deletedStates[sourceLayer][feature] ||= {};
this.deletedStates[sourceLayer][feature][key] = null;
}
} else if (featureId !== void 0) {
if (this.stateChanges[sourceLayer]?.[feature]) {
this.deletedStates[sourceLayer][feature] = {};
for (key in this.stateChanges[sourceLayer][feature]) this.deletedStates[sourceLayer][feature][key] = null;
} else this.deletedStates[sourceLayer][feature] = null;
} else this.deletedStates[sourceLayer] = null;
}
getState(sourceLayer, featureId) {
const feature = String(featureId);
const base = this.state[sourceLayer] || {};
const changes = this.stateChanges[sourceLayer] || {};
const reconciledState = extend({}, base[feature], changes[feature]);
if (this.deletedStates[sourceLayer] === null) return {};
else if (this.deletedStates[sourceLayer]) {
const featureDeletions = this.deletedStates[sourceLayer][featureId];
if (featureDeletions === null) return {};
for (const prop in featureDeletions) delete reconciledState[prop];
}
return reconciledState;
}
initializeTileState(tile, painter) {
const layerStates = {};
for (const sourceLayer in this.state) layerStates[sourceLayer] = featureStatesMapToArray(this.state[sourceLayer]);
tile.setFeatureState(layerStates, painter, this.revision);
}
coalesceChanges(inViewTiles, painter) {
const featuresChangedMap = {};
for (const sourceLayer in this.stateChanges) {
this.state[sourceLayer] ||= {};
featuresChangedMap[sourceLayer] ||= {};
for (const feature in this.stateChanges[sourceLayer]) {
this.state[sourceLayer][feature] ||= {};
extend(this.state[sourceLayer][feature], this.stateChanges[sourceLayer][feature]);
featuresChangedMap[sourceLayer][feature] = this.state[sourceLayer][feature];
}
}
for (const sourceLayer in this.deletedStates) {
this.state[sourceLayer] ||= {};
featuresChangedMap[sourceLayer] ||= {};
if (this.deletedStates[sourceLayer] === null) for (const ft in this.state[sourceLayer]) {
this.state[sourceLayer][ft] = {};
featuresChangedMap[sourceLayer][ft] = {};
}
else for (const feature in this.deletedStates[sourceLayer]) {
if (this.deletedStates[sourceLayer][feature] === null) this.state[sourceLayer][feature] = {};
else for (const key of Object.keys(this.deletedStates[sourceLayer][feature])) delete this.state[sourceLayer][feature][key];
featuresChangedMap[sourceLayer][feature] = this.state[sourceLayer][feature];
}
}
this.stateChanges = {};
this.deletedStates = {};
if (Object.keys(featuresChangedMap).length === 0) return;
this.revision++;
const featuresChanged = {};
for (const sourceLayer in featuresChangedMap) featuresChanged[sourceLayer] = featureStatesMapToArray(featuresChangedMap[sourceLayer]);
inViewTiles.setFeatureState(featuresChanged, painter, this.revision);
}
};
//#endregion
//#region src/geo/projection/covering_tiles.ts
/**
* A simple/heuristic function that returns whether the tile is visible under the current transform.
* @returns an {@link IntersectionResult}.
*/
function isTileVisible(frustum, tileBoundingVolume, plane) {
const frustumTest = tileBoundingVolume.intersectsFrustum(frustum);
if (!plane || frustumTest === 0) return frustumTest;
const planeTest = tileBoundingVolume.intersectsPlane(plane);
if (planeTest === 0) return 0;
if (frustumTest === 2 && planeTest === 2) return 2;
return 1;
}
/**
* Definite integral of cos(x)^p. The analytical solution is described in `developer-guides/covering-tiles.md`,
* but here the integral is evaluated numerically.
* @param p - the power to raise cos(x) to inside the integral
* @param x1 - the starting point of the integral.
* @param x2 - the ending point of the integral.
* @return the integral of cos(x)^p from x=x1 to x=x2
*/
function integralOfCosXByP(p, x1, x2) {
const numPoints = 10;
let sum = 0;
const dx = (x2 - x1) / numPoints;
for (let i = 0; i < numPoints; i++) {
const x = x1 + (i + .5) / numPoints * (x2 - x1);
sum += dx * Math.pow(Math.cos(x), p);
}
return sum;
}
function createCalculateTileZoomFunction(maxZoomLevelsOnScreen, tileCountMaxMinRatio) {
return function(requestedCenterZoom, distanceToTile2D, distanceToTileZ, distanceToCenter3D, cameraVerticalFOV) {
/**
* Controls how tiles are loaded at high pitch angles. Higher numbers cause fewer, lower resolution
* tiles to be loaded. Calculate the value that will result in the selected number of zoom levels in
* the worst-case condition (when the horizon is at the top of the screen). For more information, see
* `developer-guides/covering-tiles.md`
*/
const pitchTileLoadingBehavior = 2 * ((maxZoomLevelsOnScreen - 1) / scaleZoom(Math.cos(degreesToRadians(maxMercatorHorizonAngle - cameraVerticalFOV)) / Math.cos(degreesToRadians(maxMercatorHorizonAngle))) - 1);
const centerPitch = Math.acos(distanceToTileZ / distanceToCenter3D);
const tileCountPitch0 = 2 * integralOfCosXByP(pitchTileLoadingBehavior - 1, 0, degreesToRadians(cameraVerticalFOV / 2));
const highestPitch = Math.min(degreesToRadians(maxMercatorHorizonAngle), centerPitch + degreesToRadians(cameraVerticalFOV / 2));
const lowestPitch = Math.min(highestPitch, centerPitch - degreesToRadians(cameraVerticalFOV / 2));
const tileCount = integralOfCosXByP(pitchTileLoadingBehavior - 1, lowestPitch, highestPitch);
const thisTilePitch = Math.atan(distanceToTile2D / distanceToTileZ);
const distanceToTile3D = Math.hypot(distanceToTile2D, distanceToTileZ);
let thisTileDesiredZ = requestedCenterZoom;
thisTileDesiredZ = thisTileDesiredZ + scaleZoom(distanceToCenter3D / distanceToTile3D / Math.max(.5, Math.cos(degreesToRadians(cameraVerticalFOV / 2))));
thisTileDesiredZ += pitchTileLoadingBehavior * scaleZoom(Math.cos(thisTilePitch)) / 2;
thisTileDesiredZ -= scaleZoom(Math.max(1, tileCount / tileCountPitch0 / tileCountMaxMinRatio)) / 2;
return thisTileDesiredZ;
};
}
const defaultCalculateTileZoom = createCalculateTileZoomFunction(9.314, 3);
/**
* Return what zoom level of a tile source would most closely cover the tiles displayed by this transform.
* @param options - The options, most importantly the source's tile size.
* @returns An integer zoom level at which all tiles will be visible.
*/
function coveringZoomLevel(transform, options) {
const z = (options.roundZoom ? Math.round : Math.floor)(transform.zoom + scaleZoom(transform.tileSize / options.tileSize));
return Math.max(0, z);
}
/**
* Without terrain, `getTileBoundingVolume` has no knowledge of extruded features
* (eg. 3D buildings): every tile's bounding box is flat at the camera's `elevation`.
* That's a fine approximation of what's visible for most views, but it breaks down
* as the frustum's bottom edge approaches horizontal (which depends on both `pitch`
* and `fov`, not pitch alone) - a tall building can still be poking up into view
* long after its tile's ground point has dropped out of the frustum.
*
* This is an assumed upper bound on real-world feature height (in metres), used to
* grow the elevation used for tile culling as that bottom edge nears horizontal, so
* such tiles are not dropped too early. It has no effect away from that edge case.
*/
const ASSUMED_MAX_FEATURE_HEIGHT_METERS = 500;
/**
* Angle between the frustum's bottom edge and the mercator horizon below which
* the culling elevation starts to grow.
*/
const TILE_CULLING_HORIZON_ONSET_DEGREES = 15;
/**
* Returns the elevation to use when computing tile bounding volumes for culling:
* `transform.elevation`, growing by up to `ASSUMED_MAX_FEATURE_HEIGHT_METERS` as
* the frustum's bottom edge approaches the horizon, where a ground-level bounding
* box would cull tiles whose extruded features are still visible.
*/
function getElevationForTileCulling(transform) {
const bottomEdgeDegreesAboveHorizontal = maxMercatorHorizonAngle - transform.pitch - transform.fov / 2;
const proximityToHorizon = clamp((TILE_CULLING_HORIZON_ONSET_DEGREES - bottomEdgeDegreesAboveHorizontal) / TILE_CULLING_HORIZON_ONSET_DEGREES, 0, 1);
return transform.elevation + proximityToHorizon * ASSUMED_MAX_FEATURE_HEIGHT_METERS;
}
/**
* Returns a list of tiles that optimally covers the screen. Adapted for globe projection.
* Correctly handles LOD when moving over the antimeridian.
* @param transform - The transform instance.
* @param frustum - The covering frustum.
* @param plane - The clipping plane used by globe transform, or null.
* @param cameraCoord - The x, y, z position of the camera in MercatorCoordinates.
* @param centerCoord - The x, y, z position of the center point in MercatorCoordinates.
* @param options - Additional coveringTiles options.
* @param details - Interface to define required helper functions.
* @returns A list of tile coordinates, ordered by ascending distance from camera.
*/
function coveringTiles(transform, options) {
const frustum = transform.getCameraFrustum();
const plane = transform.getClippingPlane();
const cameraCoord = transform.screenPointToMercatorCoordinate(transform.getCameraPoint());
const centerCoord = MercatorCoordinate.fromLngLat(transform.center, transform.elevation);
cameraCoord.z = centerCoord.z + Math.cos(transform.pitchInRadians) * transform.cameraToCenterDistance / transform.worldSize;
const elevationForTileCulling = getElevationForTileCulling(transform);
const detailsProvider = transform.getCoveringTilesDetailsProvider();
const allowVariableZoom = detailsProvider.allowVariableZoom(transform, options);
const desiredZ = coveringZoomLevel(transform, options);
const minZoom = options.minzoom || 0;
const maxZoom = options.maxzoom !== void 0 ? options.maxzoom : transform.maxZoom;
const nominalZ = Math.min(Math.max(0, desiredZ), maxZoom);
const numTiles = Math.pow(2, nominalZ);
const cameraPoint = [
numTiles * cameraCoord.x,
numTiles * cameraCoord.y,
0
];
const centerPoint = [
numTiles * centerCoord.x,
numTiles * centerCoord.y,
0
];
const distanceToCenter2d = Math.hypot(centerCoord.x - cameraCoord.x, centerCoord.y - cameraCoord.y);
const distanceZ = Math.abs(centerCoord.z - cameraCoord.z);
const distanceToCenter3d = Math.hypot(distanceToCenter2d, distanceZ);
const newRootTile = (wrap) => {
return {
zoom: 0,
x: 0,
y: 0,
wrap,
fullyVisible: false
};
};
const stack = [];
const result = [];
if (transform.renderWorldCopies && detailsProvider.allowWorldCopies()) for (let i = 1; i <= 3; i++) {
stack.push(newRootTile(-i));
stack.push(newRootTile(i));
}
stack.push(newRootTile(0));
while (stack.length > 0) {
const it = stack.pop();
const x = it.x;
const y = it.y;
let fullyVisible = it.fullyVisible;
const tileID = {
x,
y,
z: it.zoom
};
const boundingVolume = detailsProvider.getTileBoundingVolume(tileID, it.wrap, elevationForTileCulling, options);
if (!fullyVisible) {
const intersectResult = isTileVisible(frustum, boundingVolume, plane);
if (intersectResult === 0) continue;
fullyVisible = intersectResult === 2;
}
const distToTile2d = detailsProvider.distanceToTile2d(cameraCoord.x, cameraCoord.y, tileID, boundingVolume);
let thisTileDesiredZ = desiredZ;
if (allowVariableZoom) thisTileDesiredZ = (options.calculateTileZoom || defaultCalculateTileZoom)(transform.zoom + scaleZoom(transform.tileSize / options.tileSize), distToTile2d, distanceZ, distanceToCenter3d, transform.fov);
thisTileDesiredZ = (options.roundZoom ? Math.round : Math.floor)(thisTileDesiredZ);
thisTileDesiredZ = Math.max(0, thisTileDesiredZ);
const z = Math.min(thisTileDesiredZ, maxZoom);
it.wrap = detailsProvider.getWrap(centerCoord, tileID, it.wrap);
if (it.zoom >= z) {
if (it.zoom < minZoom) continue;
const dz = nominalZ - it.zoom;
const dx = cameraPoint[0] - .5 - (x << dz);
const dy = cameraPoint[1] - .5 - (y << dz);
const overscaledZ = options.reparseOverscaled ? Math.max(it.zoom, thisTileDesiredZ) : it.zoom;
result.push({
tileID: new OverscaledTileID(it.zoom === maxZoom ? overscaledZ : it.zoom, it.wrap, it.zoom, x, y),
distanceSq: sqrLen([centerPoint[0] - .5 - x, centerPoint[1] - .5 - y]),
tileDistanceToCamera: Math.sqrt(dx * dx + dy * dy)
});
continue;
}
for (let i = 0; i < 4; i++) {
const childX = (x << 1) + i % 2;
const childY = (y << 1) + (i >> 1);
const childZ = it.zoom + 1;
stack.push({
zoom: childZ,
x: childX,
y: childY,
wrap: it.wrap,
fullyVisible
});
}
}
return result.sort((a, b) => a.distanceSq - b.distanceSq).map((a) => a.tileID);
}
//#endregion
//#region src/tile/tile_manager_raster.ts
function isRasterType(type) {
return type === "raster" || type === "image" || type === "video";
}
/**
* Designate fading bases and parents using a many-to-one relationship where the lower children fade in/out
* with their parents. Raster shaders are not currently designed for a one-to-many fade relationship.
*
* Tiles that are candidates for fading out must be loaded and rendered tiles, as loading a tile to then
* fade it out would not appear smoothly. The first source of truth for tile fading always starts at the
* ideal tile, which continually changes on map adjustment. The state of the previously rendered ideal
* tile plane indicates which direction to fade each part of the newer ideal plane (with varying z).
*
* For a pitched map, the back of the map can have decreasing zooms while the front can have increasing zooms.
* Fade logic must therefore adapt dynamically based on the previously rendered ideal tile set.
*/
function updateFadingTiles(inViewTiles, idealTileIDs, retain, maxFadingAncestorLevels, sourceMinZoom, sourceMaxZoom, rasterFadeDuration) {
const currentTime = now();
const edgeTileIDs = getEdgeTiles(idealTileIDs);
for (const idealID of idealTileIDs) {
const idealTile = inViewTiles.getTileById(idealID.key);
if (idealTile.fadingDirection === 0 || idealTile.fadeOpacity === 0) idealTile.resetFadeLogic();
if (updateFadingAncestor(inViewTiles, idealTile, retain, currentTime, maxFadingAncestorLevels, sourceMinZoom, rasterFadeDuration)) continue;
if (updateFadingDescendents(inViewTiles, idealTile, retain, currentTime, sourceMaxZoom, rasterFadeDuration)) continue;
if (updateFadingEdge(idealTile, edgeTileIDs, currentTime, rasterFadeDuration)) continue;
idealTile.resetFadeLogic();
}
}
/**
* Many-to-one cross-fade. Set 4 ideal tiles as the fading base for a rendered parent tile
* as the fading parent. Here the parent is fading out and the ideal tile is fading in.
*
* Parent tile - fading out ■ -- Fading Parent
* ┌──────────────┬──────┴───────┬──────────────┐
* Ideal tiles - fading in ■ ■ ■ ■ -- Base Role = Incoming
* ┌───┬─┴─┬───┐ ┌───┬─┴─┬───┐ ┌───┬─┴─┬───┐ ┌───┬─┴─┬───┐
* ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■
*/
function updateFadingAncestor(inViewTiles, idealTile, retain, now, maxFadingAncestorLevels, sourceMinZoom, rasterFadeDuration) {
if (!idealTile.hasData()) return false;
const { tileID: idealID, fadingRole, fadingDirection, fadingParentID } = idealTile;
if (fadingRole === 0 && fadingDirection === 1 && fadingParentID) {
retain[fadingParentID.key] = fadingParentID;
return true;
}
const minAncestorZ = Math.max(idealID.overscaledZ - maxFadingAncestorLevels, sourceMinZoom);
for (let ancestorZ = idealID.overscaledZ - 1; ancestorZ >= minAncestorZ; ancestorZ--) {
const ancestorID = idealID.scaledTo(ancestorZ);
const ancestorTile = inViewTiles.getLoadedTile(ancestorID);
if (!ancestorTile) continue;
idealTile.setCrossFadeLogic({
fadingRole: 0,
fadingDirection: 1,
fadingParentID: ancestorTile.tileID,
fadeEndTime: now + rasterFadeDuration
});
ancestorTile.setCrossFadeLogic({
fadingRole: 1,
fadingDirection: 0,
fadeEndTime: now + rasterFadeDuration
});
retain[ancestorID.key] = ancestorID;
return true;
}
return false;
}
/**
* Many-to-one cross-fade. Search descendents of ideal tiles as the fading base with the ideal tile
* as the fading parent. Here the children are fading out and the ideal tile is fading in.
*
* ■
* ┌──────────────┬──────┴───────┬──────────────┐
* Ideal tiles - fading in ■ ■ ■ ■ -- Fading Parent
* ┌───┬─┴─┬───┐ ┌───┬─┴─┬───┐ ┌───┬─┴─┬───┐ ┌───┬─┴─┬───┐
* Child tiles - fading out ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ ■ -- Base Role = Departing
*
* Try direct children first. If none found, try grandchildren. Stops at the first generation that provides a fader.
*/
function updateFadingDescendents(inViewTiles, idealTile, retain, now, sourceMaxZoom, rasterFadeDuration) {
if (!idealTile.hasData()) return false;
const idealChildren = idealTile.tileID.children(sourceMaxZoom);
let hasFader = updateFadingChildren(inViewTiles, idealTile, idealChildren, retain, now, sourceMaxZoom, rasterFadeDuration);
if (hasFader) return true;
for (const childID of idealChildren) if (updateFadingChildren(inViewTiles, idealTile, childID.children(sourceMaxZoom), retain, now, sourceMaxZoom, rasterFadeDuration)) hasFader = true;
return hasFader;
}
function updateFadingChildren(inViewTiles, idealTile, childIDs, retain, now, sourceMaxZoom, rasterFadeDuration) {
if (childIDs[0].overscaledZ >= sourceMaxZoom) return false;
let foundFader = false;
for (const childID of childIDs) {
const childTile = inViewTiles.getLoadedTile(childID);
if (!childTile) continue;
const { fadingRole, fadingDirection, fadingParentID } = childTile;
if (fadingRole !== 0 || fadingDirection !== 0 || !fadingParentID) {
childTile.setCrossFadeLogic({
fadingRole: 0,
fadingDirection: 0,
fadingParentID: idealTile.tileID,
fadeEndTime: now + rasterFadeDuration
});
idealTile.setCrossFadeLogic({
fadingRole: 1,
fadingDirection: 1,
fadeEndTime: now + rasterFadeDuration
});
}
retain[childID.key] = childID;
foundFader = true;
}
return foundFader;
}
/**
* One-to-one self fading for unloaded edge tiles (for panning sideways on map). for loading tiles over gaps it feels
* more natural for them to fade in, however if they are already loaded/cached then there is no need to fade as map will
* look cohesive with no gaps. Note that draw_raster determines fade priority, as many-to-one fade supersedes edge fading.
*/
function updateFadingEdge(idealTile, edgeTileIDs, now, rasterFadeDuration) {
const idealID = idealTile.tileID;
if (idealTile.selfFading) return true;
if (idealTile.hasData()) return false;
if (edgeTileIDs.has(idealID)) {
const fadeEndTime = now + rasterFadeDuration;
idealTile.setSelfFadeLogic(fadeEndTime);
return true;
}
return false;
}
function hasRasterTransition(inViewTiles, rasterFadeDuration) {
if (rasterFadeDuration <= 0) return false;
const currentTime = now();
for (const tile of inViewTiles.getAllTiles()) if (tile.fadeEndTime >= currentTime) return true;
return false;
}
//#endregion
//#region src/tile/tile_manager_raster_dem.ts
/**
* For raster terrain source, backfill DEM to eliminate visible tile boundaries
*/
function backfillDEM(tile, inViewTiles) {
const renderables = inViewTiles.getRenderableIds();
for (const borderId of renderables) {
if (!tile.neighboringTiles?.[borderId]) continue;
const borderTile = inViewTiles.getTileById(borderId);
if (!tile.neighboringTiles[borderId].backfilled) fillBorder(tile, borderTile);
if (borderTile.neighboringTiles?.[tile.tileID.key]?.backfilled) continue;
fillBorder(borderTile, tile);
}
}
function fillBorder(tile, borderTile) {
tile.needsHillshadePrepare = true;
tile.needsTerrainPrepare = true;
let dx = borderTile.tileID.canonical.x - tile.tileID.canonical.x;
const dy = borderTile.tileID.canonical.y - tile.tileID.canonical.y;
const dim = Math.pow(2, tile.tileID.canonical.z);
const borderId = borderTile.tileID.key;
if (dx === 0 && dy === 0) return;
if (Math.abs(dy) > 1) return;
if (Math.abs(dx) > 1) {
if (Math.abs(dx + dim) === 1) dx += dim;
else if (Math.abs(dx - dim) === 1) dx -= dim;
}
if (!borderTile.dem || !tile.dem) return;
tile.dem.backfillBorder(borderTile.dem, dx, dy);
if (tile.neighboringTiles?.[borderId]) tile.neighboringTiles[borderId].backfilled = true;
}
//#endregion
//#region src/tile/tile_manager_in_view_tiles.ts
var InViewTiles = class {
constructor() {
this._tiles = {};
}
handleWrapJump(wrapDelta) {
const tiles = {};
for (const id in this._tiles) {
const tile = this._tiles[id];
tile.tileID = tile.tileID.unwrapTo(tile.tileID.wrap + wrapDelta);
tiles[tile.tileID.key] = tile;
}
this._tiles = tiles;
}
setFeatureState(featuresChanged, painter, revision) {
for (const id in this._tiles) this._tiles[id].setFeatureState(featuresChanged, painter, revision);
}
getAllTiles() {
return Object.values(this._tiles);
}
getAllIds(sorted = false) {
if (sorted) return Object.values(this._tiles).map((tile) => tile.tileID).sort(compareTileId).map((id) => id.key);
return Object.keys(this._tiles);
}
getTileById(key) {
return this._tiles[key];
}
setTile(key, tile) {
this._tiles[key] = tile;
}
deleteTileById(key) {
delete this._tiles[key];
}
/**
* Get a currently loaded tile.
* - a cached tile is not a loaded tile
* @returns the tile if it's in view and had data, null otherwise.
*/
getLoadedTile(tileID) {
const tile = this.getTileById(tileID.key);
if (tile?.hasData()) return tile;
return null;
}
isIdRenderable(id, symbolLayer = false) {
return this.getTileById(id)?.isRenderable(symbolLayer);
}
getRenderableIds(bearingInRadians = 0, symbolLayer) {
const renderables = [];
for (const id of this.getAllIds()) if (this.isIdRenderable(id, symbolLayer)) renderables.push(this.getTileById(id));
if (symbolLayer) return renderables.sort((a_, b_) => {
const a = a_.tileID;
const b = b_.tileID;
const rotatedA = new Point(a.canonical.x, a.canonical.y)._rotate(-bearingInRadians);
const rotatedB = new Point(b.canonical.x, b.canonical.y)._rotate(-bearingInRadians);
return a.overscaledZ - b.overscaledZ || rotatedB.y - rotatedA.y || rotatedB.x - rotatedA.x;
}).map((tile) => tile.tileID.key);
return renderables.map((tile) => tile.tileID).sort(compareTileId).map((id) => id.key);
}
};
//#endregion
//#region src/tile/tile_manager.ts
/**
* @internal
* `TileManager` is responsible for
*
* - creating an instance of `Source`
* - caching tiles loaded from an instance of `Source`
* - handling incoming source data events events from `Map` and coordinating updates
* - providing the current renderable tile coordinates to the `Painter`
* - loading the tiles needed to render a given viewport
* - retaining the tiles needed as substitutes for pending loading tiles
* - retaining the tiles needed for fading between parents and children (for raster sources)
* - reloading tiles when source data or dependencies change
* - handling tile expiration and refresh timers
* - unloading cached tiles not needed to render a given viewport
* - managing tile state and feature state
*/
var TileManager = class TileManager extends Evented {
static {
this.maxUnderzooming = 10;
}
static {
this.maxOverzooming = 3;
}
constructor(id, options, dispatcher) {
super();
this.id = id;
this.dispatcher = dispatcher;
this.on("data", (e) => {
this._dataHandler(e);
});
this.on("dataloading", () => {
this._sourceErrored = false;
});
this.on("error", () => {
this._sourceErrored = this._source.loaded();
});
this._source = create(id, options, dispatcher, this);
this._inViewTiles = new InViewTiles();
this._outOfViewCache = new TileCache(0, (tile) => this._unloadTile(tile));
this._timers = {};
this._maxTileCacheSize = null;
this._maxTileCacheZoomLevels = null;
this._rasterFadeDuration = 0;
this._maxFadingAncestorLevels = 5;
this._state = new SourceFeatureState();
this._didEmitContent = false;
this._updated = false;
}
onAdd(map) {
this.map = map;
this._maxTileCacheSize = map ? map._maxTileCacheSize : null;
this._maxTileCacheZoomLevels = map ? map._maxTileCacheZoomLevels : null;
if (this._source?.onAdd) this._source.onAdd(map);
}
onRemove(map) {
for (const tile of this._inViewTiles.getAllTiles()) tile.unloadVectorData();
this.clearTiles();
if (this._source?.onRemove) this._source.onRemove(map);
this._inViewTiles = new InViewTiles();
}
/**
* Return true if no tile data is pending, tiles will not change unless
* an additional API call is received.
*/
loaded() {
if (this._sourceErrored) return true;
if (!this._sourceLoaded) return false;
if (!this._source.loaded()) return false;
if ((this.used !== void 0 || this.usedForTerrain !== void 0) && !this.used && !this.usedForTerrain) return true;
if (!this._updated) return false;
for (const tile of this._inViewTiles.getAllTiles()) if (tile.state !== "loaded" && tile.state !== "errored") return false;
return true;
}
getSource() {
return this._source;
}
getState() {
return this._state;
}
pause() {
this._paused = true;
}
resume() {
if (!this._paused) return;
const shouldReload = this._shouldReloadOnResume;
this._paused = false;
this._shouldReloadOnResume = false;
if (shouldReload) this.reload();
if (this.transform) this.update(this.transform, this.terrain);
}
async _loadTile(tile, id, state, hadData) {
try {
const result = await this._source.loadTile(tile);
this._tileLoaded(tile, id, state, hadData, result);
} catch (err) {
tile.state = "errored";
if (err.status !== 404) this._source.fire(new ErrorEvent(ensureError(err), { tile }));
else this.update(this.transform, this.terrain);
}
}
_unloadTile(tile) {
if (this._source.unloadTile) this._source.unloadTile(tile);
}
_abortTile(tile) {
if (this._source.abortTile) this._source.abortTile(tile);
this._source.fire(new MapSourceDataEvent("dataabort", {
tile,
coord: tile.tileID
}));
}
serialize() {
return this._source.serialize();
}
prepare(context) {
if (this._source.prepare) this._source.prepare();
this._state.coalesceChanges(this._inViewTiles, this.map ? this.map.painter : null);
for (const tile of this._inViewTiles.getAllTiles()) {
tile.upload(context);
tile.prepare(this.map.style.imageManager);
}
}
/**
* Return all tile ids ordered with z-order, and cast to numbers
*/
getIds() {
return this._inViewTiles.getAllIds(true);
}
getRenderableIds(symbolLayer) {
return this._inViewTiles.getRenderableIds(this.transform?.bearingInRadians, symbolLayer);
}
hasRenderableParent(tileID) {
const parentZ = tileID.overscaledZ - 1;
if (parentZ >= this._source.minzoom) {
const parentTile = this.getLoadedTile(tileID.scaledTo(parentZ));
if (parentTile) return this._inViewTiles.isIdRenderable(parentTile.tileID.key);
}
return false;
}
/**
* Reload tiles based on the current state of the source.
* @param sourceDataChanged - If `true`, reload all tiles using a state of 'expired' (errored tiles use 'loading' since they have nothing to show yet), otherwise reload only non-errored tiles using state of 'reloading'.
* @param shouldReloadTileOptions - Set of options associated with a `MapSourceDataChangedEvent` that can be passed back to the associated `Source` determine whether a tile should be reloaded.
*/
reload(sourceDataChanged, shouldReloadTileOptions = void 0) {
if (this._paused) {
this._shouldReloadOnResume = true;
return;
}
this._outOfViewCache.reset();
for (const id of this._inViewTiles.getAllIds()) {
const tile = this._inViewTiles.getTileById(id);
if (shouldReloadTileOptions && !this._source.shouldReloadTile(tile, shouldReloadTileOptions)) continue;
else if (sourceDataChanged) this._reloadTile(id, tile.state === "errored" ? "loading" : "expired");
else if (tile.state !== "errored") this._reloadTile(id, "reloading");
}
}
async _reloadTile(id, state) {
const tile = this._inViewTiles.getTileById(id);
if (!tile) return;
const hadData = tile.hasData();
if (tile.state !== "loading") tile.state = state;
await this._loadTile(tile, id, state, hadData);
}
_tileLoaded(tile, id, previousState, hadData, result) {
if (!hadData) {
tile.timeAdded = now();
if (tile.selfFading) tile.fadeEndTime = tile.timeAdded + this._rasterFadeDuration;
}
if (previousState === "expired") tile.refreshedUponExpiration = true;
this._setTileReloadTimer(id, tile);
if (result?.unmodified) return;
if (this.getSource().type === "raster-dem" && tile.dem) backfillDEM(tile, this._inViewTiles);
tile.featureStateRevision = -1;
this._state.initializeTileState(tile, this.map ? this.map.painter : null);
if (!tile.aborted) this._source.fire(new MapSourceDataEvent("data", {
tile,
coord: tile.tileID
}));
}
/**
* Get a specific tile by TileID
*/
getTile(tileID) {
return this.getTileByID(tileID.key);
}
/**
* Get a specific tile by id
*/
getTileByID(id) {
return this._inViewTiles.getTileById(id);
}
/**
* Retain the uppermost loaded children of each provided target tile, within a variable covering zoom range.
*
* On pitched maps, different parts of the screen show different zoom levels simultaneously.
* Ideal tiles are generated using coveringTiles() above, which returns the ideal tile set for
* the current pitched plane, which can carry tiles of varying zooms (overscaledZ).
* See: https://maplibre.org/maplibre-gl-js/docs/examples/level-of-detail-control/
*
* A fixed `maxCoveringZoom` on a pitched map would incorrectly intersect with some
* ideal tiles and cause distant high-pitch tiles to skip their uppermost children.
*
* To solve this, we calculate the max covering zoom for each ideal tile separately using its
* `overscaledZ`. This effectively makes the "max covering zoom plane" parallel to the
* "ideal tile plane," ensuring that we correctly capture the uppermost children
* of each ideal tile across the pitched view.
*
* Analogy: imagine two sheets of paper in 3D space:
* - one sheet = ideal tiles at varying overscaledZ
* - the second sheet = maxCoveringZoom
*
* @param retainTileMap - this parameters will be updated with the child tiles to keep
* @param idealTilesWithoutData - which of the ideal tiles currently does not have loaded data
* @return a set of tiles that need to be loaded
*/
_retainLoadedChildren(retainTileMap, idealTilesWithoutData) {
const loadedDescendents = this._getLoadedDescendents(idealTilesWithoutData);
const incomplete = /* @__PURE__ */ new Set();
for (const targetID of idealTilesWithoutData) {
const descendents = loadedDescendents[targetID.key];
if (!descendents?.length) {
incomplete.add(targetID);
continue;
}
const maxCoveringZoom = targetID.overscaledZ + TileManager.maxOverzooming;
const candidates = descendents.filter((t) => t.tileID.overscaledZ <= maxCoveringZoom);
if (!candidates.length) {
incomplete.add(targetID);
continue;
}
const topZoom = Math.min(...candidates.map((t) => t.tileID.overscaledZ));
const topIDs = candidates.filter((t) => t.tileID.overscaledZ === topZoom).map((t) => t.tileID);
for (const tileID of topIDs) retainTileMap[tileID.key] = tileID;
if (!this._areDescendentsComplete(topIDs, topZoom, targetID.overscaledZ)) incomplete.add(targetID);
}
return incomplete;
}
/**
* Return dictionary of qualified loaded descendents for each provided target tile id
*/
_getLoadedDescendents(targetTileIDs) {
const loadedDescendents = {};
for (const tile of this._inViewTiles.getAllTiles().filter((tile) => tile.hasData())) for (const targetID of targetTileIDs) if (tile.tileID.isChildOf(targetID)) {
loadedDescendents[targetID.key] ||= [];
loadedDescendents[targetID.key].push(tile);
}
return loadedDescendents;
}
/**
* Determine if tile ids fully cover the current generation.
* - 1st generation: need 4 children or 1 overscaled child
* - 2nd generation: need 16 children or 1 overscaled child
*/
_areDescendentsComplete(generationIDs, generationZ, ancestorZ) {
if (generationIDs.length === 1 && generationIDs[0].isOverscaled()) return generationIDs[0].overscaledZ === generationZ;
else return Math.pow(4, generationZ - ancestorZ) === generationIDs.length;
}
/**
* Get a currently loaded tile.
* - a cached tile is not a loaded tile
* @returns the tile if it's in view and had data, null otherwise.
*/
getLoadedTile(tileID) {
return this._inViewTiles.getLoadedTile(tileID);
}
/**
* Resizes the tile cache based on the current viewport's size
* or the maxTileCacheSize option passed during map creation
*
* Larger viewports use more tiles and need larger caches. Larger viewports
* are more likely to be found on devices with more memory and on pages where
* the map is more important.
*/
updateCacheSize(transform) {
const approxTilesInView = (Math.ceil(transform.width / this._source.tileSize) + 1) * (Math.ceil(transform.height / this._source.tileSize) + 1);
const commonZoomRange = this._maxTileCacheZoomLevels === null ? config.MAX_TILE_CACHE_ZOOM_LEVELS : this._maxTileCacheZoomLevels;
const viewDependentMaxSize = Math.floor(approxTilesInView * commonZoomRange);
const maxSize = typeof this._maxTileCacheSize === "number" ? Math.min(this._maxTileCacheSize, viewDependentMaxSize) : viewDependentMaxSize;
this._outOfViewCache.setMaxSize(maxSize);
}
handleWrapJump(lng) {
const worldDifference = (lng - (this._prevLng === void 0 ? lng : this._prevLng)) / 360;
const wrapDelta = Math.round(worldDifference);
this._prevLng = lng;
if (wrapDelta) {
this._inViewTiles.handleWrapJump(wrapDelta);
this._resetTileReloadTimers();
}
}
/**
* Removes tiles that are outside the viewport and adds new tiles that
* are inside the viewport.
*/
update(transform, terrain) {
if (!this._sourceLoaded || this._paused) return;
this.transform = transform;
this.terrain = terrain;
this.updateCacheSize(transform);
this.handleWrapJump(this.transform.center.lng);
let idealTileIDs;
if (!this.used && !this.usedForTerrain) idealTileIDs = [];
else if (this._source.tileID) idealTileIDs = transform.getVisibleUnwrappedCoordinates(this._source.tileID).map((unwrapped) => new OverscaledTileID(unwrapped.canonical.z, unwrapped.wrap, unwrapped.canonical.z, unwrapped.canonical.x, unwrapped.canonical.y));
else {
idealTileIDs = coveringTiles(transform, {
tileSize: this.usedForTerrain ? this.tileSize : this._source.tileSize,
minzoom: this._source.minzoom,
maxzoom: this._source.type === "vector" && this.map._zoomLevelsToOverscale !== void 0 ? Math.max(this._source.maxzoom, transform.maxZoom - this.map._zoomLevelsToOverscale) : this._source.maxzoom,
roundZoom: this.usedForTerrain ? false : this._source.roundZoom,
reparseOverscaled: this._source.reparseOverscaled,
terrain,
calculateTileZoom: this._source.calculateTileZoom
});
if (this._source.hasTile) idealTileIDs = idealTileIDs.filter((coord) => this._source.hasTile(coord));
}
if (this.usedForTerrain) idealTileIDs = this._addTerrainIdealTiles(idealTileIDs);
const noPendingDataEmissions = idealTileIDs.length === 0 && !this._updated && this._didEmitContent;
this._updated = true;
if (noPendingDataEmissions) this.fire(new MapSourceDataEvent("data", {
sourceDataType: "idle",
sourceId: this.id
}));
const zoom = coveringZoomLevel(transform, this._source);
const retain = this._updateRetainedTiles(idealTileIDs, zoom);
const isRaster = isRasterType(this._source.type);
if (isRaster && this._rasterFadeDuration > 0 && !terrain) updateFadingTiles(this._inViewTiles, idealTileIDs, retain, this._maxFadingAncestorLevels, this._source.minzoom, this._source.maxzoom, this._rasterFadeDuration);
if (isRaster) this._cleanUpRasterTiles(retain);
else this._cleanUpVectorTiles(retain);
}
/**
* Remove raster tiles that are no longer retained
*/
_cleanUpRasterTiles(retain) {
for (const id of this._inViewTiles.getAllIds()) if (!retain[id]) this._removeTile(id);
}
/**
* Remove vector tiles that are no longer retained and also not needed for symbol fading
*/
_cleanUpVectorTiles(retain) {
for (const id of this._inViewTiles.getAllIds()) {
const tile = this._inViewTiles.getTileById(id);
if (retain[id]) {
tile.clearSymbolFadeHold();
continue;
}
if (!tile.hasSymbolBuckets) {
this._removeTile(id);
continue;
}
if (!tile.holdingForSymbolFade()) tile.setSymbolHoldDuration(this.map._fadeDuration);
else if (tile.symbolFadeFinished()) this._removeTile(id);
}
}
/**
* Add ideal tiles needed for 3D terrain rendering
*/
_addTerrainIdealTiles(idealTileIDs) {
const ancestors = [];
for (const tileID of idealTileIDs) if (tileID.canonical.z > this._source.minzoom) {
const parent = tileID.scaledTo(tileID.canonical.z - 1);
ancestors.push(parent);
const parent2 = tileID.scaledTo(Math.max(this._source.minzoom, Math.min(tileID.canonical.z, 5)));
ancestors.push(parent2);
}
return idealTileIDs.concat(ancestors);
}
releaseSymbolFadeTiles() {
for (const id of this._inViewTiles.getAllIds()) if (this._inViewTiles.getTileById(id).holdingForSymbolFade()) this._removeTile(id);
}
/**
* Set tiles to be retained on update of the source. For ideal tiles that do not have data, retain their loaded
* children so they can be displayed as substitutes pending load of each ideal tile (to reduce flickering).
* If no loaded children are available, fallback to seeking loaded parents as an alternative substitute.
*/
_updateRetainedTiles(idealTileIDs, zoom) {
const idealTilesWithoutData = /* @__PURE__ */ new Set();
for (const idealID of idealTileIDs) if (!this._addTile(idealID).hasData()) idealTilesWithoutData.add(idealID);
const retainTileMap = idealTileIDs.reduce((acc, t) => {
acc[t.key] = t;
return acc;
}, {});
const tileIdsWithoutData = this._retainLoadedChildren(retainTileMap, idealTilesWithoutData);
const checked = {};
const minCoveringZoom = Math.max(zoom - TileManager.maxUnderzooming, this._source.minzoom);
for (const tileID of tileIdsWithoutData) {
let tile = this._inViewTiles.getTileById(tileID.key);
let parentWasRequested = tile?.wasRequested();
for (let overscaledZ = tileID.overscaledZ - 1; overscaledZ >= minCoveringZoom; --overscaledZ) {
const parentId = tileID.scaledTo(overscaledZ);
if (checked[parentId.key]) break;
checked[parentId.key] = true;
tile = this.getTile(parentId);
if (!tile && parentWasRequested) tile = this._addTile(parentId);
if (tile) {
const hasData = tile.hasData();
if (hasData || !this.map?.cancelPendingTileRequestsWhileZooming || parentWasRequested) retainTileMap[parentId.key] = parentId;
parentWasRequested = tile.wasRequested();
if (hasData) break;
}
}
}
return retainTileMap;
}
/**
* Add a tile, given its coordinate, to the pyramid.
*/
_addTile(tileID) {
let tile = this._inViewTiles.getTileById(tileID.key);
if (tile) return tile;
tile = this._outOfViewCache.getAndRemove(tileID);
if (tile) {
tile.resetFadeLogic();
this._setTileReloadTimer(tileID.key, tile);
tile.tileID = tileID;
this._state.initializeTileState(tile, this.map ? this.map.painter : null);
}
const cached = tile;
if (!tile) {
tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor());
this._loadTile(tile, tileID.key, tile.state, false);
}
tile.uses++;
this._inViewTiles.setTile(tileID.key, tile);
if (!cached) this._source.fire(new MapSourceDataEvent("dataloading", {
tile,
coord: tile.tileID
}));
return tile;
}
/**
* Set a timeout to reload the tile after it expires
*/
_setTileReloadTimer(id, tile) {
this._clearTileReloadTimer(id);
const expiryTimeout = tile.getExpiryTimeout();
if (expiryTimeout) {
const reload = () => {
this._reloadTile(id, "expired");
delete this._timers[id];
};
this._timers[id] = setTimeout(reload, expiryTimeout);
}
}
_clearTileReloadTimer(id) {
const timeout = this._timers[id];
if (timeout) {
clearTimeout(timeout);
delete this._timers[id];
}
}
_resetTileReloadTimers() {
for (const id in this._timers) {
clearTimeout(this._timers[id]);
delete this._timers[id];
}
for (const id of this._inViewTiles.getAllIds()) {
const tile = this._inViewTiles.getTileById(id);
this._setTileReloadTimer(id, tile);
}
}
/**
* Reload any currently renderable tiles that are match one of the incoming `tileId` x/y/z
*/
refreshTiles(tileIds) {
for (const id of this._inViewTiles.getAllIds()) {
const tile = this._inViewTiles.getTileById(id);
if (!this._inViewTiles.isIdRenderable(id) && tile.state != "errored") continue;
if (tileIds.some((tid) => tid.equals(tile.tileID.canonical))) this._reloadTile(id, "expired");
}
}
/**
* Remove a tile, given its id, from the pyramid
*/
_removeTile(id) {
const tile = this._inViewTiles.getTileById(id);
if (!tile) return;
tile.uses--;
this._inViewTiles.deleteTileById(id);
this._clearTileReloadTimer(id);
if (tile.uses > 0) return;
if (tile.hasData() && tile.state !== "reloading") this._outOfViewCache.add(tile.tileID, tile, tile.getExpiryTimeout());
else {
tile.aborted = true;
this._abortTile(tile);
this._unloadTile(tile);
}
}
/** @internal
* Handles incoming source data messages (i.e. after the source has been updated via a worker that has fired
* to map.ts data event). For sources with mutable data, the 'content' event fires when the underlying data
* to a source has changed. (i.e. GeoJSONSource.setData and ImageSource.setCoordinates)
*/
_dataHandler(e) {
if (e.dataType !== "source") return;
if (e.sourceDataType === "metadata") {
this._sourceLoaded = true;
return;
}
if (e.sourceDataType !== "content" || !this._sourceLoaded || this._paused) return;
this.reload(e.sourceDataChanged, e.shouldReloadTileOptions);
if (this.transform) this.update(this.transform, this.terrain);
this._didEmitContent = true;
}
/**
* Remove all tiles from this pyramid
*/
clearTiles() {
this._shouldReloadOnResume = false;
this._paused = false;
for (const id of this._inViewTiles.getAllIds()) this._removeTile(id);
this._outOfViewCache.reset();
}
/**
* Search through our current tiles and attempt to find the tiles that
* cover the given bounds.
* @param pointQueryGeometry - coordinates of the corners of bounding rectangle
* @returns result items have `{tile, minX, maxX, minY, maxY}`, where min/max bounding values are the given bounds transformed in into the coordinate space of this tile.
*/
tilesIn(pointQueryGeometry, maxPitchScaleFactor, has3DLayer) {
const tileResults = [];
const transform = this.transform;
if (!transform) return tileResults;
const allowWorldCopies = transform.getCoveringTilesDetailsProvider().allowWorldCopies();
const cameraPointQueryGeometry = has3DLayer ? transform.getCameraQueryGeometry(pointQueryGeometry) : pointQueryGeometry;
const project = (point) => transform.screenPointToMercatorCoordinate(point, this.terrain);
const queryGeometry = this.transformBbox(pointQueryGeometry, project, !allowWorldCopies);
const cameraQueryGeometry = this.transformBbox(cameraPointQueryGeometry, project, !allowWorldCopies);
const ids = this.getIds();
const cameraBounds = Bounds.fromPoints(cameraQueryGeometry);
for (const id of ids) {
const tile = this._inViewTiles.getTileById(id);
if (tile.holdingForSymbolFade()) continue;
const tileIDs = allowWorldCopies ? [tile.tileID] : [tile.tileID.unwrapTo(-1), tile.tileID.unwrapTo(0)];
const scale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ);
const queryPadding = maxPitchScaleFactor * tile.queryPadding * EXTENT / tile.tileSize / scale;
for (const tileID of tileIDs) {
const tileSpaceBounds = cameraBounds.map((point) => tileID.getTilePoint(new MercatorCoordinate(point.x, point.y)));
tileSpaceBounds.expandBy(queryPadding);
if (tileSpaceBounds.intersects(EXTENT_BOUNDS)) {
const tileSpaceQueryGeometry = queryGeometry.map((c) => tileID.getTilePoint(c));
const tileSpaceCameraQueryGeometry = cameraQueryGeometry.map((c) => tileID.getTilePoint(c));
tileResults.push({
tile,
tileID: allowWorldCopies ? tileID : tileID.unwrapTo(0),
queryGeometry: tileSpaceQueryGeometry,
cameraQueryGeometry: tileSpaceCameraQueryGeometry,
scale
});
}
}
}
return tileResults;
}
transformBbox(geom, project, checkWrap) {
let transformed = geom.map(project);
if (checkWrap) {
const bounds = Bounds.fromPoints(geom);
bounds.shrinkBy(Math.min(bounds.width(), bounds.height()) * .001);
const projected = bounds.map(project);
if (!Bounds.fromPoints(transformed).covers(projected)) transformed = transformed.map((coord) => coord.x > .5 ? new MercatorCoordinate(coord.x - 1, coord.y, coord.z) : coord);
}
return transformed;
}
getVisibleCoordinates(symbolLayer) {
const coords = this.getRenderableIds(symbolLayer).map((id) => this._inViewTiles.getTileById(id).tileID);
if (this.transform) this.transform.populateCache(coords);
return coords;
}
hasTransition() {
if (this._source.hasTransition()) return true;
return isRasterType(this._source.type) && hasRasterTransition(this._inViewTiles, this._rasterFadeDuration);
}
setRasterFadeDuration(fadeDuration) {
this._rasterFadeDuration = fadeDuration;
}
/**
* Set the value of a particular state for a feature
*/
setFeatureState(sourceLayer, featureId, state) {
sourceLayer ||= GEOJSON_TILE_LAYER_NAME;
this._state.updateState(sourceLayer, featureId, state);
}
/**
* Resets the value of a particular state key for a feature
*/
removeFeatureState(sourceLayer, featureId, key) {
sourceLayer ||= GEOJSON_TILE_LAYER_NAME;
this._state.removeFeatureState(sourceLayer, featureId, key);
}
/**
* Get the entire state object for a feature
*/
getFeatureState(sourceLayer, featureId) {
sourceLayer ||= GEOJSON_TILE_LAYER_NAME;
return this._state.getState(sourceLayer, featureId);
}
/**
* Sets the set of keys that the tile depends on. This allows tiles to
* be reloaded when their dependencies change.
*/
setDependencies(tileKey, namespace, dependencies) {
const tile = this._inViewTiles.getTileById(tileKey);
if (tile) tile.setDependencies(namespace, dependencies);
}
/**
* Reloads all tiles that depend on the given keys.
*/
reloadTilesForDependencies(namespaces, keys) {
for (const id of this._inViewTiles.getAllIds()) if (this._inViewTiles.getTileById(id).hasDependency(namespaces, keys)) this._reloadTile(id, "reloading");
this._outOfViewCache.filter((tile) => !tile.hasDependency(namespaces, keys));
}
areTilesLoaded() {
for (const tile of this._inViewTiles.getAllTiles()) if (!(tile.state === "loaded" || tile.state === "errored")) return false;
return true;
}
};
//#endregion
//#region src/symbol/path_interpolator.ts
var PathInterpolator = class {
constructor(points_, padding_) {
this.reset(points_, padding_);
}
reset(points_, padding_) {
this.points = points_ || [];
this._distances = [0];
for (let i = 1; i < this.points.length; i++) this._distances[i] = this._distances[i - 1] + this.points[i].dist(this.points[i - 1]);
this.length = this._distances[this._distances.length - 1];
this.padding = Math.min(padding_ || 0, this.length * .5);
this.paddedLength = this.length - this.padding * 2;
}
lerp(t) {
if (this.points.length === 1) return this.points[0];
t = clamp(t, 0, 1);
let currentIndex = 1;
let distOfCurrentIdx = this._distances[currentIndex];
const distToTarget = t * this.paddedLength + this.padding;
while (distOfCurrentIdx < distToTarget && currentIndex < this._distances.length) distOfCurrentIdx = this._distances[++currentIndex];
const idxOfPrevPoint = currentIndex - 1;
const distOfPrevIdx = this._distances[idxOfPrevPoint];
const segmentLength = distOfCurrentIdx - distOfPrevIdx;
const segmentT = segmentLength > 0 ? (distToTarget - distOfPrevIdx) / segmentLength : 0;
return this.points[idxOfPrevPoint].mult(1 - segmentT).add(this.points[currentIndex].mult(segmentT));
}
};
//#endregion
//#region src/symbol/grid_index.ts
function overlapAllowed(overlapA, overlapB) {
let allowed = true;
if (overlapA === "always") {} else if (overlapA === "never" || overlapB === "never") allowed = false;
return allowed;
}
/**
* @internal
* GridIndex is a data structure for testing the intersection of
* circles and rectangles in a 2d plane.
* It is optimized for rapid insertion and querying.
* GridIndex splits the plane into a set of "cells" and keeps track
* of which geometries intersect with each cell. At query time,
* full geometry comparisons are only done for items that share
* at least one cell. As long as the geometries are relatively
* uniformly distributed across the plane, this greatly reduces
* the number of comparisons necessary.
*/
var GridIndex = class {
constructor(width, height, cellSize) {
const boxCells = this.boxCells = [];
const circleCells = this.circleCells = [];
this.xCellCount = Math.ceil(width / cellSize);
this.yCellCount = Math.ceil(height / cellSize);
for (let i = 0; i < this.xCellCount * this.yCellCount; i++) {
boxCells.push([]);
circleCells.push([]);
}
this.circleKeys = [];
this.boxKeys = [];
this.bboxes = [];
this.circles = [];
this.width = width;
this.height = height;
this.xScale = this.xCellCount / width;
this.yScale = this.yCellCount / height;
this.boxUid = 0;
this.circleUid = 0;
}
keysLength() {
return this.boxKeys.length + this.circleKeys.length;
}
insert(key, x1, y1, x2, y2) {
this._forEachCell(x1, y1, x2, y2, this._insertBoxCell, this.boxUid++);
this.boxKeys.push(key);
this.bboxes.push(x1);
this.bboxes.push(y1);
this.bboxes.push(x2);
this.bboxes.push(y2);
}
insertCircle(key, x, y, radius) {
this._forEachCell(x - radius, y - radius, x + radius, y + radius, this._insertCircleCell, this.circleUid++);
this.circleKeys.push(key);
this.circles.push(x);
this.circles.push(y);
this.circles.push(radius);
}
_insertBoxCell(x1, y1, x2, y2, cellIndex, uid) {
this.boxCells[cellIndex].push(uid);
}
_insertCircleCell(x1, y1, x2, y2, cellIndex, uid) {
this.circleCells[cellIndex].push(uid);
}
_query(x1, y1, x2, y2, hitTest, overlapMode, predicate) {
if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) return [];
const result = [];
if (x1 <= 0 && y1 <= 0 && this.width <= x2 && this.height <= y2) {
if (hitTest) return [{
key: null,
x1,
y1,
x2,
y2
}];
for (let boxUid = 0; boxUid < this.boxKeys.length; boxUid++) result.push({
key: this.boxKeys[boxUid],
x1: this.bboxes[boxUid * 4],
y1: this.bboxes[boxUid * 4 + 1],
x2: this.bboxes[boxUid * 4 + 2],
y2: this.bboxes[boxUid * 4 + 3]
});
for (let circleUid = 0; circleUid < this.circleKeys.length; circleUid++) {
const x = this.circles[circleUid * 3];
const y = this.circles[circleUid * 3 + 1];
const radius = this.circles[circleUid * 3 + 2];
result.push({
key: this.circleKeys[circleUid],
x1: x - radius,
y1: y - radius,
x2: x + radius,
y2: y + radius
});
}
} else {
const queryArgs = {
hitTest,
overlapMode,
seenUids: {
box: {},
circle: {}
}
};
this._forEachCell(x1, y1, x2, y2, this._queryCell, result, queryArgs, predicate);
}
return result;
}
query(x1, y1, x2, y2) {
return this._query(x1, y1, x2, y2, false, null);
}
hitTest(x1, y1, x2, y2, overlapMode, predicate) {
return this._query(x1, y1, x2, y2, true, overlapMode, predicate).length > 0;
}
hitTestCircle(x, y, radius, overlapMode, predicate) {
const x1 = x - radius;
const x2 = x + radius;
const y1 = y - radius;
const y2 = y + radius;
if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) return false;
const result = [];
const queryArgs = {
hitTest: true,
overlapMode,
circle: {
x,
y,
radius
},
seenUids: {
box: {},
circle: {}
}
};
this._forEachCell(x1, y1, x2, y2, this._queryCellCircle, result, queryArgs, predicate);
return result.length > 0;
}
_queryCell(x1, y1, x2, y2, cellIndex, result, queryArgs, predicate) {
const { seenUids, hitTest, overlapMode } = queryArgs;
const boxCell = this.boxCells[cellIndex];
const epsilon = 1e-6;
if (boxCell !== null) {
const bboxes = this.bboxes;
for (const boxUid of boxCell) if (!seenUids.box[boxUid]) {
seenUids.box[boxUid] = true;
const offset = boxUid * 4;
const key = this.boxKeys[boxUid];
if (x1 <= bboxes[offset + 2] + epsilon && y1 <= bboxes[offset + 3] + epsilon && x2 >= bboxes[offset + 0] - epsilon && y2 >= bboxes[offset + 1] - epsilon && (!predicate || predicate(key))) {
if (!hitTest || !overlapAllowed(overlapMode, key.overlapMode)) {
result.push({
key,
x1: bboxes[offset],
y1: bboxes[offset + 1],
x2: bboxes[offset + 2],
y2: bboxes[offset + 3]
});
if (hitTest) return true;
}
}
}
}
const circleCell = this.circleCells[cellIndex];
if (circleCell !== null) {
const circles = this.circles;
for (const circleUid of circleCell) if (!seenUids.circle[circleUid]) {
seenUids.circle[circleUid] = true;
const offset = circleUid * 3;
const key = this.circleKeys[circleUid];
if (this._circleAndRectCollide(circles[offset], circles[offset + 1], circles[offset + 2], x1, y1, x2, y2) && (!predicate || predicate(key))) {
if (!hitTest || !overlapAllowed(overlapMode, key.overlapMode)) {
const x = circles[offset];
const y = circles[offset + 1];
const radius = circles[offset + 2];
result.push({
key,
x1: x - radius,
y1: y - radius,
x2: x + radius,
y2: y + radius
});
if (hitTest) return true;
}
}
}
}
return false;
}
_queryCellCircle(x1, y1, x2, y2, cellIndex, result, queryArgs, predicate) {
const { circle, seenUids, overlapMode } = queryArgs;
const boxCell = this.boxCells[cellIndex];
if (boxCell !== null) {
const bboxes = this.bboxes;
for (const boxUid of boxCell) if (!seenUids.box[boxUid]) {
seenUids.box[boxUid] = true;
const offset = boxUid * 4;
const key = this.boxKeys[boxUid];
if (this._circleAndRectCollide(circle.x, circle.y, circle.radius, bboxes[offset + 0], bboxes[offset + 1], bboxes[offset + 2], bboxes[offset + 3]) && (!predicate || predicate(key)) && !overlapAllowed(overlapMode, key.overlapMode)) {
result.push(true);
return true;
}
}
}
const circleCell = this.circleCells[cellIndex];
if (circleCell !== null) {
const circles = this.circles;
for (const circleUid of circleCell) if (!seenUids.circle[circleUid]) {
seenUids.circle[circleUid] = true;
const offset = circleUid * 3;
const key = this.circleKeys[circleUid];
if (this._circlesCollide(circles[offset], circles[offset + 1], circles[offset + 2], circle.x, circle.y, circle.radius) && (!predicate || predicate(key)) && !overlapAllowed(overlapMode, key.overlapMode)) {
result.push(true);
return true;
}
}
}
}
_forEachCell(x1, y1, x2, y2, fn, arg1, arg2, predicate) {
const cx1 = this._convertToXCellCoord(x1);
const cy1 = this._convertToYCellCoord(y1);
const cx2 = this._convertToXCellCoord(x2);
const cy2 = this._convertToYCellCoord(y2);
for (let x = cx1; x <= cx2; x++) for (let y = cy1; y <= cy2; y++) {
const cellIndex = this.xCellCount * y + x;
if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, predicate)) return;
}
}
_convertToXCellCoord(x) {
return Math.max(0, Math.min(this.xCellCount - 1, Math.floor(x * this.xScale)));
}
_convertToYCellCoord(y) {
return Math.max(0, Math.min(this.yCellCount - 1, Math.floor(y * this.yScale)));
}
_circlesCollide(x1, y1, r1, x2, y2, r2) {
const dx = x2 - x1;
const dy = y2 - y1;
const bothRadii = r1 + r2;
return bothRadii * bothRadii > dx * dx + dy * dy;
}
_circleAndRectCollide(circleX, circleY, radius, x1, y1, x2, y2) {
const halfRectWidth = (x2 - x1) / 2;
const distX = Math.abs(circleX - (x1 + halfRectWidth));
if (distX > halfRectWidth + radius) return false;
const halfRectHeight = (y2 - y1) / 2;
const distY = Math.abs(circleY - (y1 + halfRectHeight));
if (distY > halfRectHeight + radius) return false;
if (distX <= halfRectWidth || distY <= halfRectHeight) return true;
const dx = distX - halfRectWidth;
const dy = distY - halfRectHeight;
return dx * dx + dy * dy <= radius * radius;
}
};
//#endregion
//#region src/util/fast_maths.ts
function fastInvertTransformMat4(dst, src) {
const sXYSqInv = 1 / (src[0] * src[0] + src[1] * src[1] + src[2] * src[2]);
const sZSqInv = 1 / (src[8] * src[8] + src[9] * src[9] + src[10] * src[10]);
const s0 = src[0] * sXYSqInv;
const s4 = src[4] * sXYSqInv;
const s8 = src[8] * sZSqInv;
const s1 = src[1] * sXYSqInv;
const s5 = src[5] * sXYSqInv;
const s9 = src[9] * sZSqInv;
const s2 = src[2] * sXYSqInv;
const s6 = src[6] * sXYSqInv;
const s10 = src[10] * sZSqInv;
dst[0] = s0;
dst[1] = s4;
dst[2] = s8;
dst[4] = s1;
dst[5] = s5;
dst[6] = s9;
dst[8] = s2;
dst[9] = s6;
dst[10] = s10;
const t0 = src[12];
const t1 = src[13];
const t2 = src[14];
dst[12] = -s0 * t0 - s1 * t1 - s2 * t2;
dst[13] = -s4 * t0 - s5 * t1 - s6 * t2;
dst[14] = -s8 * t0 - s9 * t1 - s10 * t2;
dst[3] = 0;
dst[7] = 0;
dst[11] = 0;
dst[15] = 1;
return dst;
}
function fastInvertProjMat4(dst, src) {
dst[0] = 1 / src[0];
dst[1] = 0;
dst[2] = 0;
dst[3] = 0;
dst[4] = 0;
dst[5] = 1 / src[5];
dst[6] = 0;
dst[7] = 0;
dst[8] = 0;
dst[9] = 0;
dst[10] = 0;
dst[11] = 1 / src[14];
dst[12] = 0;
dst[13] = 0;
dst[14] = -1;
dst[15] = src[10] / src[14];
return dst;
}
function fastInvertSkewMat4(dst, src) {
const invDetXY = 1 / (src[0] * src[5] - src[1] * src[4]);
dst[0] = src[5] * invDetXY;
dst[1] = -src[1] * invDetXY;
dst[2] = 0;
dst[3] = 0;
dst[4] = -src[4] * invDetXY;
dst[5] = src[0] * invDetXY;
dst[6] = 0;
dst[7] = 0;
dst[8] = 0;
dst[9] = 0;
dst[10] = 1 / src[10];
dst[11] = 0;
dst[12] = 0;
dst[13] = 0;
dst[14] = 0;
dst[15] = 1 / src[15];
return dst;
}
//#endregion
//#region src/symbol/projection.ts
/**
* Pre-allocate objects to avoid online allocation
*/
const tmpMat4 = create$1();
function getPitchedLabelPlaneMatrix(rotateWithMap, transform, pixelsToTileUnits) {
const m = create$1();
if (!rotateWithMap) {
const { vecSouth, vecEast } = getTileSkewVectors(transform);
const skew = create$2();
skew[0] = vecEast[0];
skew[1] = vecEast[1];
skew[2] = vecSouth[0];
skew[3] = vecSouth[1];
invert(skew, skew);
m[0] = skew[0];
m[1] = skew[1];
m[4] = skew[2];
m[5] = skew[3];
}
scale(m, m, [
1 / pixelsToTileUnits,
1 / pixelsToTileUnits,
1
]);
return m;
}
function getGlCoordMatrix(pitchWithMap, rotateWithMap, transform, pixelsToTileUnits) {
if (pitchWithMap) {
const m = create$1();
if (!rotateWithMap) {
const { vecSouth, vecEast } = getTileSkewVectors(transform);
m[0] = vecEast[0];
m[1] = vecEast[1];
m[4] = vecSouth[0];
m[5] = vecSouth[1];
}
scale(m, m, [
pixelsToTileUnits,
pixelsToTileUnits,
1
]);
return m;
} else return transform.pixelsToClipSpaceMatrix;
}
function getTileSkewVectors(transform) {
const cosRoll = Math.cos(transform.rollInRadians);
const sinRoll = Math.sin(transform.rollInRadians);
const cosPitch = Math.cos(transform.pitchInRadians);
const cosBearing = Math.cos(transform.bearingInRadians);
const sinBearing = Math.sin(transform.bearingInRadians);
const vecSouth = create$3();
vecSouth[0] = -cosBearing * cosPitch * sinRoll - sinBearing * cosRoll;
vecSouth[1] = -sinBearing * cosPitch * sinRoll + cosBearing * cosRoll;
const vecSouthLen = length(vecSouth);
if (vecSouthLen < 1e-9) zero(vecSouth);
else scale$1(vecSouth, vecSouth, 1 / vecSouthLen);
const vecEast = create$3();
vecEast[0] = cosBearing * cosPitch * cosRoll - sinBearing * sinRoll;
vecEast[1] = sinBearing * cosPitch * cosRoll + cosBearing * sinRoll;
const vecEastLen = length(vecEast);
if (vecEastLen < 1e-9) zero(vecEast);
else scale$1(vecEast, vecEast, 1 / vecEastLen);
return {
vecEast,
vecSouth
};
}
/**
* Projects a point using a specified matrix, including the perspective divide.
* Uses a fast path if `getElevation` is undefined.
*/
function projectWithMatrix(x, y, matrix, getElevation) {
let pos;
if (getElevation) {
pos = [
x,
y,
getElevation(x, y),
1
];
transformMat4(pos, pos, matrix);
} else {
pos = [
x,
y,
0,
1
];
xyTransformMat4(pos, pos, matrix);
}
const w = pos[3];
return {
point: new Point(pos[0] / w, pos[1] / w),
signedDistanceFromCamera: w,
isOccluded: false
};
}
function getPerspectiveRatio(cameraToCenterDistance, signedDistanceFromCamera) {
return .5 + .5 * (cameraToCenterDistance / signedDistanceFromCamera);
}
function isVisible(p, clippingBuffer) {
return p.x >= -clippingBuffer[0] && p.x <= clippingBuffer[0] && p.y >= -clippingBuffer[1] && p.y <= clippingBuffer[1];
}
function updateLineLabels(bucket, painter, isText, pitchedLabelPlaneMatrix, pitchedLabelPlaneMatrixInverse, pitchWithMap, keepUpright, rotateToLine, unwrappedTileID, viewportWidth, viewportHeight, translation, getElevation) {
const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData;
const partiallyEvaluatedSize = evaluateSizeForZoom(sizeData, painter.transform.zoom);
const clippingBuffer = [256 / painter.width * 2 + 1, 256 / painter.height * 2 + 1];
const dynamicLayoutVertexArray = isText ? bucket.text.dynamicLayoutVertexArray : bucket.icon.dynamicLayoutVertexArray;
dynamicLayoutVertexArray.clear();
const lineVertexArray = bucket.lineVertexArray;
const placedSymbols = isText ? bucket.text.placedSymbolArray : bucket.icon.placedSymbolArray;
const aspectRatio = painter.transform.width / painter.transform.height;
let useVertical = false;
for (let s = 0; s < placedSymbols.length; s++) {
const symbol = placedSymbols.get(s);
if (symbol.hidden || symbol.writingMode === 2 && !useVertical) {
hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);
continue;
}
useVertical = false;
const tileAnchorPoint = new Point(symbol.anchorX, symbol.anchorY);
const projectionContext = {
getElevation,
pitchedLabelPlaneMatrix,
lineVertexArray,
pitchWithMap,
projectionCache: {
projections: {},
offsets: {},
cachedAnchorPoint: void 0,
anyProjectionOccluded: false
},
transform: painter.transform,
tileAnchorPoint,
unwrappedTileID,
width: viewportWidth,
height: viewportHeight,
translation
};
const anchorPos = projectTileCoordinatesToClipSpace(symbol.anchorX, symbol.anchorY, projectionContext);
if (!isVisible(anchorPos.point, clippingBuffer)) {
hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);
continue;
}
const cameraToAnchorDistance = anchorPos.signedDistanceFromCamera;
const perspectiveRatio = getPerspectiveRatio(painter.transform.cameraToCenterDistance, cameraToAnchorDistance);
const fontSize = evaluateSizeForFeature(sizeData, partiallyEvaluatedSize, symbol);
const pitchScaledFontSize = pitchWithMap ? fontSize * painter.transform.getPitchedTextCorrection(symbol.anchorX, symbol.anchorY, unwrappedTileID) / perspectiveRatio : fontSize * perspectiveRatio;
const placeUnflipped = placeGlyphsAlongLine({
projectionContext,
pitchedLabelPlaneMatrixInverse,
symbol,
fontSize: pitchScaledFontSize,
flip: false,
keepUpright,
glyphOffsetArray: bucket.glyphOffsetArray,
dynamicLayoutVertexArray,
aspectRatio,
rotateToLine
});
useVertical = placeUnflipped.useVertical;
if (placeUnflipped.notEnoughRoom || useVertical || placeUnflipped.needsFlipping && placeGlyphsAlongLine({
projectionContext,
pitchedLabelPlaneMatrixInverse,
symbol,
fontSize: pitchScaledFontSize,
flip: true,
keepUpright,
glyphOffsetArray: bucket.glyphOffsetArray,
dynamicLayoutVertexArray,
aspectRatio,
rotateToLine
}).notEnoughRoom) hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);
}
if (isText) bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray);
else bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray);
}
function placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, symbol, rotateToLine, projectionContext) {
const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs;
const lineStartIndex = symbol.lineStartIndex;
const lineEndIndex = symbol.lineStartIndex + symbol.lineLength;
const firstGlyphOffset = glyphOffsetArray.getoffsetX(symbol.glyphStartIndex);
const lastGlyphOffset = glyphOffsetArray.getoffsetX(glyphEndIndex - 1);
const firstPlacedGlyph = placeGlyphAlongLine(fontScale * firstGlyphOffset, lineOffsetX, lineOffsetY, flip, symbol.segment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine);
if (!firstPlacedGlyph) return null;
const lastPlacedGlyph = placeGlyphAlongLine(fontScale * lastGlyphOffset, lineOffsetX, lineOffsetY, flip, symbol.segment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine);
if (!lastPlacedGlyph) return null;
if (projectionContext.projectionCache.anyProjectionOccluded) return null;
return {
first: firstPlacedGlyph,
last: lastPlacedGlyph
};
}
function requiresOrientationChange(writingMode, firstPoint, lastPoint, aspectRatio) {
if (writingMode === 1) {
if (Math.abs(lastPoint.y - firstPoint.y) > Math.abs(lastPoint.x - firstPoint.x) * aspectRatio) return { useVertical: true };
}
if (writingMode === 2 ? firstPoint.y < lastPoint.y : firstPoint.x > lastPoint.x) return { needsFlipping: true };
return null;
}
function placeGlyphsAlongLine(args) {
const { projectionContext, pitchedLabelPlaneMatrixInverse, symbol, fontSize, flip, keepUpright, glyphOffsetArray, dynamicLayoutVertexArray, aspectRatio, rotateToLine } = args;
const fontScale = fontSize / 24;
const lineOffsetX = symbol.lineOffsetX * fontScale;
const lineOffsetY = symbol.lineOffsetY * fontScale;
let placedGlyphs;
if (symbol.numGlyphs > 1) {
const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs;
const lineStartIndex = symbol.lineStartIndex;
const lineEndIndex = symbol.lineStartIndex + symbol.lineLength;
const firstAndLastGlyph = placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, symbol, rotateToLine, projectionContext);
if (!firstAndLastGlyph) return { notEnoughRoom: true };
const firstPoint = projectFromLabelPlaneToClipSpace(firstAndLastGlyph.first.point.x, firstAndLastGlyph.first.point.y, projectionContext, pitchedLabelPlaneMatrixInverse);
const lastPoint = projectFromLabelPlaneToClipSpace(firstAndLastGlyph.last.point.x, firstAndLastGlyph.last.point.y, projectionContext, pitchedLabelPlaneMatrixInverse);
if (keepUpright && !flip) {
const orientationChange = requiresOrientationChange(symbol.writingMode, firstPoint, lastPoint, aspectRatio);
if (orientationChange) return orientationChange;
}
placedGlyphs = [firstAndLastGlyph.first];
for (let glyphIndex = symbol.glyphStartIndex + 1; glyphIndex < glyphEndIndex - 1; glyphIndex++) {
const placedGlyph = placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(glyphIndex), lineOffsetX, lineOffsetY, flip, symbol.segment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine);
if (!placedGlyph) return { notEnoughRoom: true };
placedGlyphs.push(placedGlyph);
}
placedGlyphs.push(firstAndLastGlyph.last);
} else {
if (keepUpright && !flip) {
const a = projectTileCoordinatesToLabelPlane(projectionContext.tileAnchorPoint.x, projectionContext.tileAnchorPoint.y, projectionContext).point;
const tileVertexIndex = symbol.lineStartIndex + symbol.segment + 1;
const tileSegmentEnd = new Point(projectionContext.lineVertexArray.getx(tileVertexIndex), projectionContext.lineVertexArray.gety(tileVertexIndex));
const projectedVertex = projectTileCoordinatesToLabelPlane(tileSegmentEnd.x, tileSegmentEnd.y, projectionContext);
const b = projectedVertex.signedDistanceFromCamera > 0 ? projectedVertex.point : projectTruncatedLineSegmentToLabelPlane(projectionContext.tileAnchorPoint, tileSegmentEnd, a, 1, projectionContext);
const clipSpaceA = projectFromLabelPlaneToClipSpace(a.x, a.y, projectionContext, pitchedLabelPlaneMatrixInverse);
const clipSpaceB = projectFromLabelPlaneToClipSpace(b.x, b.y, projectionContext, pitchedLabelPlaneMatrixInverse);
const orientationChange = requiresOrientationChange(symbol.writingMode, clipSpaceA, clipSpaceB, aspectRatio);
if (orientationChange) return orientationChange;
}
const singleGlyph = placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(symbol.glyphStartIndex), lineOffsetX, lineOffsetY, flip, symbol.segment, symbol.lineStartIndex, symbol.lineStartIndex + symbol.lineLength, projectionContext, rotateToLine);
if (!singleGlyph || projectionContext.projectionCache.anyProjectionOccluded) return { notEnoughRoom: true };
placedGlyphs = [singleGlyph];
}
for (const glyph of placedGlyphs) addDynamicAttributes(dynamicLayoutVertexArray, glyph.point, glyph.angle);
return {};
}
/**
* Takes a line and direction from `previousTilePoint` to `currentTilePoint`, projects it to the correct label plane,
* and returns a projected point along this projected line that is `minimumLength` distance away from `previousProjectedPoint`.
* Projects a "virtual" vertex along a line segment.
* @param previousTilePoint - Line start point, in tile coordinates.
* @param currentTilePoint - Line end point, in tile coordinates.
* @param previousProjectedPoint - Projection of `previousTilePoint` into label plane
* @param minimumLength - Distance in the projected space along the line for the returned point.
* @param projectionContext - Projection context, used to get terrain's `getElevation`, and to project the points to screen pixels.
*/
function projectTruncatedLineSegmentToLabelPlane(previousTilePoint, currentTilePoint, previousProjectedPoint, minimumLength, projectionContext) {
const unitVertexToBeProjected = previousTilePoint.add(previousTilePoint.sub(currentTilePoint)._unit());
const projectedUnitVertex = projectTileCoordinatesToLabelPlane(unitVertexToBeProjected.x, unitVertexToBeProjected.y, projectionContext).point;
const projectedUnitSegment = previousProjectedPoint.sub(projectedUnitVertex);
return previousProjectedPoint.add(projectedUnitSegment._mult(minimumLength / projectedUnitSegment.mag()));
}
/**
* Transform a vertex from tile coordinates to label plane coordinates
* @param index - index of vertex to project
* @param projectionContext - necessary data to project a vertex
* @returns the vertex projected to the label plane
*/
function projectLineVertexToLabelPlane(index, projectionContext, syntheticVertexArgs) {
const cache = projectionContext.projectionCache;
if (cache.projections[index]) return cache.projections[index];
const currentVertex = new Point(projectionContext.lineVertexArray.getx(index), projectionContext.lineVertexArray.gety(index));
const projection = projectTileCoordinatesToLabelPlane(currentVertex.x, currentVertex.y, projectionContext);
if (projection.signedDistanceFromCamera > 0) {
cache.projections[index] = projection.point;
cache.anyProjectionOccluded ||= projection.isOccluded;
return projection.point;
}
const previousLineVertexIndex = index - syntheticVertexArgs.direction;
const previousTilePoint = syntheticVertexArgs.distanceFromAnchor === 0 ? projectionContext.tileAnchorPoint : new Point(projectionContext.lineVertexArray.getx(previousLineVertexIndex), projectionContext.lineVertexArray.gety(previousLineVertexIndex));
const minimumLength = syntheticVertexArgs.absOffsetX - syntheticVertexArgs.distanceFromAnchor + 1;
return projectTruncatedLineSegmentToLabelPlane(previousTilePoint, currentVertex, syntheticVertexArgs.previousVertex, minimumLength, projectionContext);
}
/**
* Projects the given point in tile coordinates to the correct label plane.
* If pitchWithMap is true, the (rotated) map plane in pixels is used,
* otherwise screen pixels are used.
*/
function projectTileCoordinatesToLabelPlane(x, y, projectionContext) {
const translatedX = x + projectionContext.translation[0];
const translatedY = y + projectionContext.translation[1];
let projection;
if (projectionContext.pitchWithMap) {
projection = projectWithMatrix(translatedX, translatedY, projectionContext.pitchedLabelPlaneMatrix, projectionContext.getElevation);
projection.isOccluded = false;
} else {
projection = projectionContext.transform.projectTileCoordinates(translatedX, translatedY, projectionContext.unwrappedTileID, projectionContext.getElevation);
projection.point.x = (projection.point.x * .5 + .5) * projectionContext.width;
projection.point.y = (-projection.point.y * .5 + .5) * projectionContext.height;
}
return projection;
}
function projectFromLabelPlaneToClipSpace(x, y, projectionContext, pitchedLabelPlaneMatrixInverse) {
if (projectionContext.pitchWithMap) {
const pos = [
x,
y,
0,
1
];
transformMat4(pos, pos, pitchedLabelPlaneMatrixInverse);
return projectionContext.transform.projectTileCoordinates(pos[0] / pos[3], pos[1] / pos[3], projectionContext.unwrappedTileID, projectionContext.getElevation).point;
} else return {
x: x / projectionContext.width * 2 - 1,
y: 1 - y / projectionContext.height * 2
};
}
/**
* Projects the given point in tile coordinates to the GL clip space (-1..1).
*/
function projectTileCoordinatesToClipSpace(x, y, projectionContext) {
return projectionContext.transform.projectTileCoordinates(x, y, projectionContext.unwrappedTileID, projectionContext.getElevation);
}
/**
* Calculate the normal vector for a line segment
* @param segmentVector - will be mutated as a tiny optimization
* @param offset - magnitude of resulting vector
* @param direction - direction of line traversal
* @returns a normal vector from the segment, with magnitude equal to offset amount
*/
function transformToOffsetNormal(segmentVector, offset, direction) {
return segmentVector._unit()._perp()._mult(offset * direction);
}
/**
* Construct offset line segments for the current segment and the next segment, then extend/shrink
* the segments until they intersect. If the segments are parallel, then they will touch with no modification.
*
* @param index - Index of the current vertex
* @param prevToCurrentOffsetNormal - Normal vector of the line segment from the previous vertex to the current vertex
* @param currentVertex - Current (non-offset) vertex projected to the label plane
* @param lineStartIndex - Beginning index for the line this label is on
* @param lineEndIndex - End index for the line this label is on
* @param offsetPreviousVertex - The previous vertex projected to the label plane, and then offset along the previous segments normal
* @param lineOffsetY - Magnitude of the offset
* @param projectionContext - Necessary data for tile-to-label-plane projection
* @returns The point at which the current and next line segments intersect, once offset and extended/shrunk to their meeting point
*/
function findOffsetIntersectionPoint(index, prevToCurrentOffsetNormal, currentVertex, lineStartIndex, lineEndIndex, offsetPreviousVertex, lineOffsetY, projectionContext, syntheticVertexArgs) {
if (projectionContext.projectionCache.offsets[index]) return projectionContext.projectionCache.offsets[index];
const offsetCurrentVertex = currentVertex.add(prevToCurrentOffsetNormal);
if (index + syntheticVertexArgs.direction < lineStartIndex || index + syntheticVertexArgs.direction >= lineEndIndex) {
projectionContext.projectionCache.offsets[index] = offsetCurrentVertex;
return offsetCurrentVertex;
}
const nextVertex = projectLineVertexToLabelPlane(index + syntheticVertexArgs.direction, projectionContext, syntheticVertexArgs);
const currentToNextOffsetNormal = transformToOffsetNormal(nextVertex.sub(currentVertex), lineOffsetY, syntheticVertexArgs.direction);
const offsetNextSegmentBegin = currentVertex.add(currentToNextOffsetNormal);
const offsetNextSegmentEnd = nextVertex.add(currentToNextOffsetNormal);
projectionContext.projectionCache.offsets[index] = findLineIntersection(offsetPreviousVertex, offsetCurrentVertex, offsetNextSegmentBegin, offsetNextSegmentEnd) || offsetCurrentVertex;
return projectionContext.projectionCache.offsets[index];
}
function placeGlyphAlongLine(offsetX, lineOffsetX, lineOffsetY, flip, anchorSegment, lineStartIndex, lineEndIndex, projectionContext, rotateToLine) {
const combinedOffsetX = flip ? offsetX - lineOffsetX : offsetX + lineOffsetX;
let direction = combinedOffsetX > 0 ? 1 : -1;
let angle = 0;
if (flip) {
direction *= -1;
angle = Math.PI;
}
if (direction < 0) angle += Math.PI;
let currentIndex = direction > 0 ? lineStartIndex + anchorSegment : lineStartIndex + anchorSegment + 1;
let anchorPoint;
if (projectionContext.projectionCache.cachedAnchorPoint) anchorPoint = projectionContext.projectionCache.cachedAnchorPoint;
else {
anchorPoint = projectTileCoordinatesToLabelPlane(projectionContext.tileAnchorPoint.x, projectionContext.tileAnchorPoint.y, projectionContext).point;
projectionContext.projectionCache.cachedAnchorPoint = anchorPoint;
}
let currentVertex = anchorPoint;
let previousVertex = anchorPoint;
let offsetIntersectionPoint;
let offsetPreviousVertex;
let distanceFromAnchor = 0;
let currentSegmentDistance = 0;
const absOffsetX = Math.abs(combinedOffsetX);
const pathVertices = [];
let currentLineSegment;
while (distanceFromAnchor + currentSegmentDistance <= absOffsetX) {
currentIndex += direction;
if (currentIndex < lineStartIndex || currentIndex >= lineEndIndex) return null;
distanceFromAnchor += currentSegmentDistance;
previousVertex = currentVertex;
offsetPreviousVertex = offsetIntersectionPoint;
const syntheticVertexArgs = {
absOffsetX,
direction,
distanceFromAnchor,
previousVertex
};
currentVertex = projectLineVertexToLabelPlane(currentIndex, projectionContext, syntheticVertexArgs);
if (lineOffsetY === 0) {
pathVertices.push(previousVertex);
currentLineSegment = currentVertex.sub(previousVertex);
} else {
let prevToCurrentOffsetNormal;
const prevToCurrent = currentVertex.sub(previousVertex);
if (prevToCurrent.mag() === 0) prevToCurrentOffsetNormal = transformToOffsetNormal(projectLineVertexToLabelPlane(currentIndex + direction, projectionContext, syntheticVertexArgs).sub(currentVertex), lineOffsetY, direction);
else prevToCurrentOffsetNormal = transformToOffsetNormal(prevToCurrent, lineOffsetY, direction);
offsetPreviousVertex ||= previousVertex.add(prevToCurrentOffsetNormal);
offsetIntersectionPoint = findOffsetIntersectionPoint(currentIndex, prevToCurrentOffsetNormal, currentVertex, lineStartIndex, lineEndIndex, offsetPreviousVertex, lineOffsetY, projectionContext, syntheticVertexArgs);
pathVertices.push(offsetPreviousVertex);
currentLineSegment = offsetIntersectionPoint.sub(offsetPreviousVertex);
}
currentSegmentDistance = currentLineSegment.mag();
}
const segmentInterpolationT = (absOffsetX - distanceFromAnchor) / currentSegmentDistance;
const p = currentLineSegment._mult(segmentInterpolationT)._add(offsetPreviousVertex || previousVertex);
const segmentAngle = angle + Math.atan2(currentVertex.y - previousVertex.y, currentVertex.x - previousVertex.x);
pathVertices.push(p);
return {
point: p,
angle: rotateToLine ? segmentAngle : 0,
path: pathVertices
};
}
const hiddenGlyphAttributes = new Float32Array([
-Infinity,
-Infinity,
0,
-Infinity,
-Infinity,
0,
-Infinity,
-Infinity,
0,
-Infinity,
-Infinity,
0
]);
function hideGlyphs(num, dynamicLayoutVertexArray) {
for (let i = 0; i < num; i++) {
const offset = dynamicLayoutVertexArray.length;
dynamicLayoutVertexArray.resize(offset + 4);
dynamicLayoutVertexArray.float32.set(hiddenGlyphAttributes, offset * 3);
}
}
function xyTransformMat4(out, a, m) {
const x = a[0], y = a[1];
out[0] = m[0] * x + m[4] * y + m[12];
out[1] = m[1] * x + m[5] * y + m[13];
out[3] = m[3] * x + m[7] * y + m[15];
return out;
}
/**
* Takes a path of points that was previously projected using the `pitchedLabelPlaneMatrix`
* and projects it using the map projection's (mercator/globe...) `projectTileCoordinates` function.
* Returns a new array of the projected points.
* Does not modify the input array.
*/
function projectPathSpecialProjection(projectedPath, projectionContext) {
const inverseLabelPlaneMatrix = tmpMat4;
fastInvertSkewMat4(inverseLabelPlaneMatrix, projectionContext.pitchedLabelPlaneMatrix);
return projectedPath.map((p) => {
const backProjected = projectWithMatrix(p.x, p.y, inverseLabelPlaneMatrix, projectionContext.getElevation);
const projected = projectionContext.transform.projectTileCoordinates(backProjected.point.x, backProjected.point.y, projectionContext.unwrappedTileID, projectionContext.getElevation);
projected.point.x = (projected.point.x * .5 + .5) * projectionContext.width;
projected.point.y = (-projected.point.y * .5 + .5) * projectionContext.height;
return projected;
});
}
/**
* Takes a path of points projected to screenspace, finds the longest continuous unoccluded segment of that path
* and returns it.
* Does not modify the input array.
*/
function pathSlicedToLongestUnoccluded(path) {
let longestUnoccludedStart = 0;
let longestUnoccludedLength = 0;
let currentUnoccludedStart = 0;
let currentUnoccludedLength = 0;
for (let i = 0; i < path.length; i++) if (path[i].isOccluded) {
currentUnoccludedStart = i + 1;
currentUnoccludedLength = 0;
} else {
currentUnoccludedLength++;
if (currentUnoccludedLength > longestUnoccludedLength) {
longestUnoccludedLength = currentUnoccludedLength;
longestUnoccludedStart = currentUnoccludedStart;
}
}
return path.slice(longestUnoccludedStart, longestUnoccludedStart + longestUnoccludedLength);
}
/**
* @internal
* A collision index used to prevent symbols from overlapping. It keep tracks of
* where previous symbols have been placed and is used to check if a new
* symbol overlaps with any previously added symbols.
*
* There are two steps to insertion: first placeCollisionBox/Circles checks if
* there's room for a symbol, then insertCollisionBox/Circles actually puts the
* symbol in the index. The two step process allows paired symbols to be inserted
* together even if they overlap.
*/
var CollisionIndex = class {
constructor(transform, grid = new GridIndex(transform.width + 200, transform.height + 200, 25), ignoredGrid = new GridIndex(transform.width + 200, transform.height + 200, 25)) {
this.transform = transform;
this.grid = grid;
this.ignoredGrid = ignoredGrid;
this.pitchFactor = Math.cos(transform.pitch * Math.PI / 180) * transform.cameraToCenterDistance;
this.screenRightBoundary = transform.width + 100;
this.screenBottomBoundary = transform.height + 100;
this.gridRightBoundary = transform.width + 200;
this.gridBottomBoundary = transform.height + 200;
this.perspectiveRatioCutoff = .6;
}
placeCollisionBox(collisionBox, overlapMode, textPixelRatio, tileID, unwrappedTileID, pitchWithMap, rotateWithMap, translation, collisionGroupPredicate, getElevation, shift, simpleProjectionMatrix) {
const x = collisionBox.anchorPointX + translation[0];
const y = collisionBox.anchorPointY + translation[1];
const projectedPoint = this.projectAndGetPerspectiveRatio(x, y, unwrappedTileID, getElevation, simpleProjectionMatrix);
const tileToViewport = textPixelRatio * projectedPoint.perspectiveRatio;
let projectedBox;
if (!pitchWithMap && !rotateWithMap) {
const pointX = projectedPoint.x + (shift ? shift.x * tileToViewport : 0);
const pointY = projectedPoint.y + (shift ? shift.y * tileToViewport : 0);
projectedBox = {
allPointsOccluded: false,
box: [
pointX + collisionBox.x1 * tileToViewport,
pointY + collisionBox.y1 * tileToViewport,
pointX + collisionBox.x2 * tileToViewport,
pointY + collisionBox.y2 * tileToViewport
]
};
} else projectedBox = this._projectCollisionBox(collisionBox, tileToViewport, tileID, unwrappedTileID, pitchWithMap, rotateWithMap, translation, projectedPoint, getElevation, shift, simpleProjectionMatrix);
const [tlX, tlY, brX, brY] = projectedBox.box;
const occluded = pitchWithMap ? projectedBox.allPointsOccluded : projectedPoint.isOccluded;
let unplaceable = occluded;
unplaceable ||= projectedPoint.perspectiveRatio < this.perspectiveRatioCutoff;
unplaceable ||= !this.isInsideGrid(tlX, tlY, brX, brY);
if (unplaceable || overlapMode !== "always" && this.grid.hitTest(tlX, tlY, brX, brY, overlapMode, collisionGroupPredicate)) return {
box: [
tlX,
tlY,
brX,
brY
],
placeable: false,
offscreen: false,
occluded
};
return {
box: [
tlX,
tlY,
brX,
brY
],
placeable: true,
offscreen: this.isOffscreen(tlX, tlY, brX, brY),
occluded
};
}
placeCollisionCircles(overlapMode, symbol, lineVertexArray, glyphOffsetArray, fontSize, unwrappedTileID, pitchedLabelPlaneMatrix, showCollisionCircles, pitchWithMap, collisionGroupPredicate, circlePixelDiameter, textPixelPadding, translation, getElevation) {
const placedCollisionCircles = [];
const tileUnitAnchorPoint = new Point(symbol.anchorX, symbol.anchorY);
const perspectiveRatio = this.getPerspectiveRatio(tileUnitAnchorPoint.x, tileUnitAnchorPoint.y, unwrappedTileID, getElevation);
const labelPlaneFontScale = (pitchWithMap ? fontSize * this.transform.getPitchedTextCorrection(symbol.anchorX, symbol.anchorY, unwrappedTileID) / perspectiveRatio : fontSize * perspectiveRatio) / 24;
const projectionCache = {
projections: {},
offsets: {},
cachedAnchorPoint: void 0,
anyProjectionOccluded: false
};
const lineOffsetX = symbol.lineOffsetX * labelPlaneFontScale;
const lineOffsetY = symbol.lineOffsetY * labelPlaneFontScale;
const projectionContext = {
getElevation,
pitchedLabelPlaneMatrix,
lineVertexArray,
pitchWithMap,
projectionCache,
transform: this.transform,
tileAnchorPoint: tileUnitAnchorPoint,
unwrappedTileID,
width: this.transform.width,
height: this.transform.height,
translation
};
const firstAndLastGlyph = placeFirstAndLastGlyph(labelPlaneFontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, false, symbol, false, projectionContext);
let collisionDetected = false;
let inGrid = false;
let entirelyOffscreen = true;
if (firstAndLastGlyph) {
const radius = circlePixelDiameter * .5 * perspectiveRatio + textPixelPadding;
const screenPlaneMin = new Point(-100, -100);
const screenPlaneMax = new Point(this.screenRightBoundary, this.screenBottomBoundary);
const interpolator = new PathInterpolator();
const first = firstAndLastGlyph.first;
const last = firstAndLastGlyph.last;
let projectedPath = [];
for (let i = first.path.length - 1; i >= 1; i--) projectedPath.push(first.path[i]);
for (let i = 1; i < last.path.length; i++) projectedPath.push(last.path[i]);
const circleDist = radius * 2.5;
if (pitchWithMap) {
const screenSpacePath = this.projectPathToScreenSpace(projectedPath, projectionContext);
if (screenSpacePath.some((point) => point.signedDistanceFromCamera <= 0)) projectedPath = [];
else projectedPath = screenSpacePath.map((p) => p.point);
}
let segments = [];
if (projectedPath.length > 0) {
const minPoint = projectedPath[0].clone();
const maxPoint = projectedPath[0].clone();
for (let i = 1; i < projectedPath.length; i++) {
minPoint.x = Math.min(minPoint.x, projectedPath[i].x);
minPoint.y = Math.min(minPoint.y, projectedPath[i].y);
maxPoint.x = Math.max(maxPoint.x, projectedPath[i].x);
maxPoint.y = Math.max(maxPoint.y, projectedPath[i].y);
}
if (minPoint.x >= screenPlaneMin.x && maxPoint.x <= screenPlaneMax.x && minPoint.y >= screenPlaneMin.y && maxPoint.y <= screenPlaneMax.y) segments = [projectedPath];
else if (maxPoint.x < screenPlaneMin.x || minPoint.x > screenPlaneMax.x || maxPoint.y < screenPlaneMin.y || minPoint.y > screenPlaneMax.y) segments = [];
else segments = clipLine([projectedPath], screenPlaneMin.x, screenPlaneMin.y, screenPlaneMax.x, screenPlaneMax.y);
}
for (const seg of segments) {
interpolator.reset(seg, radius * .25);
let numCircles = 0;
if (interpolator.length <= .5 * radius) numCircles = 1;
else numCircles = Math.ceil(interpolator.paddedLength / circleDist) + 1;
for (let i = 0; i < numCircles; i++) {
const t = i / Math.max(numCircles - 1, 1);
const circlePosition = interpolator.lerp(t);
const centerX = circlePosition.x + 100;
const centerY = circlePosition.y + 100;
placedCollisionCircles.push(centerX, centerY, radius, 0);
const x1 = centerX - radius;
const y1 = centerY - radius;
const x2 = centerX + radius;
const y2 = centerY + radius;
entirelyOffscreen &&= this.isOffscreen(x1, y1, x2, y2);
inGrid ||= this.isInsideGrid(x1, y1, x2, y2);
if (overlapMode !== "always" && this.grid.hitTestCircle(centerX, centerY, radius, overlapMode, collisionGroupPredicate)) {
collisionDetected = true;
if (!showCollisionCircles) return {
circles: [],
offscreen: false,
collisionDetected
};
}
}
}
}
return {
circles: !showCollisionCircles && collisionDetected || !inGrid || perspectiveRatio < this.perspectiveRatioCutoff ? [] : placedCollisionCircles,
offscreen: entirelyOffscreen,
collisionDetected
};
}
projectPathToScreenSpace(projectedPath, projectionContext) {
return pathSlicedToLongestUnoccluded(projectPathSpecialProjection(projectedPath, projectionContext));
}
/**
* Because the geometries in the CollisionIndex are an approximation of the shape of
* symbols on the map, we use the CollisionIndex to look up the symbol part of
* `queryRenderedFeatures`.
*/
queryRenderedSymbols(viewportQueryGeometry) {
if (viewportQueryGeometry.length === 0 || this.grid.keysLength() === 0 && this.ignoredGrid.keysLength() === 0) return {};
const query = [];
const bounds = new Bounds();
for (const point of viewportQueryGeometry) {
const gridPoint = new Point(point.x + 100, point.y + 100);
bounds.extend(gridPoint);
query.push(gridPoint);
}
const { minX, minY, maxX, maxY } = bounds;
const features = this.grid.query(minX, minY, maxX, maxY).concat(this.ignoredGrid.query(minX, minY, maxX, maxY));
const seenFeatures = {};
const result = {};
for (const feature of features) {
const featureKey = feature.key;
if (seenFeatures[featureKey.bucketInstanceId] === void 0) seenFeatures[featureKey.bucketInstanceId] = {};
if (seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex]) continue;
const bbox = [
new Point(feature.x1, feature.y1),
new Point(feature.x2, feature.y1),
new Point(feature.x2, feature.y2),
new Point(feature.x1, feature.y2)
];
if (!polygonIntersectsPolygon(query, bbox)) continue;
seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex] = true;
if (result[featureKey.bucketInstanceId] === void 0) result[featureKey.bucketInstanceId] = [];
result[featureKey.bucketInstanceId].push(featureKey.featureIndex);
}
return result;
}
insertCollisionBox(collisionBox, overlapMode, ignorePlacement, bucketInstanceId, featureIndex, collisionGroupID) {
const grid = ignorePlacement ? this.ignoredGrid : this.grid;
const key = {
bucketInstanceId,
featureIndex,
collisionGroupID,
overlapMode
};
grid.insert(key, collisionBox[0], collisionBox[1], collisionBox[2], collisionBox[3]);
}
insertCollisionCircles(collisionCircles, overlapMode, ignorePlacement, bucketInstanceId, featureIndex, collisionGroupID) {
const grid = ignorePlacement ? this.ignoredGrid : this.grid;
const key = {
bucketInstanceId,
featureIndex,
collisionGroupID,
overlapMode
};
for (let k = 0; k < collisionCircles.length; k += 4) grid.insertCircle(key, collisionCircles[k], collisionCircles[k + 1], collisionCircles[k + 2]);
}
projectAndGetPerspectiveRatio(x, y, unwrappedTileID, getElevation, simpleProjectionMatrix) {
if (simpleProjectionMatrix) {
let pos;
if (getElevation) {
pos = [
x,
y,
getElevation(x, y),
1
];
transformMat4(pos, pos, simpleProjectionMatrix);
} else {
pos = [
x,
y,
0,
1
];
xyTransformMat4(pos, pos, simpleProjectionMatrix);
}
const w = pos[3];
return {
x: (pos[0] / w + 1) / 2 * this.transform.width + 100,
y: (-pos[1] / w + 1) / 2 * this.transform.height + 100,
perspectiveRatio: .5 + .5 * (this.transform.cameraToCenterDistance / w),
isOccluded: false,
signedDistanceFromCamera: w
};
} else {
const projected = this.transform.projectTileCoordinates(x, y, unwrappedTileID, getElevation);
return {
x: (projected.point.x + 1) / 2 * this.transform.width + 100,
y: (-projected.point.y + 1) / 2 * this.transform.height + 100,
perspectiveRatio: .5 + .5 * (this.transform.cameraToCenterDistance / projected.signedDistanceFromCamera),
isOccluded: projected.isOccluded,
signedDistanceFromCamera: projected.signedDistanceFromCamera
};
}
}
getPerspectiveRatio(x, y, unwrappedTileID, getElevation) {
const projected = this.transform.projectTileCoordinates(x, y, unwrappedTileID, getElevation);
return .5 + .5 * (this.transform.cameraToCenterDistance / projected.signedDistanceFromCamera);
}
isOffscreen(x1, y1, x2, y2) {
return x2 < 100 || x1 >= this.screenRightBoundary || y2 < 100 || y1 > this.screenBottomBoundary;
}
isInsideGrid(x1, y1, x2, y2) {
return x2 >= 0 && x1 < this.gridRightBoundary && y2 >= 0 && y1 < this.gridBottomBoundary;
}
getViewportMatrix() {
const m = identity([]);
translate(m, m, [
-100,
-100,
0
]);
return m;
}
/**
* Applies all layout+paint properties of the given box in order to find as good approximation of its screen-space bounding box as possible.
*/
_projectCollisionBox(collisionBox, tileToViewport, tileID, unwrappedTileID, pitchWithMap, rotateWithMap, translation, projectedPoint, getElevation, shift, simpleProjectionMatrix) {
let vecEastX = 1;
let vecEastY = 0;
let vecSouthX = 0;
let vecSouthY = 1;
const translatedAnchorX = collisionBox.anchorPointX + translation[0];
const translatedAnchorY = collisionBox.anchorPointY + translation[1];
if (rotateWithMap && !pitchWithMap) {
const projectedEast = this.projectAndGetPerspectiveRatio(translatedAnchorX + 1, translatedAnchorY, unwrappedTileID, getElevation, simpleProjectionMatrix);
const toEastX = projectedEast.x - projectedPoint.x;
const toEastY = projectedEast.y - projectedPoint.y;
const angle = Math.atan(toEastY / toEastX) + (toEastX < 0 ? Math.PI : 0);
const sin = Math.sin(angle);
const cos = Math.cos(angle);
vecEastX = cos;
vecEastY = sin;
vecSouthX = -sin;
vecSouthY = cos;
} else if (!rotateWithMap && pitchWithMap) {
const skew = getTileSkewVectors(this.transform);
vecEastX = skew.vecEast[0];
vecEastY = skew.vecEast[1];
vecSouthX = skew.vecSouth[0];
vecSouthY = skew.vecSouth[1];
}
let basePointX = projectedPoint.x;
let basePointY = projectedPoint.y;
let distanceMultiplier = tileToViewport;
if (pitchWithMap) {
basePointX = translatedAnchorX;
basePointY = translatedAnchorY;
const zoomFraction = this.transform.zoom - tileID.overscaledZ;
distanceMultiplier = Math.pow(2, -zoomFraction);
distanceMultiplier *= this.transform.getPitchedTextCorrection(translatedAnchorX, translatedAnchorY, unwrappedTileID);
if (!shift) {
const distanceRatio = projectedPoint.signedDistanceFromCamera / this.transform.cameraToCenterDistance;
const perspectiveRatio = clamp(.5 + .5 * distanceRatio, 0, 4);
distanceMultiplier *= perspectiveRatio;
}
}
if (shift) {
basePointX += vecEastX * shift.x * distanceMultiplier + vecSouthX * shift.y * distanceMultiplier;
basePointY += vecEastY * shift.x * distanceMultiplier + vecSouthY * shift.y * distanceMultiplier;
}
const offsetXmin = collisionBox.x1 * distanceMultiplier;
const offsetXmax = collisionBox.x2 * distanceMultiplier;
const offsetXhalf = (offsetXmin + offsetXmax) / 2;
const offsetYmin = collisionBox.y1 * distanceMultiplier;
const offsetYmax = collisionBox.y2 * distanceMultiplier;
const offsetYhalf = (offsetYmin + offsetYmax) / 2;
const offsetsArray = [
{
offsetX: offsetXmin,
offsetY: offsetYmin
},
{
offsetX: offsetXhalf,
offsetY: offsetYmin
},
{
offsetX: offsetXmax,
offsetY: offsetYmin
},
{
offsetX: offsetXmax,
offsetY: offsetYhalf
},
{
offsetX: offsetXmax,
offsetY: offsetYmax
},
{
offsetX: offsetXhalf,
offsetY: offsetYmax
},
{
offsetX: offsetXmin,
offsetY: offsetYmax
},
{
offsetX: offsetXmin,
offsetY: offsetYhalf
}
];
let points = [];
for (const { offsetX, offsetY } of offsetsArray) points.push(new Point(basePointX + vecEastX * offsetX + vecSouthX * offsetY, basePointY + vecEastY * offsetX + vecSouthY * offsetY));
let anyPointVisible = false;
if (pitchWithMap) {
const projected = points.map((p) => this.projectAndGetPerspectiveRatio(p.x, p.y, unwrappedTileID, getElevation, simpleProjectionMatrix));
anyPointVisible = projected.some((p) => !p.isOccluded);
points = projected.map((p) => new Point(p.x, p.y));
} else anyPointVisible = true;
return {
box: getAABB(points),
allPointsOccluded: !anyPointVisible
};
}
};
//#endregion
//#region src/symbol/placement.ts
var OpacityState = class {
constructor(prevState, increment, placed, skipFade) {
if (prevState) this.opacity = Math.max(0, Math.min(1, prevState.opacity + (prevState.placed ? increment : -increment)));
else this.opacity = skipFade && placed ? 1 : 0;
this.placed = placed;
}
isHidden() {
return this.opacity === 0 && !this.placed;
}
};
var JointOpacityState = class {
constructor(prevState, increment, placedText, placedIcon, skipFade) {
this.text = new OpacityState(prevState ? prevState.text : null, increment, placedText, skipFade);
this.icon = new OpacityState(prevState ? prevState.icon : null, increment, placedIcon, skipFade);
}
isHidden() {
return this.text.isHidden() && this.icon.isHidden();
}
};
var JointPlacement = class {
constructor(text, icon, skipFade) {
this.text = text;
this.icon = icon;
this.skipFade = skipFade;
}
};
var RetainedQueryData = class {
constructor(bucketInstanceId, featureIndex, sourceLayerIndex, bucketIndex, tileID) {
this.bucketInstanceId = bucketInstanceId;
this.featureIndex = featureIndex;
this.sourceLayerIndex = sourceLayerIndex;
this.bucketIndex = bucketIndex;
this.tileID = tileID;
}
};
var CollisionGroups = class {
constructor(crossSourceCollisions) {
this.crossSourceCollisions = crossSourceCollisions;
this.maxGroupID = 0;
this.collisionGroups = {};
}
get(sourceID) {
if (!this.crossSourceCollisions) {
if (!this.collisionGroups[sourceID]) {
const nextGroupID = ++this.maxGroupID;
this.collisionGroups[sourceID] = {
ID: nextGroupID,
predicate: (key) => {
return key.collisionGroupID === nextGroupID;
}
};
}
return this.collisionGroups[sourceID];
} else return {
ID: 0,
predicate: null
};
}
};
function calculateVariableLayoutShift(anchor, width, height, textOffset, textBoxScale) {
const { horizontalAlign, verticalAlign } = getAnchorAlignment(anchor);
const shiftX = -(horizontalAlign - .5) * width;
const shiftY = -(verticalAlign - .5) * height;
return new Point(shiftX + textOffset[0] * textBoxScale, shiftY + textOffset[1] * textBoxScale);
}
var Placement = class {
constructor(transform, terrain, fadeDuration, crossSourceCollisions, prevPlacement) {
this.transform = transform.clone();
this.terrain = terrain;
this.collisionIndex = new CollisionIndex(this.transform);
this.placements = {};
this.opacities = {};
this.variableOffsets = {};
this.stale = false;
this.commitTime = 0;
this.fadeDuration = fadeDuration;
this.retainedQueryData = {};
this.collisionGroups = new CollisionGroups(crossSourceCollisions);
this.collisionCircleArrays = {};
this.collisionBoxArrays = /* @__PURE__ */ new Map();
this.prevPlacement = prevPlacement;
if (prevPlacement) prevPlacement.prevPlacement = void 0;
this.placedOrientations = {};
}
_getTerrainElevationFunc(tileID) {
const terrain = this.terrain;
if (!terrain) return null;
return (x, y) => terrain.getElevation(tileID, x, y);
}
getBucketParts(results, styleLayer, tile, sortAcrossTiles) {
const symbolBucket = tile.getBucket(styleLayer);
const bucketFeatureIndex = tile.latestFeatureIndex;
if (!symbolBucket || !bucketFeatureIndex || styleLayer.id !== symbolBucket.layerIds[0]) return;
const collisionBoxArray = tile.collisionBoxArray;
const layout = symbolBucket.layers[0].layout;
const paint = symbolBucket.layers[0].paint;
const scale = Math.pow(2, this.transform.zoom - tile.tileID.overscaledZ);
const textPixelRatio = tile.tileSize / EXTENT;
const unwrappedTileID = tile.tileID.toUnwrapped();
const rotateWithMap = layout.get("text-rotation-alignment") === "map";
const pixelsToTiles = pixelsToTileUnits(tile, 1, this.transform.zoom);
const translationText = translatePosition(this.collisionIndex.transform, tile, paint.get("text-translate"), paint.get("text-translate-anchor"));
const translationIcon = translatePosition(this.collisionIndex.transform, tile, paint.get("icon-translate"), paint.get("icon-translate-anchor"));
const pitchedLabelPlaneMatrix = getPitchedLabelPlaneMatrix(rotateWithMap, this.transform, pixelsToTiles);
this.retainedQueryData[symbolBucket.bucketInstanceId] = new RetainedQueryData(symbolBucket.bucketInstanceId, bucketFeatureIndex, symbolBucket.sourceLayerIndex, symbolBucket.index, tile.tileID);
const parameters = {
bucket: symbolBucket,
layout,
translationText,
translationIcon,
unwrappedTileID,
pitchedLabelPlaneMatrix,
scale,
textPixelRatio,
holdingForFade: tile.holdingForSymbolFade(),
collisionBoxArray,
partiallyEvaluatedTextSize: evaluateSizeForZoom(symbolBucket.textSizeData, this.transform.zoom),
collisionGroup: this.collisionGroups.get(symbolBucket.sourceID)
};
if (sortAcrossTiles) for (const range of symbolBucket.sortKeyRanges) {
const { sortKey, symbolInstanceStart, symbolInstanceEnd } = range;
results.push({
sortKey,
symbolInstanceStart,
symbolInstanceEnd,
parameters
});
}
else results.push({
symbolInstanceStart: 0,
symbolInstanceEnd: symbolBucket.symbolInstances.length,
parameters
});
}
attemptAnchorPlacement(textAnchorOffset, textBox, width, height, textBoxScale, rotateWithMap, pitchWithMap, textPixelRatio, tileID, unwrappedTileID, collisionGroup, textOverlapMode, symbolInstance, bucket, orientation, translationText, translationIcon, iconBox, getElevation, simpleProjectionMatrix) {
const anchor = TextAnchorEnum[textAnchorOffset.textAnchor];
const textOffset = [textAnchorOffset.textOffset0, textAnchorOffset.textOffset1];
const shift = calculateVariableLayoutShift(anchor, width, height, textOffset, textBoxScale);
const placedGlyphBoxes = this.collisionIndex.placeCollisionBox(textBox, textOverlapMode, textPixelRatio, tileID, unwrappedTileID, pitchWithMap, rotateWithMap, translationText, collisionGroup.predicate, getElevation, shift, simpleProjectionMatrix);
if (iconBox) {
if (!this.collisionIndex.placeCollisionBox(iconBox, textOverlapMode, textPixelRatio, tileID, unwrappedTileID, pitchWithMap, rotateWithMap, translationIcon, collisionGroup.predicate, getElevation, shift, simpleProjectionMatrix).placeable) return;
}
if (placedGlyphBoxes.placeable) {
let prevAnchor;
if (this.prevPlacement?.variableOffsets[symbolInstance.crossTileID] && this.prevPlacement?.placements[symbolInstance.crossTileID]?.text) prevAnchor = this.prevPlacement.variableOffsets[symbolInstance.crossTileID].anchor;
if (symbolInstance.crossTileID === 0) throw new Error("symbolInstance.crossTileID can't be 0");
this.variableOffsets[symbolInstance.crossTileID] = {
textOffset,
width,
height,
anchor,
textBoxScale,
prevAnchor
};
this.markUsedJustification(bucket, anchor, symbolInstance, orientation);
if (bucket.allowVerticalPlacement) {
this.markUsedOrientation(bucket, orientation, symbolInstance);
this.placedOrientations[symbolInstance.crossTileID] = orientation;
}
return {
shift,
placedGlyphBoxes
};
}
}
placeLayerBucketPart(bucketPart, seenCrossTileIDs, showCollisionBoxes) {
const { bucket, layout, translationText, translationIcon, unwrappedTileID, pitchedLabelPlaneMatrix, textPixelRatio, holdingForFade, collisionBoxArray, partiallyEvaluatedTextSize, collisionGroup } = bucketPart.parameters;
const textOptional = layout.get("text-optional");
const iconOptional = layout.get("icon-optional");
const textOverlapMode = getOverlapMode(layout, "text-overlap", "text-allow-overlap");
const textAlwaysOverlap = textOverlapMode === "always";
const iconOverlapMode = getOverlapMode(layout, "icon-overlap", "icon-allow-overlap");
const iconAlwaysOverlap = iconOverlapMode === "always";
const rotateWithMap = layout.get("text-rotation-alignment") === "map";
const pitchWithMap = layout.get("text-pitch-alignment") === "map";
const hasIconTextFit = layout.get("icon-text-fit") !== "none";
const zOrderByViewportY = layout.get("symbol-z-order") === "viewport-y";
const alwaysShowText = textAlwaysOverlap && (iconAlwaysOverlap || !bucket.hasIconData() || iconOptional);
const alwaysShowIcon = iconAlwaysOverlap && (textAlwaysOverlap || !bucket.hasTextData() || textOptional);
if (!bucket.collisionArrays && collisionBoxArray) bucket.deserializeCollisionBoxes(collisionBoxArray);
const tileID = this.retainedQueryData[bucket.bucketInstanceId].tileID;
const getElevation = this._getTerrainElevationFunc(tileID);
const simpleProjectionMatrix = this.transform.getFastPathSimpleProjectionMatrix(tileID);
const placeSymbol = (symbolInstance, collisionArrays, symbolIndex) => {
if (seenCrossTileIDs[symbolInstance.crossTileID]) return;
if (holdingForFade) {
this.placements[symbolInstance.crossTileID] = new JointPlacement(false, false, false);
return;
}
let placeText = false;
let placeIcon = false;
let offscreen = true;
let shift = null;
let placed = {
box: null,
placeable: false,
offscreen: null,
occluded: false
};
let placedVerticalText = {
box: null,
placeable: false,
offscreen: null
};
let placedGlyphBoxes = null;
let placedGlyphCircles = null;
let placedIconBoxes = null;
let textFeatureIndex = 0;
let verticalTextFeatureIndex = 0;
let iconFeatureIndex = 0;
if (collisionArrays.textFeatureIndex) textFeatureIndex = collisionArrays.textFeatureIndex;
else if (symbolInstance.useRuntimeCollisionCircles) textFeatureIndex = symbolInstance.featureIndex;
if (collisionArrays.verticalTextFeatureIndex) verticalTextFeatureIndex = collisionArrays.verticalTextFeatureIndex;
const textBox = collisionArrays.textBox;
if (textBox) {
const updatePreviousOrientationIfNotPlaced = (isPlaced) => {
let previousOrientation = 1;
if (bucket.allowVerticalPlacement && !isPlaced && this.prevPlacement) {
const prevPlacedOrientation = this.prevPlacement.placedOrientations[symbolInstance.crossTileID];
if (prevPlacedOrientation) {
this.placedOrientations[symbolInstance.crossTileID] = prevPlacedOrientation;
previousOrientation = prevPlacedOrientation;
this.markUsedOrientation(bucket, previousOrientation, symbolInstance);
}
}
return previousOrientation;
};
const placeTextForPlacementModes = (placeHorizontalFn, placeVerticalFn) => {
if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && collisionArrays.verticalTextBox) for (const placementMode of bucket.writingModes) {
if (placementMode === 2) {
placed = placeVerticalFn();
placedVerticalText = placed;
} else placed = placeHorizontalFn();
if (placed?.placeable) break;
}
else placed = placeHorizontalFn();
};
const textAnchorOffsetStart = symbolInstance.textAnchorOffsetStartIndex;
const textAnchorOffsetEnd = symbolInstance.textAnchorOffsetEndIndex;
if (textAnchorOffsetEnd === textAnchorOffsetStart) {
const placeBox = (collisionTextBox, orientation) => {
const placedFeature = this.collisionIndex.placeCollisionBox(collisionTextBox, textOverlapMode, textPixelRatio, tileID, unwrappedTileID, pitchWithMap, rotateWithMap, translationText, collisionGroup.predicate, getElevation, void 0, simpleProjectionMatrix);
if (placedFeature?.placeable) {
this.markUsedOrientation(bucket, orientation, symbolInstance);
this.placedOrientations[symbolInstance.crossTileID] = orientation;
}
return placedFeature;
};
const placeHorizontal = () => {
return placeBox(textBox, 1);
};
const placeVertical = () => {
const verticalTextBox = collisionArrays.verticalTextBox;
if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) return placeBox(verticalTextBox, 2);
return {
box: null,
offscreen: null
};
};
placeTextForPlacementModes(placeHorizontal, placeVertical);
updatePreviousOrientationIfNotPlaced(placed?.placeable);
} else {
let prevAnchor = TextAnchorEnum[this.prevPlacement?.variableOffsets[symbolInstance.crossTileID]?.anchor];
const placeBoxForVariableAnchors = (collisionTextBox, collisionIconBox, orientation) => {
const width = collisionTextBox.x2 - collisionTextBox.x1;
const height = collisionTextBox.y2 - collisionTextBox.y1;
const textBoxScale = symbolInstance.textBoxScale;
const variableIconBox = hasIconTextFit && iconOverlapMode === "never" ? collisionIconBox : null;
let placedBox = null;
let placementPasses = textOverlapMode === "never" ? 1 : 2;
let overlapMode = "never";
if (prevAnchor) placementPasses++;
for (let pass = 0; pass < placementPasses; pass++) {
for (let i = textAnchorOffsetStart; i < textAnchorOffsetEnd; i++) {
const textAnchorOffset = bucket.textAnchorOffsets.get(i);
if (prevAnchor && textAnchorOffset.textAnchor !== prevAnchor) continue;
const result = this.attemptAnchorPlacement(textAnchorOffset, collisionTextBox, width, height, textBoxScale, rotateWithMap, pitchWithMap, textPixelRatio, tileID, unwrappedTileID, collisionGroup, overlapMode, symbolInstance, bucket, orientation, translationText, translationIcon, variableIconBox, getElevation);
if (result) {
placedBox = result.placedGlyphBoxes;
if (placedBox?.placeable) {
placeText = true;
shift = result.shift;
return placedBox;
}
}
}
if (prevAnchor) prevAnchor = null;
else overlapMode = textOverlapMode;
}
if (showCollisionBoxes && !placedBox) placedBox = {
box: this.collisionIndex.placeCollisionBox(textBox, "always", textPixelRatio, tileID, unwrappedTileID, pitchWithMap, rotateWithMap, translationText, collisionGroup.predicate, getElevation, void 0, simpleProjectionMatrix).box,
offscreen: false,
placeable: false,
occluded: false
};
return placedBox;
};
const placeHorizontal = () => {
return placeBoxForVariableAnchors(textBox, collisionArrays.iconBox, 1);
};
const placeVertical = () => {
const verticalTextBox = collisionArrays.verticalTextBox;
const wasPlaced = placed?.placeable;
if (bucket.allowVerticalPlacement && !wasPlaced && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) return placeBoxForVariableAnchors(verticalTextBox, collisionArrays.verticalIconBox, 2);
return {
box: null,
occluded: true,
offscreen: null
};
};
placeTextForPlacementModes(placeHorizontal, placeVertical);
if (placed) {
placeText = placed.placeable;
offscreen = placed.offscreen;
}
const prevOrientation = updatePreviousOrientationIfNotPlaced(placed?.placeable);
if (!placeText && this.prevPlacement) {
const prevOffset = this.prevPlacement.variableOffsets[symbolInstance.crossTileID];
if (prevOffset) {
this.variableOffsets[symbolInstance.crossTileID] = prevOffset;
this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, prevOrientation);
}
}
}
}
placedGlyphBoxes = placed;
placeText = placedGlyphBoxes?.placeable;
offscreen = placedGlyphBoxes?.offscreen;
if (symbolInstance.useRuntimeCollisionCircles && symbolInstance.centerJustifiedTextSymbolIndex >= 0) {
const placedSymbol = bucket.text.placedSymbolArray.get(symbolInstance.centerJustifiedTextSymbolIndex);
const fontSize = evaluateSizeForFeature(bucket.textSizeData, partiallyEvaluatedTextSize, placedSymbol);
const textPixelPadding = layout.get("text-padding");
const circlePixelDiameter = symbolInstance.collisionCircleDiameter;
placedGlyphCircles = this.collisionIndex.placeCollisionCircles(textOverlapMode, placedSymbol, bucket.lineVertexArray, bucket.glyphOffsetArray, fontSize, unwrappedTileID, pitchedLabelPlaneMatrix, showCollisionBoxes, pitchWithMap, collisionGroup.predicate, circlePixelDiameter, textPixelPadding, translationText, getElevation);
if (placedGlyphCircles.circles.length && placedGlyphCircles.collisionDetected && !showCollisionBoxes) warnOnce("Collisions detected, but collision boxes are not shown");
placeText = textAlwaysOverlap || placedGlyphCircles.circles.length > 0 && !placedGlyphCircles.collisionDetected;
offscreen &&= placedGlyphCircles.offscreen;
}
if (collisionArrays.iconFeatureIndex) iconFeatureIndex = collisionArrays.iconFeatureIndex;
if (collisionArrays.iconBox) {
const placeIconFeature = (iconBox) => {
return this.collisionIndex.placeCollisionBox(iconBox, iconOverlapMode, textPixelRatio, tileID, unwrappedTileID, pitchWithMap, rotateWithMap, translationIcon, collisionGroup.predicate, getElevation, hasIconTextFit && shift ? shift : void 0, simpleProjectionMatrix);
};
if (placedVerticalText && placedVerticalText.placeable && collisionArrays.verticalIconBox) {
placedIconBoxes = placeIconFeature(collisionArrays.verticalIconBox);
placeIcon = placedIconBoxes.placeable;
} else {
placedIconBoxes = placeIconFeature(collisionArrays.iconBox);
placeIcon = placedIconBoxes.placeable;
}
offscreen &&= placedIconBoxes.offscreen;
}
const iconWithoutText = textOptional || symbolInstance.numHorizontalGlyphVertices === 0 && symbolInstance.numVerticalGlyphVertices === 0;
const textWithoutIcon = iconOptional || symbolInstance.numIconVertices === 0;
if (!iconWithoutText && !textWithoutIcon) placeIcon = placeText = placeIcon && placeText;
else if (!textWithoutIcon) placeText = placeIcon && placeText;
else if (!iconWithoutText) placeIcon &&= placeText;
const hasTextBox = placeText && placedGlyphBoxes.placeable;
const hasIconBox = placeIcon && placedIconBoxes.placeable;
if (hasTextBox) {
if (placedVerticalText && placedVerticalText.placeable && verticalTextFeatureIndex) this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, textOverlapMode, layout.get("text-ignore-placement"), bucket.bucketInstanceId, verticalTextFeatureIndex, collisionGroup.ID);
else this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, textOverlapMode, layout.get("text-ignore-placement"), bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID);
}
if (hasIconBox) this.collisionIndex.insertCollisionBox(placedIconBoxes.box, iconOverlapMode, layout.get("icon-ignore-placement"), bucket.bucketInstanceId, iconFeatureIndex, collisionGroup.ID);
if (placedGlyphCircles) {
if (placeText) this.collisionIndex.insertCollisionCircles(placedGlyphCircles.circles, textOverlapMode, layout.get("text-ignore-placement"), bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID);
}
if (showCollisionBoxes) this.storeCollisionData(bucket.bucketInstanceId, symbolIndex, collisionArrays, placedGlyphBoxes, placedIconBoxes, placedGlyphCircles);
if (symbolInstance.crossTileID === 0) throw new Error("symbolInstance.crossTileID can't be 0");
if (bucket.bucketInstanceId === 0) throw new Error("bucket.bucketInstanceId can't be 0");
const textVisible = (placeText || alwaysShowText) && !placedGlyphBoxes?.occluded;
const iconVisible = (placeIcon || alwaysShowIcon) && !placedIconBoxes?.occluded;
this.placements[symbolInstance.crossTileID] = new JointPlacement(textVisible, iconVisible, offscreen || bucket.justReloaded);
seenCrossTileIDs[symbolInstance.crossTileID] = true;
};
if (zOrderByViewportY) {
if (bucketPart.symbolInstanceStart !== 0) throw new Error("bucket.bucketInstanceId should be 0");
const symbolIndexes = bucket.getSortedSymbolIndexes(-this.transform.bearingInRadians);
for (let i = symbolIndexes.length - 1; i >= 0; --i) {
const symbolIndex = symbolIndexes[i];
placeSymbol(bucket.symbolInstances.get(symbolIndex), bucket.collisionArrays[symbolIndex], symbolIndex);
}
} else for (let i = bucketPart.symbolInstanceStart; i < bucketPart.symbolInstanceEnd; i++) placeSymbol(bucket.symbolInstances.get(i), bucket.collisionArrays[i], i);
bucket.justReloaded = false;
}
storeCollisionData(bucketInstanceId, symbolIndex, collisionArrays, placedGlyphBoxes, placedIconBoxes, placedGlyphCircles) {
if (collisionArrays.textBox || collisionArrays.iconBox) {
let boxArray;
if (this.collisionBoxArrays.has(bucketInstanceId)) boxArray = this.collisionBoxArrays.get(bucketInstanceId);
else {
boxArray = /* @__PURE__ */ new Map();
this.collisionBoxArrays.set(bucketInstanceId, boxArray);
}
let realCollisionBox;
if (boxArray.has(symbolIndex)) realCollisionBox = boxArray.get(symbolIndex);
else {
realCollisionBox = {
text: null,
icon: null
};
boxArray.set(symbolIndex, realCollisionBox);
}
if (collisionArrays.textBox) realCollisionBox.text = placedGlyphBoxes.box;
if (collisionArrays.iconBox) realCollisionBox.icon = placedIconBoxes.box;
}
if (placedGlyphCircles) {
let circleArray = this.collisionCircleArrays[bucketInstanceId];
if (circleArray === void 0) circleArray = this.collisionCircleArrays[bucketInstanceId] = [];
for (let i = 0; i < placedGlyphCircles.circles.length; i += 4) {
circleArray.push(placedGlyphCircles.circles[i + 0] - 100);
circleArray.push(placedGlyphCircles.circles[i + 1] - 100);
circleArray.push(placedGlyphCircles.circles[i + 2]);
circleArray.push(placedGlyphCircles.collisionDetected ? 1 : 0);
}
}
}
markUsedJustification(bucket, placedAnchor, symbolInstance, orientation) {
const justifications = {
"left": symbolInstance.leftJustifiedTextSymbolIndex,
"center": symbolInstance.centerJustifiedTextSymbolIndex,
"right": symbolInstance.rightJustifiedTextSymbolIndex
};
let autoIndex;
if (orientation === 2) autoIndex = symbolInstance.verticalPlacedTextSymbolIndex;
else autoIndex = justifications[getAnchorJustification(placedAnchor)];
const indexes = [
symbolInstance.leftJustifiedTextSymbolIndex,
symbolInstance.centerJustifiedTextSymbolIndex,
symbolInstance.rightJustifiedTextSymbolIndex,
symbolInstance.verticalPlacedTextSymbolIndex
];
for (const index of indexes) if (index >= 0) {
if (autoIndex >= 0 && index !== autoIndex) bucket.text.placedSymbolArray.get(index).crossTileID = 0;
else bucket.text.placedSymbolArray.get(index).crossTileID = symbolInstance.crossTileID;
}
}
markUsedOrientation(bucket, orientation, symbolInstance) {
const horizontal = orientation === 1 || orientation === 3 ? orientation : 0;
const vertical = orientation === 2 ? orientation : 0;
const horizontalIndexes = [
symbolInstance.leftJustifiedTextSymbolIndex,
symbolInstance.centerJustifiedTextSymbolIndex,
symbolInstance.rightJustifiedTextSymbolIndex
];
for (const index of horizontalIndexes) bucket.text.placedSymbolArray.get(index).placedOrientation = horizontal;
if (symbolInstance.verticalPlacedTextSymbolIndex) bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).placedOrientation = vertical;
}
commit(now) {
this.commitTime = now;
this.zoomAtLastRecencyCheck = this.transform.zoom;
const prevPlacement = this.prevPlacement;
let placementChanged = false;
this.prevZoomAdjustment = prevPlacement ? prevPlacement.zoomAdjustment(this.transform.zoom) : 0;
const increment = prevPlacement ? prevPlacement.symbolFadeChange(now) : 1;
const prevOpacities = prevPlacement ? prevPlacement.opacities : {};
const prevOffsets = prevPlacement ? prevPlacement.variableOffsets : {};
const prevOrientations = prevPlacement ? prevPlacement.placedOrientations : {};
for (const crossTileID in this.placements) {
const jointPlacement = this.placements[crossTileID];
const prevOpacity = prevOpacities[crossTileID];
if (prevOpacity) {
this.opacities[crossTileID] = new JointOpacityState(prevOpacity, increment, jointPlacement.text, jointPlacement.icon);
placementChanged ||= jointPlacement.text !== prevOpacity.text.placed;
placementChanged ||= jointPlacement.icon !== prevOpacity.icon.placed;
} else {
this.opacities[crossTileID] = new JointOpacityState(null, increment, jointPlacement.text, jointPlacement.icon, jointPlacement.skipFade);
placementChanged ||= jointPlacement.text || jointPlacement.icon;
}
}
for (const crossTileID in prevOpacities) {
const prevOpacity = prevOpacities[crossTileID];
if (!this.opacities[crossTileID]) {
const jointOpacity = new JointOpacityState(prevOpacity, increment, false, false);
if (!jointOpacity.isHidden()) {
this.opacities[crossTileID] = jointOpacity;
placementChanged ||= prevOpacity.text.placed;
placementChanged ||= prevOpacity.icon.placed;
}
}
}
for (const crossTileID in prevOffsets) if (!this.variableOffsets[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) this.variableOffsets[crossTileID] = prevOffsets[crossTileID];
for (const crossTileID in prevOrientations) if (!this.placedOrientations[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) this.placedOrientations[crossTileID] = prevOrientations[crossTileID];
if (prevPlacement && prevPlacement.lastPlacementChangeTime === void 0) throw new Error("Last placement time for previous placement is not defined");
if (placementChanged) this.lastPlacementChangeTime = now;
else if (typeof this.lastPlacementChangeTime !== "number") this.lastPlacementChangeTime = prevPlacement ? prevPlacement.lastPlacementChangeTime : now;
}
updateLayerOpacities(styleLayer, tiles) {
const seenCrossTileIDs = {};
for (const tile of tiles) {
const symbolBucket = tile.getBucket(styleLayer);
if (symbolBucket && tile.latestFeatureIndex && styleLayer.id === symbolBucket.layerIds[0]) this.updateBucketOpacities(symbolBucket, tile.tileID, seenCrossTileIDs, tile.collisionBoxArray);
}
}
updateBucketOpacities(bucket, tileID, seenCrossTileIDs, collisionBoxArray) {
if (bucket.hasTextData()) {
bucket.text.opacityVertexArray.clear();
bucket.text.hasVisibleVertices = false;
}
if (bucket.hasIconData()) {
bucket.icon.opacityVertexArray.clear();
bucket.icon.hasVisibleVertices = false;
}
if (bucket.hasIconCollisionBoxData()) bucket.iconCollisionBox.collisionVertexArray.clear();
if (bucket.hasTextCollisionBoxData()) bucket.textCollisionBox.collisionVertexArray.clear();
const layer = bucket.layers[0];
const layout = layer.layout;
const duplicateOpacityState = new JointOpacityState(null, 0, false, false, true);
const textAllowOverlap = layout.get("text-allow-overlap");
const iconAllowOverlap = layout.get("icon-allow-overlap");
const hasVariablePlacement = layer._unevaluatedLayout.hasValue("text-variable-anchor") || layer._unevaluatedLayout.hasValue("text-variable-anchor-offset");
const rotateWithMap = layout.get("text-rotation-alignment") === "map";
const pitchWithMap = layout.get("text-pitch-alignment") === "map";
const hasIconTextFit = layout.get("icon-text-fit") !== "none";
const defaultOpacityState = new JointOpacityState(null, 0, textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || layout.get("icon-optional")), iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || layout.get("text-optional")), true);
if (!bucket.collisionArrays && collisionBoxArray && (bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData())) bucket.deserializeCollisionBoxes(collisionBoxArray);
const addOpacities = (iconOrText, numVertices, opacity) => {
for (let i = 0; i < numVertices / 4; i++) iconOrText.opacityVertexArray.emplaceBack(opacity);
iconOrText.hasVisibleVertices ||= opacity !== PACKED_HIDDEN_OPACITY;
};
const boxArrays = this.collisionBoxArrays.get(bucket.bucketInstanceId);
for (let s = 0; s < bucket.symbolInstances.length; s++) {
const symbolInstance = bucket.symbolInstances.get(s);
const { numHorizontalGlyphVertices, numVerticalGlyphVertices, crossTileID } = symbolInstance;
const isDuplicate = seenCrossTileIDs[crossTileID];
let opacityState = this.opacities[crossTileID];
if (isDuplicate) opacityState = duplicateOpacityState;
else if (!opacityState) {
opacityState = defaultOpacityState;
this.opacities[crossTileID] = opacityState;
}
seenCrossTileIDs[crossTileID] = true;
const hasText = numHorizontalGlyphVertices > 0 || numVerticalGlyphVertices > 0;
const hasIcon = symbolInstance.numIconVertices > 0;
const placedOrientation = this.placedOrientations[symbolInstance.crossTileID];
const horizontalHidden = placedOrientation === 2;
const verticalHidden = placedOrientation === 1 || placedOrientation === 3;
if (hasText) {
const packedOpacity = packOpacity(opacityState.text);
const horizontalOpacity = horizontalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity;
addOpacities(bucket.text, numHorizontalGlyphVertices, horizontalOpacity);
const verticalOpacity = verticalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity;
addOpacities(bucket.text, numVerticalGlyphVertices, verticalOpacity);
const symbolHidden = opacityState.text.isHidden();
const textSymbolIndexes = [
symbolInstance.rightJustifiedTextSymbolIndex,
symbolInstance.centerJustifiedTextSymbolIndex,
symbolInstance.leftJustifiedTextSymbolIndex
];
for (const index of textSymbolIndexes) if (index >= 0) bucket.text.placedSymbolArray.get(index).hidden = symbolHidden || horizontalHidden ? 1 : 0;
if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).hidden = symbolHidden || verticalHidden ? 1 : 0;
const prevOffset = this.variableOffsets[symbolInstance.crossTileID];
if (prevOffset) this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, placedOrientation);
const prevOrientation = this.placedOrientations[symbolInstance.crossTileID];
if (prevOrientation) {
this.markUsedJustification(bucket, "left", symbolInstance, prevOrientation);
this.markUsedOrientation(bucket, prevOrientation, symbolInstance);
}
}
if (hasIcon) {
const packedOpacity = packOpacity(opacityState.icon);
const useHorizontal = !(hasIconTextFit && symbolInstance.verticalPlacedIconSymbolIndex && horizontalHidden);
if (symbolInstance.placedIconSymbolIndex >= 0) {
const horizontalOpacity = useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY;
addOpacities(bucket.icon, symbolInstance.numIconVertices, horizontalOpacity);
bucket.icon.placedSymbolArray.get(symbolInstance.placedIconSymbolIndex).hidden = opacityState.icon.isHidden();
}
if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) {
const verticalOpacity = !useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY;
addOpacities(bucket.icon, symbolInstance.numVerticalIconVertices, verticalOpacity);
bucket.icon.placedSymbolArray.get(symbolInstance.verticalPlacedIconSymbolIndex).hidden = opacityState.icon.isHidden();
}
}
const realBoxes = boxArrays?.has(s) ? boxArrays.get(s) : {
text: null,
icon: null
};
if (bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()) {
const collisionArrays = bucket.collisionArrays[s];
if (collisionArrays) {
let shift = new Point(0, 0);
if (collisionArrays.textBox || collisionArrays.verticalTextBox) {
let used = true;
if (hasVariablePlacement) {
const variableOffset = this.variableOffsets[crossTileID];
if (variableOffset) {
shift = calculateVariableLayoutShift(variableOffset.anchor, variableOffset.width, variableOffset.height, variableOffset.textOffset, variableOffset.textBoxScale);
if (rotateWithMap) shift._rotate(pitchWithMap ? -this.transform.bearingInRadians : this.transform.bearingInRadians);
} else used = false;
}
if (collisionArrays.textBox || collisionArrays.verticalTextBox) {
let hidden;
if (collisionArrays.textBox) hidden = horizontalHidden;
if (collisionArrays.verticalTextBox) hidden = verticalHidden;
updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || hidden, realBoxes.text, shift.x, shift.y);
}
}
if (collisionArrays.iconBox || collisionArrays.verticalIconBox) {
const verticalIconUsed = Boolean(!verticalHidden && collisionArrays.verticalIconBox);
let hidden;
if (collisionArrays.iconBox) hidden = verticalIconUsed;
if (collisionArrays.verticalIconBox) hidden = !verticalIconUsed;
updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, hidden, realBoxes.icon, hasIconTextFit ? shift.x : 0, hasIconTextFit ? shift.y : 0);
}
}
}
}
bucket.sortFeatures(-this.transform.bearingInRadians);
if (this.retainedQueryData[bucket.bucketInstanceId]) this.retainedQueryData[bucket.bucketInstanceId].featureSortOrder = bucket.featureSortOrder;
if (bucket.hasTextData() && bucket.text.opacityVertexBuffer) bucket.text.opacityVertexBuffer.updateData(bucket.text.opacityVertexArray);
if (bucket.hasIconData() && bucket.icon.opacityVertexBuffer) bucket.icon.opacityVertexBuffer.updateData(bucket.icon.opacityVertexArray);
if (bucket.hasIconCollisionBoxData() && bucket.iconCollisionBox.collisionVertexBuffer) bucket.iconCollisionBox.collisionVertexBuffer.updateData(bucket.iconCollisionBox.collisionVertexArray);
if (bucket.hasTextCollisionBoxData() && bucket.textCollisionBox.collisionVertexBuffer) bucket.textCollisionBox.collisionVertexBuffer.updateData(bucket.textCollisionBox.collisionVertexArray);
if (bucket.text.opacityVertexArray.length !== bucket.text.layoutVertexArray.length / 4) throw new Error(`bucket.text.opacityVertexArray.length (= ${bucket.text.opacityVertexArray.length}) !== bucket.text.layoutVertexArray.length (= ${bucket.text.layoutVertexArray.length}) / 4`);
if (bucket.icon.opacityVertexArray.length !== bucket.icon.layoutVertexArray.length / 4) throw new Error(`bucket.icon.opacityVertexArray.length (= ${bucket.icon.opacityVertexArray.length}) !== bucket.icon.layoutVertexArray.length (= ${bucket.icon.layoutVertexArray.length}) / 4`);
if (bucket.bucketInstanceId in this.collisionCircleArrays) {
bucket.collisionCircleArray = this.collisionCircleArrays[bucket.bucketInstanceId];
delete this.collisionCircleArrays[bucket.bucketInstanceId];
}
}
symbolFadeChange(now) {
return this.fadeDuration === 0 ? 1 : (now - this.commitTime) / this.fadeDuration + this.prevZoomAdjustment;
}
zoomAdjustment(zoom) {
return Math.max(0, (this.transform.zoom - zoom) / 1.5);
}
hasTransitions(now) {
return this.stale || now - this.lastPlacementChangeTime < this.fadeDuration;
}
stillRecent(now, zoom) {
const durationAdjustment = this.zoomAtLastRecencyCheck === zoom ? 1 - this.zoomAdjustment(zoom) : 1;
this.zoomAtLastRecencyCheck = zoom;
return this.commitTime + this.fadeDuration * durationAdjustment > now;
}
setStale() {
this.stale = true;
}
};
function updateCollisionVertices(collisionVertexArray, placed, notUsed, realBox, shiftX, shiftY) {
if (!realBox || realBox.length === 0) realBox = [
0,
0,
0,
0
];
const tlX = realBox[0] - 100;
const tlY = realBox[1] - 100;
const brX = realBox[2] - 100;
const brY = realBox[3] - 100;
collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, tlX, tlY);
collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, brX, tlY);
collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, brX, brY);
collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0, tlX, brY);
}
const shift25 = Math.pow(2, 25);
const shift24 = Math.pow(2, 24);
const shift17 = Math.pow(2, 17);
const shift16 = Math.pow(2, 16);
const shift9 = Math.pow(2, 9);
const shift8 = Math.pow(2, 8);
const shift1 = Math.pow(2, 1);
function packOpacity(opacityState) {
if (opacityState.opacity === 0 && !opacityState.placed) return 0;
else if (opacityState.opacity === 1 && opacityState.placed) return 4294967295;
const targetBit = opacityState.placed ? 1 : 0;
const opacityBits = Math.floor(opacityState.opacity * 127);
return opacityBits * shift25 + targetBit * shift24 + opacityBits * shift17 + targetBit * shift16 + opacityBits * shift9 + targetBit * shift8 + opacityBits * shift1 + targetBit;
}
const PACKED_HIDDEN_OPACITY = 0;
//#endregion
//#region src/style/pauseable_placement.ts
var LayerPlacement = class {
constructor(styleLayer) {
this._sortAcrossTiles = styleLayer.layout.get("symbol-z-order") !== "viewport-y" && !styleLayer.layout.get("symbol-sort-key").isConstant();
this._currentTileIndex = 0;
this._currentPartIndex = 0;
this._seenCrossTileIDs = {};
this._bucketParts = [];
}
continuePlacement(tiles, placement, showCollisionBoxes, styleLayer, shouldPausePlacement) {
const bucketParts = this._bucketParts;
while (this._currentTileIndex < tiles.length) {
const tile = tiles[this._currentTileIndex];
placement.getBucketParts(bucketParts, styleLayer, tile, this._sortAcrossTiles);
this._currentTileIndex++;
if (shouldPausePlacement()) return true;
}
if (this._sortAcrossTiles) {
this._sortAcrossTiles = false;
bucketParts.sort((a, b) => a.sortKey - b.sortKey);
}
while (this._currentPartIndex < bucketParts.length) {
const bucketPart = bucketParts[this._currentPartIndex];
placement.placeLayerBucketPart(bucketPart, this._seenCrossTileIDs, showCollisionBoxes);
this._currentPartIndex++;
if (shouldPausePlacement()) return true;
}
return false;
}
};
var PauseablePlacement = class {
constructor(transform, terrain, order, forceFullPlacement, showCollisionBoxes, fadeDuration, crossSourceCollisions, prevPlacement) {
this.placement = new Placement(transform, terrain, fadeDuration, crossSourceCollisions, prevPlacement);
this._currentPlacementIndex = order.length - 1;
this._forceFullPlacement = forceFullPlacement;
this._showCollisionBoxes = showCollisionBoxes;
this._done = false;
}
isDone() {
return this._done;
}
continuePlacement(order, layers, layerTiles) {
const startTime = now();
const shouldPausePlacement = () => {
return this._forceFullPlacement ? false : now() - startTime > 2;
};
while (this._currentPlacementIndex >= 0) {
const layer = layers[order[this._currentPlacementIndex]];
const placementZoom = this.placement.collisionIndex.transform.zoom;
if (isSymbolStyleLayer(layer) && layer.layout && (!layer.minzoom || layer.minzoom <= placementZoom) && (!layer.maxzoom || layer.maxzoom > placementZoom)) {
this._inProgressLayer ||= new LayerPlacement(layer);
if (this._inProgressLayer.continuePlacement(layerTiles[layer.source], this.placement, this._showCollisionBoxes, layer, shouldPausePlacement)) return;
delete this._inProgressLayer;
}
this._currentPlacementIndex--;
}
this._done = true;
}
commit(now) {
this.placement.commit(now);
return this.placement;
}
};
//#endregion
//#region node_modules/kdbush/index.js
const ARRAY_TYPES = [
Int8Array,
Uint8Array,
Uint8ClampedArray,
Int16Array,
Uint16Array,
Int32Array,
Uint32Array,
Float32Array,
Float64Array
];
/** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */
/** @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array} TypedArray */
const VERSION = 1;
const HEADER_SIZE = 8;
const STACK = /* @__PURE__ */ new Uint32Array(96);
var KDBush = class KDBush {
/**
* Creates an index from raw `ArrayBuffer` data.
* @param {ArrayBufferLike} data
*/
static from(data) {
if (!data || data.byteLength === void 0 || data.buffer) throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");
const [magic, versionAndType] = new Uint8Array(data, 0, 2);
if (magic !== 219) throw new Error("Data does not appear to be in a KDBush format.");
const version = versionAndType >> 4;
if (version !== VERSION) throw new Error(`Got v${version} data when expected v${VERSION}.`);
const ArrayType = ARRAY_TYPES[versionAndType & 15];
if (!ArrayType) throw new Error("Unrecognized array type.");
const [nodeSize] = new Uint16Array(data, 2, 1);
const [numItems] = new Uint32Array(data, 4, 1);
return new KDBush(numItems, nodeSize, ArrayType, void 0, data);
}
/**
* Creates an index that will hold a given number of items.
* @param {number} numItems
* @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).
* @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).
* @param {ArrayBufferConstructor | SharedArrayBufferConstructor} [ArrayBufferType=ArrayBuffer] The array buffer type used for storage (`ArrayBuffer` by default).
* @param {ArrayBufferLike} [data] (For internal use only)
*/
constructor(numItems, nodeSize = 64, ArrayType = Float64Array, ArrayBufferType = ArrayBuffer, data) {
if (isNaN(numItems) || numItems < 0) throw new Error(`Unexpected numItems value: ${numItems}.`);
this.numItems = +numItems;
this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);
this.ArrayType = ArrayType;
this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;
const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);
const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;
const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;
const padCoords = (8 - idsByteSize % 8) % 8;
if (arrayTypeIndex < 0) throw new Error(`Unexpected typed array class: ${ArrayType}.`);
if (data) {
this.data = data;
this.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems);
this.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
this._pos = numItems * 2;
this._finished = true;
} else {
const data = this.data = new ArrayBufferType(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);
this.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems);
this.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
this._pos = 0;
this._finished = false;
new Uint8Array(data, 0, 2).set([219, 16 + arrayTypeIndex]);
new Uint16Array(data, 2, 1)[0] = nodeSize;
new Uint32Array(data, 4, 1)[0] = numItems;
}
}
/**
* Add a point to the index.
* @param {number} x
* @param {number} y
* @returns {number} An incremental index associated with the added item (starting from `0`).
*/
add(x, y) {
const index = this._pos >> 1;
this.ids[index] = index;
this.coords[this._pos++] = x;
this.coords[this._pos++] = y;
return index;
}
/**
* Perform indexing of the added points.
*/
finish() {
const numAdded = this._pos >> 1;
if (numAdded !== this.numItems) throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`);
sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);
this._finished = true;
return this;
}
/**
* Search the index for items within a given bounding box.
* @param {number} minX
* @param {number} minY
* @param {number} maxX
* @param {number} maxY
* @returns {number[]} An array of indices correponding to the found items.
*/
range(minX, minY, maxX, maxY) {
if (!this._finished) throw new Error("Data not yet indexed - call index.finish().");
const { ids, coords, nodeSize } = this;
STACK[0] = 0;
STACK[1] = ids.length - 1;
STACK[2] = 0;
let sp = 3;
const result = [];
while (sp > 0) {
const axis = STACK[--sp];
const right = STACK[--sp];
const left = STACK[--sp];
if (right - left <= nodeSize) {
for (let i = left; i <= right; i++) {
const x = coords[2 * i];
const y = coords[2 * i + 1];
if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);
}
continue;
}
const m = left + right >> 1;
const x = coords[2 * m];
const y = coords[2 * m + 1];
if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);
if (axis === 0 ? minX <= x : minY <= y) {
STACK[sp++] = left;
STACK[sp++] = m - 1;
STACK[sp++] = 1 - axis;
}
if (axis === 0 ? maxX >= x : maxY >= y) {
STACK[sp++] = m + 1;
STACK[sp++] = right;
STACK[sp++] = 1 - axis;
}
}
return result;
}
/**
* Search the index for items within a given radius.
* @param {number} qx
* @param {number} qy
* @param {number} r Query radius.
* @returns {number[]} An array of indices correponding to the found items.
*/
within(qx, qy, r) {
const result = [];
this.withinInto(qx, qy, r, result);
return result;
}
/**
* Search the index for items within a given radius, writing matching ids into `out`
* via indexed assignment (`out[i] = id`). Accepts any indexed-writable container —
* a typed array sized to the expected upper bound (allocation-free, fast) or a plain
* `Array` (which will grow as needed). Returns the number of matches written.
* @param {number} qx
* @param {number} qy
* @param {number} r Query radius.
* @param {number[] | TypedArray} out Container to write matching ids into.
* @returns {number} The number of matches written to `out`.
*/
withinInto(qx, qy, r, out) {
if (!this._finished) throw new Error("Data not yet indexed - call index.finish().");
const { ids, coords, nodeSize } = this;
STACK[0] = 0;
STACK[1] = ids.length - 1;
STACK[2] = 0;
let sp = 3;
let count = 0;
const r2 = r * r;
while (sp > 0) {
const axis = STACK[--sp];
const right = STACK[--sp];
const left = STACK[--sp];
if (right - left <= nodeSize) {
for (let i = left; i <= right; i++) if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) out[count++] = ids[i];
continue;
}
const m = left + right >> 1;
const x = coords[2 * m];
const y = coords[2 * m + 1];
if (sqDist(x, y, qx, qy) <= r2) out[count++] = ids[m];
if (axis === 0 ? qx - r <= x : qy - r <= y) {
STACK[sp++] = left;
STACK[sp++] = m - 1;
STACK[sp++] = 1 - axis;
}
if (axis === 0 ? qx + r >= x : qy + r >= y) {
STACK[sp++] = m + 1;
STACK[sp++] = right;
STACK[sp++] = 1 - axis;
}
}
return count;
}
};
/**
* @param {Uint16Array | Uint32Array} ids
* @param {TypedArray} coords
* @param {number} nodeSize
* @param {number} left
* @param {number} right
* @param {number} axis
*/
function sort(ids, coords, nodeSize, left, right, axis) {
if (right - left <= nodeSize) return;
const m = left + right >> 1;
select(ids, coords, m, left, right, axis);
sort(ids, coords, nodeSize, left, m - 1, 1 - axis);
sort(ids, coords, nodeSize, m + 1, right, 1 - axis);
}
/**
* Custom Floyd-Rivest selection algorithm: sort ids and coords so that
* [left..k-1] items are smaller than k-th item (on either x or y axis)
* @param {Uint16Array | Uint32Array} ids
* @param {TypedArray} coords
* @param {number} k
* @param {number} left
* @param {number} right
* @param {number} axis
*/
function select(ids, coords, k, left, right, axis) {
while (right > left) {
if (right - left > 600) {
const n = right - left + 1;
const m = k - left + 1;
const z = Math.log(n);
const s = .5 * Math.exp(2 * z / 3);
const sd = .5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
select(ids, coords, k, Math.max(left, Math.floor(k - m * s / n + sd)), Math.min(right, Math.floor(k + (n - m) * s / n + sd)), axis);
}
const t = coords[2 * k + axis];
let i = left;
let j = right;
swapItem(ids, coords, left, k);
if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);
while (i < j) {
swapItem(ids, coords, i, j);
i++;
j--;
while (coords[2 * i + axis] < t) i++;
while (coords[2 * j + axis] > t) j--;
}
if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);
else {
j++;
swapItem(ids, coords, j, right);
}
if (j <= k) left = j + 1;
if (k <= j) right = j - 1;
}
}
/**
* @param {Uint16Array | Uint32Array} ids
* @param {TypedArray} coords
* @param {number} i
* @param {number} j
*/
function swapItem(ids, coords, i, j) {
swap(ids, i, j);
swap(coords, 2 * i, 2 * j);
swap(coords, 2 * i + 1, 2 * j + 1);
}
/**
* @param {TypedArray} arr
* @param {number} i
* @param {number} j
*/
function swap(arr, i, j) {
const tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
/**
* @param {number} ax
* @param {number} ay
* @param {number} bx
* @param {number} by
*/
function sqDist(ax, ay, bx, by) {
const dx = ax - bx;
const dy = ay - by;
return dx * dx + dy * dy;
}
//#endregion
//#region src/symbol/cross_tile_symbol_index.ts
const roundingFactor = 512 / EXTENT / 2;
var TileLayerIndex = class {
constructor(tileID, symbolInstances, bucketInstanceId) {
this.tileID = tileID;
this.bucketInstanceId = bucketInstanceId;
this._symbolsByKey = {};
const symbolInstancesByKey = /* @__PURE__ */ new Map();
for (let i = 0; i < symbolInstances.length; i++) {
const symbolInstance = symbolInstances.get(i);
const key = symbolInstance.key;
const instances = symbolInstancesByKey.get(key);
if (instances) instances.push(symbolInstance);
else symbolInstancesByKey.set(key, [symbolInstance]);
}
for (const [key, symbols] of symbolInstancesByKey) {
const entry = {
positions: symbols.map((symbolInstance) => ({
x: Math.floor(symbolInstance.anchorX * roundingFactor),
y: Math.floor(symbolInstance.anchorY * roundingFactor)
})),
crossTileIDs: symbols.map((v) => v.crossTileID)
};
if (entry.positions.length > 128) {
const index = new KDBush(entry.positions.length, 16, Uint16Array);
for (const { x, y } of entry.positions) index.add(x, y);
index.finish();
delete entry.positions;
entry.index = index;
}
this._symbolsByKey[key] = entry;
}
}
getScaledCoordinates(symbolInstance, childTileID) {
const { x: localX, y: localY, z: localZ } = this.tileID.canonical;
const { x, y, z } = childTileID.canonical;
const zDifference = z - localZ;
const scale = roundingFactor / Math.pow(2, zDifference);
const xWorld = (x * EXTENT + symbolInstance.anchorX) * scale;
const yWorld = (y * EXTENT + symbolInstance.anchorY) * scale;
const xOffset = localX * EXTENT * roundingFactor;
const yOffset = localY * EXTENT * roundingFactor;
return {
x: Math.floor(xWorld - xOffset),
y: Math.floor(yWorld - yOffset)
};
}
findMatches(symbolInstances, newTileID, zoomCrossTileIDs) {
const tolerance = this.tileID.canonical.z < newTileID.canonical.z ? 1 : Math.pow(2, this.tileID.canonical.z - newTileID.canonical.z);
for (let i = 0; i < symbolInstances.length; i++) {
const symbolInstance = symbolInstances.get(i);
if (symbolInstance.crossTileID) continue;
const entry = this._symbolsByKey[symbolInstance.key];
if (!entry) continue;
const scaledSymbolCoord = this.getScaledCoordinates(symbolInstance, newTileID);
if (entry.index) this.findMatchesForIndexedEntry(entry, symbolInstance, scaledSymbolCoord, tolerance, zoomCrossTileIDs);
else if (entry.positions) this.findMatchesForNonIndexedEntry(entry, symbolInstance, scaledSymbolCoord, tolerance, zoomCrossTileIDs);
}
}
/**
* Matches a symbol instance against an entry backed by a KDBush spatial index
* (used for keys with more than {@link KDBUSH_THRESHHOLD} symbols).
*
* Matches any symbol with the same key whose coordinates are within one grid
* unit (with a 4px grid, this covers a 12px by 12px area). The lowest-index
* unclaimed candidate is claimed in a single pass rather than sorting the
* whole result set on every query: `range()` can return many candidates where
* symbols are coincident (e.g. stacked point markers), so a per-query sort
* would dominate placement cost on dense layers.
*
* Once a symbol is marked duplicate against a parent symbol, no other symbol
* at the same zoom level may duplicate against the same parent (see issue #5993).
*/
findMatchesForIndexedEntry(entry, symbolInstance, scaledSymbolCoord, tolerance, zoomCrossTileIDs) {
const indexes = entry.index.range(scaledSymbolCoord.x - tolerance, scaledSymbolCoord.y - tolerance, scaledSymbolCoord.x + tolerance, scaledSymbolCoord.y + tolerance);
let bestIndex = Infinity;
for (const candidate of indexes) if (candidate < bestIndex && !zoomCrossTileIDs[entry.crossTileIDs[candidate]]) bestIndex = candidate;
if (bestIndex !== Infinity) {
const crossTileID = entry.crossTileIDs[bestIndex];
zoomCrossTileIDs[crossTileID] = true;
symbolInstance.crossTileID = crossTileID;
}
}
/**
* Matches a symbol instance against an entry that stores its positions as a
* plain array (used for keys with at most {@link KDBUSH_THRESHHOLD} symbols).
*
* Matches any symbol with the same key whose coordinates are within one grid
* unit (with a 4px grid, this covers a 12px by 12px area). Positions are
* stored in symbol-instance order, so the first unclaimed match is also the
* lowest-index one.
*
* Once a symbol is marked duplicate against a parent symbol, no other symbol
* at the same zoom level may duplicate against the same parent (see issue #5993).
*/
findMatchesForNonIndexedEntry(entry, symbolInstance, scaledSymbolCoord, tolerance, zoomCrossTileIDs) {
for (let i = 0; i < entry.positions.length; i++) {
const thisTileSymbol = entry.positions[i];
const crossTileID = entry.crossTileIDs[i];
if (Math.abs(thisTileSymbol.x - scaledSymbolCoord.x) <= tolerance && Math.abs(thisTileSymbol.y - scaledSymbolCoord.y) <= tolerance && !zoomCrossTileIDs[crossTileID]) {
zoomCrossTileIDs[crossTileID] = true;
symbolInstance.crossTileID = crossTileID;
break;
}
}
}
getCrossTileIDsLists() {
return Object.values(this._symbolsByKey).map(({ crossTileIDs }) => crossTileIDs);
}
};
var CrossTileIDs = class {
constructor() {
this.maxCrossTileID = 0;
}
generate() {
return ++this.maxCrossTileID;
}
};
var CrossTileSymbolLayerIndex = class {
constructor() {
this.indexes = {};
this.usedCrossTileIDs = {};
this.lng = 0;
}
handleWrapJump(lng) {
const wrapDelta = Math.round((lng - this.lng) / 360);
if (wrapDelta !== 0) for (const zoom in this.indexes) {
const zoomIndexes = this.indexes[zoom];
const newZoomIndex = {};
for (const key in zoomIndexes) {
const index = zoomIndexes[key];
index.tileID = index.tileID.unwrapTo(index.tileID.wrap + wrapDelta);
newZoomIndex[index.tileID.key] = index;
}
this.indexes[zoom] = newZoomIndex;
}
this.lng = lng;
}
addBucket(tileID, bucket, crossTileIDs) {
if (this.indexes[tileID.overscaledZ]?.[tileID.key]) {
if (this.indexes[tileID.overscaledZ][tileID.key].bucketInstanceId === bucket.bucketInstanceId) return false;
else this.removeBucketCrossTileIDs(tileID.overscaledZ, this.indexes[tileID.overscaledZ][tileID.key]);
}
for (let i = 0; i < bucket.symbolInstances.length; i++) {
const symbolInstance = bucket.symbolInstances.get(i);
symbolInstance.crossTileID = 0;
}
this.usedCrossTileIDs[tileID.overscaledZ] ||= {};
const zoomCrossTileIDs = this.usedCrossTileIDs[tileID.overscaledZ];
for (const zoom in this.indexes) {
const zoomIndexes = this.indexes[zoom];
if (Number(zoom) > tileID.overscaledZ) for (const id in zoomIndexes) {
const childIndex = zoomIndexes[id];
if (childIndex.tileID.isChildOf(tileID)) childIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs);
}
else {
const parentIndex = zoomIndexes[tileID.scaledTo(Number(zoom)).key];
if (parentIndex) parentIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs);
}
}
for (let i = 0; i < bucket.symbolInstances.length; i++) {
const symbolInstance = bucket.symbolInstances.get(i);
if (!symbolInstance.crossTileID) {
symbolInstance.crossTileID = crossTileIDs.generate();
zoomCrossTileIDs[symbolInstance.crossTileID] = true;
}
}
if (this.indexes[tileID.overscaledZ] === void 0) this.indexes[tileID.overscaledZ] = {};
this.indexes[tileID.overscaledZ][tileID.key] = new TileLayerIndex(tileID, bucket.symbolInstances, bucket.bucketInstanceId);
return true;
}
removeBucketCrossTileIDs(zoom, removedBucket) {
for (const crossTileIDs of removedBucket.getCrossTileIDsLists()) for (const crossTileID of crossTileIDs) delete this.usedCrossTileIDs[zoom][crossTileID];
}
removeStaleBuckets(currentIDs) {
let tilesChanged = false;
for (const z in this.indexes) {
const zoomIndexes = this.indexes[z];
for (const tileKey in zoomIndexes) if (!currentIDs[zoomIndexes[tileKey].bucketInstanceId]) {
this.removeBucketCrossTileIDs(z, zoomIndexes[tileKey]);
delete zoomIndexes[tileKey];
tilesChanged = true;
}
}
return tilesChanged;
}
};
var CrossTileSymbolIndex = class {
constructor() {
this.layerIndexes = {};
this.crossTileIDs = new CrossTileIDs();
this.maxBucketInstanceId = 0;
this.bucketsInCurrentPlacement = {};
}
addLayer(styleLayer, tiles, lng) {
let layerIndex = this.layerIndexes[styleLayer.id];
if (layerIndex === void 0) layerIndex = this.layerIndexes[styleLayer.id] = new CrossTileSymbolLayerIndex();
let symbolBucketsChanged = false;
const currentBucketIDs = {};
layerIndex.handleWrapJump(lng);
for (const tile of tiles) {
const symbolBucket = tile.getBucket(styleLayer);
if (styleLayer.id !== symbolBucket?.layerIds[0]) continue;
if (!symbolBucket.bucketInstanceId) {
this.maxBucketInstanceId += 1;
symbolBucket.bucketInstanceId = this.maxBucketInstanceId;
}
if (layerIndex.addBucket(tile.tileID, symbolBucket, this.crossTileIDs)) symbolBucketsChanged = true;
currentBucketIDs[symbolBucket.bucketInstanceId] = true;
}
if (layerIndex.removeStaleBuckets(currentBucketIDs)) symbolBucketsChanged = true;
return symbolBucketsChanged;
}
pruneUnusedLayers(usedLayers) {
const usedLayerMap = {};
for (const usedLayer of usedLayers) usedLayerMap[usedLayer] = true;
for (const layerId in this.layerIndexes) if (!usedLayerMap[layerId]) delete this.layerIndexes[layerId];
}
};
//#endregion
//#region src/shaders/glsl/_prelude.fragment.glsl.g.ts
var _prelude_fragment_glsl_g_default = "#ifdef GL_ES\nprecision mediump float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nout highp vec4 fragColor;";
//#endregion
//#region src/shaders/glsl/_prelude.vertex.glsl.g.ts
var _prelude_vertex_glsl_g_default = "#ifdef GL_ES\nprecision highp float;\n#else\n#if !defined(lowp)\n#define lowp\n#endif\n#if !defined(mediump)\n#define mediump\n#endif\n#if !defined(highp)\n#define highp\n#endif\n#endif\nvec2 unpack_float(const float packedValue) {int packedIntValue=int(packedValue);int v0=packedIntValue/256;return vec2(v0,packedIntValue-v0*256);}vec2 unpack_opacity(const uint packedOpacity) {return vec2(float(packedOpacity >> 1u)/127.0,float(packedOpacity & 1u));}vec4 decode_color(const vec2 encodedColor) {return vec4(unpack_float(encodedColor[0])/255.0,unpack_float(encodedColor[1])/255.0\n);}float unpack_mix_vec2(const vec2 packedValue,const float t) {return mix(packedValue[0],packedValue[1],t);}vec4 unpack_mix_color(const vec4 packedColors,const float t) {vec4 minColor=decode_color(vec2(packedColors[0],packedColors[1]));vec4 maxColor=decode_color(vec2(packedColors[2],packedColors[3]));return mix(minColor,maxColor,t);}vec2 get_pattern_pos(const vec2 pixel_coord_upper,const vec2 pixel_coord_lower,const vec2 pattern_size,const float tile_units_to_pixels,const vec2 pos) {vec2 offset=mod(mod(mod(pixel_coord_upper,pattern_size)*256.0,pattern_size)*256.0+pixel_coord_lower,pattern_size);return (tile_units_to_pixels*pos+offset)/pattern_size;}mat3 rotationMatrixFromAxisAngle(vec3 u,float angle) {float c=cos(angle);float s=sin(angle);float c2=1.0-c;return mat3(u.x*u.x*c2+ c,u.x*u.y*c2-u.z*s,u.x*u.z*c2+u.y*s,u.y*u.x*c2+u.z*s,u.y*u.y*c2+ c,u.y*u.z*c2-u.x*s,u.z*u.x*c2-u.y*s,u.z*u.y*c2+u.x*s,u.z*u.z*c2+ c\n);}\n#ifdef TERRAIN3D\nuniform sampler2D u_terrain;uniform float u_terrain_dim;uniform mat4 u_terrain_matrix;uniform vec4 u_terrain_unpack;uniform float u_terrain_exaggeration;uniform highp sampler2D u_depth;\n#endif\nconst highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitShifts=vec4(1.)/bitSh;highp float unpack(highp vec4 color) {return dot(color,bitShifts);}highp float depthOpacity(vec3 frag) {\n#ifdef TERRAIN3D\nhighp float d=unpack(texture(u_depth,frag.xy*0.5+0.5))+0.0001-frag.z;return 1.0-max(0.0,min(1.0,-d*500.0));\n#else\nreturn 1.0;\n#endif\n}float calculate_visibility(vec4 pos) {\n#ifdef TERRAIN3D\nvec3 frag=pos.xyz/pos.w;highp float d=depthOpacity(frag);if (d > 0.95) return 1.0;return (d+depthOpacity(frag+vec3(0.0,0.01,0.0)))/2.0;\n#else\nreturn 1.0;\n#endif\n}float ele(ivec2 pos) {\n#ifdef TERRAIN3D\nvec4 rgb=(texelFetch(u_terrain,pos,0)*255.0)*u_terrain_unpack;return rgb.r+rgb.g+rgb.b-u_terrain_unpack.a;\n#else\nreturn 0.0;\n#endif\n}float get_elevation(vec2 pos) {\n#ifdef TERRAIN3D\n#ifdef GLOBE\nif ((pos.y <-32767.5) || (pos.y > 32766.5)) {return 0.0;}\n#endif\nvec2 coord=(u_terrain_matrix*vec4(pos,0.0,1.0)).xy*u_terrain_dim+1.0;vec2 f=fract(coord);ivec2 c=ivec2(floor(coord));ivec2 hi=textureSize(u_terrain,0)-1;float tl=ele(clamp(c,ivec2(0),hi));float tr=ele(clamp(c+ivec2(1,0),ivec2(0),hi));float bl=ele(clamp(c+ivec2(0,1),ivec2(0),hi));float br=ele(clamp(c+ivec2(1,1),ivec2(0),hi));float elevation=mix(mix(tl,tr,f.x),mix(bl,br,f.x),f.y);return elevation*u_terrain_exaggeration;\n#else\nreturn 0.0;\n#endif\n}const float PI=3.141592653589793;uniform mat4 u_projection_matrix;";
//#endregion
//#region src/shaders/glsl/background.fragment.glsl.g.ts
var background_fragment_glsl_g_default = "uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}";
//#endregion
//#region src/shaders/glsl/background.vertex.glsl.g.ts
var background_vertex_glsl_g_default = "layout(location=0) in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}";
//#endregion
//#region src/shaders/glsl/background_pattern.fragment.glsl.g.ts
var background_pattern_fragment_glsl_g_default = "uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}";
//#endregion
//#region src/shaders/glsl/background_pattern.vertex.glsl.g.ts
var background_pattern_vertex_glsl_g_default = "uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;layout(location=0) in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}";
//#endregion
//#region src/shaders/glsl/circle.fragment.glsl.g.ts
var circle_fragment_glsl_g_default = "in vec3 v_data;flat in float v_visibility;\n#pragma maplibre: define highp vec4 color\n#pragma maplibre: define mediump float radius\n#pragma maplibre: define lowp float blur\n#pragma maplibre: define lowp float opacity\n#pragma maplibre: define highp vec4 stroke_color\n#pragma maplibre: define mediump float stroke_width\n#pragma maplibre: define lowp float stroke_opacity\nvoid main() {\n#pragma maplibre: initialize highp vec4 color\n#pragma maplibre: initialize mediump float radius\n#pragma maplibre: initialize lowp float blur\n#pragma maplibre: initialize lowp float opacity\n#pragma maplibre: initialize highp vec4 stroke_color\n#pragma maplibre: initialize mediump float stroke_width\n#pragma maplibre: initialize lowp float stroke_opacity\nvec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_blur=v_data.z;float opacity_t=smoothstep(0.0,antialiased_blur,extrude_length-1.0);float color_t=stroke_width < 0.01 ? 0.0 : smoothstep(antialiased_blur,0.0,extrude_length-radius/(radius+stroke_width));fragColor=v_visibility*opacity_t*mix(color*opacity,stroke_color*stroke_opacity,color_t);const float epsilon=0.5/255.0;if (fragColor.r < epsilon && fragColor.g < epsilon && fragColor.b < epsilon && fragColor.a < epsilon) {discard;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}";
//#endregion
//#region src/shaders/glsl/circle.vertex.glsl.g.ts
var circle_vertex_glsl_g_default = "uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform lowp float u_device_pixel_ratio;uniform highp float u_camera_to_center_distance;uniform vec2 u_translate;layout(location=0) in ivec2 a_pos;out vec3 v_data;flat out float v_visibility;\n#pragma maplibre: define highp vec4 color\n#pragma maplibre: define mediump float radius\n#pragma maplibre: define lowp float blur\n#pragma maplibre: define lowp float opacity\n#pragma maplibre: define highp vec4 stroke_color\n#pragma maplibre: define mediump float stroke_width\n#pragma maplibre: define lowp float stroke_opacity\nvoid main(void) {\n#pragma maplibre: initialize highp vec4 color\n#pragma maplibre: initialize mediump float radius\n#pragma maplibre: initialize lowp float blur\n#pragma maplibre: initialize lowp float opacity\n#pragma maplibre: initialize highp vec4 stroke_color\n#pragma maplibre: initialize mediump float stroke_width\n#pragma maplibre: initialize lowp float stroke_opacity\nivec2 pos_raw=a_pos+32768;vec2 extrude=vec2(pos_raw & 7)/7.0*2.0-1.0;vec2 circle_center=vec2(pos_raw >> 3)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {\n#ifdef GLOBE\nvec3 center_vector=projectToSphere(circle_center);\n#endif\nfloat angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {\n#ifdef GLOBE\nvec4 projected_center=interpolateProjection(circle_center,center_vector,ele);\n#else\nvec4 projected_center=projectTileWithElevation(circle_center,ele);\n#endif\ncorner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}\n#ifdef GLOBE\nvec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);\n#else\ngl_Position=projectTileWithElevation(corner_position,ele);\n#endif\n} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}";
//#endregion
//#region src/shaders/glsl/clipping_mask.fragment.glsl.g.ts
var clipping_mask_fragment_glsl_g_default = "void main() {fragColor=vec4(1.0);}";
//#endregion
//#region src/shaders/shaders.ts
const shaders = {
prelude: prepare(_prelude_fragment_glsl_g_default, _prelude_vertex_glsl_g_default),
projectionMercator: prepare("\nvoid clipAntimeridian() {}", "float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}"),
projectionGlobe: prepare("uniform bool u_projection_clip_antimeridian;in highp float v_projection_tile_x;void clipAntimeridian() {if (u_projection_clip_antimeridian && (v_projection_tile_x < 0.0 || v_projection_tile_x >=8192.0)) {discard;}}", "#define GLOBE_RADIUS 6371008.8\nuniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;out highp float v_projection_tile_x;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos\n);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float t=exp(PI-(mercator_pos_y*PI*2.0));return (2.0*t)/(t*t+1.0);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY);if (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;float spherical_x=mercator_pos.x*PI*2.0+PI;float t=exp(PI-(mercator_pos.y*PI*2.0));float t2=t*t;float denom=t2+1.0;float sin_sy=(t2-1.0)/denom;float cos_sy=(2.0*t)/denom;vec3 pos=vec3(sin(spherical_x)*cos_sy,sin_sy,cos(spherical_x)*cos_sy\n);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {v_projection_tile_x=posInTile.x;vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {v_projection_tile_x=posInTile.x;vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}"),
background: prepare(background_fragment_glsl_g_default, background_vertex_glsl_g_default),
backgroundPattern: prepare(background_pattern_fragment_glsl_g_default, background_pattern_vertex_glsl_g_default),
circle: prepare(circle_fragment_glsl_g_default, circle_vertex_glsl_g_default),
clippingMask: prepare(clipping_mask_fragment_glsl_g_default, "layout(location=0) in vec2 a_pos;void main() {gl_Position=projectTile(a_pos);}"),
heatmap: prepare("uniform highp float u_intensity;in vec2 v_extrude;\n#pragma maplibre: define highp float weight\n#define GAUSS_COEF 0.3989422804014327\nvoid main() {\n#pragma maplibre: initialize highp float weight\nfloat d=-0.5*3.0*3.0*dot(v_extrude,v_extrude);float val=weight*u_intensity*GAUSS_COEF*exp(d);fragColor=vec4(val,1.0,1.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "uniform float u_extrude_scale;uniform float u_opacity;uniform float u_intensity;uniform highp float u_globe_extrude_scale;layout(location=0) in ivec2 a_pos;out vec2 v_extrude;\n#pragma maplibre: define highp float weight\n#pragma maplibre: define mediump float radius\nconst highp float ZERO=1.0/255.0/16.0;\n#define GAUSS_COEF 0.3989422804014327\nvoid main(void) {\n#pragma maplibre: initialize highp float weight\n#pragma maplibre: initialize mediump float radius\nivec2 pos_raw=a_pos+32768;vec2 unscaled_extrude=vec2(pos_raw & 7)/7.0*2.0-1.0;float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 circle_center=vec2(pos_raw >> 3);\n#ifdef GLOBE\nvec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);\n#else\ngl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));\n#endif\n}"),
heatmapTexture: prepare("uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(0.0);\n#endif\n}", "uniform mat4 u_matrix;uniform vec2 u_world;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),
collisionBox: prepare("flat in float v_placed;flat in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}", "layout(location=0) in vec2 a_anchor_pos;layout(location=1) in vec2 a_placed;layout(location=2) in vec2 a_box_real;uniform vec2 u_pixel_extrude_scale;flat out float v_placed;flat out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}"),
collisionCircle: prepare("flat in float v_radius;in vec2 v_extrude;flat in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}", "layout(location=0) in vec2 a_pos;layout(location=1) in float a_radius;layout(location=2) in vec2 a_flags;uniform vec2 u_viewport_size;flat out float v_radius;out vec2 v_extrude;flat out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}"),
colorRelief: prepare("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;uniform vec4 u_unpack;uniform sampler2D u_elevation_stops;uniform sampler2D u_color_stops;uniform int u_color_ramp_size;uniform float u_opacity;in vec2 v_pos;float getElevation(vec2 coord) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}float getElevationStop(int stop) {vec4 data=texelFetch(u_elevation_stops,ivec2(stop,0),0)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {float el=getElevation(v_pos);int r=(u_color_ramp_size-1);int l=0;float el_l=getElevationStop(l);float el_r=getElevationStop(r);while(r-l > 1){int m=(r+l)/2;float el_m=getElevationStop(m);if(el < el_m){r=m;el_r=el_m;}else\n{l=m;el_l=el_m;}}float x=(float(l)+(el-el_l)/(el_r-el_l)+0.5)/float(u_color_ramp_size);fragColor=u_opacity*texture(u_color_stops,vec2(x,0));\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "uniform vec2 u_dimension;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_pos/8192.0)*scale+epsilon;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),
debug: prepare("uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}", "layout(location=0) in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}"),
depth: prepare(clipping_mask_fragment_glsl_g_default, "layout(location=0) in vec2 a_pos;void main() {\n#ifdef GLOBE\ngl_Position=projectTileFor3D(a_pos,0.0);\n#else\ngl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);\n#endif\n}"),
fill: prepare("#pragma maplibre: define highp vec4 color\n#pragma maplibre: define lowp float opacity\nvoid main() {\n#pragma maplibre: initialize highp vec4 color\n#pragma maplibre: initialize lowp float opacity\nfragColor=color*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "uniform vec2 u_fill_translate;layout(location=0) in vec2 a_pos;\n#pragma maplibre: define highp vec4 color\n#pragma maplibre: define lowp float opacity\nvoid main() {\n#pragma maplibre: initialize highp vec4 color\n#pragma maplibre: initialize lowp float opacity\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}gl_Position=projectTile(a_pos+u_fill_translate,a_pos);}"),
fillOutline: prepare("in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma maplibre: define highp vec4 outline_color\n#pragma maplibre: define lowp float opacity\nvoid main() {\n#pragma maplibre: initialize highp vec4 outline_color\n#pragma maplibre: initialize lowp float opacity\nfloat dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=outline_color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "uniform vec2 u_world;uniform vec2 u_fill_translate;layout(location=0) in vec2 a_pos;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma maplibre: define highp vec4 outline_color\n#pragma maplibre: define lowp float opacity\nvoid main() {\n#pragma maplibre: initialize highp vec4 outline_color\n#pragma maplibre: initialize lowp float opacity\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),
fillOutlinePattern: prepare("uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma maplibre: define lowp float opacity\n#pragma maplibre: define lowp vec4 pattern_from\n#pragma maplibre: define lowp vec4 pattern_to\nvoid main() {\n#pragma maplibre: initialize lowp float opacity\n#pragma maplibre: initialize mediump vec4 pattern_from\n#pragma maplibre: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);float dist=length(v_pos-gl_FragCoord.xy);float alpha=1.0-smoothstep(0.0,1.0,dist);fragColor=mix(color1,color2,u_fade)*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "uniform vec2 u_world;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;layout(location=0) in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;out vec2 v_pos;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma maplibre: define lowp float opacity\n#pragma maplibre: define lowp vec4 pattern_from\n#pragma maplibre: define lowp vec4 pattern_to\n#pragma maplibre: define lowp float pixel_ratio_from\n#pragma maplibre: define lowp float pixel_ratio_to\nvoid main() {\n#pragma maplibre: initialize lowp float opacity\n#pragma maplibre: initialize mediump vec4 pattern_from\n#pragma maplibre: initialize mediump vec4 pattern_to\n#pragma maplibre: initialize lowp float pixel_ratio_from\n#pragma maplibre: initialize lowp float pixel_ratio_to\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}vec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,a_pos);v_pos=(gl_Position.xy/gl_Position.w+1.0)/2.0*u_world;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n}"),
fillPattern: prepare("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;\n#pragma maplibre: define lowp float opacity\n#pragma maplibre: define lowp vec4 pattern_from\n#pragma maplibre: define lowp vec4 pattern_to\nvoid main() {\n#pragma maplibre: initialize lowp float opacity\n#pragma maplibre: initialize mediump vec4 pattern_from\n#pragma maplibre: initialize mediump vec4 pattern_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_fade)*opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform vec3 u_scale;uniform vec2 u_fill_translate;layout(location=0) in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;\n#pragma maplibre: define lowp float opacity\n#pragma maplibre: define lowp vec4 pattern_from\n#pragma maplibre: define lowp vec4 pattern_to\n#pragma maplibre: define lowp float pixel_ratio_from\n#pragma maplibre: define lowp float pixel_ratio_to\nvoid main() {\n#pragma maplibre: initialize lowp float opacity\n#pragma maplibre: initialize mediump vec4 pattern_from\n#pragma maplibre: initialize mediump vec4 pattern_to\n#pragma maplibre: initialize lowp float pixel_ratio_from\n#pragma maplibre: initialize lowp float pixel_ratio_to\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}vec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}"),
fillExtrusion: prepare("in vec4 v_color;void main() {fragColor=v_color;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;layout(location=0) in vec2 a_pos;layout(location=1) in ivec4 a_normal_ed;\n#ifdef TERRAIN3D\nlayout(location=2) in vec2 a_centroid;\n#endif\nout vec4 v_color;\n#pragma maplibre: define highp float base\n#pragma maplibre: define highp float height\n#pragma maplibre: define highp vec4 color\nvoid main() {\n#pragma maplibre: initialize highp float base\n#pragma maplibre: initialize highp float height\n#pragma maplibre: initialize highp vec4 color\nvec3 normal=vec3(a_normal_ed.xyz);\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=float(a_normal_ed.x & 1);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nfloat colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);\n#ifdef GLOBE\nmat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);\n#endif\ndirectional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}"),
fillExtrusionPattern: prepare("uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;\n#pragma maplibre: define lowp float base\n#pragma maplibre: define lowp float height\n#pragma maplibre: define lowp vec4 pattern_from\n#pragma maplibre: define lowp vec4 pattern_to\n#pragma maplibre: define lowp float pixel_ratio_from\n#pragma maplibre: define lowp float pixel_ratio_to\nvoid main() {\n#pragma maplibre: initialize lowp float base\n#pragma maplibre: initialize lowp float height\n#pragma maplibre: initialize mediump vec4 pattern_from\n#pragma maplibre: initialize mediump vec4 pattern_to\n#pragma maplibre: initialize lowp float pixel_ratio_from\n#pragma maplibre: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(pattern_tl_a/u_texsize,pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(pattern_tl_b/u_texsize,pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);vec4 mixedColor=mix(color1,color2,u_fade);fragColor=mixedColor*v_lighting;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;layout(location=0) in vec2 a_pos;layout(location=1) in ivec4 a_normal_ed;\n#ifdef TERRAIN3D\nlayout(location=2) in vec2 a_centroid;\n#endif\n#ifdef GLOBE\nout vec3 v_sphere_pos;\n#endif\nout vec2 v_pos_a;out vec2 v_pos_b;out vec4 v_lighting;\n#pragma maplibre: define lowp float base\n#pragma maplibre: define lowp float height\n#pragma maplibre: define lowp vec4 pattern_from\n#pragma maplibre: define lowp vec4 pattern_to\n#pragma maplibre: define lowp float pixel_ratio_from\n#pragma maplibre: define lowp float pixel_ratio_to\nvoid main() {\n#pragma maplibre: initialize lowp float base\n#pragma maplibre: initialize lowp float height\n#pragma maplibre: initialize mediump vec4 pattern_from\n#pragma maplibre: initialize mediump vec4 pattern_to\n#pragma maplibre: initialize lowp float pixel_ratio_from\n#pragma maplibre: initialize lowp float pixel_ratio_to\nvec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=vec3(a_normal_ed.xyz);float edgedistance=float(a_normal_ed.w);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;\n#ifdef TERRAIN3D\nfloat height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);\n#else\nfloat height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;\n#endif\nbase=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=float(a_normal_ed.x & 1);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;\n#ifdef GLOBE\nvec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);\n#else\ngl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);\n#endif\nvec2 pos=a_normal_ed.x==1 && a_normal_ed.y==0 && a_normal_ed.z==16384\n? a_pos\n: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.y !=0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+base)*pow(height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}"),
hillshadePrepare: prepare("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;float getElevation(ivec2 texel) {vec4 data=texelFetch(u_image,texel,0)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {ivec2 pos=ivec2(gl_FragCoord.xy)+ivec2(1);float tileSize=u_dimension.x-2.0;float a=getElevation(pos+ivec2(-1,-1));float b=getElevation(pos+ivec2(0,-1));float c=getElevation(pos+ivec2(1,-1));float d=getElevation(pos+ivec2(-1,0));float e=getElevation(pos);float f=getElevation(pos+ivec2(1,0));float g=getElevation(pos+ivec2(-1,1));float h=getElevation(pos+ivec2(0,1));float i=getElevation(pos+ivec2(1,1));float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))*tileSize/pow(2.0,exaggeration+(28.2562-u_zoom));fragColor=clamp(vec4(deriv.x/8.0+0.5,deriv.y/8.0+0.5,1.0,1.0),0.0,1.0);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "uniform mat4 u_matrix;uniform vec2 u_dimension;layout(location=0) in vec2 a_pos;layout(location=1) in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}"),
hillshade: prepare("uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_latrange;uniform float u_exaggeration;uniform vec4 u_accent;uniform int u_method;uniform float u_altitudes[NUM_ILLUMINATION_SOURCES];uniform float u_azimuths[NUM_ILLUMINATION_SOURCES];uniform vec4 u_shadows[NUM_ILLUMINATION_SOURCES];uniform vec4 u_highlights[NUM_ILLUMINATION_SOURCES];\n#define PI 3.141592653589793\n#define STANDARD 0\n#define COMBINED 1\n#define IGOR 2\n#define MULTIDIRECTIONAL 3\n#define BASIC 4\nfloat get_aspect(vec2 deriv){return deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/2.0*(deriv.y > 0.0 ? 1.0 :-1.0);}void igor_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float aspect=get_aspect(deriv);float azimuth=u_azimuths[0]+PI;float slope_stength=atan(length(deriv))*2.0/PI;float aspect_strength=1.0-abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);float shadow_strength=slope_stength*aspect_strength;float highlight_strength=slope_stength*(1.0-aspect_strength);fragColor=u_shadows[0]*shadow_strength+u_highlights[0]*highlight_strength;}void standard_hillshade(vec2 deriv){float azimuth=u_azimuths[0]+PI;float slope=atan(0.625*length(deriv));float aspect=get_aspect(deriv);float intensity=u_exaggeration;float base=1.875-intensity*1.75;float maxValue=0.5*PI;float scaledSlope=intensity !=0.5 ? ((pow(base,slope)-1.0)/(pow(base,maxValue)-1.0))*maxValue : slope;float accent=cos(scaledSlope);vec4 accent_color=(1.0-accent)*u_accent*clamp(intensity*2.0,0.0,1.0);float shade=abs(mod((aspect+azimuth)/PI+0.5,2.0)-1.0);vec4 shade_color=mix(u_shadows[0],u_highlights[0],shade)*sin(scaledSlope)*clamp(intensity*2.0,0.0,1.0);fragColor=accent_color*(1.0-shade_color.a)+shade_color;}void basic_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor=u_highlights[0]*(2.0*shade-1.0);}else\n{fragColor=u_shadows[0]*(1.0-2.0*shade);}}void multidirectional_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;fragColor=vec4(0,0,0,0);for(int i=0; i < NUM_ILLUMINATION_SOURCES; i++){float cos_alt=cos(u_altitudes[i]);float sin_alt=sin(u_altitudes[i]);float cos_az=-cos(u_azimuths[i]);float sin_az=-sin(u_azimuths[i]);float cang=(sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv));float shade=clamp(cang,0.0,1.0);if(shade > 0.5){fragColor+=u_highlights[i]*(2.0*shade-1.0)/float(NUM_ILLUMINATION_SOURCES);}else\n{fragColor+=u_shadows[i]*(1.0-2.0*shade)/float(NUM_ILLUMINATION_SOURCES);}}}void combined_hillshade(vec2 deriv){deriv=deriv*u_exaggeration*2.0;float azimuth=u_azimuths[0]+PI;float cos_az=cos(azimuth);float sin_az=sin(azimuth);float cos_alt=cos(u_altitudes[0]);float sin_alt=sin(u_altitudes[0]);float cang=acos((sin_alt-(deriv.y*cos_az*cos_alt-deriv.x*sin_az*cos_alt))/sqrt(1.0+dot(deriv,deriv)));cang=clamp(cang,0.0,PI/2.0);float shade=cang*atan(length(deriv))*4.0/PI/PI;float highlight=(PI/2.0-cang)*atan(length(deriv))*4.0/PI/PI;fragColor=u_shadows[0]*shade+u_highlights[0]*highlight;}void main() {vec4 pixel=texture(u_image,v_pos);float scaleFactor=cos(radians((u_latrange[0]-u_latrange[1])*(1.0-v_pos.y)+u_latrange[1]));vec2 deriv=((pixel.rg*8.0)-4.0)/scaleFactor;if (u_method==BASIC) {basic_hillshade(deriv);} else if (u_method==COMBINED) {combined_hillshade(deriv);} else if (u_method==IGOR) {igor_hillshade(deriv);} else if (u_method==MULTIDIRECTIONAL) {multidirectional_hillshade(deriv);} else if (u_method==STANDARD) {standard_hillshade(deriv);} else {standard_hillshade(deriv);}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "uniform mat4 u_matrix;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}"),
line: prepare("uniform lowp float u_device_pixel_ratio;flat in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma maplibre: define highp vec4 color\n#pragma maplibre: define lowp float blur\n#pragma maplibre: define lowp float opacity\nvoid main() {\n#pragma maplibre: initialize highp vec4 color\n#pragma maplibre: initialize lowp float blur\n#pragma maplibre: initialize lowp float opacity\nclipAntimeridian();float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "\n#define scale 0.015873016\nlayout(location=0) in ivec2 a_pos_normal;layout(location=1) in uvec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform vec2 u_units_to_pixels;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;flat out vec2 v_width2;out float v_gamma_scale;out highp float v_linesofar;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma maplibre: define highp vec4 color\n#pragma maplibre: define lowp float blur\n#pragma maplibre: define lowp float opacity\n#pragma maplibre: define mediump float gapwidth\n#pragma maplibre: define lowp float offset\n#pragma maplibre: define mediump float width\nvoid main() {\n#pragma maplibre: initialize highp vec4 color\n#pragma maplibre: initialize lowp float blur\n#pragma maplibre: initialize lowp float opacity\n#pragma maplibre: initialize mediump float gapwidth\n#pragma maplibre: initialize lowp float offset\n#pragma maplibre: initialize mediump float width\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(ivec2(a_data.xy)-128);float a_direction=float(int(a_data.z & 3u)-1);v_linesofar=float((a_data.z >> 2u)+a_data.w*64u)*2.0;vec2 pos=vec2(a_pos_normal >> 1);mediump vec2 normal=vec2(a_pos_normal & 1);normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),
lineGradient: prepare("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;flat in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma maplibre: define lowp float blur\n#pragma maplibre: define lowp float opacity\nvoid main() {\n#pragma maplibre: initialize lowp float blur\n#pragma maplibre: initialize lowp float opacity\nclipAntimeridian();float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture(u_image,v_uv);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "\n#define scale 0.015873016\nlayout(location=0) in ivec2 a_pos_normal;layout(location=1) in uvec4 a_data;layout(location=2) in float a_uv_x;layout(location=3) in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;out vec2 v_normal;flat out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma maplibre: define lowp float blur\n#pragma maplibre: define lowp float opacity\n#pragma maplibre: define mediump float gapwidth\n#pragma maplibre: define lowp float offset\n#pragma maplibre: define mediump float width\nvoid main() {\n#pragma maplibre: initialize lowp float blur\n#pragma maplibre: initialize lowp float opacity\n#pragma maplibre: initialize mediump float gapwidth\n#pragma maplibre: initialize lowp float offset\n#pragma maplibre: initialize mediump float width\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(ivec2(a_data.xy)-128);float a_direction=float(int(a_data.z & 3u)-1);highp float texel_height=1.0/u_image_height;highp float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=vec2(a_pos_normal >> 1);mediump vec2 normal=vec2(a_pos_normal & 1);normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_width2=vec2(outset,inset);}"),
linePattern: prepare("#ifdef GL_ES\nprecision highp float;\n#endif\nuniform lowp float u_device_pixel_ratio;uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;in vec2 v_normal;flat in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;flat in float v_width;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma maplibre: define lowp vec4 pattern_from\n#pragma maplibre: define lowp vec4 pattern_to\n#pragma maplibre: define lowp float pixel_ratio_from\n#pragma maplibre: define lowp float pixel_ratio_to\n#pragma maplibre: define lowp float blur\n#pragma maplibre: define lowp float opacity\nvoid main() {\n#pragma maplibre: initialize mediump vec4 pattern_from\n#pragma maplibre: initialize mediump vec4 pattern_to\n#pragma maplibre: initialize lowp float pixel_ratio_from\n#pragma maplibre: initialize lowp float pixel_ratio_to\n#pragma maplibre: initialize lowp float blur\n#pragma maplibre: initialize lowp float opacity\nclipAntimeridian();vec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;vec2 pattern_size_a=vec2(display_size_a.x*fromScale/tileZoomRatio,display_size_a.y);vec2 pattern_size_b=vec2(display_size_b.x*toScale/tileZoomRatio,display_size_b.y);float aspect_a=display_size_a.y/v_width;float aspect_b=display_size_b.y/v_width;float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float x_a=mod(v_linesofar/pattern_size_a.x*aspect_a,1.0);float x_b=mod(v_linesofar/pattern_size_b.x*aspect_b,1.0);float y=0.5*v_normal.y+0.5;vec2 texel_size=1.0/u_texsize;vec2 pos_a=mix(pattern_tl_a*texel_size-texel_size,pattern_br_a*texel_size+texel_size,vec2(x_a,y));vec2 pos_b=mix(pattern_tl_b*texel_size-texel_size,pattern_br_b*texel_size+texel_size,vec2(x_b,y));vec4 color=mix(texture(u_image,pos_a),texture(u_image,pos_b),u_fade);fragColor=color*alpha*opacity;\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nlayout(location=0) in ivec2 a_pos_normal;layout(location=1) in uvec4 a_data;uniform vec2 u_translation;uniform vec2 u_units_to_pixels;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;out vec2 v_normal;flat out vec2 v_width2;out float v_linesofar;out float v_gamma_scale;flat out float v_width;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma maplibre: define lowp float blur\n#pragma maplibre: define lowp float opacity\n#pragma maplibre: define lowp float offset\n#pragma maplibre: define mediump float gapwidth\n#pragma maplibre: define mediump float width\n#pragma maplibre: define lowp float floorwidth\n#pragma maplibre: define lowp vec4 pattern_from\n#pragma maplibre: define lowp vec4 pattern_to\n#pragma maplibre: define lowp float pixel_ratio_from\n#pragma maplibre: define lowp float pixel_ratio_to\nvoid main() {\n#pragma maplibre: initialize lowp float blur\n#pragma maplibre: initialize lowp float opacity\n#pragma maplibre: initialize lowp float offset\n#pragma maplibre: initialize mediump float gapwidth\n#pragma maplibre: initialize mediump float width\n#pragma maplibre: initialize lowp float floorwidth\n#pragma maplibre: initialize mediump vec4 pattern_from\n#pragma maplibre: initialize mediump vec4 pattern_to\n#pragma maplibre: initialize lowp float pixel_ratio_from\n#pragma maplibre: initialize lowp float pixel_ratio_to\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(ivec2(a_data.xy)-128);float a_direction=float(int(a_data.z & 3u)-1);float a_linesofar=float((a_data.z >> 2u)+a_data.w*64u)*LINE_DISTANCE_SCALE;vec2 pos=vec2(a_pos_normal >> 1);mediump vec2 normal=vec2(a_pos_normal & 1);normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nv_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}"),
lineSDF: prepare("uniform lowp float u_device_pixel_ratio;uniform lowp float u_lineatlas_width;uniform sampler2D u_image;uniform float u_mix;in vec2 v_normal;flat in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma maplibre: define highp vec4 color\n#pragma maplibre: define lowp float blur\n#pragma maplibre: define lowp float opacity\n#pragma maplibre: define mediump float width\n#pragma maplibre: define lowp float floorwidth\n#pragma maplibre: define mediump vec4 dasharray_from\n#pragma maplibre: define mediump vec4 dasharray_to\nvoid main() {\n#pragma maplibre: initialize highp vec4 color\n#pragma maplibre: initialize lowp float blur\n#pragma maplibre: initialize lowp float opacity\n#pragma maplibre: initialize mediump float width\n#pragma maplibre: initialize lowp float floorwidth\n#pragma maplibre: initialize mediump vec4 dasharray_from\n#pragma maplibre: initialize mediump vec4 dasharray_to\nclipAntimeridian();float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);float sdfdist_a=texture(u_image,v_tex_a).a;float sdfdist_b=texture(u_image,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);float sdfgamma=(u_lineatlas_width/256.0/u_device_pixel_ratio)/min(dasharray_from.w,dasharray_to.w);alpha*=smoothstep(0.5-sdfgamma/floorwidth,0.5+sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nlayout(location=0) in ivec2 a_pos_normal;layout(location=1) in uvec4 a_data;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_tileratio;uniform float u_crossfade_from;uniform float u_crossfade_to;uniform float u_lineatlas_height;out vec2 v_normal;flat out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma maplibre: define highp vec4 color\n#pragma maplibre: define lowp float blur\n#pragma maplibre: define lowp float opacity\n#pragma maplibre: define mediump float gapwidth\n#pragma maplibre: define lowp float offset\n#pragma maplibre: define mediump float width\n#pragma maplibre: define lowp float floorwidth\n#pragma maplibre: define mediump vec4 dasharray_from\n#pragma maplibre: define mediump vec4 dasharray_to\nvoid main() {\n#pragma maplibre: initialize highp vec4 color\n#pragma maplibre: initialize lowp float blur\n#pragma maplibre: initialize lowp float opacity\n#pragma maplibre: initialize mediump float gapwidth\n#pragma maplibre: initialize lowp float offset\n#pragma maplibre: initialize mediump float width\n#pragma maplibre: initialize lowp float floorwidth\n#pragma maplibre: initialize mediump vec4 dasharray_from\n#pragma maplibre: initialize mediump vec4 dasharray_to\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(ivec2(a_data.xy)-128);float a_direction=float(int(a_data.z & 3u)-1);float a_linesofar=float((a_data.z >> 2u)+a_data.w*64u)*LINE_DISTANCE_SCALE;vec2 pos=vec2(a_pos_normal >> 1);mediump vec2 normal=vec2(a_pos_normal & 1);normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nfloat u_patternscale_a_x=u_tileratio/dasharray_from.w/u_crossfade_from;float u_patternscale_a_y=-dasharray_from.z/2.0/u_lineatlas_height;float u_patternscale_b_x=u_tileratio/dasharray_to.w/u_crossfade_to;float u_patternscale_b_y=-dasharray_to.z/2.0/u_lineatlas_height;v_tex_a=vec2(a_linesofar*u_patternscale_a_x/floorwidth,normal.y*u_patternscale_a_y+(float(dasharray_from.y)+0.5)/u_lineatlas_height);v_tex_b=vec2(a_linesofar*u_patternscale_b_x/floorwidth,normal.y*u_patternscale_b_y+(float(dasharray_to.y)+0.5)/u_lineatlas_height);v_width2=vec2(outset,inset);}"),
lineGradientSDF: prepare("uniform lowp float u_device_pixel_ratio;uniform sampler2D u_image;uniform sampler2D u_image_dash;uniform float u_mix;uniform lowp float u_lineatlas_width;in vec2 v_normal;flat in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;in highp vec2 v_uv;\n#ifdef GLOBE\nin float v_depth;\n#endif\n#pragma maplibre: define lowp float blur\n#pragma maplibre: define lowp float opacity\n#pragma maplibre: define mediump float width\n#pragma maplibre: define lowp float floorwidth\n#pragma maplibre: define mediump vec4 dasharray_from\n#pragma maplibre: define mediump vec4 dasharray_to\nvoid main() {\n#pragma maplibre: initialize lowp float blur\n#pragma maplibre: initialize lowp float opacity\n#pragma maplibre: initialize mediump float width\n#pragma maplibre: initialize lowp float floorwidth\n#pragma maplibre: initialize mediump vec4 dasharray_from\n#pragma maplibre: initialize mediump vec4 dasharray_to\nclipAntimeridian();float dist=length(v_normal)*v_width2.s;float blur2=(blur+1.0/u_device_pixel_ratio)*v_gamma_scale;float alpha=clamp(min(dist-(v_width2.t-blur2),v_width2.s-dist)/blur2,0.0,1.0);vec4 color=texture(u_image,v_uv);float sdfdist_a=texture(u_image_dash,v_tex_a).a;float sdfdist_b=texture(u_image_dash,v_tex_b).a;float sdfdist=mix(sdfdist_a,sdfdist_b,u_mix);float sdfgamma=(u_lineatlas_width/256.0)/min(dasharray_from.w,dasharray_to.w);float dash_alpha=smoothstep(0.5-sdfgamma/floorwidth,0.5+sdfgamma/floorwidth,sdfdist);fragColor=color*(alpha*dash_alpha*opacity);\n#ifdef GLOBE\nif (v_depth > 1.0) {discard;}\n#endif\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "\n#define scale 0.015873016\n#define LINE_DISTANCE_SCALE 2.0\nlayout(location=0) in ivec2 a_pos_normal;layout(location=1) in uvec4 a_data;layout(location=2) in float a_uv_x;layout(location=3) in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform lowp float u_device_pixel_ratio;uniform vec2 u_units_to_pixels;uniform float u_image_height;uniform float u_tileratio;uniform float u_crossfade_from;uniform float u_crossfade_to;uniform float u_lineatlas_height;out vec2 v_normal;flat out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;out vec2 v_tex_a;out vec2 v_tex_b;\n#ifdef GLOBE\nout float v_depth;\n#endif\n#pragma maplibre: define lowp float blur\n#pragma maplibre: define lowp float opacity\n#pragma maplibre: define mediump float gapwidth\n#pragma maplibre: define lowp float offset\n#pragma maplibre: define mediump float width\n#pragma maplibre: define lowp float floorwidth\n#pragma maplibre: define mediump vec4 dasharray_from\n#pragma maplibre: define mediump vec4 dasharray_to\nvoid main() {\n#pragma maplibre: initialize lowp float blur\n#pragma maplibre: initialize lowp float opacity\n#pragma maplibre: initialize mediump float gapwidth\n#pragma maplibre: initialize lowp float offset\n#pragma maplibre: initialize mediump float width\n#pragma maplibre: initialize lowp float floorwidth\n#pragma maplibre: initialize mediump vec4 dasharray_from\n#pragma maplibre: initialize mediump vec4 dasharray_to\nif (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(ivec2(a_data.xy)-128);float a_direction=float(int(a_data.z & 3u)-1);float a_linesofar=float((a_data.z >> 2u)+a_data.w*64u)*LINE_DISTANCE_SCALE;float texel_height=1.0/u_image_height;float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=vec2(a_pos_normal >> 1);mediump vec2 normal=vec2(a_pos_normal & 1);normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump float u=0.5*a_direction;mediump float t=1.0-abs(u);mediump vec2 offset2=offset*a_extrude*scale*normal.y*mat2(t,-u,u,t);float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;\n#ifdef GLOBE\nv_depth=gl_Position.z/gl_Position.w;\n#endif\n#ifdef TERRAIN3D\nv_gamma_scale=1.0;\n#else\nfloat extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;\n#endif\nfloat u_patternscale_a_x=u_tileratio/dasharray_from.w/u_crossfade_from;float u_patternscale_a_y=-dasharray_from.z/2.0/u_lineatlas_height;float u_patternscale_b_x=u_tileratio/dasharray_to.w/u_crossfade_to;float u_patternscale_b_y=-dasharray_to.z/2.0/u_lineatlas_height;v_tex_a=vec2(a_linesofar*u_patternscale_a_x/floorwidth,normal.y*u_patternscale_a_y+(float(dasharray_from.y)+0.5)/u_lineatlas_height);v_tex_b=vec2(a_linesofar*u_patternscale_b_x/floorwidth,normal.y*u_patternscale_b_y+(float(dasharray_to.y)+0.5)/u_lineatlas_height);v_width2=vec2(outset,inset);}"),
layerOpacity: prepare("uniform sampler2D u_image;uniform float u_opacity;in vec2 v_pos;void main() {fragColor=texture(u_image,v_pos)*u_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(0.0);\n#endif\n}", "layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=vec4(a_pos.x*2.0-1.0,1.0-a_pos.y*2.0,0.0,1.0);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}"),
raster: prepare("uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec3 v_pos0;in vec3 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0.xy/v_pos0.z);vec4 color1=texture(u_image1,v_pos1.xy/v_pos1.z);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_buffer_scale;uniform vec3 u_image_warp;uniform vec4 u_coords_top;uniform vec4 u_coords_bottom;layout(location=0) in vec2 a_pos;out vec3 v_pos0;out vec3 v_pos1;void main() {vec2 fractionalPos=a_pos/8192.0;vec2 topLeft=u_coords_top.xy;vec2 topRight=u_coords_top.zw;vec2 bottomLeft=u_coords_bottom.xy;vec2 bottomRight=u_coords_bottom.zw;vec2 bilinearPos=mix(mix(topLeft,topRight,fractionalPos.x),mix(bottomLeft,bottomRight,fractionalPos.x),fractionalPos.y);float denominator=dot(u_image_warp.xy,fractionalPos)+1.0;vec2 acrossTop=topRight-topLeft+u_image_warp.x*topRight;vec2 downLeft=bottomLeft-topLeft+u_image_warp.y*bottomLeft;vec2 projectivePos=(acrossTop*fractionalPos.x+downLeft*fractionalPos.y+topLeft)/denominator;vec2 position=mix(projectivePos,bilinearPos,u_image_warp.z);gl_Position=projectTile(position,position);vec2 texturePos=((fractionalPos-0.5)/u_buffer_scale)+0.5;\n#ifdef GLOBE\nif (a_pos.y <-32767.5) {texturePos.y=0.0;}if (a_pos.y > 32766.5) {texturePos.y=1.0;}\n#endif\nfloat perspectiveRatio=mix(1.0/denominator,1.0,u_image_warp.z);v_pos0=vec3(texturePos*perspectiveRatio,perspectiveRatio);vec2 parentPos=(texturePos*u_scale_parent)+u_tl_parent;v_pos1=vec3(parentPos*perspectiveRatio,perspectiveRatio);}"),
symbolIcon: prepare("uniform sampler2D u_texture;in vec2 v_tex;flat in float v_total_opacity;void main() {fragColor=texture(u_texture,v_tex)*v_total_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "layout(location=0) in vec4 a_pos_offset;layout(location=1) in uvec4 a_data;layout(location=2) in vec4 a_pixeloffset;layout(location=3) in vec3 a_projected_pos;layout(location=4) in uint a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform highp float u_camera_to_center_distance;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform float u_fade_change;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform vec2 u_texsize;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;uniform bool u_is_offset;out vec2 v_tex;flat out float v_total_opacity;\n#pragma maplibre: define lowp float opacity\nvoid main() {\n#pragma maplibre: initialize lowp float opacity\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=vec2(a_data.xy);vec2 a_size=vec2(a_data.zw);float a_size_min=float(a_data.z >> 1u);vec2 a_pxoffset=a_pixeloffset.xy;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);vec2 fade_opacity=unpack_opacity(a_fade_opacity);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float visibility=calculate_visibility(projectedPoint);v_total_opacity=opacity*max(0.0,min(visibility,fade_opacity[0]+fade_change));if (v_total_opacity < 0.1){gl_Position=vec4(-2.,-2.,-2.,1.);return;}highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);if (!u_is_offset) {size*=perspective_ratio;}float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;}"),
symbolSDF: prepare("#define SDF_PX 8.0\nuniform bool u_is_halo;uniform bool u_is_plain;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;\n#pragma maplibre: define highp vec4 fill_color\n#pragma maplibre: define highp vec4 halo_color\n#pragma maplibre: define lowp float halo_width\n#pragma maplibre: define lowp float halo_blur\nvoid main() {\n#pragma maplibre: initialize highp vec4 fill_color\n#pragma maplibre: initialize highp vec4 halo_color\n#pragma maplibre: initialize lowp float halo_width\n#pragma maplibre: initialize lowp float halo_blur\nfloat EDGE_GAMMA=0.105/u_device_pixel_ratio;vec2 tex=v_data0.xy;float gamma_scale=v_data1.x;float size=v_data1.y;float total_opacity=v_data1[2];float fontScale=u_is_text ? size/24.0 : size;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float inner_edge=(256.0-64.0)/256.0;lowp float dist=texture(u_texture,tex).a;lowp vec4 color_alpha_out_text,color_alpha_out_halo;if (u_is_plain){highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(inner_edge-gamma_scaled,inner_edge+gamma_scaled,dist);color_alpha_out_text=total_opacity*alpha*fill_color;}if (u_is_halo) {float gamma_halo=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);float inner_edge_halo=inner_edge+gamma_halo*gamma_scale;highp float gamma_scaled_halo=gamma_halo*gamma_scale;highp float alpha_halo=smoothstep(inner_edge_halo-gamma_scaled_halo,inner_edge_halo+gamma_scaled_halo,dist);highp float halo_edge=(6.0-halo_width/fontScale)/SDF_PX;alpha_halo= min(smoothstep(halo_edge-gamma_scaled_halo,halo_edge+gamma_scaled_halo,dist),1.0-alpha_halo);color_alpha_out_halo=total_opacity*alpha_halo*halo_color;}if (u_is_plain && u_is_halo) {fragColor=color_alpha_out_text+(1.-color_alpha_out_text.a)*color_alpha_out_halo;} else if (u_is_halo){fragColor=color_alpha_out_halo;} else {fragColor=color_alpha_out_text;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "layout(location=0) in vec4 a_pos_offset;layout(location=1) in uvec4 a_data;layout(location=2) in vec4 a_pixeloffset;layout(location=3) in vec3 a_projected_pos;layout(location=4) in uint a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_translation;uniform float u_pitched_scale;uniform bool u_is_offset;out vec2 v_data0;out vec3 v_data1;\n#pragma maplibre: define highp vec4 fill_color\n#pragma maplibre: define highp vec4 halo_color\n#pragma maplibre: define lowp float opacity\n#pragma maplibre: define lowp float halo_width\n#pragma maplibre: define lowp float halo_blur\nvoid main() {\n#pragma maplibre: initialize highp vec4 fill_color\n#pragma maplibre: initialize highp vec4 halo_color\n#pragma maplibre: initialize lowp float opacity\n#pragma maplibre: initialize lowp float halo_width\n#pragma maplibre: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=vec2(a_data.xy);vec2 a_size=vec2(a_data.zw);float a_size_min=float(a_data.z >> 1u);vec2 a_pxoffset=a_pixeloffset.xy/16.0;vec2 a_minFontScale=a_pixeloffset.zw/256.0;float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));float total_opacity=opacity*interpolated_fade_opacity;if (total_opacity < 0.1){gl_Position=vec4(-2.,-2.,-2.,1.);return;}highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);if (!u_is_offset) {size*=perspective_ratio;}float fontScale=u_is_text ? size/24.0 : size;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,total_opacity);}"),
symbolTextAndIcon: prepare("#define SDF_PX 8.0\n#define SDF 1.0\n#define ICON 0.0\nuniform bool u_is_halo;uniform bool u_is_text;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;in vec4 v_data0;in vec3 v_data1;flat in float v_is_sdf;\n#pragma maplibre: define highp vec4 fill_color\n#pragma maplibre: define highp vec4 halo_color\n#pragma maplibre: define lowp float halo_width\n#pragma maplibre: define lowp float halo_blur\nvoid main() {\n#pragma maplibre: initialize highp vec4 fill_color\n#pragma maplibre: initialize highp vec4 halo_color\n#pragma maplibre: initialize lowp float halo_width\n#pragma maplibre: initialize lowp float halo_blur\nfloat total_opacity=v_data1[2];if (v_is_sdf==ICON) {vec2 tex_icon=v_data0.zw;fragColor=texture(u_texture_icon,tex_icon)*total_opacity;\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\nreturn;}vec2 tex=v_data0.xy;float EDGE_GAMMA=0.105/u_device_pixel_ratio;float gamma_scale=v_data1.x;float size=v_data1.y;float fontScale=size/24.0;highp float gamma=EDGE_GAMMA/(fontScale*u_gamma_scale);lowp float buff=(256.0-64.0)/256.0;lowp float dist=texture(u_texture,tex).a;lowp vec4 color_alpha_out,color_alpha_out_halo;if (u_is_text) {highp float gamma_scaled=gamma*gamma_scale;highp float alpha=smoothstep(buff-gamma_scaled,buff+gamma_scaled,dist);color_alpha_out=fill_color*(alpha*total_opacity);}if (u_is_halo) {highp float gamma_halo=(halo_blur*1.19/SDF_PX+EDGE_GAMMA)/(fontScale*u_gamma_scale);lowp float buff_halo=(6.0-halo_width/fontScale)/SDF_PX;highp float gamma_scaled_halo=gamma_halo*gamma_scale;highp float alpha_halo=smoothstep(buff_halo-gamma_scaled_halo,buff_halo+gamma_scaled_halo,dist);color_alpha_out_halo=halo_color*(alpha_halo*total_opacity);}if (u_is_text && u_is_halo) {fragColor=color_alpha_out+(1.-color_alpha_out.a)*color_alpha_out_halo;} else if (u_is_halo) {fragColor=color_alpha_out_halo;} else {fragColor=color_alpha_out;}\n#ifdef OVERDRAW_INSPECTOR\nfragColor=vec4(1.0);\n#endif\n}", "layout(location=0) in vec4 a_pos_offset;layout(location=1) in uvec4 a_data;layout(location=2) in vec3 a_projected_pos;layout(location=3) in uint a_fade_opacity;uniform bool u_is_size_zoom_constant;uniform bool u_is_size_feature_constant;uniform highp float u_size_t;uniform highp float u_size;uniform mat4 u_label_plane_matrix;uniform mat4 u_coord_matrix;uniform bool u_is_text;uniform bool u_pitch_with_map;uniform highp float u_pitch;uniform bool u_rotate_symbol;uniform highp float u_aspect_ratio;uniform highp float u_camera_to_center_distance;uniform float u_fade_change;uniform vec2 u_texsize;uniform vec2 u_texsize_icon;uniform bool u_is_along_line;uniform bool u_is_variable_anchor;uniform vec2 u_translation;uniform float u_pitched_scale;uniform bool u_is_offset;out vec4 v_data0;out vec3 v_data1;flat out float v_is_sdf;\n#pragma maplibre: define highp vec4 fill_color\n#pragma maplibre: define highp vec4 halo_color\n#pragma maplibre: define lowp float opacity\n#pragma maplibre: define lowp float halo_width\n#pragma maplibre: define lowp float halo_blur\nvoid main() {\n#pragma maplibre: initialize highp vec4 fill_color\n#pragma maplibre: initialize highp vec4 halo_color\n#pragma maplibre: initialize lowp float opacity\n#pragma maplibre: initialize lowp float halo_width\n#pragma maplibre: initialize lowp float halo_blur\nvec2 a_pos=a_pos_offset.xy;vec2 a_offset=a_pos_offset.zw;vec2 a_tex=vec2(a_data.xy);vec2 a_size=vec2(a_data.zw);float a_size_min=float(a_data.z >> 1u);float is_sdf=float(a_data.z & 1u);float ele=get_elevation(a_pos);highp float segment_angle=-a_projected_pos[2];float size;if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {size=mix(a_size_min,a_size[1],u_size_t)/128.0;} else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {size=a_size_min/128.0;} else {size=u_size;}vec2 translated_a_pos=a_pos+u_translation;vec4 projectedPoint=projectTileWithElevation(translated_a_pos,ele);vec2 fade_opacity=unpack_opacity(a_fade_opacity);float visibility=calculate_visibility(projectedPoint);float fade_change=fade_opacity[1] > 0.5 ? u_fade_change :-u_fade_change;float interpolated_fade_opacity=max(0.0,min(visibility,fade_opacity[0]+fade_change));float total_opacity=opacity*interpolated_fade_opacity;if (total_opacity < 0.1){gl_Position=vec4(-2.,-2.,-2.,1.);return;}highp float camera_to_anchor_distance=projectedPoint.w;highp float distance_ratio=u_pitch_with_map ?\ncamera_to_anchor_distance/u_camera_to_center_distance :\nu_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ratio=clamp(0.5+0.5*distance_ratio,0.0,4.0);if (!u_is_offset) {size*=perspective_ratio;}float fontScale=size/24.0;highp float symbol_rotation=0.0;if (u_rotate_symbol) {vec4 offsetProjectedPoint=projectTileWithElevation(translated_a_pos+vec2(1,0),ele);vec2 a=projectedPoint.xy/projectedPoint.w;vec2 b=offsetProjectedPoint.xy/offsetProjectedPoint.w;symbol_rotation=atan((b.y-a.y)/u_aspect_ratio,b.x-a.x);}highp float angle_sin=sin(segment_angle+symbol_rotation);highp float angle_cos=cos(segment_angle+symbol_rotation);mat2 rotation_matrix=mat2(angle_cos,-1.0*angle_sin,angle_sin,angle_cos);vec4 projected_pos;if (u_is_along_line || u_is_variable_anchor) {projected_pos=vec4(a_projected_pos.xy,ele,1.0);} else if (u_pitch_with_map) {projected_pos=u_label_plane_matrix*vec4(a_projected_pos.xy+u_translation,ele,1.0);} else {projected_pos=u_label_plane_matrix*projectTileWithElevation(a_projected_pos.xy+u_translation,ele);}float z=float(u_pitch_with_map)*projected_pos.z/projected_pos.w;float projectionScaling=1.0;\n#ifdef GLOBE\nif(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}\n#endif\nvec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec3(gamma_scale,size,total_opacity);v_is_sdf=is_sdf;}"),
terrain: prepare("uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && u_fog_ground_blend_opacity > 0.0 && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}", "layout(location=0) in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}"),
terrainDepth: prepare("in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}", "layout(location=0) in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}"),
terrainCoords: prepare("precision mediump float;uniform sampler2D u_texture;uniform float u_terrain_coords_id;in vec2 v_texture_pos;void main() {vec4 rgba=texture(u_texture,v_texture_pos);fragColor=vec4(rgba.r,rgba.g,rgba.b,u_terrain_coords_id);}", "layout(location=0) in vec3 a_pos3d;uniform float u_ele_delta;out vec2 v_texture_pos;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}"),
atmosphere: prepare("#ifdef GL_ES\nprecision highp float;\n#endif\nin vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758\n);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}", "layout(location=0) in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}"),
sky: prepare("uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor=mix(fragColor,vec4(vec3(0.0),0.0),u_sky_blend);}", "layout(location=0) in vec2 a_pos;void main() {gl_Position=vec4(a_pos,1.0,1.0);}")
};
/** Expand #pragmas to #ifdefs, extract attributes and uniforms */
function prepare(fragmentSource, vertexSource) {
const re = /#pragma maplibre: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g;
const vertexAttributes = vertexSource.match(/in ([\w]+) ([\w]+)/g);
const fragmentUniforms = fragmentSource.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g);
const vertexUniforms = vertexSource.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g);
const shaderUniforms = vertexUniforms ? vertexUniforms.concat(fragmentUniforms) : fragmentUniforms;
let locationCounter = vertexAttributes ? vertexAttributes.length : 0;
const fragmentPragmas = {};
fragmentSource = fragmentSource.replace(re, (match, operation, precision, type, name) => {
fragmentPragmas[name] = true;
if (operation === "define") return `
#ifndef HAS_UNIFORM_u_${name}
in ${precision} ${type} ${name};
#else
uniform ${precision} ${type} u_${name};
#endif
`;
else return `
#ifdef HAS_UNIFORM_u_${name}
${precision} ${type} ${name} = u_${name};
#endif
`;
});
vertexSource = vertexSource.replace(re, (match, operation, precision, type, name) => {
const attrType = type === "float" ? "vec2" : "vec4";
const unpackType = name.match(/color/) ? "color" : attrType;
if (fragmentPragmas[name]) {
if (operation === "define") return `
#ifndef HAS_UNIFORM_u_${name}
uniform lowp float u_${name}_t;
layout(location = ${locationCounter++}) in ${precision} ${attrType} a_${name};
out ${precision} ${type} ${name};
#else
uniform ${precision} ${type} u_${name};
#endif
`;
else if (unpackType === "vec4") return `
#ifndef HAS_UNIFORM_u_${name}
${name} = a_${name};
#else
${precision} ${type} ${name} = u_${name};
#endif
`;
else return `
#ifndef HAS_UNIFORM_u_${name}
${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t);
#else
${precision} ${type} ${name} = u_${name};
#endif
`;
} else if (operation === "define") return `
#ifndef HAS_UNIFORM_u_${name}
uniform lowp float u_${name}_t;
layout(location = ${locationCounter++}) in ${precision} ${attrType} a_${name};
#else
uniform ${precision} ${type} u_${name};
#endif
`;
else if (unpackType === "vec4") return `
#ifndef HAS_UNIFORM_u_${name}
${precision} ${type} ${name} = a_${name};
#else
${precision} ${type} ${name} = u_${name};
#endif
`;
else return `
#ifndef HAS_UNIFORM_u_${name}
${precision} ${type} ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t);
#else
${precision} ${type} ${name} = u_${name};
#endif
`;
});
return {
fragmentSource,
vertexSource,
staticAttributes: vertexAttributes,
staticUniforms: shaderUniforms
};
}
//#endregion
//#region src/geo/projection/mercator_projection.ts
const MercatorShaderDefine = "#define PROJECTION_MERCATOR";
const MercatorShaderVariantKey = "mercator";
var MercatorProjection = class {
constructor() {
this._cachedMesh = null;
}
get name() {
return "mercator";
}
get useSubdivision() {
return false;
}
get shaderVariantName() {
return MercatorShaderVariantKey;
}
get shaderDefine() {
return MercatorShaderDefine;
}
get shaderPreludeCode() {
return shaders.projectionMercator;
}
get vertexShaderPreludeCode() {
return shaders.projectionMercator.vertexSource;
}
get subdivisionGranularity() {
return SubdivisionGranularitySetting.noSubdivision;
}
get useGlobeControls() {
return false;
}
get transitionState() {
return 0;
}
destroy() {}
getMeshFromTileID(context, _tileID, _hasBorder, _allowPoles, _usage) {
if (this._cachedMesh) return this._cachedMesh;
const tileExtentArray = new PosArray();
tileExtentArray.emplaceBack(0, 0);
tileExtentArray.emplaceBack(EXTENT, 0);
tileExtentArray.emplaceBack(0, EXTENT);
tileExtentArray.emplaceBack(EXTENT, EXTENT);
const tileExtentBuffer = context.createVertexBuffer(tileExtentArray, posAttributes.members);
const tileExtentSegments = SegmentVector.simpleSegment(0, 0, 4, 2);
const quadTriangleIndices = new TriangleIndexArray();
quadTriangleIndices.emplaceBack(1, 0, 2);
quadTriangleIndices.emplaceBack(1, 2, 3);
const quadTriangleIndexBuffer = context.createIndexBuffer(quadTriangleIndices);
this._cachedMesh = new Mesh(tileExtentBuffer, quadTriangleIndexBuffer, tileExtentSegments);
return this._cachedMesh;
}
recalculate() {}
hasTransition() {
return false;
}
};
//#endregion
//#region src/geo/edge_insets.ts
/**
* An `EdgeInset` object represents screen space padding applied to the edges of the viewport.
* This shifts the apparent center or the vanishing point of the map. This is useful for adding floating UI elements
* on top of the map and having the vanishing point shift as UI elements resize.
*
* @group Geography and Geometry
*/
var EdgeInsets = class EdgeInsets {
constructor(top = 0, bottom = 0, left = 0, right = 0) {
if (isNaN(top) || top < 0 || isNaN(bottom) || bottom < 0 || isNaN(left) || left < 0 || isNaN(right) || right < 0) throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");
this.top = top;
this.bottom = bottom;
this.left = left;
this.right = right;
}
/**
* Interpolates the inset in-place.
* This maintains the current inset value for any inset not present in `target`.
* @param start - interpolation start
* @param target - interpolation target
* @param t - interpolation step/weight
* @returns the insets
*/
interpolate(start, target, t) {
if (target.top != null && start.top != null) this.top = interpolateFactory.number(start.top, target.top, t);
if (target.bottom != null && start.bottom != null) this.bottom = interpolateFactory.number(start.bottom, target.bottom, t);
if (target.left != null && start.left != null) this.left = interpolateFactory.number(start.left, target.left, t);
if (target.right != null && start.right != null) this.right = interpolateFactory.number(start.right, target.right, t);
return this;
}
/**
* Utility method that computes the new apparent center or vanishing point after applying insets.
* This is in pixels and with the top left being (0.0) and +y being downwards.
*
* @param width - the width
* @param height - the height
* @returns the point
*/
getCenter(width, height) {
const x = clamp((this.left + width - this.right) / 2, 0, width);
const y = clamp((this.top + height - this.bottom) / 2, 0, height);
return new Point(x, y);
}
equals(other) {
return this.top === other.top && this.bottom === other.bottom && this.left === other.left && this.right === other.right;
}
clone() {
return new EdgeInsets(this.top, this.bottom, this.left, this.right);
}
/**
* Returns the current state as json, useful when you want to have a
* read-only representation of the inset.
*
* @returns state as json
*/
toJSON() {
return {
top: this.top,
bottom: this.bottom,
left: this.left,
right: this.right
};
}
};
//#endregion
//#region src/geo/transform_helper.ts
/**
* If a path crossing the antimeridian would be shorter, extend the final coordinate so that
* interpolating between the two endpoints will cross it.
* @param center - The LngLat object of the desired center. This object will be mutated.
*/
function normalizeCenter(tr, center) {
if (!tr.renderWorldCopies || tr.lngRange) return;
const delta = center.lng - tr.center.lng;
center.lng += delta > 180 ? -360 : delta < -180 ? 360 : 0;
}
function getTileZoom(zoom) {
return Math.max(0, Math.floor(zoom));
}
/**
* @internal
* This class stores all values that define a transform's state,
* such as center, zoom, minZoom, etc.
* This can be used as a helper for implementing the ITransform interface.
*/
var TransformHelper = class {
constructor(callbacks, options) {
this.applyConstrain = (lngLat, zoom) => {
if (this._constrainOverride !== null) return this._constrainOverride(lngLat, zoom);
else return this._callbacks.defaultConstrain(lngLat, zoom);
};
this._callbacks = callbacks;
this._tileSize = 512;
this._renderWorldCopies = options?.renderWorldCopies === void 0 ? true : !!options?.renderWorldCopies;
this._minZoom = options?.minZoom || 0;
this._maxZoom = options?.maxZoom || 22;
this._minPitch = options?.minPitch === void 0 || options?.minPitch === null ? 0 : options?.minPitch;
this._maxPitch = options?.maxPitch === void 0 || options?.maxPitch === null ? 60 : options?.maxPitch;
this._constrainOverride = options?.constrainOverride ?? null;
this.setMaxBounds();
this._width = 0;
this._height = 0;
this._center = new LngLat(0, 0);
this._elevation = 0;
this._zoom = 0;
this._tileZoom = getTileZoom(this._zoom);
this._scale = zoomScale(this._zoom);
this._bearingInRadians = 0;
this._fovInRadians = .6435011087932844;
this._pitchInRadians = 0;
this._rollInRadians = 0;
this._unmodified = true;
this._edgeInsets = new EdgeInsets();
this._minElevationForCurrentTile = 0;
this._autoCalculateNearFarZ = true;
}
apply(thatI, constrain, forceOverrideZ) {
this._constrainOverride = thatI.constrainOverride;
this._latRange = thatI.latRange;
this._lngRange = thatI.lngRange;
this._width = thatI.width;
this._height = thatI.height;
this._center = thatI.center;
this._elevation = thatI.elevation;
this._minElevationForCurrentTile = thatI.minElevationForCurrentTile;
this._zoom = thatI.zoom;
this._tileZoom = getTileZoom(this._zoom);
this._scale = zoomScale(this._zoom);
this._bearingInRadians = thatI.bearingInRadians;
this._fovInRadians = thatI.fovInRadians;
this._pitchInRadians = thatI.pitchInRadians;
this._rollInRadians = thatI.rollInRadians;
this._unmodified = thatI.unmodified;
this._edgeInsets = new EdgeInsets(thatI.padding.top, thatI.padding.bottom, thatI.padding.left, thatI.padding.right);
this._minZoom = thatI.minZoom;
this._maxZoom = thatI.maxZoom;
this._minPitch = thatI.minPitch;
this._maxPitch = thatI.maxPitch;
this._renderWorldCopies = thatI.renderWorldCopies;
this._cameraToCenterDistance = thatI.cameraToCenterDistance;
this._nearZ = thatI.nearZ;
this._farZ = thatI.farZ;
this._autoCalculateNearFarZ = !forceOverrideZ && thatI.autoCalculateNearFarZ;
if (constrain) this.constrainInternal();
this._calcMatrices();
}
get pixelsToClipSpaceMatrix() {
return this._pixelsToClipSpaceMatrix;
}
get clipSpaceToPixelsMatrix() {
return this._clipSpaceToPixelsMatrix;
}
get minElevationForCurrentTile() {
return this._minElevationForCurrentTile;
}
setMinElevationForCurrentTile(ele) {
this._minElevationForCurrentTile = ele;
}
get tileSize() {
return this._tileSize;
}
get tileZoom() {
return this._tileZoom;
}
get scale() {
return this._scale;
}
/**
* Gets the transform's width in pixels. Use {@link resize} to set the transform's size.
*/
get width() {
return this._width;
}
/**
* Gets the transform's height in pixels. Use {@link resize} to set the transform's size.
*/
get height() {
return this._height;
}
/**
* Gets the transform's bearing in radians.
*/
get bearingInRadians() {
return this._bearingInRadians;
}
get lngRange() {
return this._lngRange;
}
get latRange() {
return this._latRange;
}
get pixelsToGLUnits() {
return this._pixelsToGLUnits;
}
get minZoom() {
return this._minZoom;
}
setMinZoom(zoom) {
if (this._minZoom === zoom) return;
this._minZoom = zoom;
this.setZoom(this.applyConstrain(this._center, this.zoom).zoom);
}
get maxZoom() {
return this._maxZoom;
}
setMaxZoom(zoom) {
if (this._maxZoom === zoom) return;
this._maxZoom = zoom;
this.setZoom(this.applyConstrain(this._center, this.zoom).zoom);
}
get minPitch() {
return this._minPitch;
}
setMinPitch(pitch) {
if (this._minPitch === pitch) return;
this._minPitch = pitch;
this.setPitch(Math.max(this.pitch, pitch));
}
get maxPitch() {
return this._maxPitch;
}
setMaxPitch(pitch) {
if (this._maxPitch === pitch) return;
this._maxPitch = pitch;
this.setPitch(Math.min(this.pitch, pitch));
}
get renderWorldCopies() {
return this._renderWorldCopies;
}
setRenderWorldCopies(renderWorldCopies) {
if (renderWorldCopies === void 0) renderWorldCopies = true;
else if (renderWorldCopies === null) renderWorldCopies = false;
this._renderWorldCopies = renderWorldCopies;
}
get constrainOverride() {
return this._constrainOverride;
}
setConstrainOverride(constrain) {
if (constrain === void 0) constrain = null;
if (this._constrainOverride === constrain) return;
this._constrainOverride = constrain;
this.constrainInternal();
this._calcMatrices();
}
get worldSize() {
return this._tileSize * this._scale;
}
get centerOffset() {
return this.centerPoint._sub(this.size._div(2));
}
/**
* Gets the transform's dimensions packed into a Point object.
*/
get size() {
return new Point(this._width, this._height);
}
get bearing() {
return this._bearingInRadians / Math.PI * 180;
}
setBearing(bearing) {
const b = wrap(bearing, -180, 180) * Math.PI / 180;
if (this._bearingInRadians === b) return;
this._unmodified = false;
this._bearingInRadians = b;
this._calcMatrices();
this._rotationMatrix = create$2();
rotate(this._rotationMatrix, this._rotationMatrix, -this._bearingInRadians);
}
get rotationMatrix() {
return this._rotationMatrix;
}
get pitchInRadians() {
return this._pitchInRadians;
}
get pitch() {
return this._pitchInRadians / Math.PI * 180;
}
setPitch(pitch) {
const p = clamp(pitch, this.minPitch, this.maxPitch) / 180 * Math.PI;
if (this._pitchInRadians === p) return;
this._unmodified = false;
this._pitchInRadians = p;
this._calcMatrices();
}
get rollInRadians() {
return this._rollInRadians;
}
get roll() {
return this._rollInRadians / Math.PI * 180;
}
setRoll(roll) {
const r = roll / 180 * Math.PI;
if (this._rollInRadians === r) return;
this._unmodified = false;
this._rollInRadians = r;
this._calcMatrices();
}
get fovInRadians() {
return this._fovInRadians;
}
get fov() {
return radiansToDegrees(this._fovInRadians);
}
setFov(fov) {
fov = clamp(fov, .1, 150);
if (this.fov === fov) return;
this._unmodified = false;
this._fovInRadians = degreesToRadians(fov);
this._calcMatrices();
}
get zoom() {
return this._zoom;
}
setZoom(zoom) {
const constrainedZoom = this.applyConstrain(this._center, zoom).zoom;
if (this._zoom === constrainedZoom) return;
this._unmodified = false;
this._zoom = constrainedZoom;
this._tileZoom = Math.max(0, Math.floor(constrainedZoom));
this._scale = zoomScale(constrainedZoom);
this.constrainInternal();
this._calcMatrices();
}
get center() {
return this._center;
}
setCenter(center) {
if (center.lat === this._center.lat && center.lng === this._center.lng) return;
this._unmodified = false;
this._center = center;
this.constrainInternal();
this._calcMatrices();
}
/**
* Elevation at current center point, meters above sea level
*/
get elevation() {
return this._elevation;
}
setElevation(elevation) {
if (elevation === this._elevation) return;
this._elevation = elevation;
this.constrainInternal();
this._calcMatrices();
}
get padding() {
return this._edgeInsets.toJSON();
}
setPadding(padding) {
if (this._edgeInsets.equals(padding)) return;
this._unmodified = false;
this._edgeInsets.interpolate(this._edgeInsets, padding, 1);
this._calcMatrices();
}
/**
* The center of the screen in pixels with the top-left corner being (0,0)
* and +y axis pointing downwards. This accounts for padding.
*/
get centerPoint() {
return this._edgeInsets.getCenter(this._width, this._height);
}
/**
* @internal
*/
get pixelsPerMeter() {
return this._pixelPerMeter;
}
get unmodified() {
return this._unmodified;
}
get cameraToCenterDistance() {
return this._cameraToCenterDistance;
}
get nearZ() {
return this._nearZ;
}
get farZ() {
return this._farZ;
}
get autoCalculateNearFarZ() {
return this._autoCalculateNearFarZ;
}
overrideNearFarZ(nearZ, farZ) {
this._autoCalculateNearFarZ = false;
this._nearZ = nearZ;
this._farZ = farZ;
this._calcMatrices();
}
clearNearFarZOverride() {
this._autoCalculateNearFarZ = true;
this._calcMatrices();
}
/**
* Returns if the padding params match
*
* @param padding - the padding to check against
* @returns true if they are equal, false otherwise
*/
isPaddingEqual(padding) {
return this._edgeInsets.equals(padding);
}
/**
* Helper method to update edge-insets in place
*
* @param start - the starting padding
* @param target - the target padding
* @param t - the step/weight
*/
interpolatePadding(start, target, t) {
this._unmodified = false;
this._edgeInsets.interpolate(start, target, t);
this.constrainInternal();
this._calcMatrices();
}
resize(width, height, constrain = true) {
this._width = width;
this._height = height;
if (constrain) this.constrainInternal();
this._calcMatrices();
}
/**
* Returns the maximum geographical bounds the map is constrained to, or `null` if none set.
* @returns max bounds
*/
getMaxBounds() {
if (this._latRange?.length !== 2 || this._lngRange?.length !== 2) return null;
return new LngLatBounds([this._lngRange[0], this._latRange[0]], [this._lngRange[1], this._latRange[1]]);
}
/**
* Sets or clears the map's geographical constraints.
* @param bounds - A {@link LngLatBounds} object describing the new geographic boundaries of the map.
*/
setMaxBounds(bounds) {
if (bounds) {
this._lngRange = [bounds.getWest(), bounds.getEast()];
this._latRange = [bounds.getSouth(), bounds.getNorth()];
this.constrainInternal();
} else {
this._lngRange = null;
this._latRange = [-MAX_VALID_LATITUDE, MAX_VALID_LATITUDE];
}
}
/**
* When the map is pitched, some of the 3D features that intersect a query will not intersect
* the query at the surface of the earth. Instead the feature may be closer and only intersect
* the query because it extrudes into the air.
* @param queryGeometry - For point queries, the line from the query point to the "camera point",
* for other geometries, the envelope of the query geometry and the "camera point"
* @returns a geometry that includes all of the original query as well as all possible ares of the
* screen where the *base* of a visible extrusion could be.
*
*/
getCameraQueryGeometry(cameraPoint, queryGeometry) {
if (queryGeometry.length === 1) return [queryGeometry[0], cameraPoint];
else {
const { minX, minY, maxX, maxY } = Bounds.fromPoints(queryGeometry).extend(cameraPoint);
return [
new Point(minX, minY),
new Point(maxX, minY),
new Point(maxX, maxY),
new Point(minX, maxY),
new Point(minX, minY)
];
}
}
/**
* @internal
* Snaps the transform's center, zoom, etc. into the valid range.
*/
constrainInternal() {
if (!this.center || !this._width || !this._height || this._constraining) return;
this._constraining = true;
const unmodified = this._unmodified;
const { center, zoom } = this.applyConstrain(this.center, this.zoom);
this.setCenter(center);
this.setZoom(zoom);
this._unmodified = unmodified;
this._constraining = false;
}
/**
* This function is called every time one of the transform's defining properties (center, pitch, etc.) changes.
* This function should update the transform's internal data, such as matrices.
* Any derived `_calcMatrices` function should also call the base function first. The base function only depends on the `_width` and `_height` fields.
*/
_calcMatrices() {
if (this._width && this._height) {
this._pixelsToGLUnits = [2 / this._width, -2 / this._height];
let m = identity(/* @__PURE__ */ new Float64Array(16));
scale(m, m, [
this._width / 2,
-this._height / 2,
1
]);
translate(m, m, [
1,
-1,
0
]);
this._clipSpaceToPixelsMatrix = m;
m = identity(/* @__PURE__ */ new Float64Array(16));
scale(m, m, [
1,
-1,
1
]);
translate(m, m, [
-1,
-1,
0
]);
scale(m, m, [
2 / this._width,
2 / this._height,
1
]);
this._pixelsToClipSpaceMatrix = m;
const halfFov = this.fovInRadians / 2;
this._cameraToCenterDistance = .5 / Math.tan(halfFov) * this._height;
}
this._callbacks.calcMatrices();
}
calculateCenterFromCameraLngLatAlt(lnglat, alt, bearing, pitch) {
const cameraBearing = bearing !== void 0 ? bearing : this.bearing;
const cameraPitch = pitch = pitch !== void 0 ? pitch : this.pitch;
const { distanceToCenter, clampedElevation } = this._distanceToCenterFromAltElevationPitch(alt, this.elevation, cameraPitch);
const { x, y } = cameraDirectionFromPitchBearing(cameraPitch, cameraBearing);
const camMercator = MercatorCoordinate.fromLngLat(lnglat, alt);
let metersPerMercUnit = altitudeFromMercatorZ(1, camMercator.y);
let centerMercator;
let dMercator;
let iter = 0;
const maxIter = 10;
do {
iter += 1;
if (iter > maxIter) break;
dMercator = distanceToCenter / metersPerMercUnit;
const dx = x * dMercator;
const dy = y * dMercator;
centerMercator = new MercatorCoordinate(camMercator.x + dx, camMercator.y + dy);
metersPerMercUnit = 1 / centerMercator.meterInMercatorCoordinateUnits();
} while (Math.abs(distanceToCenter - dMercator * metersPerMercUnit) > 1e-12);
return {
center: centerMercator.toLngLat(),
elevation: clampedElevation,
zoom: scaleZoom(this.height / 2 / Math.tan(this.fovInRadians / 2) / dMercator / this.tileSize)
};
}
recalculateZoomAndCenter(elevation) {
if (this.elevation - elevation === 0) return;
const mercUnitsPerPixel = 1 / this.worldSize;
const originalPixelsPerMeter = mercatorZfromAltitude(1, this.center.lat) * this.worldSize;
const originalCenterMercator = MercatorCoordinate.fromLngLat(this.center, this.elevation);
const originalCenterPixelX = originalCenterMercator.x / mercUnitsPerPixel;
const originalCenterPixelY = originalCenterMercator.y / mercUnitsPerPixel;
const originalCenterPixelZ = originalCenterMercator.z / mercUnitsPerPixel;
const cameraPitch = this.pitch;
const cameraBearing = this.bearing;
const { x, y, z } = cameraDirectionFromPitchBearing(cameraPitch, cameraBearing);
const dCamPixel = this.cameraToCenterDistance;
const camPixelX = originalCenterPixelX + dCamPixel * -x;
const camPixelY = originalCenterPixelY + dCamPixel * -y;
const camPixelZ = originalCenterPixelZ + dCamPixel * z;
const { distanceToCenter, clampedElevation } = this._distanceToCenterFromAltElevationPitch(camPixelZ / originalPixelsPerMeter, elevation, cameraPitch);
const distanceToCenterPixels = distanceToCenter * originalPixelsPerMeter;
const centerPixelX = camPixelX + x * distanceToCenterPixels;
const centerPixelY = camPixelY + y * distanceToCenterPixels;
const center = new MercatorCoordinate(centerPixelX * mercUnitsPerPixel, centerPixelY * mercUnitsPerPixel, 0).toLngLat();
const mercUnitsPerMeter = mercatorZfromAltitude(1, center.lat);
const zoom = scaleZoom(this.height / 2 / Math.tan(this.fovInRadians / 2) / distanceToCenter / mercUnitsPerMeter / this.tileSize);
this._elevation = clampedElevation;
this._center = center;
this.setZoom(zoom);
}
_distanceToCenterFromAltElevationPitch(alt, elevation, pitch) {
const dzNormalized = -Math.cos(degreesToRadians(pitch));
const altitudeAGL = alt - elevation;
let distanceToCenter;
let clampedElevation = elevation;
if (dzNormalized * altitudeAGL >= 0 || Math.abs(dzNormalized) < .1) {
distanceToCenter = 1e4;
clampedElevation = alt + distanceToCenter * dzNormalized;
} else distanceToCenter = -altitudeAGL / dzNormalized;
return {
distanceToCenter,
clampedElevation
};
}
getCameraPoint() {
const pitch = this.pitchInRadians;
const offset = Math.tan(pitch) * (this.cameraToCenterDistance || 1);
return this.centerPoint.add(new Point(offset * Math.sin(this.rollInRadians), offset * Math.cos(this.rollInRadians)));
}
getCameraAltitude() {
return Math.cos(this.pitchInRadians) * this._cameraToCenterDistance / this._pixelPerMeter + this.elevation;
}
getCameraLngLat() {
const pixelPerMeter = mercatorZfromAltitude(1, this.center.lat) * this.worldSize;
const cameraToCenterDistanceMeters = this.cameraToCenterDistance / pixelPerMeter;
return cameraMercatorCoordinateFromCenterAndRotation(this.center, this.elevation, this.pitch, this.bearing, cameraToCenterDistanceMeters).toLngLat();
}
getMercatorTileCoordinates(overscaledTileID) {
if (!overscaledTileID) return [
0,
0,
1,
1
];
const scale = overscaledTileID.canonical.z >= 0 ? 1 << overscaledTileID.canonical.z : Math.pow(2, overscaledTileID.canonical.z);
return [
overscaledTileID.canonical.x / scale,
overscaledTileID.canonical.y / scale,
1 / scale / EXTENT,
1 / scale / EXTENT
];
}
};
//#endregion
//#region src/util/primitives/aabb.ts
var Aabb = class Aabb {
constructor(min_, max_) {
this.min = min_;
this.max = max_;
this.center = scale$2([], add([], this.min, this.max), .5);
}
quadrant(index) {
const split = [index % 2 === 0, index < 2];
const qMin = clone(this.min);
const qMax = clone(this.max);
for (let axis = 0; axis < split.length; axis++) {
qMin[axis] = split[axis] ? this.min[axis] : this.center[axis];
qMax[axis] = split[axis] ? this.center[axis] : this.max[axis];
}
qMax[2] = this.max[2];
return new Aabb(qMin, qMax);
}
distanceX(point) {
return Math.max(Math.min(this.max[0], point[0]), this.min[0]) - point[0];
}
distanceY(point) {
return Math.max(Math.min(this.max[1], point[1]), this.min[1]) - point[1];
}
/**
* Performs a frustum-aabb intersection test.
*/
intersectsFrustum(frustum) {
let fullyInside = true;
for (const plane of frustum.planes) {
const planeIntersection = this.intersectsPlane(plane);
if (planeIntersection === 0) return 0;
if (planeIntersection === 1) fullyInside = false;
}
if (fullyInside) return 2;
if (frustum.aabb.min[0] > this.max[0] || frustum.aabb.min[1] > this.max[1] || frustum.aabb.min[2] > this.max[2] || frustum.aabb.max[0] < this.min[0] || frustum.aabb.max[1] < this.min[1] || frustum.aabb.max[2] < this.min[2]) return 0;
return 1;
}
/**
* Performs a halfspace-aabb intersection test.
*/
intersectsPlane(plane) {
let distMin = plane[3];
let distMax = plane[3];
for (let i = 0; i < 3; i++) if (plane[i] > 0) {
distMin += plane[i] * this.min[i];
distMax += plane[i] * this.max[i];
} else {
distMax += plane[i] * this.min[i];
distMin += plane[i] * this.max[i];
}
if (distMin >= 0) return 2;
if (distMax < 0) return 0;
return 1;
}
};
//#endregion
//#region src/geo/projection/mercator_covering_tiles_details_provider.ts
var MercatorCoveringTilesDetailsProvider = class {
distanceToTile2d(pointX, pointY, _tileID, boundingVolume) {
const aabb = boundingVolume;
const distanceX = aabb.distanceX([pointX, pointY]);
const distanceY = aabb.distanceY([pointX, pointY]);
return Math.hypot(distanceX, distanceY);
}
/**
* Returns the wrap value for a given tile, computed so that tiles will remain loaded when crossing the antimeridian.
*/
getWrap(centerCoord, tileID, parentWrap) {
return parentWrap;
}
/**
* Returns the AABB of the specified tile.
* @param tileID - Tile x, y and z for zoom.
*/
getTileBoundingVolume(tileID, wrap, elevation, options) {
let minElevation = Math.min(0, elevation);
let maxElevation = Math.max(0, elevation);
if (options?.terrain) {
const overscaledTileID = new OverscaledTileID(tileID.z, wrap, tileID.z, tileID.x, tileID.y);
const minMax = options.terrain.getMinMaxElevation(overscaledTileID);
minElevation = minMax.minElevation ?? minElevation;
maxElevation = minMax.maxElevation ?? maxElevation;
}
const numTiles = 1 << tileID.z;
return new Aabb([
wrap + tileID.x / numTiles,
tileID.y / numTiles,
minElevation
], [
wrap + (tileID.x + 1) / numTiles,
(tileID.y + 1) / numTiles,
maxElevation
]);
}
allowVariableZoom(transform, options) {
const zfov = transform.fov * (Math.abs(Math.cos(transform.rollInRadians)) * transform.height + Math.abs(Math.sin(transform.rollInRadians)) * transform.width) / transform.height;
const maxConstantZoomPitch = clamp(78.5 - zfov / 2, 0, 60);
return !!options.terrain || transform.pitch > maxConstantZoomPitch;
}
allowWorldCopies() {
return true;
}
prepareNextFrame() {}
};
//#endregion
//#region src/util/primitives/frustum.ts
var Frustum = class Frustum {
constructor(points, planes, aabb) {
this.points = points;
this.planes = planes;
this.aabb = aabb;
}
static fromInvProjectionMatrix(invProj, worldSize = 1, zoom = 0, horizonPlane, flippedNearFar) {
const clipSpaceCorners = [
[
-1,
1,
-1,
1
],
[
1,
1,
-1,
1
],
[
1,
-1,
-1,
1
],
[
-1,
-1,
-1,
1
],
[
-1,
1,
1,
1
],
[
1,
1,
1,
1
],
[
1,
-1,
1,
1
],
[
-1,
-1,
1,
1
]
];
const frustumPlanePointIndices = flippedNearFar ? [
[
6,
5,
4
],
[
0,
1,
2
],
[
0,
3,
7
],
[
2,
1,
5
],
[
3,
2,
6
],
[
0,
4,
5
]
] : [
[
0,
1,
2
],
[
6,
5,
4
],
[
0,
3,
7
],
[
2,
1,
5
],
[
3,
2,
6
],
[
0,
4,
5
]
];
const scale = Math.pow(2, zoom);
const frustumCoords = clipSpaceCorners.map((v) => unprojectClipSpacePoint(v, invProj, worldSize, scale));
if (horizonPlane) adjustFarPlaneByHorizonPlane(frustumCoords, frustumPlanePointIndices[0], horizonPlane, flippedNearFar);
const frustumPlanes = frustumPlanePointIndices.map((p) => {
const a = sub([], frustumCoords[p[0]], frustumCoords[p[1]]);
const b = sub([], frustumCoords[p[2]], frustumCoords[p[1]]);
const n = normalize([], cross([], a, b));
const d = -dot(n, frustumCoords[p[1]]);
return n.concat(d);
});
const min = [
Number.POSITIVE_INFINITY,
Number.POSITIVE_INFINITY,
Number.POSITIVE_INFINITY
];
const max = [
Number.NEGATIVE_INFINITY,
Number.NEGATIVE_INFINITY,
Number.NEGATIVE_INFINITY
];
for (const p of frustumCoords) for (let i = 0; i < 3; i++) {
min[i] = Math.min(min[i], p[i]);
max[i] = Math.max(max[i], p[i]);
}
return new Frustum(frustumCoords, frustumPlanes, new Aabb(min, max));
}
};
function unprojectClipSpacePoint(point, invProj, worldSize, scale) {
const v = transformMat4([], point, invProj);
const s = 1 / v[3] / worldSize * scale;
return mul(v, v, [
s,
s,
1 / v[3],
s
]);
}
/**
* Modifies points in the supplied `frustumCoords` array so that the frustum's far plane only lies as far as the horizon,
* which improves frustum culling effectiveness.
* @param frustumCoords - Points of the frustum.
* @param nearPlanePointsIndices - Which indices in the `frustumCoords` form the near plane.
* @param horizonPlane - The horizon plane.
*/
function adjustFarPlaneByHorizonPlane(frustumCoords, nearPlanePointsIndices, horizonPlane, flippedNearFar) {
const nearPlanePointsOffset = flippedNearFar ? 4 : 0;
const farPlanePointsOffset = flippedNearFar ? 0 : 4;
let maxDist = 0;
const cornerRayLengths = [];
const cornerRayNormalizedDirections = [];
for (let i = 0; i < 4; i++) {
const dir = sub([], frustumCoords[i + farPlanePointsOffset], frustumCoords[i + nearPlanePointsOffset]);
const len = length$1(dir);
scale$2(dir, dir, 1 / len);
cornerRayLengths.push(len);
cornerRayNormalizedDirections.push(dir);
}
for (let i = 0; i < 4; i++) {
const dist = rayPlaneIntersection(frustumCoords[i + nearPlanePointsOffset], cornerRayNormalizedDirections[i], horizonPlane);
if (dist !== null && dist >= 0) maxDist = Math.max(maxDist, dist);
else maxDist = Math.max(maxDist, cornerRayLengths[i]);
}
const nearPlaneNormalized = getNormalizedNearPlane(frustumCoords, nearPlanePointsIndices);
const idealFarPlaneDistanceFromNearPlane = getIdealNearFarPlaneDistance(horizonPlane, nearPlaneNormalized);
if (idealFarPlaneDistanceFromNearPlane !== null) {
const idealCornerRayLength = idealFarPlaneDistanceFromNearPlane / dot(cornerRayNormalizedDirections[0], nearPlaneNormalized);
maxDist = Math.min(maxDist, idealCornerRayLength);
}
for (let i = 0; i < 4; i++) {
const targetLength = Math.min(maxDist, cornerRayLengths[i]);
frustumCoords[i + farPlanePointsOffset] = [
frustumCoords[i + nearPlanePointsOffset][0] + cornerRayNormalizedDirections[i][0] * targetLength,
frustumCoords[i + nearPlanePointsOffset][1] + cornerRayNormalizedDirections[i][1] * targetLength,
frustumCoords[i + nearPlanePointsOffset][2] + cornerRayNormalizedDirections[i][2] * targetLength,
1
];
}
}
/**
* Returns the near plane equation with unit length direction.
* @param frustumCoords - Points of the frustum.
* @param nearPlanePointsIndices - Which indices in the `frustumCoords` form the near plane.
*/
function getNormalizedNearPlane(frustumCoords, nearPlanePointsIndices) {
const nearPlaneA = sub([], frustumCoords[nearPlanePointsIndices[0]], frustumCoords[nearPlanePointsIndices[1]]);
const nearPlaneB = sub([], frustumCoords[nearPlanePointsIndices[2]], frustumCoords[nearPlanePointsIndices[1]]);
const nearPlaneNormalized = [
0,
0,
0,
0
];
normalize(nearPlaneNormalized, cross([], nearPlaneA, nearPlaneB));
nearPlaneNormalized[3] = -dot(nearPlaneNormalized, frustumCoords[nearPlanePointsIndices[0]]);
return nearPlaneNormalized;
}
/**
* Returns the ideal distance between the frustum's near and far plane so that the far plane only lies as far as the horizon.
*/
function getIdealNearFarPlaneDistance(horizonPlane, nearPlaneNormalized) {
const horizonPlaneLen = len(horizonPlane);
const normalizedHorizonPlane = scale$3([], horizonPlane, 1 / horizonPlaneLen);
const projectedViewDirection = sub([], nearPlaneNormalized, scale$2([], normalizedHorizonPlane, dot(nearPlaneNormalized, normalizedHorizonPlane)));
const projectedViewLength = len(projectedViewDirection);
if (projectedViewLength > 0) {
const horizonCircleRadius = Math.sqrt(1 - normalizedHorizonPlane[3] * normalizedHorizonPlane[3]);
const horizonCircleCenter = scale$2([], normalizedHorizonPlane, -normalizedHorizonPlane[3]);
const pointFurthestOnHorizonCircle = add([], horizonCircleCenter, scale$2([], projectedViewDirection, horizonCircleRadius / projectedViewLength));
return pointPlaneSignedDistance(nearPlaneNormalized, pointFurthestOnHorizonCircle);
} else return null;
}
//#endregion
//#region src/geo/projection/mercator_transform.ts
var MercatorTransform = class MercatorTransform {
get pixelsToClipSpaceMatrix() {
return this._helper.pixelsToClipSpaceMatrix;
}
get clipSpaceToPixelsMatrix() {
return this._helper.clipSpaceToPixelsMatrix;
}
get pixelsToGLUnits() {
return this._helper.pixelsToGLUnits;
}
get centerOffset() {
return this._helper.centerOffset;
}
get size() {
return this._helper.size;
}
get rotationMatrix() {
return this._helper.rotationMatrix;
}
get centerPoint() {
return this._helper.centerPoint;
}
get pixelsPerMeter() {
return this._helper.pixelsPerMeter;
}
setMinZoom(zoom) {
this._helper.setMinZoom(zoom);
}
setMaxZoom(zoom) {
this._helper.setMaxZoom(zoom);
}
setMinPitch(pitch) {
this._helper.setMinPitch(pitch);
}
setMaxPitch(pitch) {
this._helper.setMaxPitch(pitch);
}
setRenderWorldCopies(renderWorldCopies) {
this._helper.setRenderWorldCopies(renderWorldCopies);
}
setBearing(bearing) {
this._helper.setBearing(bearing);
}
setPitch(pitch) {
this._helper.setPitch(pitch);
}
setRoll(roll) {
this._helper.setRoll(roll);
}
setFov(fov) {
this._helper.setFov(fov);
}
setZoom(zoom) {
this._helper.setZoom(zoom);
}
setCenter(center) {
this._helper.setCenter(center);
}
setElevation(elevation) {
this._helper.setElevation(elevation);
}
setMinElevationForCurrentTile(elevation) {
this._helper.setMinElevationForCurrentTile(elevation);
}
setPadding(padding) {
this._helper.setPadding(padding);
}
interpolatePadding(start, target, t) {
this._helper.interpolatePadding(start, target, t);
}
isPaddingEqual(padding) {
return this._helper.isPaddingEqual(padding);
}
resize(width, height, constrain = true) {
this._helper.resize(width, height, constrain);
}
getMaxBounds() {
return this._helper.getMaxBounds();
}
setMaxBounds(bounds) {
this._helper.setMaxBounds(bounds);
}
setConstrainOverride(constrain) {
this._helper.setConstrainOverride(constrain);
}
overrideNearFarZ(nearZ, farZ) {
this._helper.overrideNearFarZ(nearZ, farZ);
}
clearNearFarZOverride() {
this._helper.clearNearFarZOverride();
}
getCameraQueryGeometry(queryGeometry) {
return this._helper.getCameraQueryGeometry(this.getCameraPoint(), queryGeometry);
}
get tileSize() {
return this._helper.tileSize;
}
get tileZoom() {
return this._helper.tileZoom;
}
get scale() {
return this._helper.scale;
}
get worldSize() {
return this._helper.worldSize;
}
get width() {
return this._helper.width;
}
get height() {
return this._helper.height;
}
get lngRange() {
return this._helper.lngRange;
}
get latRange() {
return this._helper.latRange;
}
get minZoom() {
return this._helper.minZoom;
}
get maxZoom() {
return this._helper.maxZoom;
}
get zoom() {
return this._helper.zoom;
}
get center() {
return this._helper.center;
}
get minPitch() {
return this._helper.minPitch;
}
get maxPitch() {
return this._helper.maxPitch;
}
get pitch() {
return this._helper.pitch;
}
get pitchInRadians() {
return this._helper.pitchInRadians;
}
get roll() {
return this._helper.roll;
}
get rollInRadians() {
return this._helper.rollInRadians;
}
get bearing() {
return this._helper.bearing;
}
get bearingInRadians() {
return this._helper.bearingInRadians;
}
get fov() {
return this._helper.fov;
}
get fovInRadians() {
return this._helper.fovInRadians;
}
get elevation() {
return this._helper.elevation;
}
get minElevationForCurrentTile() {
return this._helper.minElevationForCurrentTile;
}
get padding() {
return this._helper.padding;
}
get unmodified() {
return this._helper.unmodified;
}
get renderWorldCopies() {
return this._helper.renderWorldCopies;
}
get cameraToCenterDistance() {
return this._helper.cameraToCenterDistance;
}
get constrainOverride() {
return this._helper.constrainOverride;
}
get nearZ() {
return this._helper.nearZ;
}
get farZ() {
return this._helper.farZ;
}
get autoCalculateNearFarZ() {
return this._helper.autoCalculateNearFarZ;
}
setTransitionState(_value) {}
constructor(options) {
this._posMatrixCache = /* @__PURE__ */ new Map();
this._alignedPosMatrixCache = /* @__PURE__ */ new Map();
this._fogMatrixCacheF32 = /* @__PURE__ */ new Map();
this.defaultConstrain = (lngLat, zoom) => {
zoom = clamp(+zoom, this.minZoom, this.maxZoom);
const result = {
center: new LngLat(lngLat.lng, lngLat.lat),
zoom
};
let lngRange = this._helper._lngRange;
if (!this._helper._renderWorldCopies && lngRange === null) lngRange = [-179.9999999999, 180 - 1e-10];
const worldSize = this.tileSize * zoomScale(result.zoom);
let minY = 0;
let maxY = worldSize;
let minX = 0;
let maxX = worldSize;
let scaleY = 0;
let scaleX = 0;
const { x: screenWidth, y: screenHeight } = this.size;
if (this._helper._latRange) {
const latRange = this._helper._latRange;
minY = mercatorYfromLat(latRange[1]) * worldSize;
maxY = mercatorYfromLat(latRange[0]) * worldSize;
if (maxY - minY < screenHeight) scaleY = screenHeight / (maxY - minY);
}
if (lngRange) {
minX = wrap(mercatorXfromLng(lngRange[0]) * worldSize, 0, worldSize);
maxX = wrap(mercatorXfromLng(lngRange[1]) * worldSize, 0, worldSize);
if (maxX < minX) maxX += worldSize;
if (maxX - minX < screenWidth) scaleX = screenWidth / (maxX - minX);
}
const { x: originalX, y: originalY } = projectToWorldCoordinates(worldSize, lngLat);
let modifiedX, modifiedY;
const scale = Math.max(scaleX || 0, scaleY || 0);
if (scale) {
const newPoint = new Point(scaleX ? (maxX + minX) / 2 : originalX, scaleY ? (maxY + minY) / 2 : originalY);
result.center = unprojectFromWorldCoordinates(worldSize, newPoint).wrap();
result.zoom += scaleZoom(scale);
return result;
}
if (this._helper._latRange) {
const h2 = screenHeight / 2;
if (originalY - h2 < minY) modifiedY = minY + h2;
if (originalY + h2 > maxY) modifiedY = maxY - h2;
}
if (lngRange) {
const centerX = (minX + maxX) / 2;
let wrappedX = originalX;
if (this._helper._renderWorldCopies) wrappedX = wrap(originalX, centerX - worldSize / 2, centerX + worldSize / 2);
const w2 = screenWidth / 2;
if (wrappedX - w2 < minX) modifiedX = minX + w2;
if (wrappedX + w2 > maxX) modifiedX = maxX - w2;
}
if (modifiedX !== void 0 || modifiedY !== void 0) {
const newPoint = new Point(modifiedX ?? originalX, modifiedY ?? originalY);
result.center = unprojectFromWorldCoordinates(worldSize, newPoint).wrap();
}
return result;
};
this.applyConstrain = (lngLat, zoom) => {
return this._helper.applyConstrain(lngLat, zoom);
};
this._helper = new TransformHelper({
calcMatrices: () => this._calcMatrices(),
defaultConstrain: (center, zoom) => {
return this.defaultConstrain(center, zoom);
}
}, options);
this._coveringTilesDetailsProvider = new MercatorCoveringTilesDetailsProvider();
}
clone() {
const clone = new MercatorTransform();
clone.apply(this, false);
return clone;
}
apply(that, constrain, forceOverrideZ) {
this._helper.apply(that, constrain, forceOverrideZ);
}
get cameraPosition() {
return this._cameraPosition;
}
get projectionMatrix() {
return this._projectionMatrix;
}
get modelViewProjectionMatrix() {
return this._viewProjMatrix;
}
get inverseProjectionMatrix() {
return this._invProjMatrix;
}
get mercatorMatrix() {
return this._mercatorMatrix;
}
getVisibleUnwrappedCoordinates(tileID) {
const result = [new UnwrappedTileID(0, tileID)];
if (this._helper._renderWorldCopies) {
const utl = this.screenPointToMercatorCoordinate(new Point(0, 0));
const utr = this.screenPointToMercatorCoordinate(new Point(this._helper._width, 0));
const ubl = this.screenPointToMercatorCoordinate(new Point(this._helper._width, this._helper._height));
const ubr = this.screenPointToMercatorCoordinate(new Point(0, this._helper._height));
const w0 = Math.floor(Math.min(utl.x, utr.x, ubl.x, ubr.x));
const w1 = Math.floor(Math.max(utl.x, utr.x, ubl.x, ubr.x));
const extraWorldCopy = 1;
for (let w = w0 - extraWorldCopy; w <= w1 + extraWorldCopy; w++) {
if (w === 0) continue;
result.push(new UnwrappedTileID(w, tileID));
}
}
return result;
}
getCameraFrustum() {
return Frustum.fromInvProjectionMatrix(this._invViewProjMatrix, this.worldSize);
}
getClippingPlane() {
return null;
}
getCoveringTilesDetailsProvider() {
return this._coveringTilesDetailsProvider;
}
recalculateZoomAndCenter(terrain) {
const center = this.screenPointToLocation(this.centerPoint, terrain);
const elevation = terrain ? terrain.getElevationForLngLatZoom(center, this._helper._tileZoom) : 0;
this._helper.recalculateZoomAndCenter(elevation);
}
/**
* Moves the center so that `lnglat`, on the ground at `elevation` meters, renders
* at the screen `point`. Both rays are cast through the same inverse pixel matrix
* so its inversion error cancels out of their difference; the current-center ray
* must be intersected at the center's own elevation (z=0) — intersecting it with
* the elevated plane would land `(elevation - centerElevation)·tan(pitch)` away
* from the center and make repeated calls drift.
*/
setLocationAtPoint(lnglat, point, elevation = this.elevation) {
const z = elevation - this.elevation;
const a = this.screenPointToMercatorCoordinateAtZ(point, z);
const b = this.screenPointToMercatorCoordinateAtZ(this.centerPoint, 0);
const loc = MercatorCoordinate.fromLngLat(lnglat);
const newCenter = new MercatorCoordinate(loc.x - (a.x - b.x), loc.y - (a.y - b.y));
this.setCenter(newCenter?.toLngLat());
if (this._helper._renderWorldCopies) this.setCenter(this.center.wrap());
}
locationToScreenPoint(lnglat, terrain) {
return terrain ? this.coordinatePoint(MercatorCoordinate.fromLngLat(lnglat), terrain.getElevationForLngLat(lnglat, this), this._pixelMatrix3D) : this.coordinatePoint(MercatorCoordinate.fromLngLat(lnglat));
}
screenPointToLocation(p, terrain) {
return this.screenPointToMercatorCoordinate(p, terrain)?.toLngLat();
}
screenPointToLocationAtElevation(p, elevation) {
return this.screenPointToMercatorCoordinateAtZ(p, elevation - this.elevation)?.toLngLat();
}
screenPointToMercatorCoordinate(p, terrain) {
if (terrain) {
const coordinate = terrain.pointCoordinate(p);
if (coordinate != null) return coordinate;
}
return this.screenPointToMercatorCoordinateAtZ(p);
}
/**
* Intersects the ray through a screen point with the horizontal plane at `z`,
* given in meters relative to the plane at the center's elevation (not mercator units).
*/
screenPointToMercatorCoordinateAtZ(p, z) {
const targetZ = z ? z : 0;
const coord0 = [
p.x,
p.y,
0,
1
];
const coord1 = [
p.x,
p.y,
1,
1
];
transformMat4(coord0, coord0, this._pixelMatrixInverse);
transformMat4(coord1, coord1, this._pixelMatrixInverse);
const w0 = coord0[3];
const w1 = coord1[3];
const x0 = coord0[0] / w0;
const x1 = coord1[0] / w1;
const y0 = coord0[1] / w0;
const y1 = coord1[1] / w1;
const z0 = coord0[2] / w0;
const z1 = coord1[2] / w1;
const t = z0 === z1 ? 0 : (targetZ - z0) / (z1 - z0);
return new MercatorCoordinate(interpolateFactory.number(x0, x1, t) / this.worldSize, interpolateFactory.number(y0, y1, t) / this.worldSize, targetZ);
}
/**
* Given a coordinate, return the screen point that corresponds to it
* @param coord - the coordinates
* @param elevation - the elevation
* @param pixelMatrix - the pixel matrix
* @returns screen point
*/
coordinatePoint(coord, elevation = 0, pixelMatrix = this._pixelMatrix) {
const p = [
coord.x * this.worldSize,
coord.y * this.worldSize,
elevation,
1
];
transformMat4(p, p, pixelMatrix);
return new Point(p[0] / p[3], p[1] / p[3]);
}
getBounds() {
const top = Math.max(0, this._helper._height / 2 - getMercatorHorizon(this));
return new LngLatBounds().extend(this.screenPointToLocation(new Point(0, top))).extend(this.screenPointToLocation(new Point(this._helper._width, top))).extend(this.screenPointToLocation(new Point(this._helper._width, this._helper._height))).extend(this.screenPointToLocation(new Point(0, this._helper._height)));
}
isPointOnMapSurface(p, terrain) {
if (terrain) return terrain.pointCoordinate(p) != null;
return p.y > this.height / 2 - getMercatorHorizon(this);
}
calculatePosMatrix(tileID, aligned = false, useFloat32 = false) {
const posMatrixKey = tileID.key ?? calculateTileKey(tileID.wrap, tileID.canonical.z, tileID.canonical.z, tileID.canonical.x, tileID.canonical.y);
const cache = aligned ? this._alignedPosMatrixCache : this._posMatrixCache;
if (cache.has(posMatrixKey)) {
const matrices = cache.get(posMatrixKey);
return useFloat32 ? matrices.f32 : matrices.f64;
}
const tileMatrix = calculateTileMatrix(tileID, this.worldSize);
multiply(tileMatrix, aligned ? this._alignedProjMatrix : this._viewProjMatrix, tileMatrix);
const matrices = {
f64: tileMatrix,
f32: new Float32Array(tileMatrix)
};
cache.set(posMatrixKey, matrices);
return useFloat32 ? matrices.f32 : matrices.f64;
}
calculateFogMatrix(unwrappedTileID) {
const posMatrixKey = unwrappedTileID.key;
const cache = this._fogMatrixCacheF32;
if (cache.has(posMatrixKey)) return cache.get(posMatrixKey);
const fogMatrix = calculateTileMatrix(unwrappedTileID, this.worldSize);
multiply(fogMatrix, this._fogMatrix, fogMatrix);
cache.set(posMatrixKey, new Float32Array(fogMatrix));
return cache.get(posMatrixKey);
}
calculateCenterFromCameraLngLatAlt(lnglat, alt, bearing, pitch) {
return this._helper.calculateCenterFromCameraLngLatAlt(lnglat, alt, bearing, pitch);
}
_calculateNearFarZIfNeeded(cameraToSeaLevelDistance, limitedPitchRadians, offset) {
if (!this._helper.autoCalculateNearFarZ) return;
const minElevation = Math.min(this.elevation, this.minElevationForCurrentTile, this.getCameraAltitude() - 100);
const cameraToLowestPointDistance = cameraToSeaLevelDistance - minElevation * this._helper._pixelPerMeter / Math.cos(limitedPitchRadians);
const lowestPlane = minElevation < 0 ? cameraToLowestPointDistance : cameraToSeaLevelDistance;
const groundAngle = Math.PI / 2 + this.pitchInRadians;
const fovAboveCenter = degreesToRadians(this.fov) * (Math.abs(Math.cos(degreesToRadians(this.roll))) * this.height + Math.abs(Math.sin(degreesToRadians(this.roll))) * this.width) / this.height * (.5 + offset.y / this.height);
const topHalfSurfaceDistance = Math.sin(fovAboveCenter) * lowestPlane / Math.sin(clamp(Math.PI - groundAngle - fovAboveCenter, .01, Math.PI - .01));
const horizon = getMercatorHorizon(this);
const horizonAngle = Math.atan(horizon / this._helper.cameraToCenterDistance);
const minFovCenterToHorizonRadians = degreesToRadians(90 - maxMercatorHorizonAngle);
const fovCenterToHorizon = horizonAngle > minFovCenterToHorizonRadians ? 2 * horizonAngle * (.5 + offset.y / (horizon * 2)) : minFovCenterToHorizonRadians;
const topHalfSurfaceDistanceHorizon = Math.sin(fovCenterToHorizon) * lowestPlane / Math.sin(clamp(Math.PI - groundAngle - fovCenterToHorizon, .01, Math.PI - .01));
const topHalfMinDistance = Math.min(topHalfSurfaceDistance, topHalfSurfaceDistanceHorizon);
this._helper._farZ = (Math.cos(Math.PI / 2 - limitedPitchRadians) * topHalfMinDistance + lowestPlane) * 1.01;
this._helper._nearZ = this._helper._height / 50;
}
_calcMatrices() {
if (!this._helper._height) return;
const offset = this.centerOffset;
const point = projectToWorldCoordinates(this.worldSize, this.center);
const x = point.x, y = point.y;
this._helper._pixelPerMeter = mercatorZfromAltitude(1, this.center.lat) * this.worldSize;
const limitedPitchRadians = degreesToRadians(Math.min(this.pitch, maxMercatorHorizonAngle));
const cameraToSeaLevelDistance = Math.max(this._helper.cameraToCenterDistance / 2, this._helper.cameraToCenterDistance + this._helper._elevation * this._helper._pixelPerMeter / Math.cos(limitedPitchRadians));
this._calculateNearFarZIfNeeded(cameraToSeaLevelDistance, limitedPitchRadians, offset);
let m;
m = /* @__PURE__ */ new Float64Array(16);
perspective(m, this.fovInRadians, this._helper._width / this._helper._height, this._helper._nearZ, this._helper._farZ);
this._invProjMatrix = /* @__PURE__ */ new Float64Array(16);
fastInvertProjMat4(this._invProjMatrix, m);
m[8] = -offset.x * 2 / this._helper._width;
m[9] = offset.y * 2 / this._helper._height;
this._projectionMatrix = clone$1(m);
scale(m, m, [
1,
-1,
1
]);
translate(m, m, [
0,
0,
-this._helper.cameraToCenterDistance
]);
rotateZ(m, m, -this.rollInRadians);
rotateX(m, m, this.pitchInRadians);
rotateZ(m, m, -this.bearingInRadians);
translate(m, m, [
-x,
-y,
0
]);
this._mercatorMatrix = scale([], m, [
this.worldSize,
this.worldSize,
this.worldSize
]);
scale(m, m, [
1,
1,
this._helper._pixelPerMeter
]);
this._pixelMatrix = multiply(/* @__PURE__ */ new Float64Array(16), this.clipSpaceToPixelsMatrix, m);
translate(m, m, [
0,
0,
-this.elevation
]);
this._viewProjMatrix = m;
this._invViewProjMatrix = invert$1([], m);
const cameraPos = [
0,
0,
-1,
1
];
transformMat4(cameraPos, cameraPos, this._invViewProjMatrix);
this._cameraPosition = [
cameraPos[0] / cameraPos[3],
cameraPos[1] / cameraPos[3],
cameraPos[2] / cameraPos[3]
];
this._fogMatrix = /* @__PURE__ */ new Float64Array(16);
perspective(this._fogMatrix, this.fovInRadians, this.width / this.height, cameraToSeaLevelDistance, this._helper._farZ);
this._fogMatrix[8] = -offset.x * 2 / this.width;
this._fogMatrix[9] = offset.y * 2 / this.height;
scale(this._fogMatrix, this._fogMatrix, [
1,
-1,
1
]);
translate(this._fogMatrix, this._fogMatrix, [
0,
0,
-this.cameraToCenterDistance
]);
rotateZ(this._fogMatrix, this._fogMatrix, -this.rollInRadians);
rotateX(this._fogMatrix, this._fogMatrix, this.pitchInRadians);
rotateZ(this._fogMatrix, this._fogMatrix, -this.bearingInRadians);
translate(this._fogMatrix, this._fogMatrix, [
-x,
-y,
0
]);
scale(this._fogMatrix, this._fogMatrix, [
1,
1,
this._helper._pixelPerMeter
]);
translate(this._fogMatrix, this._fogMatrix, [
0,
0,
-this.elevation
]);
this._pixelMatrix3D = multiply(/* @__PURE__ */ new Float64Array(16), this.clipSpaceToPixelsMatrix, m);
const xShift = this._helper._width % 2 / 2, yShift = this._helper._height % 2 / 2, angleCos = Math.cos(this.bearingInRadians), angleSin = Math.sin(-this.bearingInRadians), dx = x - Math.round(x) + angleCos * xShift + angleSin * yShift, dy = y - Math.round(y) + angleCos * yShift + angleSin * xShift;
const alignedM = new Float64Array(m);
translate(alignedM, alignedM, [
dx > .5 ? dx - 1 : dx,
dy > .5 ? dy - 1 : dy,
0
]);
this._alignedProjMatrix = alignedM;
m = invert$1(/* @__PURE__ */ new Float64Array(16), this._pixelMatrix);
if (!m) throw new Error("failed to invert matrix");
this._pixelMatrixInverse = m;
this._clearMatrixCaches();
}
_clearMatrixCaches() {
this._posMatrixCache.clear();
this._alignedPosMatrixCache.clear();
this._fogMatrixCacheF32.clear();
}
maxPitchScaleFactor() {
if (!this._pixelMatrixInverse) return 1;
const coord = this.screenPointToMercatorCoordinate(new Point(0, 0));
const p = [
coord.x * this.worldSize,
coord.y * this.worldSize,
0,
1
];
return transformMat4(p, p, this._pixelMatrix)[3] / this._helper.cameraToCenterDistance;
}
getCameraPoint() {
return this._helper.getCameraPoint();
}
getCameraAltitude() {
return this._helper.getCameraAltitude();
}
getCameraLngLat() {
const pixelPerMeter = mercatorZfromAltitude(1, this.center.lat) * this.worldSize;
const cameraToCenterDistanceMeters = this._helper.cameraToCenterDistance / pixelPerMeter;
return cameraMercatorCoordinateFromCenterAndRotation(this.center, this.elevation, this.pitch, this.bearing, cameraToCenterDistanceMeters).toLngLat();
}
lngLatToCameraDepth(lngLat, elevation) {
const coord = MercatorCoordinate.fromLngLat(lngLat);
const p = [
coord.x * this.worldSize,
coord.y * this.worldSize,
elevation,
1
];
transformMat4(p, p, this._viewProjMatrix);
return p[2] / p[3];
}
getProjectionData(params) {
const { overscaledTileID, aligned, applyTerrainMatrix } = params;
const mercatorTileCoordinates = this._helper.getMercatorTileCoordinates(overscaledTileID);
const tilePosMatrix = overscaledTileID ? this.calculatePosMatrix(overscaledTileID, aligned, true) : null;
let mainMatrix;
if (overscaledTileID?.terrainRttPosMatrix32f && applyTerrainMatrix) mainMatrix = overscaledTileID.terrainRttPosMatrix32f;
else if (tilePosMatrix) mainMatrix = tilePosMatrix;
else mainMatrix = createIdentityMat4f32();
return {
mainMatrix,
tileMercatorCoords: mercatorTileCoordinates,
clippingPlane: [
0,
0,
0,
0
],
projectionTransition: 0,
fallbackMatrix: mainMatrix,
clipAntimeridian: false
};
}
isLocationOccluded(_) {
return false;
}
getPixelScale() {
return 1;
}
getCircleRadiusCorrection() {
return 1;
}
getPitchedTextCorrection(_textAnchorX, _textAnchorY, _tileID) {
return 1;
}
transformLightDirection(dir) {
return clone(dir);
}
getRayDirectionFromPixel(_p) {
throw new Error("Not implemented.");
}
projectTileCoordinates(x, y, unwrappedTileID, getElevation) {
const matrix = this.calculatePosMatrix(unwrappedTileID);
let pos;
if (getElevation) {
pos = [
x,
y,
getElevation(x, y),
1
];
transformMat4(pos, pos, matrix);
} else {
pos = [
x,
y,
0,
1
];
xyTransformMat4(pos, pos, matrix);
}
const w = pos[3];
return {
point: new Point(pos[0] / w, pos[1] / w),
signedDistanceFromCamera: w,
isOccluded: false
};
}
populateCache(coords) {
for (const coord of coords) this.calculatePosMatrix(coord);
}
getProjectionDataForCustomLayer(applyGlobeMatrix = true) {
const tileID = new OverscaledTileID(0, 0, 0, 0, 0);
const rendererProjectionData = this.getProjectionData({
overscaledTileID: tileID,
applyGlobeMatrix
});
const tileMatrix = calculateTileMatrix(tileID, this.worldSize);
multiply(tileMatrix, this._viewProjMatrix, tileMatrix);
const scale$4 = [
EXTENT,
EXTENT,
this.worldSize / this._helper.pixelsPerMeter
];
const projectionMatrixScaled = createMat4f64();
scale(projectionMatrixScaled, tileMatrix, scale$4);
return {
...rendererProjectionData,
tileMercatorCoords: [
0,
0,
1,
1
],
fallbackMatrix: projectionMatrixScaled,
mainMatrix: projectionMatrixScaled
};
}
getFastPathSimpleProjectionMatrix(tileID) {
return this.calculatePosMatrix(tileID);
}
};
//#endregion
//#region src/geo/projection/camera_helper.ts
/**
* @internal
*/
function cameraBoundsWarning() {
warnOnce("Map cannot fit within canvas with the given bounds, padding, and/or offset.");
}
/**
* @internal
* Set a transform's rotation to a value interpolated between startEulerAngles and endEulerAngles
*/
function updateRotation(args) {
if (args.useSlerp) {
if (args.k < 1) {
const startRotation = rollPitchBearingToQuat(args.startEulerAngles.roll, args.startEulerAngles.pitch, args.startEulerAngles.bearing);
const endRotation = rollPitchBearingToQuat(args.endEulerAngles.roll, args.endEulerAngles.pitch, args.endEulerAngles.bearing);
const rotation = /* @__PURE__ */ new Float64Array(4);
slerp(rotation, startRotation, endRotation, args.k);
const eulerAngles = getRollPitchBearing(rotation);
args.tr.setRoll(eulerAngles.roll);
args.tr.setPitch(eulerAngles.pitch);
args.tr.setBearing(eulerAngles.bearing);
} else {
args.tr.setRoll(args.endEulerAngles.roll);
args.tr.setPitch(args.endEulerAngles.pitch);
args.tr.setBearing(args.endEulerAngles.bearing);
}
} else {
args.tr.setRoll(interpolateFactory.number(args.startEulerAngles.roll, args.endEulerAngles.roll, args.k));
args.tr.setPitch(interpolateFactory.number(args.startEulerAngles.pitch, args.endEulerAngles.pitch, args.k));
args.tr.setBearing(interpolateFactory.number(args.startEulerAngles.bearing, args.endEulerAngles.bearing, args.k));
}
}
function cameraForBoxAndBearing(options, padding, bounds, bearing, tr) {
const edgePadding = tr.padding;
const nwWorld = projectToWorldCoordinates(tr.worldSize, bounds.getNorthWest());
const neWorld = projectToWorldCoordinates(tr.worldSize, bounds.getNorthEast());
const seWorld = projectToWorldCoordinates(tr.worldSize, bounds.getSouthEast());
const swWorld = projectToWorldCoordinates(tr.worldSize, bounds.getSouthWest());
const bearingRadians = degreesToRadians(-bearing);
const nwRotatedWorld = nwWorld.rotate(bearingRadians);
const neRotatedWorld = neWorld.rotate(bearingRadians);
const seRotatedWorld = seWorld.rotate(bearingRadians);
const swRotatedWorld = swWorld.rotate(bearingRadians);
const upperRight = new Point(Math.max(nwRotatedWorld.x, neRotatedWorld.x, swRotatedWorld.x, seRotatedWorld.x), Math.max(nwRotatedWorld.y, neRotatedWorld.y, swRotatedWorld.y, seRotatedWorld.y));
const lowerLeft = new Point(Math.min(nwRotatedWorld.x, neRotatedWorld.x, swRotatedWorld.x, seRotatedWorld.x), Math.min(nwRotatedWorld.y, neRotatedWorld.y, swRotatedWorld.y, seRotatedWorld.y));
const size = upperRight.sub(lowerLeft);
const availableWidth = tr.width - (edgePadding.left + edgePadding.right + padding.left + padding.right);
const availableHeight = tr.height - (edgePadding.top + edgePadding.bottom + padding.top + padding.bottom);
const scaleX = availableWidth / size.x;
const scaleY = availableHeight / size.y;
if (scaleY < 0 || scaleX < 0) {
cameraBoundsWarning();
return;
}
const zoom = Math.min(scaleZoom(tr.scale * Math.min(scaleX, scaleY)), options.maxZoom);
const offset = Point.convert(options.offset);
const paddingOffsetX = (padding.left - padding.right) / 2;
const paddingOffsetY = (padding.top - padding.bottom) / 2;
const rotatedPaddingOffset = new Point(paddingOffsetX, paddingOffsetY).rotate(degreesToRadians(bearing));
const offsetAtFinalZoom = offset.add(rotatedPaddingOffset).mult(tr.scale / zoomScale(zoom));
return {
center: unprojectFromWorldCoordinates(tr.worldSize, nwWorld.add(seWorld).div(2).sub(offsetAtFinalZoom)),
zoom,
bearing
};
}
//#endregion
//#region src/geo/projection/mercator_camera_helper.ts
/**
* @internal
*/
var MercatorCameraHelper = class {
get useGlobeControls() {
return false;
}
handlePanInertia(pan, transform) {
const offsetLength = pan.mag();
const pixelsToHorizon = Math.abs(getMercatorHorizon(transform));
return {
easingOffset: pan.mult(Math.min(pixelsToHorizon * .75 / offsetLength, 1)),
easingCenter: transform.center
};
}
handleMapControlsRollPitchBearingZoom(deltas, tr) {
if (deltas.bearingDelta) tr.setBearing(tr.bearing + deltas.bearingDelta);
if (deltas.pitchDelta) tr.setPitch(tr.pitch + deltas.pitchDelta);
if (deltas.rollDelta) tr.setRoll(tr.roll + deltas.rollDelta);
if (deltas.zoomDelta) tr.setZoom(tr.zoom + deltas.zoomDelta);
}
handleMapControlsPan(deltas, tr, preZoomAroundLoc) {
if (deltas.around.distSqr(tr.centerPoint) < .01) return;
tr.setLocationAtPoint(preZoomAroundLoc, deltas.around, deltas.aroundElevation);
}
cameraForBoxAndBearing(options, padding, bounds, bearing, tr) {
return cameraForBoxAndBearing(options, padding, bounds, bearing, tr);
}
handleJumpToCenterZoom(tr, options) {
const zoom = typeof options.zoom !== "undefined" ? +options.zoom : tr.zoom;
if (tr.zoom !== zoom) tr.setZoom(+options.zoom);
if (options.center !== void 0) tr.setCenter(LngLat.convert(options.center));
}
handleEaseTo(tr, options) {
const startZoom = tr.zoom;
const startPadding = tr.padding;
const startEulerAngles = {
roll: tr.roll,
pitch: tr.pitch,
bearing: tr.bearing
};
const endEulerAngles = {
roll: options.roll === void 0 ? tr.roll : options.roll,
pitch: options.pitch === void 0 ? tr.pitch : options.pitch,
bearing: options.bearing === void 0 ? tr.bearing : options.bearing
};
const optionsZoom = typeof options.zoom !== "undefined";
const doPadding = !tr.isPaddingEqual(options.padding);
let isZooming = false;
const zoom = optionsZoom ? +options.zoom : tr.zoom;
let pointAtOffset = tr.centerPoint.add(options.offsetAsPoint);
const locationAtOffset = tr.screenPointToLocation(pointAtOffset);
const { center, zoom: endZoom } = tr.applyConstrain(LngLat.convert(options.center || locationAtOffset), zoom ?? startZoom);
normalizeCenter(tr, center);
const from = projectToWorldCoordinates(tr.worldSize, locationAtOffset);
const delta = projectToWorldCoordinates(tr.worldSize, center).sub(from);
const finalScale = zoomScale(endZoom - startZoom);
isZooming = endZoom !== startZoom;
const easeFunc = (k) => {
if (isZooming) tr.setZoom(interpolateFactory.number(startZoom, endZoom, k));
if (!rollPitchBearingEqual(startEulerAngles, endEulerAngles)) updateRotation({
startEulerAngles,
endEulerAngles,
tr,
k,
useSlerp: startEulerAngles.roll != endEulerAngles.roll
});
if (doPadding) {
tr.interpolatePadding(startPadding, options.padding, k);
pointAtOffset = tr.centerPoint.add(options.offsetAsPoint);
}
if (options.around) tr.setLocationAtPoint(options.around, options.aroundPoint);
else {
const scale = zoomScale(tr.zoom - startZoom);
const speedup = Math.pow(endZoom > startZoom ? Math.min(2, finalScale) : Math.max(.5, finalScale), 1 - k);
const newCenter = unprojectFromWorldCoordinates(tr.worldSize, from.add(delta.mult(k * speedup)).mult(scale));
tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset);
}
};
return {
easeFunc,
isZooming,
elevationCenter: center
};
}
handleFlyTo(tr, options) {
const optionsZoom = typeof options.zoom !== "undefined";
const startZoom = tr.zoom;
const constrained = tr.applyConstrain(LngLat.convert(options.center || options.locationAtOffset), optionsZoom ? +options.zoom : startZoom);
const targetCenter = constrained.center;
const targetZoom = constrained.zoom;
normalizeCenter(tr, targetCenter);
const startWorldSize = tr.worldSize;
const from = projectToWorldCoordinates(startWorldSize, options.locationAtOffset);
const delta = projectToWorldCoordinates(startWorldSize, targetCenter).sub(from);
const pixelPathLength = delta.mag();
const scaleOfZoom = zoomScale(targetZoom - startZoom);
const requestedMinZoom = typeof options.minZoom !== "undefined" ? +options.minZoom : tr.minZoom;
const effectiveMinZoom = Math.max(requestedMinZoom, tr.minZoom);
const minZoomPreConstrain = Math.min(effectiveMinZoom, startZoom, targetZoom);
const minZoom = tr.applyConstrain(targetCenter, minZoomPreConstrain).zoom;
const scaleOfMinZoom = zoomScale(minZoom - startZoom);
const easeFunc = (k, scale, centerFactor, pointAtOffset) => {
tr.setZoom(k === 1 ? targetZoom : startZoom + scaleZoom(scale));
const newCenter = k === 1 ? targetCenter : unprojectFromWorldCoordinates(startWorldSize, from.add(delta.mult(centerFactor)));
tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset);
};
return {
easeFunc,
scaleOfZoom,
targetCenter,
scaleOfMinZoom,
pixelPathLength
};
}
};
//#endregion
//#region src/style/projection_properties.g.ts
let properties;
const getProperties = () => properties = properties || new Properties({ "type": new DataConstantProperty(latest["projection"]["type"], "type") });
//#endregion
//#region src/geo/projection/vertical_perspective_projection.ts
const VerticalPerspectiveShaderDefine = "#define GLOBE";
const VerticalPerspectiveShaderVariantKey = "globe";
const granularitySettingsGlobe = new SubdivisionGranularitySetting({
fill: new SubdivisionGranularityExpression(128, 2),
line: new SubdivisionGranularityExpression(512, 0),
tile: new SubdivisionGranularityExpression(128, 32),
stencil: new SubdivisionGranularityExpression(128, 1),
circle: 3
});
var VerticalPerspectiveProjection = class {
constructor() {
this._tileMeshCache = {};
}
get name() {
return "vertical-perspective";
}
get transitionState() {
return 1;
}
get useSubdivision() {
return true;
}
get shaderVariantName() {
return VerticalPerspectiveShaderVariantKey;
}
get shaderDefine() {
return VerticalPerspectiveShaderDefine;
}
get shaderPreludeCode() {
return shaders.projectionGlobe;
}
get vertexShaderPreludeCode() {
return shaders.projectionMercator.vertexSource;
}
get subdivisionGranularity() {
return granularitySettingsGlobe;
}
get useGlobeControls() {
return true;
}
destroy() {}
_getMeshKey(options) {
return `${options.granularity.toString(36)}_${options.generateBorders ? "b" : ""}${options.extendToNorthPole ? "n" : ""}${options.extendToSouthPole ? "s" : ""}`;
}
getMeshFromTileID(context, canonical, hasBorder, allowPoles, usage) {
const granularity = (usage === "stencil" ? granularitySettingsGlobe.stencil : granularitySettingsGlobe.tile).getGranularityForZoomLevel(canonical.z);
const north = canonical.y === 0 && allowPoles;
const south = canonical.y === (1 << canonical.z) - 1 && allowPoles;
return this._getMesh(context, {
granularity,
generateBorders: hasBorder,
extendToNorthPole: north,
extendToSouthPole: south
});
}
_getMesh(context, options) {
const key = this._getMeshKey(options);
if (key in this._tileMeshCache) return this._tileMeshCache[key];
const mesh = createTileMeshWithBuffers(context, options);
this._tileMeshCache[key] = mesh;
return mesh;
}
recalculate(_params) {}
hasTransition() {
return false;
}
};
//#endregion
//#region src/geo/projection/globe_projection.ts
var GlobeProjection = class extends Evented {
constructor(projection, globalState) {
super();
this._transitionable = new Transitionable(getProperties(), "projection", globalState);
this.setProjection(projection);
this._transitioning = this._transitionable.untransitioned();
this.recalculate(new EvaluationParameters(0));
this._mercatorProjection = new MercatorProjection();
this._verticalPerspectiveProjection = new VerticalPerspectiveProjection();
}
get transitionState() {
const currentProjectionSpecValue = this.properties.get("type");
if (typeof currentProjectionSpecValue === "string" && currentProjectionSpecValue === "mercator") return 0;
if (typeof currentProjectionSpecValue === "string" && currentProjectionSpecValue === "vertical-perspective") return 1;
if (currentProjectionSpecValue instanceof ProjectionDefinition) {
if (currentProjectionSpecValue.from === currentProjectionSpecValue.to) return currentProjectionSpecValue.from === "mercator" ? 0 : 1;
if (currentProjectionSpecValue.from === "vertical-perspective" && currentProjectionSpecValue.to === "mercator") return 1 - currentProjectionSpecValue.transition;
if (currentProjectionSpecValue.from === "mercator" && currentProjectionSpecValue.to === "vertical-perspective") return currentProjectionSpecValue.transition;
}
return 1;
}
get useGlobeRendering() {
return this.transitionState > 0;
}
get currentProjection() {
return this.useGlobeRendering ? this._verticalPerspectiveProjection : this._mercatorProjection;
}
get name() {
return "globe";
}
get useSubdivision() {
return this.currentProjection.useSubdivision;
}
get shaderVariantName() {
return this.currentProjection.shaderVariantName;
}
get shaderDefine() {
return this.currentProjection.shaderDefine;
}
get shaderPreludeCode() {
return this.currentProjection.shaderPreludeCode;
}
get vertexShaderPreludeCode() {
return this.currentProjection.vertexShaderPreludeCode;
}
get subdivisionGranularity() {
return this.currentProjection.subdivisionGranularity;
}
get useGlobeControls() {
return this.transitionState > 0;
}
destroy() {
this._mercatorProjection.destroy();
this._verticalPerspectiveProjection.destroy();
}
getMeshFromTileID(context, _tileID, _hasBorder, _allowPoles, _usage) {
return this.currentProjection.getMeshFromTileID(context, _tileID, _hasBorder, _allowPoles, _usage);
}
setProjection(projection) {
this._transitionable.setValue("type", projection?.type || "mercator");
}
updateTransitions(parameters) {
this._transitioning = this._transitionable.transitioned(parameters, this._transitioning);
}
hasTransition() {
return this._transitioning.hasTransition() || this.currentProjection.hasTransition();
}
recalculate(parameters) {
this.properties = this._transitioning.possiblyEvaluate(parameters);
}
};
//#endregion
//#region src/geo/projection/globe_utils.ts
function getGlobeCircumferencePixels(transform) {
const radius = getGlobeRadiusPixels(transform.worldSize, transform.center.lat);
return 2 * Math.PI * radius;
}
function globeDistanceOfLocationsPixels(transform, a, b) {
const vecA = angularCoordinatesToSurfaceVector(a);
const vecB = angularCoordinatesToSurfaceVector(b);
const dot$2 = dot(vecA, vecB);
const radians = Math.acos(dot$2);
const circumference = getGlobeCircumferencePixels(transform);
return radians / (2 * Math.PI) * circumference;
}
/**
* For given mercator coordinates in range 0..1, returns the angular coordinates on the sphere's surface, in radians.
*/
function mercatorCoordinatesToAngularCoordinatesRadians(mercatorX, mercatorY) {
return [mod(mercatorX * Math.PI * 2 + Math.PI, Math.PI * 2), 2 * Math.atan(Math.exp(Math.PI - mercatorY * Math.PI * 2)) - Math.PI * .5];
}
/**
* For a given longitude and latitude (note: in radians) returns the normalized vector from the planet center to the specified place on the surface.
* @param lngRadians - Longitude in radians.
* @param latRadians - Latitude in radians.
*/
function angularCoordinatesRadiansToVector(lngRadians, latRadians) {
const len = Math.cos(latRadians);
const vec = /* @__PURE__ */ new Float64Array(3);
vec[0] = Math.sin(lngRadians) * len;
vec[1] = Math.sin(latRadians);
vec[2] = Math.cos(lngRadians) * len;
return vec;
}
/**
* Projects a point within a tile to the surface of the unit sphere globe.
* @param inTileX - X coordinate inside the tile in range [0 .. 8192].
* @param inTileY - Y coordinate inside the tile in range [0 .. 8192].
* @param tileIdX - Tile's X coordinate in range [0 .. 2^zoom - 1].
* @param tileIdY - Tile's Y coordinate in range [0 .. 2^zoom - 1].
* @param tileIdZ - Tile's zoom.
* @returns A 3D vector - coordinates of the projected point on a unit sphere.
*/
function projectTileCoordinatesToSphere(inTileX, inTileY, tileIdX, tileIdY, tileIdZ) {
const scale = 1 / (1 << tileIdZ);
const mercatorX = inTileX / EXTENT * scale + tileIdX * scale;
const mercatorY = inTileY / EXTENT * scale + tileIdY * scale;
const sphericalX = mod(mercatorX * Math.PI * 2 + Math.PI, Math.PI * 2);
const sphericalY = 2 * Math.atan(Math.exp(Math.PI - mercatorY * Math.PI * 2)) - Math.PI * .5;
const len = Math.cos(sphericalY);
const vec = /* @__PURE__ */ new Float64Array(3);
vec[0] = Math.sin(sphericalX) * len;
vec[1] = Math.sin(sphericalY);
vec[2] = Math.cos(sphericalX) * len;
return vec;
}
/**
* For a given longitude and latitude (note: in degrees) returns the normalized vector from the planet center to the specified place on the surface.
*/
function angularCoordinatesToSurfaceVector(lngLat) {
return angularCoordinatesRadiansToVector(lngLat.lng * Math.PI / 180, lngLat.lat * Math.PI / 180);
}
function getGlobeRadiusPixels(worldSize, latitudeDegrees) {
return worldSize / (2 * Math.PI) / Math.cos(latitudeDegrees * Math.PI / 180);
}
/**
* Given a 3D point on the surface of a unit sphere, returns its angular coordinates in degrees.
* The input vector must be normalized.
*/
function sphereSurfacePointToCoordinates(surface) {
const latDegrees = Math.asin(surface[1]) / Math.PI * 180;
const lengthXZ = Math.sqrt(surface[0] * surface[0] + surface[2] * surface[2]);
if (lengthXZ > 1e-6) {
const projX = surface[0] / lengthXZ;
const projZ = surface[2] / lengthXZ;
const acosZ = Math.acos(projZ);
const lngDegrees = (projX > 0 ? acosZ : -acosZ) / Math.PI * 180;
return new LngLat(wrap(lngDegrees, -180, 180), latDegrees);
} else return new LngLat(0, latDegrees);
}
/**
* Returns the globe orientation quaternion for the given map center and bearing.
* The inverse of {@link lngLatBearingFromOrientation}.
*/
function orientationFromLngLatBearing(lngLat, bearing) {
return fromEuler(createVec4f64(), -lngLat.lng, -lngLat.lat, bearing);
}
/**
* Given a globe orientation quaternion, returns the corresponding map center and bearing.
* The inverse of {@link orientationFromLngLatBearing}.
*/
function lngLatBearingFromOrientation(q) {
const x = q[0], y = q[1], z = q[2], w = q[3];
return {
lng: -Math.atan2(2 * (w * x + y * z), 1 - 2 * (x * x + y * y)) * 180 / Math.PI,
lat: -Math.asin(clamp(2 * (w * y - z * x), -1, 1)) * 180 / Math.PI,
bearing: Math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)) * 180 / Math.PI
};
}
/** Kept just below a half turn so the center cannot land exactly on the far side of the globe. */
const PAN_MAX_ANGLE = Math.PI * .98;
/**
* Returns the point on the globe that a drag towards `point` should aim at.
*
* Exact tracking breaks down at the silhouette: the ray meets the globe at `asin(D sin a) - a`,
* whose slope runs away to infinity as the ray goes tangent, and past it there is no intersection
* at all. So the exact curve is left {@link PAN_FALLOFF_BAND} early and continued with a hyperbola
* matching it in value and slope, easing off and saturating short of the far side. Bell's virtual
* trackball takes the same idea of easing a sphere into a hyperbola before the rim, though it fits
* the curve differently: SGI's `trackball.c`, described in Henriksen, Sporring and Hornbæk,
* "Virtual Trackballs Revisited", IEEE TVCG 10(2):206-216, 2004.
*
* The angle comes from atan2, so a ray pointing away from the globe is a wide angle the falloff
* saturates rather than a case to reject.
* @param tr - The transform being dragged.
* @param point - The cursor position.
*/
function panSurfaceLocation(tr, point) {
const origin = tr.cameraPosition;
const distance = length$1(origin);
if (distance <= 1) return tr.screenPointToLocation(point);
const u = createVec3f64();
normalize(u, origin);
const direction = tr.getRayDirectionFromPixel(point);
const c = -dot(direction, u);
const lateral = createVec3f64();
scaleAndAdd(lateral, direction, u, c);
const s = length$1(lateral);
if (s < 1e-9) return tr.screenPointToLocation(point);
const angle = Math.atan2(s, c);
const handoverAngle = Math.asin(1 / distance) * .9;
if (angle < handoverAngle) return tr.screenPointToLocation(point);
const sinHandover = distance * Math.sin(handoverAngle);
const targetAtHandover = Math.asin(clamp(sinHandover, -1, 1)) - handoverAngle;
const slopeAtHandover = distance * Math.cos(handoverAngle) / Math.sqrt(Math.max(1 - sinHandover * sinHandover, 1e-12)) - 1;
const room = PAN_MAX_ANGLE - targetAtHandover;
const excess = angle - handoverAngle;
const target = targetAtHandover + room * (slopeAtHandover * excess) / (room + slopeAtHandover * excess);
const e = createVec3f64();
scale$2(e, lateral, 1 / s);
const surface = createVec3f64();
scale$2(surface, u, Math.cos(clamp(target, 0, PAN_MAX_ANGLE)));
scaleAndAdd(surface, surface, e, Math.sin(clamp(target, 0, PAN_MAX_ANGLE)));
normalize(surface, surface);
return sphereSurfacePointToCoordinates(surface);
}
/**
* Rotates the globe so that the given location appears at the given screen point, by composing
* versors, the unit quaternions that represent rotations. Unlike the bearing-preserving
* {@link ITransform.setLocationAtPoint}, this stays smooth near and across the poles, and keeps
* panning once the cursor leaves the globe.
*
* Note: the delta rotation's axis is in the surface-vector frame of
* {@link angularCoordinatesToSurfaceVector}, while the orientation quaternion uses the Euler frame
* of {@link orientationFromLngLatBearing}, hence the component swizzle where they combine. Zoom is
* adjusted to keep the planet the same size, as `setLocationAtPoint` does.
* @param tr - The transform to rotate.
* @param lnglat - The location to bring under `point`.
* @param point - The screen point that `lnglat` should appear at.
* @param panDelta - The drag's pixel delta. Used to re-derive the previous cursor location through
* {@link panSurfaceLocation}, since both ends of the rotation must come from the same mapping.
* @param fixedBearing - Applies the swing only, keeping the bearing fixed, which is what dragging
* the globe does. Pass `false` to apply the twist about the view axis as well, so that the grabbed
* location tracks the cursor exactly and the bearing drifts with it.
*/
function versorSetLocationAtPoint(tr, lnglat, point, panDelta, fixedBearing = true) {
const pointLngLat = panSurfaceLocation(tr, point);
let sourceLngLat = lnglat;
if (panDelta) sourceLngLat = panSurfaceLocation(tr, point.sub(panDelta));
else if (!tr.isPointOnMapSurface(point)) return;
const vecToPixelCurrent = angularCoordinatesToSurfaceVector(pointLngLat);
const vecToTarget = angularCoordinatesToSurfaceVector(sourceLngLat);
const centerQuat = orientationFromLngLatBearing(tr.center, tr.bearing);
const w = cross(createVec3f64(), vecToTarget, vecToPixelCurrent);
const l = Math.sqrt(dot(w, w));
const t = Math.acos(clamp(dot(vecToTarget, vecToPixelCurrent), -1, 1)) / 2;
const s = Math.sin(t);
const delta = l ? fromValues(w[1] / l * s, -w[0] / l * s, w[2] / l * s, Math.cos(t)) : fromValues(0, 0, 0, 1);
const { lng: newCenterLng, lat: newCenterLat, bearing: newBearing } = lngLatBearingFromOrientation(multiply$1(createVec4f64(), centerQuat, delta));
const oldLat = tr.center.lat;
const oldZoom = tr.zoom;
const finalLat = clamp(newCenterLat, -90, 90);
const finalLng = fixedBearing ? fixedBearingLongitude(tr, point, panDelta, newCenterLng) : newCenterLng;
tr.setCenter(new LngLat(wrap(finalLng, -180, 180), finalLat));
if (!fixedBearing) tr.setBearing(newBearing);
tr.setZoom(oldZoom + getZoomAdjustment(oldLat, tr.center.lat));
}
/**
* Returns the center longitude for a bearing-preserving drag.
*
* The swing longitude becomes ill-conditioned near the pole and the grabbed location slips away
* from the cursor, so within the last ~12 degrees of latitude the cursor is treated as turning a
* dial around the pole, blended in with a smoothstep anchored on {@link MAX_VALID_LATITUDE}, the
* highest latitude the center can reach. The sweep comes from the raw pixel delta rather than a
* round-tripped previous cursor position, which would lose its sign to cancellation at the pole,
* and is damped within {@link DIAL_MIN_RADIUS_PIXELS} so it eases to nothing there instead of
* being dropped, which would leave a spot where the drag could not move at all.
* @param tr - The transform being dragged.
* @param point - The cursor position.
* @param panDelta - The drag's pixel delta, or undefined to use the swing longitude only.
* @param newCenterLng - The swing target longitude.
* @returns the center longitude to apply.
*/
function fixedBearingLongitude(tr, point, panDelta, newCenterLng) {
const oldLng = tr.center.lng;
const oldLat = tr.center.lat;
const poleLat = oldLat >= 0 ? 90 : -90;
const polePoint = tr.locationToScreenPoint(new LngLat(0, poleLat));
const rx = point.x - polePoint.x, ry = point.y - polePoint.y;
const r2 = rx * rx + ry * ry;
const tRamp = clamp(1 - (MAX_VALID_LATITUDE - Math.abs(oldLat)) / 12, 0, 1);
const dial = tRamp * tRamp * (3 - 2 * tRamp);
const dLngSwing = mod(newCenterLng - oldLng + 180, 360) - 180;
let dLngDial = 0;
if (dial > 0 && panDelta) {
const dTheta = (rx * panDelta.y - ry * panDelta.x) / Math.max(r2, 400);
dLngDial = (poleLat > 0 ? 1 : -1) * dTheta * 180 / Math.PI;
}
return oldLng + (1 - dial) * dLngSwing + dial * dLngDial;
}
/**
* Given a normalized horizon plane in Ax+By+Cz+D=0 format, compute the center and radius of
* the circle in that plain that contains the entire visible portion of the unit sphere from horizon
* to horizon.
* @param horizonPlane - The plane that passes through visible horizon in Ax + By + Cz + D = 0 format where mag(A,B,C)=1
* @returns the center point and radius of the disc that passes through the entire visible horizon
*/
function horizonPlaneToCenterAndRadius(horizonPlane) {
const center = createVec3f64();
center[0] = horizonPlane[0] * -horizonPlane[3];
center[1] = horizonPlane[1] * -horizonPlane[3];
center[2] = horizonPlane[2] * -horizonPlane[3];
return {
center,
radius: Math.sqrt(1 - horizonPlane[3] * horizonPlane[3])
};
}
/**
* Computes the closest point on a sphere to `point`.
* @param center - Center of the sphere
* @param radius - Radius of the sphere
* @param point - Point inside or outside the sphere
* @returns A 3d vector of the point on the sphere closest to `point`
*/
function clampToSphere(center, radius, point) {
const relativeToCenter = createVec3f64();
sub(relativeToCenter, point, center);
const clamped = createVec3f64();
scaleAndAdd(clamped, center, relativeToCenter, radius / len(relativeToCenter));
return clamped;
}
function planetScaleAtLatitude(latitudeDegrees) {
return Math.cos(latitudeDegrees * Math.PI / 180);
}
/**
* Computes how much to modify zoom to keep the globe size constant when changing latitude.
* @param transform - An instance of any transform. Does not have any relation on the computed values.
* @param oldLat - Latitude before change, in degrees.
* @param newLat - Latitude after change, in degrees.
* @returns A value to add to zoom level used for old latitude to keep same planet radius at new latitude.
*/
function getZoomAdjustment(oldLat, newLat) {
const oldCircumference = planetScaleAtLatitude(oldLat);
const newCircumference = planetScaleAtLatitude(newLat);
return scaleZoom(newCircumference / oldCircumference);
}
function getDegreesPerPixel(worldSize, lat) {
return 360 / getGlobeCircumferencePixels({
worldSize,
center: { lat }
});
}
/**
* Returns transform's new center rotation after applying panning.
* @param panDelta - Panning delta, in same units as what is supplied to {@link HandlerManager}.
* @param tr - Current transform. This object is not modified by the function.
* @returns New center location to set to the map's transform to apply the specified panning.
*/
function computeGlobePanCenter(panDelta, tr) {
const rotatedPanDelta = panDelta.rotate(tr.bearingInRadians);
const normalizedGlobeZoom = tr.zoom + getZoomAdjustment(tr.center.lat, 0);
const lngSpeed = lerp(1 / planetScaleAtLatitude(tr.center.lat), 1 / planetScaleAtLatitude(Math.min(Math.abs(tr.center.lat), 60)), remapSaturate(normalizedGlobeZoom, 7, 3, 0, 1));
const panningDegreesPerPixel = getDegreesPerPixel(tr.worldSize, tr.center.lat);
return new LngLat(tr.center.lng - rotatedPanDelta.x * panningDegreesPerPixel * lngSpeed, clamp(tr.center.lat + rotatedPanDelta.y * panningDegreesPerPixel, -MAX_VALID_LATITUDE, MAX_VALID_LATITUDE));
}
/**
* Integration of `1 / cos(x)`.
*/
function integrateSecX(x) {
const xHalf = .5 * x;
const sin = Math.sin(xHalf);
const cos = Math.cos(xHalf);
return Math.log(sin + cos) - Math.log(cos - sin);
}
/**
* Interpolates globe center between two locations while preserving apparent rotation speed during interpolation.
* @param start - The starting location of the interpolation.
* @param deltaLng - Longitude delta to the end of the interpolation.
* @param deltaLat - Latitude delta to the end of the interpolation.
* @param t - The interpolation point in [0..1], where 0 is starting location, 1 is end location and other values are in between.
* @returns The interpolated location.
*/
function interpolateLngLatForGlobe(start, deltaLng, deltaLat, t) {
const interpolatedLat = start.lat + deltaLat * t;
if (Math.abs(deltaLat) > 1) {
const endLat = start.lat + deltaLat;
const samplePointStart = (Math.sign(endLat) !== Math.sign(start.lat) ? -Math.abs(start.lat) : Math.abs(start.lat)) * Math.PI / 180;
const samplePointEnd = Math.abs(start.lat + deltaLat) * Math.PI / 180;
const valueT = integrateSecX(samplePointStart + t * (samplePointEnd - samplePointStart));
const valueStart = integrateSecX(samplePointStart);
const valueEnd = integrateSecX(samplePointEnd);
const newT = (valueT - valueStart) / (valueEnd - valueStart);
const interpolatedLng = start.lng + deltaLng * newT;
return new LngLat(interpolatedLng, interpolatedLat);
} else {
const interpolatedLng = start.lng + deltaLng * t;
return new LngLat(interpolatedLng, interpolatedLat);
}
}
//#endregion
//#region src/util/primitives/bounding_volume_cache.ts
var BoundingVolumeCache = class {
constructor(boundingVolumeFactory) {
this._cachePrevious = /* @__PURE__ */ new Map();
this._cache = /* @__PURE__ */ new Map();
this._hadAnyChanges = false;
this._boundingVolumeFactory = boundingVolumeFactory;
}
/**
* Prepares bounding volume cache for next frame. Call at the beginning of a frame.
* Bounding volume of any tile accesses in the last frame is kept in the cache, other (unaccessed) bounding volumes are deleted.
*/
swapBuffers() {
if (!this._hadAnyChanges) return;
const oldCache = this._cachePrevious;
this._cachePrevious = this._cache;
this._cache = oldCache;
this._cache.clear();
this._hadAnyChanges = false;
}
/**
* Returns the bounding volume of the specified tile, fetching it from cache or creating it using the factory function if needed.
* @param tileID - Tile x, y and z for zoom.
*/
getTileBoundingVolume(tileID, wrap, elevation, options) {
const key = `${tileID.z}_${tileID.x}_${tileID.y}_${options?.terrain ? "t" : ""}_${Math.round(elevation)}`;
const cached = this._cache.get(key);
if (cached) return cached;
const cachedPrevious = this._cachePrevious.get(key);
if (cachedPrevious) {
this._cache.set(key, cachedPrevious);
return cachedPrevious;
}
const boundingVolume = this._boundingVolumeFactory(tileID, wrap, elevation, options);
this._cache.set(key, boundingVolume);
this._hadAnyChanges = true;
return boundingVolume;
}
};
//#endregion
//#region src/util/primitives/convex_volume.ts
/**
* A general convex bounding volume, defined by a set of points.
*/
var ConvexVolume = class ConvexVolume {
/**
* Creates an instance of a general convex bounding volume.
* Note that the provided points array is used *as is*, its contents are not copied!
*
* Additionally, an AABB must be provided for rejecting frustum intersections.
* This AABB does not need to bound this convex volume (it may be smaller),
* but it *must* accurately bound the actual shape this volume is approximating.
* @param points - Points forming the convex shape. Note that this array reference is used *as is*, its contents are not copied!
* @param min - The bounding AABB's min point.
* @param max - The bounding AABB's min point.
*/
constructor(points, planes, min, max) {
this.min = min;
this.max = max;
this.points = points;
this.planes = planes;
}
/**
* Creates a convex BV equivalent to the specified AABB.
* @param min - The AABB's min point.
* @param max - The AABB's max point.
*/
static fromAabb(min, max) {
const points = [];
for (let i = 0; i < 8; i++) points.push([
(i >> 0 & 1) === 1 ? max[0] : min[0],
(i >> 1 & 1) === 1 ? max[1] : min[1],
(i >> 2 & 1) === 1 ? max[2] : min[2]
]);
return new ConvexVolume(points, [
[
-1,
0,
0,
max[0]
],
[
1,
0,
0,
-min[0]
],
[
0,
-1,
0,
max[1]
],
[
0,
1,
0,
-min[1]
],
[
0,
0,
-1,
max[2]
],
[
0,
0,
1,
-min[2]
]
], min, max);
}
/**
* Creates a convex bounding volume that is actually an oriented bounding box created from the specified center, half-size and rotation angles.
* @param center - Center of the OBB.
* @param halfSize - The half-size of the OBB in each axis. The box will extend by this value in each direction for the given axis.
* @param angles - The rotation of the box. Euler angles, in degrees.
*/
static fromCenterSizeAngles(center, halfSize, angles) {
const q = fromEuler([], angles[0], angles[1], angles[2]);
const axisX = transformQuat([], [
halfSize[0],
0,
0
], q);
const axisY = transformQuat([], [
0,
halfSize[1],
0
], q);
const axisZ = transformQuat([], [
0,
0,
halfSize[2]
], q);
const min = [...center];
const max = [...center];
for (let i = 0; i < 8; i++) for (let axis = 0; axis < 3; axis++) {
const point = center[axis] + axisX[axis] * ((i >> 0 & 1) === 1 ? 1 : -1) + axisY[axis] * ((i >> 1 & 1) === 1 ? 1 : -1) + axisZ[axis] * ((i >> 2 & 1) === 1 ? 1 : -1);
min[axis] = Math.min(min[axis], point);
max[axis] = Math.max(max[axis], point);
}
const points = [];
for (let i = 0; i < 8; i++) {
const p = [...center];
add(p, p, scale$2([], axisX, (i >> 0 & 1) === 1 ? 1 : -1));
add(p, p, scale$2([], axisY, (i >> 1 & 1) === 1 ? 1 : -1));
add(p, p, scale$2([], axisZ, (i >> 2 & 1) === 1 ? 1 : -1));
points.push(p);
}
return new ConvexVolume(points, [
[...axisX, -dot(axisX, points[0])],
[...axisY, -dot(axisY, points[0])],
[...axisZ, -dot(axisZ, points[0])],
[
-axisX[0],
-axisX[1],
-axisX[2],
-dot(axisX, points[7])
],
[
-axisY[0],
-axisY[1],
-axisY[2],
-dot(axisY, points[7])
],
[
-axisZ[0],
-axisZ[1],
-axisZ[2],
-dot(axisZ, points[7])
]
], min, max);
}
/**
* Performs an approximate frustum-obb intersection test.
*/
intersectsFrustum(frustum) {
let fullyInside = true;
const boxPointCount = this.points.length;
const boxPlaneCount = this.planes.length;
const frustumPlaneCount = frustum.planes.length;
const frustumPointCount = frustum.points.length;
for (let i = 0; i < frustumPlaneCount; i++) {
const plane = frustum.planes[i];
let boxPointsPassed = 0;
for (let j = 0; j < boxPointCount; j++) {
const point = this.points[j];
if (plane[0] * point[0] + plane[1] * point[1] + plane[2] * point[2] + plane[3] >= 0) boxPointsPassed++;
}
if (boxPointsPassed === 0) return 0;
if (boxPointsPassed < boxPointCount) fullyInside = false;
}
if (fullyInside) return 2;
for (let i = 0; i < boxPlaneCount; i++) {
const plane = this.planes[i];
let frustumPointsPassed = 0;
for (let j = 0; j < frustumPointCount; j++) {
const point = frustum.points[j];
if (plane[0] * point[0] + plane[1] * point[1] + plane[2] * point[2] + plane[3] >= 0) frustumPointsPassed++;
}
if (frustumPointsPassed === 0) return 0;
}
return 1;
}
/**
* Performs an intersection test with a halfspace.
*/
intersectsPlane(plane) {
const pointCount = this.points.length;
let positivePoints = 0;
for (let i = 0; i < pointCount; i++) {
const point = this.points[i];
if (plane[0] * point[0] + plane[1] * point[1] + plane[2] * point[2] + plane[3] >= 0) positivePoints++;
}
if (positivePoints === pointCount) return 2;
if (positivePoints === 0) return 0;
return 1;
}
};
//#endregion
//#region src/geo/projection/globe_covering_tiles_details_provider.ts
/**
* Computes distance of a point to a tile in an arbitrary axis.
* World is assumed to have size 1, distance returned is to the nearer tile edge.
* @param point - Point position.
* @param tile - Tile position.
* @param tileSize - Tile size.
*/
function distanceToTileSimple(point, tile, tileSize) {
const delta = point - tile;
return delta < 0 ? -delta : Math.max(0, delta - tileSize);
}
function distanceToTileWrapX(pointX, pointY, tileCornerX, tileCornerY, tileSize) {
const tileCornerToPointX = pointX - tileCornerX;
let distanceX;
if (tileCornerToPointX < 0) distanceX = Math.min(-tileCornerToPointX, 1 + tileCornerToPointX - tileSize);
else if (tileCornerToPointX > tileSize) distanceX = Math.min(Math.max(tileCornerToPointX - tileSize, 0), 1 - tileCornerToPointX);
else distanceX = 0;
return Math.max(distanceX, distanceToTileSimple(pointY, tileCornerY, tileSize));
}
var GlobeCoveringTilesDetailsProvider = class {
constructor() {
this._boundingVolumeCache = new BoundingVolumeCache(this._computeTileBoundingVolume);
}
/**
* Prepares the internal bounding volume cache for the next frame.
*/
prepareNextFrame() {
this._boundingVolumeCache.swapBuffers();
}
/**
* Returns the distance of a point to a square tile. If the point is inside the tile, returns 0.
* Assumes the world to be of size 1.
* Handles distances on a sphere correctly: X is wrapped when crossing the antimeridian,
* when crossing the poles Y is mirrored and X is shifted by half world size.
*/
distanceToTile2d(pointX, pointY, tileID, _bv) {
const scale = 1 << tileID.z;
const tileMercatorSize = 1 / scale;
const tileCornerX = tileID.x / scale;
const tileCornerY = tileID.y / scale;
const halfWorld = .5;
let smallestDistance = 2;
smallestDistance = Math.min(smallestDistance, distanceToTileWrapX(pointX, pointY, tileCornerX, tileCornerY, tileMercatorSize));
smallestDistance = Math.min(smallestDistance, distanceToTileWrapX(pointX, pointY, tileCornerX + halfWorld, -tileCornerY - tileMercatorSize, tileMercatorSize));
smallestDistance = Math.min(smallestDistance, distanceToTileWrapX(pointX, pointY, tileCornerX + halfWorld, 2 - tileCornerY - tileMercatorSize, tileMercatorSize));
return smallestDistance;
}
/**
* Returns the wrap value for a given tile, computed so that tiles will remain loaded when crossing the antimeridian.
*/
getWrap(centerCoord, tileID, _parentWrap) {
const scale = 1 << tileID.z;
const tileMercatorSize = 1 / scale;
const tileX = tileID.x / scale;
const distanceCurrent = distanceToTileSimple(centerCoord.x, tileX, tileMercatorSize);
const distanceLeft = distanceToTileSimple(centerCoord.x, tileX - 1, tileMercatorSize);
const distanceRight = distanceToTileSimple(centerCoord.x, tileX + 1, tileMercatorSize);
const distanceSmallest = Math.min(distanceCurrent, distanceLeft, distanceRight);
if (distanceSmallest === distanceRight) return 1;
if (distanceSmallest === distanceLeft) return -1;
return 0;
}
allowVariableZoom(transform, options) {
return coveringZoomLevel(transform, options) > 4;
}
allowWorldCopies() {
return false;
}
getTileBoundingVolume(tileID, wrap, elevation, options) {
return this._boundingVolumeCache.getTileBoundingVolume(tileID, wrap, elevation, options);
}
_computeTileBoundingVolume(tileID, wrap, elevation, options) {
let minElevation = Math.min(0, elevation);
let maxElevation = Math.max(0, elevation);
if (options?.terrain) {
const overscaledTileID = new OverscaledTileID(tileID.z, wrap, tileID.z, tileID.x, tileID.y);
const minMax = options.terrain.getMinMaxElevation(overscaledTileID);
minElevation = minMax.minElevation ?? minElevation;
maxElevation = minMax.maxElevation ?? maxElevation;
}
minElevation /= earthRadius;
maxElevation /= earthRadius;
minElevation += 1;
maxElevation += 1;
if (tileID.z <= 0) return ConvexVolume.fromAabb([
-maxElevation,
-maxElevation,
-maxElevation
], [
maxElevation,
maxElevation,
maxElevation
]);
else if (tileID.z === 1) return ConvexVolume.fromAabb([
tileID.x === 0 ? -maxElevation : 0,
tileID.y === 0 ? 0 : -maxElevation,
-maxElevation
], [
tileID.x === 0 ? 0 : maxElevation,
tileID.y === 0 ? maxElevation : 0,
maxElevation
]);
else {
const corners = [
projectTileCoordinatesToSphere(0, 0, tileID.x, tileID.y, tileID.z),
projectTileCoordinatesToSphere(EXTENT, 0, tileID.x, tileID.y, tileID.z),
projectTileCoordinatesToSphere(EXTENT, EXTENT, tileID.x, tileID.y, tileID.z),
projectTileCoordinatesToSphere(0, EXTENT, tileID.x, tileID.y, tileID.z)
];
const extremesPoints = [];
for (const c of corners) extremesPoints.push(scale$2([], c, maxElevation));
if (maxElevation !== minElevation) for (const c of corners) extremesPoints.push(scale$2([], c, minElevation));
if (tileID.y === 0) extremesPoints.push([
0,
1,
0
]);
if (tileID.y === (1 << tileID.z) - 1) extremesPoints.push([
0,
-1,
0
]);
const aabbMin = [
1,
1,
1
];
const aabbMax = [
-1,
-1,
-1
];
for (const c of extremesPoints) for (let i = 0; i < 3; i++) {
aabbMin[i] = Math.min(aabbMin[i], c[i]);
aabbMax[i] = Math.max(aabbMax[i], c[i]);
}
const center = projectTileCoordinatesToSphere(EXTENT / 2, EXTENT / 2, tileID.x, tileID.y, tileID.z);
const centerEast = cross([], [
0,
1,
0
], center);
normalize(centerEast, centerEast);
const north = cross([], center, centerEast);
normalize(north, north);
const axisEast = cross([], corners[2], corners[1]);
normalize(axisEast, axisEast);
const axisWest = cross([], corners[0], corners[3]);
normalize(axisWest, axisWest);
extremesPoints.push(scale$2([], center, maxElevation));
if (tileID.y >= (1 << tileID.z) / 2) extremesPoints.push(scale$2([], projectTileCoordinatesToSphere(EXTENT / 2, 0, tileID.x, tileID.y, tileID.z), maxElevation));
if (tileID.y < (1 << tileID.z) / 2) extremesPoints.push(scale$2([], projectTileCoordinatesToSphere(EXTENT / 2, EXTENT, tileID.x, tileID.y, tileID.z), maxElevation));
const upDownMinMax = findAxisMinMax(center, extremesPoints);
const northSouthMinMax = findAxisMinMax(north, extremesPoints);
const planeUp = [
-center[0],
-center[1],
-center[2],
upDownMinMax.max
];
const planeDown = [
center[0],
center[1],
center[2],
-upDownMinMax.min
];
const planeNorth = [
-north[0],
-north[1],
-north[2],
northSouthMinMax.max
];
const planeSouth = [
north[0],
north[1],
north[2],
-northSouthMinMax.min
];
const planeEast = [...axisEast, 0];
const planeWest = [...axisWest, 0];
const points = [];
if (tileID.y === 0) points.push(threePlaneIntersection(planeWest, planeEast, planeUp), threePlaneIntersection(planeWest, planeEast, planeDown));
else points.push(threePlaneIntersection(planeNorth, planeEast, planeUp), threePlaneIntersection(planeNorth, planeEast, planeDown), threePlaneIntersection(planeNorth, planeWest, planeUp), threePlaneIntersection(planeNorth, planeWest, planeDown));
if (tileID.y === (1 << tileID.z) - 1) points.push(threePlaneIntersection(planeWest, planeEast, planeUp), threePlaneIntersection(planeWest, planeEast, planeDown));
else points.push(threePlaneIntersection(planeSouth, planeEast, planeUp), threePlaneIntersection(planeSouth, planeEast, planeDown), threePlaneIntersection(planeSouth, planeWest, planeUp), threePlaneIntersection(planeSouth, planeWest, planeDown));
return new ConvexVolume(points, [
planeUp,
planeDown,
planeNorth,
planeSouth,
planeEast,
planeWest
], aabbMin, aabbMax);
}
}
};
function findAxisMinMax(axis, points) {
let min = Infinity;
let max = -Infinity;
for (const c of points) {
const dot$1 = dot(axis, c);
min = Math.min(min, dot$1);
max = Math.max(max, dot$1);
}
return {
min,
max
};
}
//#endregion
//#region src/geo/projection/vertical_perspective_transform.ts
var VerticalPerspectiveTransform = class VerticalPerspectiveTransform {
get pixelsToClipSpaceMatrix() {
return this._helper.pixelsToClipSpaceMatrix;
}
get clipSpaceToPixelsMatrix() {
return this._helper.clipSpaceToPixelsMatrix;
}
get pixelsToGLUnits() {
return this._helper.pixelsToGLUnits;
}
get centerOffset() {
return this._helper.centerOffset;
}
get size() {
return this._helper.size;
}
get rotationMatrix() {
return this._helper.rotationMatrix;
}
get centerPoint() {
return this._helper.centerPoint;
}
get pixelsPerMeter() {
return this._helper.pixelsPerMeter;
}
setMinZoom(zoom) {
this._helper.setMinZoom(zoom);
}
setMaxZoom(zoom) {
this._helper.setMaxZoom(zoom);
}
setMinPitch(pitch) {
this._helper.setMinPitch(pitch);
}
setMaxPitch(pitch) {
this._helper.setMaxPitch(pitch);
}
setRenderWorldCopies(renderWorldCopies) {
this._helper.setRenderWorldCopies(renderWorldCopies);
}
setBearing(bearing) {
this._helper.setBearing(bearing);
}
setPitch(pitch) {
this._helper.setPitch(pitch);
}
setRoll(roll) {
this._helper.setRoll(roll);
}
setFov(fov) {
this._helper.setFov(fov);
}
setZoom(zoom) {
this._helper.setZoom(zoom);
}
setCenter(center) {
this._helper.setCenter(center);
}
setElevation(elevation) {
this._helper.setElevation(elevation);
}
setMinElevationForCurrentTile(elevation) {
this._helper.setMinElevationForCurrentTile(elevation);
}
setPadding(padding) {
this._helper.setPadding(padding);
}
interpolatePadding(start, target, t) {
this._helper.interpolatePadding(start, target, t);
}
isPaddingEqual(padding) {
return this._helper.isPaddingEqual(padding);
}
resize(width, height) {
this._helper.resize(width, height);
}
getMaxBounds() {
return this._helper.getMaxBounds();
}
setMaxBounds(bounds) {
this._helper.setMaxBounds(bounds);
}
setConstrainOverride(constrain) {
this._helper.setConstrainOverride(constrain);
}
overrideNearFarZ(nearZ, farZ) {
this._helper.overrideNearFarZ(nearZ, farZ);
}
clearNearFarZOverride() {
this._helper.clearNearFarZOverride();
}
getCameraQueryGeometry(queryGeometry) {
return this._helper.getCameraQueryGeometry(this.getCameraPoint(), queryGeometry);
}
get tileSize() {
return this._helper.tileSize;
}
get tileZoom() {
return this._helper.tileZoom;
}
get scale() {
return this._helper.scale;
}
get worldSize() {
return this._helper.worldSize;
}
get width() {
return this._helper.width;
}
get height() {
return this._helper.height;
}
get lngRange() {
return this._helper.lngRange;
}
get latRange() {
return this._helper.latRange;
}
get minZoom() {
return this._helper.minZoom;
}
get maxZoom() {
return this._helper.maxZoom;
}
get zoom() {
return this._helper.zoom;
}
get center() {
return this._helper.center;
}
get minPitch() {
return this._helper.minPitch;
}
get maxPitch() {
return this._helper.maxPitch;
}
get pitch() {
return this._helper.pitch;
}
get pitchInRadians() {
return this._helper.pitchInRadians;
}
get roll() {
return this._helper.roll;
}
get rollInRadians() {
return this._helper.rollInRadians;
}
get bearing() {
return this._helper.bearing;
}
get bearingInRadians() {
return this._helper.bearingInRadians;
}
get fov() {
return this._helper.fov;
}
get fovInRadians() {
return this._helper.fovInRadians;
}
get elevation() {
return this._helper.elevation;
}
get minElevationForCurrentTile() {
return this._helper.minElevationForCurrentTile;
}
get padding() {
return this._helper.padding;
}
get unmodified() {
return this._helper.unmodified;
}
get renderWorldCopies() {
return this._helper.renderWorldCopies;
}
get constrainOverride() {
return this._helper.constrainOverride;
}
get nearZ() {
return this._helper.nearZ;
}
get farZ() {
return this._helper.farZ;
}
get autoCalculateNearFarZ() {
return this._helper.autoCalculateNearFarZ;
}
setTransitionState(_value) {}
constructor(options) {
this._cachedClippingPlane = createVec4f64();
this._projectionMatrix = createIdentityMat4f64();
this._globeViewProjMatrix32f = createIdentityMat4f32();
this._globeViewProjMatrixF64 = createIdentityMat4f64();
this._globeViewProjMatrixF64Inverted = createIdentityMat4f64();
this._globeProjMatrixInverted = createIdentityMat4f64();
this._cameraPosition = createVec3f64();
this.defaultConstrain = (lngLat, zoom) => {
const constrainedLat = clamp(lngLat.lat, -MAX_VALID_LATITUDE, MAX_VALID_LATITUDE);
const constrainedZoom = clamp(+zoom, this.minZoom + getZoomAdjustment(0, constrainedLat), this.maxZoom);
return {
center: new LngLat(lngLat.lng, constrainedLat),
zoom: constrainedZoom
};
};
this.applyConstrain = (lngLat, zoom) => {
return this._helper.applyConstrain(lngLat, zoom);
};
this._helper = new TransformHelper({
calcMatrices: () => this._calcMatrices(),
defaultConstrain: (center, zoom) => {
return this.defaultConstrain(center, zoom);
}
}, options);
this._coveringTilesDetailsProvider = new GlobeCoveringTilesDetailsProvider();
}
clone() {
const clone = new VerticalPerspectiveTransform();
clone.apply(this, false);
return clone;
}
apply(that, constrain) {
this._helper.apply(that, constrain);
}
get projectionMatrix() {
return this._projectionMatrix;
}
get modelViewProjectionMatrix() {
return this._globeViewProjMatrixF64;
}
get inverseProjectionMatrix() {
return this._globeProjMatrixInverted;
}
get cameraPosition() {
const copy = createVec3f64();
copy[0] = this._cameraPosition[0];
copy[1] = this._cameraPosition[1];
copy[2] = this._cameraPosition[2];
return copy;
}
get cameraToCenterDistance() {
return this._helper.cameraToCenterDistance;
}
getProjectionData(params) {
const { overscaledTileID, applyGlobeMatrix } = params;
const mercatorTileCoordinates = this._helper.getMercatorTileCoordinates(overscaledTileID);
return {
mainMatrix: this._globeViewProjMatrix32f,
tileMercatorCoords: mercatorTileCoordinates,
clippingPlane: this._cachedClippingPlane,
projectionTransition: applyGlobeMatrix ? 1 : 0,
fallbackMatrix: this._globeViewProjMatrix32f,
clipAntimeridian: overscaledTileID?.canonical.z === 0
};
}
_computeClippingPlane(globeRadiusPixels) {
const pitch = this.pitchInRadians;
const distanceCameraToB = this.cameraToCenterDistance / globeRadiusPixels;
const radius = 1;
const distanceCameraToA = Math.sin(pitch) * distanceCameraToB;
const distanceAtoC = Math.cos(pitch) * distanceCameraToB + radius;
const tangentPlaneDistanceToC = radius / Math.sqrt(distanceCameraToA * distanceCameraToA + distanceAtoC * distanceAtoC) * radius;
let vectorCtoCamX = -distanceCameraToA;
let vectorCtoCamY = distanceAtoC;
const vectorCtoCamLength = Math.sqrt(vectorCtoCamX * vectorCtoCamX + vectorCtoCamY * vectorCtoCamY);
vectorCtoCamX /= vectorCtoCamLength;
vectorCtoCamY /= vectorCtoCamLength;
const planeVector = [
0,
vectorCtoCamX,
vectorCtoCamY
];
rotateZ$1(planeVector, planeVector, [
0,
0,
0
], -this.bearingInRadians);
rotateX$1(planeVector, planeVector, [
0,
0,
0
], -1 * this.center.lat * Math.PI / 180);
rotateY(planeVector, planeVector, [
0,
0,
0
], this.center.lng * Math.PI / 180);
const scale = 1 / length$1(planeVector);
scale$2(planeVector, planeVector, scale);
return [...planeVector, -tangentPlaneDistanceToC * scale];
}
isLocationOccluded(location) {
return !this.isSurfacePointVisible(angularCoordinatesToSurfaceVector(location));
}
transformLightDirection(dir) {
const sphereX = this._helper._center.lng * Math.PI / 180;
const sphereY = this._helper._center.lat * Math.PI / 180;
const len = Math.cos(sphereY);
const spherePos = [
Math.sin(sphereX) * len,
Math.sin(sphereY),
Math.cos(sphereX) * len
];
const axisRight = [
spherePos[2],
0,
-spherePos[0]
];
const axisDown = [
0,
0,
0
];
cross(axisDown, axisRight, spherePos);
normalize(axisRight, axisRight);
normalize(axisDown, axisDown);
const transformed = [
axisRight[0] * dir[0] + axisDown[0] * dir[1] + spherePos[0] * dir[2],
axisRight[1] * dir[0] + axisDown[1] * dir[1] + spherePos[1] * dir[2],
axisRight[2] * dir[0] + axisDown[2] * dir[1] + spherePos[2] * dir[2]
];
const normalized = [
0,
0,
0
];
normalize(normalized, transformed);
return normalized;
}
getPixelScale() {
return 1 / Math.cos(this._helper._center.lat * Math.PI / 180);
}
getCircleRadiusCorrection() {
return Math.cos(this._helper._center.lat * Math.PI / 180);
}
getPitchedTextCorrection(textAnchorX, textAnchorY, tileID) {
const mercator = tileCoordinatesToMercatorCoordinates(textAnchorX, textAnchorY, tileID.canonical);
const angular = mercatorCoordinatesToAngularCoordinatesRadians(mercator.x, mercator.y);
return this.getCircleRadiusCorrection() / Math.cos(angular[1]);
}
projectTileCoordinates(x, y, unwrappedTileID, getElevation) {
const canonical = unwrappedTileID.canonical;
const spherePos = projectTileCoordinatesToSphere(x, y, canonical.x, canonical.y, canonical.z);
const vectorMultiplier = 1 + (getElevation ? getElevation(x, y) : 0) / earthRadius;
const pos = [
spherePos[0] * vectorMultiplier,
spherePos[1] * vectorMultiplier,
spherePos[2] * vectorMultiplier,
1
];
transformMat4(pos, pos, this._globeViewProjMatrixF64);
const plane = this._cachedClippingPlane;
const isOccluded = plane[0] * spherePos[0] + plane[1] * spherePos[1] + plane[2] * spherePos[2] + plane[3] < 0;
return {
point: new Point(pos[0] / pos[3], pos[1] / pos[3]),
signedDistanceFromCamera: pos[3],
isOccluded
};
}
_calcMatrices() {
if (!this._helper._width || !this._helper._height) return;
const globeRadiusPixels = getGlobeRadiusPixels(this.worldSize, this.center.lat);
const globeMatrix = createMat4f64();
if (this._helper.autoCalculateNearFarZ) {
this._helper._nearZ = .5;
this._helper._farZ = this.cameraToCenterDistance + globeRadiusPixels * 2;
}
perspective(globeMatrix, this.fovInRadians, this.width / this.height, this._helper._nearZ, this._helper._farZ);
const offset = this.centerOffset;
globeMatrix[8] = -offset.x * 2 / this._helper._width;
globeMatrix[9] = offset.y * 2 / this._helper._height;
this._projectionMatrix = clone$1(globeMatrix);
this._globeProjMatrixInverted = createMat4f64();
invert$1(this._globeProjMatrixInverted, globeMatrix);
translate(globeMatrix, globeMatrix, [
0,
0,
-this.cameraToCenterDistance
]);
rotateZ(globeMatrix, globeMatrix, this.rollInRadians);
rotateX(globeMatrix, globeMatrix, -this.pitchInRadians);
rotateZ(globeMatrix, globeMatrix, this.bearingInRadians);
translate(globeMatrix, globeMatrix, [
0,
0,
-globeRadiusPixels
]);
const scaleVec = createVec3f64();
scaleVec[0] = globeRadiusPixels;
scaleVec[1] = globeRadiusPixels;
scaleVec[2] = globeRadiusPixels;
rotateX(globeMatrix, globeMatrix, this.center.lat * Math.PI / 180);
rotateY$1(globeMatrix, globeMatrix, -this.center.lng * Math.PI / 180);
scale(globeMatrix, globeMatrix, scaleVec);
this._globeViewProjMatrixF64 = globeMatrix;
this._globeViewProjMatrix32f = new Float32Array(globeMatrix);
this._globeViewProjMatrixF64Inverted = createMat4f64();
invert$1(this._globeViewProjMatrixF64Inverted, globeMatrix);
const zero = createVec3f64();
this._cameraPosition = createVec3f64();
this._cameraPosition[2] = this.cameraToCenterDistance / globeRadiusPixels;
rotateZ$1(this._cameraPosition, this._cameraPosition, zero, -this.rollInRadians);
rotateX$1(this._cameraPosition, this._cameraPosition, zero, this.pitchInRadians);
rotateZ$1(this._cameraPosition, this._cameraPosition, zero, -this.bearingInRadians);
add(this._cameraPosition, this._cameraPosition, [
0,
0,
1
]);
rotateX$1(this._cameraPosition, this._cameraPosition, zero, -this.center.lat * Math.PI / 180);
rotateY(this._cameraPosition, this._cameraPosition, zero, this.center.lng * Math.PI / 180);
this._cachedClippingPlane = this._computeClippingPlane(globeRadiusPixels);
const matrix = clone$1(this._globeViewProjMatrixF64Inverted);
scale(matrix, matrix, [
1,
1,
-1
]);
this._cachedFrustum = Frustum.fromInvProjectionMatrix(matrix, 1, 0, this._cachedClippingPlane, true);
}
calculateFogMatrix(_unwrappedTileID) {
warnOnce("calculateFogMatrix is not supported on globe projection.");
const m = createMat4f64();
identity(m);
return m;
}
getVisibleUnwrappedCoordinates(tileID) {
return [new UnwrappedTileID(0, tileID)];
}
getCameraFrustum() {
return this._cachedFrustum;
}
getClippingPlane() {
return this._cachedClippingPlane;
}
getCoveringTilesDetailsProvider() {
return this._coveringTilesDetailsProvider;
}
recalculateZoomAndCenter(terrain) {
if (terrain) {
warnOnce("terrain is not fully supported on vertical perspective projection.");
return;
}
this._helper.recalculateZoomAndCenter(0);
}
maxPitchScaleFactor() {
return 1;
}
getCameraPoint() {
return this._helper.getCameraPoint();
}
getCameraAltitude() {
return this._helper.getCameraAltitude();
}
getCameraLngLat() {
return this._helper.getCameraLngLat();
}
lngLatToCameraDepth(lngLat, elevation) {
if (!this._globeViewProjMatrixF64) return 1;
const vec = angularCoordinatesToSurfaceVector(lngLat);
scale$2(vec, vec, 1 + elevation / earthRadius);
const result = createVec4f64();
transformMat4(result, [
vec[0],
vec[1],
vec[2],
1
], this._globeViewProjMatrixF64);
return result[2] / result[3];
}
populateCache(_coords) {}
getBounds() {
const xMid = this.width * .5;
const yMid = this.height * .5;
const testPoints = [
new Point(0, 0),
new Point(xMid, 0),
new Point(this.width, 0),
new Point(this.width, yMid),
new Point(this.width, this.height),
new Point(xMid, this.height),
new Point(0, this.height),
new Point(0, yMid)
];
const projectedPoints = [];
for (const p of testPoints) projectedPoints.push(this.unprojectScreenPoint(p));
let mostEast = 0, mostWest = 0, mostNorth = 0, mostSouth = 0;
const center = this.center;
for (const p of projectedPoints) {
const dLng = differenceOfAnglesDegrees(center.lng, p.lng);
const dLat = differenceOfAnglesDegrees(center.lat, p.lat);
if (dLng < mostWest) mostWest = dLng;
if (dLng > mostEast) mostEast = dLng;
if (dLat < mostSouth) mostSouth = dLat;
if (dLat > mostNorth) mostNorth = dLat;
}
const boundsArray = [
center.lng + mostWest,
center.lat + mostSouth,
center.lng + mostEast,
center.lat + mostNorth
];
if (this.isSurfacePointOnScreen([
0,
1,
0
])) {
boundsArray[3] = 90;
boundsArray[0] = -180;
boundsArray[2] = 180;
}
if (this.isSurfacePointOnScreen([
0,
-1,
0
])) {
boundsArray[1] = -90;
boundsArray[0] = -180;
boundsArray[2] = 180;
}
return new LngLatBounds(boundsArray);
}
calculateCenterFromCameraLngLatAlt(lngLat, alt, bearing, pitch) {
return this._helper.calculateCenterFromCameraLngLatAlt(lngLat, alt, bearing, pitch);
}
/**
* Note: automatically adjusts zoom to keep planet size consistent
* (same size before and after a {@link setLocationAtPoint} call).
*/
setLocationAtPoint(lnglat, point, _elevation) {
const vecToPixelCurrent = angularCoordinatesToSurfaceVector(this.unprojectScreenPoint(point));
const vecToTarget = angularCoordinatesToSurfaceVector(lnglat);
const zero = createVec3f64();
zero$1(zero);
const rotatedPixelVector = createVec3f64();
rotateY(rotatedPixelVector, vecToPixelCurrent, zero, -this.center.lng * Math.PI / 180);
rotateX$1(rotatedPixelVector, rotatedPixelVector, zero, this.center.lat * Math.PI / 180);
const vecToTargetXZLengthSquared = vecToTarget[0] * vecToTarget[0] + vecToTarget[2] * vecToTarget[2];
const targetXSquared = rotatedPixelVector[0] * rotatedPixelVector[0];
if (vecToTargetXZLengthSquared < targetXSquared) return;
const intersectionA = Math.sqrt(vecToTargetXZLengthSquared - targetXSquared);
const intersectionB = -intersectionA;
const lngA = angleToRotateBetweenVectors2D(vecToTarget[0], vecToTarget[2], rotatedPixelVector[0], intersectionA);
const lngB = angleToRotateBetweenVectors2D(vecToTarget[0], vecToTarget[2], rotatedPixelVector[0], intersectionB);
const vecToTargetLngA = createVec3f64();
rotateY(vecToTargetLngA, vecToTarget, zero, -lngA);
const latA = angleToRotateBetweenVectors2D(vecToTargetLngA[1], vecToTargetLngA[2], rotatedPixelVector[1], rotatedPixelVector[2]);
const vecToTargetLngB = createVec3f64();
rotateY(vecToTargetLngB, vecToTarget, zero, -lngB);
const latB = angleToRotateBetweenVectors2D(vecToTargetLngB[1], vecToTargetLngB[2], rotatedPixelVector[1], rotatedPixelVector[2]);
const limit = Math.PI * .5;
const isValidA = latA >= -limit && latA <= limit;
const isValidB = latB >= -limit && latB <= limit;
let validLng;
let validLat;
if (isValidA && isValidB) {
const centerLngRadians = this.center.lng * Math.PI / 180;
const centerLatRadians = this.center.lat * Math.PI / 180;
const lngDistA = distanceOfAnglesRadians(lngA, centerLngRadians);
const latDistA = distanceOfAnglesRadians(latA, centerLatRadians);
const lngDistB = distanceOfAnglesRadians(lngB, centerLngRadians);
const latDistB = distanceOfAnglesRadians(latB, centerLatRadians);
if (lngDistA + latDistA < lngDistB + latDistB) {
validLng = lngA;
validLat = latA;
} else {
validLng = lngB;
validLat = latB;
}
} else if (isValidA) {
validLng = lngA;
validLat = latA;
} else if (isValidB) {
validLng = lngB;
validLat = latB;
} else return;
const newLng = validLng / Math.PI * 180;
const newLat = validLat / Math.PI * 180;
const oldLat = this.center.lat;
this.setCenter(new LngLat(newLng, clamp(newLat, -90, 90)));
this.setZoom(this.zoom + getZoomAdjustment(oldLat, this.center.lat));
}
locationToScreenPoint(lnglat, terrain) {
const pos = angularCoordinatesToSurfaceVector(lnglat);
if (terrain) {
const elevation = terrain.getElevationForLngLatZoom(lnglat, this._helper._tileZoom);
scale$2(pos, pos, 1 + elevation / earthRadius);
}
return this._projectSurfacePointToScreen(pos);
}
/**
* Projects a given vector on the surface of a unit sphere (or possible above the surface)
* and returns its coordinates on screen in pixels.
*/
_projectSurfacePointToScreen(pos) {
const projected = createVec4f64();
transformMat4(projected, [...pos, 1], this._globeViewProjMatrixF64);
projected[0] /= projected[3];
projected[1] /= projected[3];
return new Point((projected[0] * .5 + .5) * this.width, (-projected[1] * .5 + .5) * this.height);
}
screenPointToMercatorCoordinate(p, terrain) {
if (terrain) {
const coordinate = terrain.pointCoordinate(p);
if (coordinate) return coordinate;
}
return MercatorCoordinate.fromLngLat(this.unprojectScreenPoint(p));
}
screenPointToLocation(p, terrain) {
return this.screenPointToMercatorCoordinate(p, terrain)?.toLngLat();
}
screenPointToLocationAtElevation(p, _elevation) {
return this.screenPointToLocation(p);
}
isPointOnMapSurface(p, _terrain) {
const rayOrigin = this._cameraPosition;
const rayDirection = this.getRayDirectionFromPixel(p);
return !!this.rayPlanetIntersection(rayOrigin, rayDirection);
}
/**
* Computes normalized direction of a ray from the camera to the given screen pixel.
*/
getRayDirectionFromPixel(p) {
const pos = createVec4f64();
pos[0] = p.x / this.width * 2 - 1;
pos[1] = (p.y / this.height * 2 - 1) * -1;
pos[2] = 1;
pos[3] = 1;
transformMat4(pos, pos, this._globeViewProjMatrixF64Inverted);
pos[0] /= pos[3];
pos[1] /= pos[3];
pos[2] /= pos[3];
const ray = createVec3f64();
ray[0] = pos[0] - this._cameraPosition[0];
ray[1] = pos[1] - this._cameraPosition[1];
ray[2] = pos[2] - this._cameraPosition[2];
const rayNormalized = createVec3f64();
normalize(rayNormalized, ray);
return rayNormalized;
}
/**
* For a given point on the unit sphere of the planet, returns whether it is visible from
* camera's position (not taking into account camera rotation at all).
*/
isSurfacePointVisible(p) {
const plane = this._cachedClippingPlane;
return plane[0] * p[0] + plane[1] * p[1] + plane[2] * p[2] + plane[3] >= 0;
}
/**
* Returns whether surface point is visible on screen.
* It must both project to a pixel in screen bounds and not be occluded by the planet.
*/
isSurfacePointOnScreen(vec) {
if (!this.isSurfacePointVisible(vec)) return false;
const projected = createVec4f64();
transformMat4(projected, [...vec, 1], this._globeViewProjMatrixF64);
projected[0] /= projected[3];
projected[1] /= projected[3];
projected[2] /= projected[3];
return projected[0] > -1 && projected[0] < 1 && projected[1] > -1 && projected[1] < 1 && projected[2] > -1 && projected[2] < 1;
}
/**
* Returns the two intersection points of the ray and the planet's sphere,
* or null if no intersection occurs.
* The intersections are encoded as the parameter for parametric ray equation,
* with `tMin` being the first intersection and `tMax` being the second.
* Eg. the nearer intersection point can then be computed as `origin + direction * tMin`.
* @param origin - The ray origin.
* @param direction - The normalized ray direction.
*/
rayPlanetIntersection(origin, direction) {
const originDotDirection = dot(origin, direction);
const planetRadiusSquared = 1;
const inner = createVec3f64();
const scaledDir = createVec3f64();
scale$2(scaledDir, direction, originDotDirection);
sub(inner, origin, scaledDir);
const discriminant = planetRadiusSquared - dot(inner, inner);
if (discriminant < 0) return null;
const c = dot(origin, origin) - planetRadiusSquared;
const q = -originDotDirection + (originDotDirection < 0 ? 1 : -1) * Math.sqrt(discriminant);
const t0 = c / q;
const t1 = q;
return {
tMin: Math.min(t0, t1),
tMax: Math.max(t0, t1)
};
}
/**
* @internal
* Returns a {@link LngLat} representing geographical coordinates that correspond to the specified pixel coordinates.
* Note: if the point does not lie on the globe, returns a location on the visible globe horizon (edge) that is
* as close to the point as possible.
* @param p - Screen point in pixels to unproject.
* @param terrain - Optional terrain.
*/
unprojectScreenPoint(p) {
const rayOrigin = this._cameraPosition;
const rayDirection = this.getRayDirectionFromPixel(p);
const intersection = this.rayPlanetIntersection(rayOrigin, rayDirection);
if (intersection) {
const intersectionPoint = createVec3f64();
add(intersectionPoint, rayOrigin, [
rayDirection[0] * intersection.tMin,
rayDirection[1] * intersection.tMin,
rayDirection[2] * intersection.tMin
]);
const sphereSurface = createVec3f64();
normalize(sphereSurface, intersectionPoint);
return sphereSurfacePointToCoordinates(sphereSurface);
}
const horizonPlane = this._cachedClippingPlane;
const directionDotPlaneXyz = horizonPlane[0] * rayDirection[0] + horizonPlane[1] * rayDirection[1] + horizonPlane[2] * rayDirection[2];
const distanceToIntersection = -pointPlaneSignedDistance(horizonPlane, rayOrigin) / directionDotPlaneXyz;
const maxRayLength = 2;
const planeIntersection = createVec3f64();
if (distanceToIntersection > 0) add(planeIntersection, rayOrigin, [
rayDirection[0] * distanceToIntersection,
rayDirection[1] * distanceToIntersection,
rayDirection[2] * distanceToIntersection
]);
else {
const distantPoint = createVec3f64();
add(distantPoint, rayOrigin, [
rayDirection[0] * maxRayLength,
rayDirection[1] * maxRayLength,
rayDirection[2] * maxRayLength
]);
const distanceFromPlane = pointPlaneSignedDistance(this._cachedClippingPlane, distantPoint);
sub(planeIntersection, distantPoint, [
this._cachedClippingPlane[0] * distanceFromPlane,
this._cachedClippingPlane[1] * distanceFromPlane,
this._cachedClippingPlane[2] * distanceFromPlane
]);
}
const horizonDisk = horizonPlaneToCenterAndRadius(horizonPlane);
return sphereSurfacePointToCoordinates(clampToSphere(horizonDisk.center, horizonDisk.radius, planeIntersection));
}
getProjectionDataForCustomLayer(applyGlobeMatrix = true) {
const globeData = this.getProjectionData({
overscaledTileID: new OverscaledTileID(0, 0, 0, 0, 0),
applyGlobeMatrix
});
globeData.tileMercatorCoords = [
0,
0,
1,
1
];
return globeData;
}
getFastPathSimpleProjectionMatrix(_tileID) {}
};
//#endregion
//#region src/geo/projection/globe_transform.ts
/**
* Globe transform is a transform that moves between vertical perspective and mercator projections.
*/
var GlobeTransform = class GlobeTransform {
get pixelsToClipSpaceMatrix() {
return this._helper.pixelsToClipSpaceMatrix;
}
get clipSpaceToPixelsMatrix() {
return this._helper.clipSpaceToPixelsMatrix;
}
get pixelsToGLUnits() {
return this._helper.pixelsToGLUnits;
}
get centerOffset() {
return this._helper.centerOffset;
}
get size() {
return this._helper.size;
}
get rotationMatrix() {
return this._helper.rotationMatrix;
}
get centerPoint() {
return this._helper.centerPoint;
}
get pixelsPerMeter() {
return this._helper.pixelsPerMeter;
}
setMinZoom(zoom) {
this._helper.setMinZoom(zoom);
}
setMaxZoom(zoom) {
this._helper.setMaxZoom(zoom);
}
setMinPitch(pitch) {
this._helper.setMinPitch(pitch);
}
setMaxPitch(pitch) {
this._helper.setMaxPitch(pitch);
}
setRenderWorldCopies(renderWorldCopies) {
this._helper.setRenderWorldCopies(renderWorldCopies);
}
setBearing(bearing) {
this._helper.setBearing(bearing);
}
setPitch(pitch) {
this._helper.setPitch(pitch);
}
setRoll(roll) {
this._helper.setRoll(roll);
}
setFov(fov) {
this._helper.setFov(fov);
}
setZoom(zoom) {
this._helper.setZoom(zoom);
}
setCenter(center) {
this._helper.setCenter(center);
}
setElevation(elevation) {
this._helper.setElevation(elevation);
}
setMinElevationForCurrentTile(elevation) {
this._helper.setMinElevationForCurrentTile(elevation);
}
setPadding(padding) {
this._helper.setPadding(padding);
}
interpolatePadding(start, target, t) {
this._helper.interpolatePadding(start, target, t);
}
isPaddingEqual(padding) {
return this._helper.isPaddingEqual(padding);
}
resize(width, height, constrainTransform = true) {
this._helper.resize(width, height, constrainTransform);
}
getMaxBounds() {
return this._helper.getMaxBounds();
}
setMaxBounds(bounds) {
this._helper.setMaxBounds(bounds);
}
setConstrainOverride(constrain) {
this._helper.setConstrainOverride(constrain);
}
overrideNearFarZ(nearZ, farZ) {
this._helper.overrideNearFarZ(nearZ, farZ);
}
clearNearFarZOverride() {
this._helper.clearNearFarZOverride();
}
getCameraQueryGeometry(queryGeometry) {
return this._helper.getCameraQueryGeometry(this.getCameraPoint(), queryGeometry);
}
get tileSize() {
return this._helper.tileSize;
}
get tileZoom() {
return this._helper.tileZoom;
}
get scale() {
return this._helper.scale;
}
get worldSize() {
return this._helper.worldSize;
}
get width() {
return this._helper.width;
}
get height() {
return this._helper.height;
}
get lngRange() {
return this._helper.lngRange;
}
get latRange() {
return this._helper.latRange;
}
get minZoom() {
return this._helper.minZoom;
}
get maxZoom() {
return this._helper.maxZoom;
}
get zoom() {
return this._helper.zoom;
}
get center() {
return this._helper.center;
}
get minPitch() {
return this._helper.minPitch;
}
get maxPitch() {
return this._helper.maxPitch;
}
get pitch() {
return this._helper.pitch;
}
get pitchInRadians() {
return this._helper.pitchInRadians;
}
get roll() {
return this._helper.roll;
}
get rollInRadians() {
return this._helper.rollInRadians;
}
get bearing() {
return this._helper.bearing;
}
get bearingInRadians() {
return this._helper.bearingInRadians;
}
get fov() {
return this._helper.fov;
}
get fovInRadians() {
return this._helper.fovInRadians;
}
get elevation() {
return this._helper.elevation;
}
get minElevationForCurrentTile() {
return this._helper.minElevationForCurrentTile;
}
get padding() {
return this._helper.padding;
}
get unmodified() {
return this._helper.unmodified;
}
get renderWorldCopies() {
return this._helper.renderWorldCopies;
}
get cameraToCenterDistance() {
return this._helper.cameraToCenterDistance;
}
get constrainOverride() {
return this._helper.constrainOverride;
}
get nearZ() {
return this._helper.nearZ;
}
get farZ() {
return this._helper.farZ;
}
get autoCalculateNearFarZ() {
return this._helper.autoCalculateNearFarZ;
}
/**
* True when globe render path should be used instead of the old but simpler mercator rendering.
* Globe automatically transitions to mercator at high zoom levels, which causes a switch from
* globe to mercator render path.
*/
get isGlobeRendering() {
return this._globeness > 0;
}
setTransitionState(globeness) {
this._globeness = globeness;
this._calcMatrices();
this._verticalPerspectiveTransform.getCoveringTilesDetailsProvider().prepareNextFrame();
this._mercatorTransform.getCoveringTilesDetailsProvider().prepareNextFrame();
}
get currentTransform() {
return this.isGlobeRendering ? this._verticalPerspectiveTransform : this._mercatorTransform;
}
constructor(options) {
this._globeness = 1;
this.defaultConstrain = (lngLat, zoom) => {
return this.currentTransform.defaultConstrain(lngLat, zoom);
};
this.applyConstrain = (lngLat, zoom) => {
return this._helper.applyConstrain(lngLat, zoom);
};
this._helper = new TransformHelper({
calcMatrices: () => this._calcMatrices(),
defaultConstrain: (center, zoom) => {
return this.defaultConstrain(center, zoom);
}
}, options);
this._globeness = 1;
this._mercatorTransform = new MercatorTransform();
this._verticalPerspectiveTransform = new VerticalPerspectiveTransform();
}
clone() {
const clone = new GlobeTransform();
clone._globeness = this._globeness;
clone.apply(this, false);
return clone;
}
apply(that, constrain) {
this._helper.apply(that, constrain);
this._mercatorTransform.apply(this, false);
this._verticalPerspectiveTransform.apply(this, false);
}
get projectionMatrix() {
return this.currentTransform.projectionMatrix;
}
get modelViewProjectionMatrix() {
return this.currentTransform.modelViewProjectionMatrix;
}
get inverseProjectionMatrix() {
return this.currentTransform.inverseProjectionMatrix;
}
get cameraPosition() {
return this.currentTransform.cameraPosition;
}
getProjectionData(params) {
const mercatorProjectionData = this._mercatorTransform.getProjectionData(params);
const verticalPerspectiveProjectionData = this._verticalPerspectiveTransform.getProjectionData(params);
return {
mainMatrix: this.isGlobeRendering ? verticalPerspectiveProjectionData.mainMatrix : mercatorProjectionData.mainMatrix,
clippingPlane: verticalPerspectiveProjectionData.clippingPlane,
tileMercatorCoords: verticalPerspectiveProjectionData.tileMercatorCoords,
projectionTransition: params.applyGlobeMatrix ? this._globeness : 0,
fallbackMatrix: mercatorProjectionData.fallbackMatrix,
clipAntimeridian: verticalPerspectiveProjectionData.clipAntimeridian
};
}
isLocationOccluded(location) {
return this.currentTransform.isLocationOccluded(location);
}
transformLightDirection(dir) {
return this.currentTransform.transformLightDirection(dir);
}
getPixelScale() {
return lerp(this._mercatorTransform.getPixelScale(), this._verticalPerspectiveTransform.getPixelScale(), this._globeness);
}
getCircleRadiusCorrection() {
return lerp(this._mercatorTransform.getCircleRadiusCorrection(), this._verticalPerspectiveTransform.getCircleRadiusCorrection(), this._globeness);
}
getPitchedTextCorrection(textAnchorX, textAnchorY, tileID) {
const mercatorCorrection = this._mercatorTransform.getPitchedTextCorrection(textAnchorX, textAnchorY, tileID);
const verticalCorrection = this._verticalPerspectiveTransform.getPitchedTextCorrection(textAnchorX, textAnchorY, tileID);
return lerp(mercatorCorrection, verticalCorrection, this._globeness);
}
projectTileCoordinates(x, y, unwrappedTileID, getElevation) {
return this.currentTransform.projectTileCoordinates(x, y, unwrappedTileID, getElevation);
}
_calcMatrices() {
if (!this._helper._width || !this._helper._height) return;
this._verticalPerspectiveTransform.apply(this, false);
this._helper._nearZ = this._verticalPerspectiveTransform.nearZ;
this._helper._farZ = this._verticalPerspectiveTransform.farZ;
this._mercatorTransform.apply(this, true, this.isGlobeRendering);
this._helper._nearZ = this._mercatorTransform.nearZ;
this._helper._farZ = this._mercatorTransform.farZ;
}
calculateFogMatrix(unwrappedTileID) {
return this.currentTransform.calculateFogMatrix(unwrappedTileID);
}
getVisibleUnwrappedCoordinates(tileID) {
return this.currentTransform.getVisibleUnwrappedCoordinates(tileID);
}
getCameraFrustum() {
return this.currentTransform.getCameraFrustum();
}
getClippingPlane() {
return this.currentTransform.getClippingPlane();
}
getCoveringTilesDetailsProvider() {
return this.currentTransform.getCoveringTilesDetailsProvider();
}
recalculateZoomAndCenter(terrain) {
this.currentTransform.recalculateZoomAndCenter(terrain);
}
maxPitchScaleFactor() {
return this._mercatorTransform.maxPitchScaleFactor();
}
getCameraPoint() {
return this._helper.getCameraPoint();
}
getCameraAltitude() {
return this._helper.getCameraAltitude();
}
getCameraLngLat() {
return this._helper.getCameraLngLat();
}
lngLatToCameraDepth(lngLat, elevation) {
return this.currentTransform.lngLatToCameraDepth(lngLat, elevation);
}
populateCache(coords) {
this._mercatorTransform.populateCache(coords);
this._verticalPerspectiveTransform.populateCache(coords);
}
getBounds() {
return this.currentTransform.getBounds();
}
calculateCenterFromCameraLngLatAlt(lngLat, alt, bearing, pitch) {
return this._helper.calculateCenterFromCameraLngLatAlt(lngLat, alt, bearing, pitch);
}
/**
* Note: automatically adjusts zoom to keep planet size consistent
* (same size before and after a {@link setLocationAtPoint} call).
*/
setLocationAtPoint(lnglat, point, elevation) {
if (!this.isGlobeRendering) {
this._mercatorTransform.setLocationAtPoint(lnglat, point, elevation);
this.apply(this._mercatorTransform, false);
return;
}
this._verticalPerspectiveTransform.setLocationAtPoint(lnglat, point, elevation);
this.apply(this._verticalPerspectiveTransform, false);
}
locationToScreenPoint(lnglat, terrain) {
return this.currentTransform.locationToScreenPoint(lnglat, terrain);
}
screenPointToMercatorCoordinate(p, terrain) {
return this.currentTransform.screenPointToMercatorCoordinate(p, terrain);
}
screenPointToLocation(p, terrain) {
return this.currentTransform.screenPointToLocation(p, terrain);
}
screenPointToLocationAtElevation(p, elevation) {
return this.currentTransform.screenPointToLocationAtElevation(p, elevation);
}
isPointOnMapSurface(p, terrain) {
return this.currentTransform.isPointOnMapSurface(p, terrain);
}
/**
* Computes normalized direction of a ray from the camera to the given screen pixel.
*/
getRayDirectionFromPixel(p) {
return this._verticalPerspectiveTransform.getRayDirectionFromPixel(p);
}
getProjectionDataForCustomLayer(applyGlobeMatrix = true) {
const mercatorData = this._mercatorTransform.getProjectionDataForCustomLayer(applyGlobeMatrix);
if (!this.isGlobeRendering) return mercatorData;
const globeData = this._verticalPerspectiveTransform.getProjectionDataForCustomLayer(applyGlobeMatrix);
globeData.fallbackMatrix = mercatorData.mainMatrix;
globeData.projectionTransition = this._globeness;
return globeData;
}
getFastPathSimpleProjectionMatrix(tileID) {
return this.currentTransform.getFastPathSimpleProjectionMatrix(tileID);
}
};
//#endregion
//#region src/geo/projection/vertical_perspective_camera_helper.ts
/**
* Zoom movement slowing starts when the mouse ray passes further than this above the planet surface,
* so a cursor off the globe does not move the map unnaturally. Globe radius is 1, so 0.3 is ~2000 km.
*/
const RAY_SURFACE_DISTANCE_FOR_SLOWING_START = .3;
/** How sharply zoom movement slows as the mouse ray rises above the planet surface. Lower is more gradual. */
const SLOWING_MULTIPLIER = .5;
/** Longitude difference between zoom location and map center at which the blend from exact to heuristic zooming starts, in degrees. */
const INTERPOLATE_TO_HEURISTIC_START_LNG = 45;
/** Longitude difference at which the blend to heuristic zooming is complete, in degrees. */
const INTERPOLATE_TO_HEURISTIC_END_LNG = 85;
/** Exponent applied to the blend factor: below 1, so the blend leans towards heuristic zooming and flattens as it completes. */
const INTERPOLATE_TO_HEURISTIC_EXPONENT = .25;
/**
* Distance of the mouse ray from the globe center at which the blend from exact to heuristic zooming
* starts. Globe radius is 1, so 1 is a ray grazing the horizon.
*/
const INTERPOLATE_TO_HEURISTIC_START_HORIZON = .95;
/** Ray distance at which the blend to heuristic zooming is complete. */
const INTERPOLATE_TO_HEURISTIC_END_HORIZON = .999;
/**
* Globe radius relative to the smaller viewport dimension below which zoom movement near the horizon
* starts being inhibited, avoiding unnatural movements when the map is zoomed out a lot.
*/
const SLOWING_RADIUS_START = .9;
/** Globe radius relative to the smaller viewport dimension at which that inhibition is at full strength. */
const SLOWING_RADIUS_STOP = .5;
/** Fraction of the zoom movement that remains once the globe has shrunk to `SLOWING_RADIUS_STOP`. */
const SLOWING_RADIUS_SLOW_FACTOR = .25;
/**
* @internal
*/
var VerticalPerspectiveCameraHelper = class VerticalPerspectiveCameraHelper {
get useGlobeControls() {
return true;
}
handlePanInertia(pan, transform) {
const panCenter = computeGlobePanCenter(pan, transform);
if (Math.abs(panCenter.lng - transform.center.lng) > 180) panCenter.lng = transform.center.lng + 179.5 * Math.sign(panCenter.lng - transform.center.lng);
return {
easingCenter: panCenter,
easingOffset: new Point(0, 0)
};
}
/**
* Zooms around the pointer.
*
* `setLocationAtPoint` is exact but degenerates when called repeatedly for a
* location whose longitude is far from the center's, or one near the horizon,
* so those cases blend towards a heuristic.
*/
handleMapControlsRollPitchBearingZoom(deltas, tr) {
const zoomPixel = deltas.around;
const zoomLoc = tr.screenPointToLocation(zoomPixel);
if (deltas.bearingDelta) tr.setBearing(tr.bearing + deltas.bearingDelta);
if (deltas.pitchDelta) tr.setPitch(tr.pitch + deltas.pitchDelta);
if (deltas.rollDelta) tr.setRoll(tr.roll + deltas.rollDelta);
const oldZoomPreZoomDelta = tr.zoom;
if (deltas.zoomDelta) tr.setZoom(tr.zoom + deltas.zoomDelta);
const actualZoomDelta = tr.zoom - oldZoomPreZoomDelta;
if (actualZoomDelta === 0) return;
const dLngRaw = differenceOfAnglesDegrees(tr.center.lng, zoomLoc.lng);
const dLng = dLngRaw / (Math.abs(dLngRaw / 180) + 1);
const dLat = differenceOfAnglesDegrees(tr.center.lat, zoomLoc.lat);
const rayDirection = tr.getRayDirectionFromPixel(zoomPixel);
const rayOrigin = tr.cameraPosition;
const distanceToClosestPoint = dot(rayOrigin, rayDirection) * -1;
const closestPoint = createVec3f64();
add(closestPoint, rayOrigin, [
rayDirection[0] * distanceToClosestPoint,
rayDirection[1] * distanceToClosestPoint,
rayDirection[2] * distanceToClosestPoint
]);
const rayDistanceFromGlobeCenter = length$1(closestPoint);
const distanceFromSurface = rayDistanceFromGlobeCenter - 1;
const distanceFactor = Math.exp(-Math.max(distanceFromSurface - RAY_SURFACE_DISTANCE_FOR_SLOWING_START, 0) * SLOWING_MULTIPLIER);
const interpolationFactorHorizon = remapSaturate(rayDistanceFromGlobeCenter, INTERPOLATE_TO_HEURISTIC_START_HORIZON, INTERPOLATE_TO_HEURISTIC_END_HORIZON, 0, 1);
const radius = getGlobeRadiusPixels(tr.worldSize, tr.center.lat) / Math.min(tr.width, tr.height);
const radiusFactor = remapSaturate(radius, SLOWING_RADIUS_START, SLOWING_RADIUS_STOP, 1, SLOWING_RADIUS_SLOW_FACTOR);
const slowingFactor = Math.min(distanceFactor, lerp(1, radiusFactor, interpolationFactorHorizon));
const factor = (1 - zoomScale(-actualZoomDelta)) * slowingFactor;
const oldCenterLat = tr.center.lat;
const oldZoom = tr.zoom;
const heuristicCenter = new LngLat(tr.center.lng + dLng * factor, clamp(tr.center.lat + dLat * factor, -MAX_VALID_LATITUDE, MAX_VALID_LATITUDE));
tr.setLocationAtPoint(zoomLoc, zoomPixel);
const exactCenter = tr.center;
const interpolationFactorLongitude = remapSaturate(Math.abs(dLngRaw), INTERPOLATE_TO_HEURISTIC_START_LNG, INTERPOLATE_TO_HEURISTIC_END_LNG, 0, 1);
const heuristicFactor = Math.pow(Math.max(interpolationFactorLongitude, interpolationFactorHorizon), INTERPOLATE_TO_HEURISTIC_EXPONENT);
const lngExactToHeuristic = differenceOfAnglesDegrees(exactCenter.lng, heuristicCenter.lng);
const latExactToHeuristic = differenceOfAnglesDegrees(exactCenter.lat, heuristicCenter.lat);
tr.setCenter(new LngLat(exactCenter.lng + lngExactToHeuristic * heuristicFactor, exactCenter.lat + latExactToHeuristic * heuristicFactor).wrap());
tr.setZoom(oldZoom + getZoomAdjustment(oldCenterLat, tr.center.lat));
}
/**
* Pans the globe by rotating it with a single quaternion that brings the grabbed location back
* under the cursor. This stays consistent near and across the poles, where the previous
* bearing-preserving mapping inverted and stalled (#5296).
* @param deltas - The deltas accumulated for this frame.
* @param tr - The transform to pan.
* @param preZoomAroundLoc - The location that was under the cursor before this frame.
*/
handleMapControlsPan(deltas, tr, preZoomAroundLoc) {
if (!deltas.panDelta) return;
versorSetLocationAtPoint(tr, preZoomAroundLoc, tr.isPointOnMapSurface(deltas.around) ? deltas.around : tr.centerPoint, deltas.panDelta);
}
cameraForBoxAndBearing(options, padding, bounds, bearing, tr) {
const result = cameraForBoxAndBearing(options, padding, bounds, bearing, tr);
const xLeft = padding.left / tr.width * 2 - 1;
const xRight = (tr.width - padding.right) / tr.width * 2 - 1;
const yTop = padding.top / tr.height * -2 + 1;
const yBottom = (tr.height - padding.bottom) / tr.height * -2 + 1;
const flipEastWest = differenceOfAnglesDegrees(bounds.getWest(), bounds.getEast()) < 0;
const lngWest = flipEastWest ? bounds.getEast() : bounds.getWest();
const lngEast = flipEastWest ? bounds.getWest() : bounds.getEast();
const latNorth = Math.max(bounds.getNorth(), bounds.getSouth());
const latSouth = Math.min(bounds.getNorth(), bounds.getSouth());
const lngMid = lngWest + differenceOfAnglesDegrees(lngWest, lngEast) * .5;
const latMid = latNorth + differenceOfAnglesDegrees(latNorth, latSouth) * .5;
const clonedTr = tr.clone();
clonedTr.setCenter(result.center);
clonedTr.setBearing(result.bearing);
clonedTr.setPitch(0);
clonedTr.setRoll(0);
clonedTr.setZoom(result.zoom);
const matrix = clonedTr.modelViewProjectionMatrix;
const testVectors = [
angularCoordinatesToSurfaceVector(bounds.getNorthWest()),
angularCoordinatesToSurfaceVector(bounds.getNorthEast()),
angularCoordinatesToSurfaceVector(bounds.getSouthWest()),
angularCoordinatesToSurfaceVector(bounds.getSouthEast()),
angularCoordinatesToSurfaceVector(new LngLat(lngEast, latMid)),
angularCoordinatesToSurfaceVector(new LngLat(lngWest, latMid)),
angularCoordinatesToSurfaceVector(new LngLat(lngMid, latNorth)),
angularCoordinatesToSurfaceVector(new LngLat(lngMid, latSouth))
];
const vecToCenter = angularCoordinatesToSurfaceVector(result.center);
let smallestNeededScale = Number.POSITIVE_INFINITY;
for (const vec of testVectors) {
if (xLeft < 0) smallestNeededScale = VerticalPerspectiveCameraHelper.getLesserNonNegativeNonNull(smallestNeededScale, VerticalPerspectiveCameraHelper.solveVectorScale(vec, vecToCenter, matrix, "x", xLeft));
if (xRight > 0) smallestNeededScale = VerticalPerspectiveCameraHelper.getLesserNonNegativeNonNull(smallestNeededScale, VerticalPerspectiveCameraHelper.solveVectorScale(vec, vecToCenter, matrix, "x", xRight));
if (yTop > 0) smallestNeededScale = VerticalPerspectiveCameraHelper.getLesserNonNegativeNonNull(smallestNeededScale, VerticalPerspectiveCameraHelper.solveVectorScale(vec, vecToCenter, matrix, "y", yTop));
if (yBottom < 0) smallestNeededScale = VerticalPerspectiveCameraHelper.getLesserNonNegativeNonNull(smallestNeededScale, VerticalPerspectiveCameraHelper.solveVectorScale(vec, vecToCenter, matrix, "y", yBottom));
}
if (!Number.isFinite(smallestNeededScale) || smallestNeededScale === 0) {
cameraBoundsWarning();
return;
}
result.zoom = Math.min(clonedTr.zoom + scaleZoom(smallestNeededScale), options.maxZoom);
return result;
}
/**
* Handles the zoom and center change during camera jumpTo.
*/
handleJumpToCenterZoom(tr, options) {
const startingLat = tr.center.lat;
const constrainedCenter = tr.applyConstrain(options.center ? LngLat.convert(options.center) : tr.center, tr.zoom).center;
tr.setCenter(constrainedCenter.wrap());
const targetZoom = typeof options.zoom !== "undefined" ? +options.zoom : tr.zoom + getZoomAdjustment(startingLat, constrainedCenter.lat);
if (tr.zoom !== targetZoom) tr.setZoom(targetZoom);
}
handleEaseTo(tr, options) {
const startZoom = tr.zoom;
const startCenter = tr.center;
const startPadding = tr.padding;
const startEulerAngles = {
roll: tr.roll,
pitch: tr.pitch,
bearing: tr.bearing
};
const endEulerAngles = {
roll: options.roll === void 0 ? tr.roll : options.roll,
pitch: options.pitch === void 0 ? tr.pitch : options.pitch,
bearing: options.bearing === void 0 ? tr.bearing : options.bearing
};
const optionsZoom = typeof options.zoom !== "undefined";
const doPadding = !tr.isPaddingEqual(options.padding);
let isZooming = false;
const preConstrainCenter = options.center ? LngLat.convert(options.center) : startCenter;
const constrainedCenter = tr.applyConstrain(preConstrainCenter, startZoom).center;
normalizeCenter(tr, constrainedCenter);
const clonedTr = tr.clone();
clonedTr.setCenter(constrainedCenter);
clonedTr.setZoom(optionsZoom ? +options.zoom : startZoom + getZoomAdjustment(startCenter.lat, preConstrainCenter.lat));
clonedTr.setBearing(options.bearing);
const clampedPoint = new Point(clamp(tr.centerPoint.x + options.offsetAsPoint.x, 0, tr.width), clamp(tr.centerPoint.y + options.offsetAsPoint.y, 0, tr.height));
clonedTr.setLocationAtPoint(constrainedCenter, clampedPoint);
const endCenterWithShift = (options.offset && options.offsetAsPoint.mag()) > 0 ? clonedTr.center : constrainedCenter;
const endZoomWithShift = optionsZoom ? +options.zoom : startZoom + getZoomAdjustment(startCenter.lat, endCenterWithShift.lat);
const normalizedStartZoom = startZoom + getZoomAdjustment(startCenter.lat, 0);
const normalizedEndZoom = endZoomWithShift + getZoomAdjustment(endCenterWithShift.lat, 0);
const deltaLng = differenceOfAnglesDegrees(startCenter.lng, endCenterWithShift.lng);
const deltaLat = differenceOfAnglesDegrees(startCenter.lat, endCenterWithShift.lat);
const finalScale = zoomScale(normalizedEndZoom - normalizedStartZoom);
isZooming = endZoomWithShift !== startZoom;
const easeFunc = (k) => {
if (!rollPitchBearingEqual(startEulerAngles, endEulerAngles)) updateRotation({
startEulerAngles,
endEulerAngles,
tr,
k,
useSlerp: startEulerAngles.roll != endEulerAngles.roll
});
if (doPadding) tr.interpolatePadding(startPadding, options.padding, k);
if (options.around) {
warnOnce("Easing around a point is not supported under globe projection.");
tr.setLocationAtPoint(options.around, options.aroundPoint);
} else {
const factor = k * Math.pow(normalizedEndZoom > normalizedStartZoom ? Math.min(2, finalScale) : Math.max(.5, finalScale), 1 - k);
const newCenter = interpolateLngLatForGlobe(startCenter, deltaLng, deltaLat, factor);
tr.setCenter(newCenter.wrap());
}
if (isZooming) {
const interpolatedZoom = interpolateFactory.number(normalizedStartZoom, normalizedEndZoom, k) + getZoomAdjustment(0, tr.center.lat);
tr.setZoom(interpolatedZoom);
}
};
return {
easeFunc,
isZooming,
elevationCenter: endCenterWithShift
};
}
handleFlyTo(tr, options) {
const optionsZoom = typeof options.zoom !== "undefined";
const startCenter = tr.center;
const startZoom = tr.zoom;
const startPadding = tr.padding;
const doPadding = !tr.isPaddingEqual(options.padding);
const constrainedCenter = tr.applyConstrain(LngLat.convert(options.center || options.locationAtOffset), startZoom).center;
const targetZoom = optionsZoom ? +options.zoom : tr.zoom + getZoomAdjustment(tr.center.lat, constrainedCenter.lat);
const clonedTr = tr.clone();
clonedTr.setCenter(constrainedCenter);
clonedTr.setZoom(targetZoom);
clonedTr.setBearing(options.bearing);
const clampedPoint = new Point(clamp(tr.centerPoint.x + options.offsetAsPoint.x, 0, tr.width), clamp(tr.centerPoint.y + options.offsetAsPoint.y, 0, tr.height));
clonedTr.setLocationAtPoint(constrainedCenter, clampedPoint);
const targetCenter = clonedTr.center;
normalizeCenter(tr, targetCenter);
const pixelPathLength = globeDistanceOfLocationsPixels(tr, startCenter, targetCenter);
const normalizedStartZoom = startZoom + getZoomAdjustment(startCenter.lat, 0);
const normalizedTargetZoom = targetZoom + getZoomAdjustment(targetCenter.lat, 0);
const scaleOfZoom = zoomScale(normalizedTargetZoom - normalizedStartZoom);
const requestedMinZoom = typeof options.minZoom === "number" ? +options.minZoom : tr.minZoom;
const normalizedEffectiveMinZoom = Math.max(requestedMinZoom, tr.minZoom) + getZoomAdjustment(targetCenter.lat, 0);
const minZoomPreConstrain = Math.min(normalizedEffectiveMinZoom, normalizedStartZoom, normalizedTargetZoom) + getZoomAdjustment(0, targetCenter.lat);
const normalizedMinZoom = tr.applyConstrain(targetCenter, minZoomPreConstrain).zoom + getZoomAdjustment(targetCenter.lat, 0);
const scaleOfMinZoom = zoomScale(normalizedMinZoom - normalizedStartZoom);
const deltaLng = differenceOfAnglesDegrees(startCenter.lng, targetCenter.lng);
const deltaLat = differenceOfAnglesDegrees(startCenter.lat, targetCenter.lat);
const easeFunc = (k, scale, centerFactor, _pointAtOffset) => {
const interpolatedCenter = interpolateLngLatForGlobe(startCenter, deltaLng, deltaLat, centerFactor);
if (doPadding) tr.interpolatePadding(startPadding, options.padding, k);
const newCenter = k === 1 ? targetCenter : interpolatedCenter;
tr.setCenter(newCenter.wrap());
const interpolatedZoom = normalizedStartZoom + scaleZoom(scale);
tr.setZoom(k === 1 ? targetZoom : interpolatedZoom + getZoomAdjustment(0, newCenter.lat));
};
return {
easeFunc,
scaleOfZoom,
targetCenter,
scaleOfMinZoom,
pixelPathLength
};
}
/**
* Computes how much to scale the globe in order for a given point on its surface (a location) to project to a given clip space coordinate in either the X or the Y axis.
* @param vector - Position of the queried location on the surface of the unit sphere globe.
* @param toCenter - Position of current transform center on the surface of the unit sphere globe.
* This is needed because zooming the globe not only changes its scale,
* but also moves the camera closer or further away along this vector (pitch is disregarded).
* @param projection - The globe projection matrix.
* @param targetDimension - The dimension in which the scaled vector must match the target value in clip space.
* @param targetValue - The target clip space value in the specified dimension to which the queried vector must project.
* @returns How much to scale the globe.
*/
static solveVectorScale(vector, toCenter, projection, targetDimension, targetValue) {
const k = targetValue;
const columnXorY = targetDimension === "x" ? [
projection[0],
projection[4],
projection[8],
projection[12]
] : [
projection[1],
projection[5],
projection[9],
projection[13]
];
const columnZ = [
projection[3],
projection[7],
projection[11],
projection[15]
];
const vecDotXY = vector[0] * columnXorY[0] + vector[1] * columnXorY[1] + vector[2] * columnXorY[2];
const vecDotZ = vector[0] * columnZ[0] + vector[1] * columnZ[1] + vector[2] * columnZ[2];
const toCenterDotXY = toCenter[0] * columnXorY[0] + toCenter[1] * columnXorY[1] + toCenter[2] * columnXorY[2];
const toCenterDotZ = toCenter[0] * columnZ[0] + toCenter[1] * columnZ[1] + toCenter[2] * columnZ[2];
const t = (toCenterDotXY + columnXorY[3] - k * toCenterDotZ - k * columnZ[3]) / (toCenterDotXY - vecDotXY - k * toCenterDotZ + k * vecDotZ);
if (toCenterDotXY + k * vecDotZ === vecDotXY + k * toCenterDotZ || columnZ[3] * (vecDotXY - toCenterDotXY) + columnXorY[3] * (toCenterDotZ - vecDotZ) + vecDotXY * toCenterDotZ === toCenterDotXY * vecDotZ) return null;
return t;
}
/**
* Returns `newValue` if it is:
*
* - not null AND
* - not negative AND
* - smaller than `newValue`,
*
* ...otherwise returns `oldValue`.
*/
static getLesserNonNegativeNonNull(oldValue, newValue) {
if (newValue !== null && newValue >= 0 && newValue < oldValue) return newValue;
else return oldValue;
}
};
//#endregion
//#region src/geo/projection/globe_camera_helper.ts
/**
* @internal
*/
var GlobeCameraHelper = class {
constructor(globe) {
this._globe = globe;
this._mercatorCameraHelper = new MercatorCameraHelper();
this._verticalPerspectiveCameraHelper = new VerticalPerspectiveCameraHelper();
}
get useGlobeControls() {
return this._globe.useGlobeRendering;
}
get currentHelper() {
return this.useGlobeControls ? this._verticalPerspectiveCameraHelper : this._mercatorCameraHelper;
}
handlePanInertia(pan, transform) {
return this.currentHelper.handlePanInertia(pan, transform);
}
handleMapControlsRollPitchBearingZoom(deltas, tr) {
this.currentHelper.handleMapControlsRollPitchBearingZoom(deltas, tr);
}
handleMapControlsPan(deltas, tr, preZoomAroundLoc) {
this.currentHelper.handleMapControlsPan(deltas, tr, preZoomAroundLoc);
}
cameraForBoxAndBearing(options, padding, bounds, bearing, tr) {
return this.currentHelper.cameraForBoxAndBearing(options, padding, bounds, bearing, tr);
}
/**
* Handles the zoom and center change during camera jumpTo.
*/
handleJumpToCenterZoom(tr, options) {
this.currentHelper.handleJumpToCenterZoom(tr, options);
}
handleEaseTo(tr, options) {
return this.currentHelper.handleEaseTo(tr, options);
}
handleFlyTo(tr, options) {
return this.currentHelper.handleFlyTo(tr, options);
}
};
//#endregion
//#region src/geo/projection/projection_factory.ts
function createProjectionFromName(name, transformConstrain, globalState) {
const transformOptions = { constrainOverride: transformConstrain };
if (Array.isArray(name)) {
const globeProjection = new GlobeProjection({ type: name }, globalState);
return {
projection: globeProjection,
transform: new GlobeTransform(transformOptions),
cameraHelper: new GlobeCameraHelper(globeProjection)
};
}
switch (name) {
case "mercator": return {
projection: new MercatorProjection(),
transform: new MercatorTransform(transformOptions),
cameraHelper: new MercatorCameraHelper()
};
case "globe": {
const globeProjection = new GlobeProjection({ type: [
"interpolate",
["linear"],
["zoom"],
11,
"vertical-perspective",
12,
"mercator"
] }, {});
return {
projection: globeProjection,
transform: new GlobeTransform(transformOptions),
cameraHelper: new GlobeCameraHelper(globeProjection)
};
}
case "vertical-perspective": return {
projection: new VerticalPerspectiveProjection(),
transform: new VerticalPerspectiveTransform(transformOptions),
cameraHelper: new VerticalPerspectiveCameraHelper()
};
default:
warnOnce(`Unknown projection name: ${name}. Falling back to mercator projection.`);
return {
projection: new MercatorProjection(),
transform: new MercatorTransform(transformOptions),
cameraHelper: new MercatorCameraHelper()
};
}
}
//#endregion
//#region src/style/style.ts
const empty = emptyStyle();
/**
* The Style base class
*/
var Style = class extends Evented {
constructor(map, options = {}) {
super();
this._rtlPluginLoaded = () => {
for (const id in this.tileManagers) {
const sourceType = this.tileManagers[id].getSource().type;
if (sourceType === "vector" || sourceType === "geojson") this.tileManagers[id].reload();
}
};
this.map = map;
this.dispatcher = new Dispatcher(getGlobalWorkerPool(), map._getMapId());
this.dispatcher.registerMessageHandler("GG", (mapId, params) => {
return this.getGlyphs(mapId, params);
});
this.dispatcher.registerMessageHandler("GI", (mapId, params) => {
return this.getImages(mapId, params);
});
this.dispatcher.registerMessageHandler("GDA", (mapId, params) => {
return this.getDashes(mapId, params);
});
this.imageManager = new ImageManager();
this.imageManager.setEventedParent(this);
this.imageManager.setMissingImageResolver(map._missingStyleImageResolver);
this.patternAtlas = new PatternAtlas(this.imageManager);
const glyphLang = map._container?.lang || typeof document !== "undefined" && document.documentElement?.lang || void 0;
this.glyphManager = new GlyphManager(map._requestManager, options.localIdeographFontFamily, glyphLang);
this.lineAtlas = new LineAtlas(256, 512);
this.crossTileSymbolIndex = new CrossTileSymbolIndex();
this._setInitialValues();
this._resetUpdates();
this.dispatcher.broadcast("SR", getReferrer());
rtlMainThreadPluginFactory().on(RTLPluginLoadedEventName, this._rtlPluginLoaded);
this.on("data", (event) => {
if (event.dataType !== "source" || event.sourceDataType !== "metadata") return;
const tileManager = this.tileManagers[event.sourceId];
if (!tileManager) return;
const source = tileManager.getSource();
if (!source?.vectorLayerIds) return;
for (const layerId in this._layers) {
const layer = this._layers[layerId];
if (layer.source === source.id) this._validateLayer(layer);
}
});
}
_setInitialValues() {
this._layers = {};
this._order = [];
this.tileManagers = {};
this.zoomHistory = new ZoomHistory();
this._imagesListDirty = false;
this._globalState = {};
this._serializedLayers = {};
this.stylesheet = null;
this.light = null;
this.sky = null;
if (this.projection) {
this.projection.destroy();
delete this.projection;
}
this._loaded = false;
this._changed = false;
this._updatedLayers = {};
this._updatedSources = {};
this._changedImages = {};
this._glyphsDidChange = false;
this._updatedPaintProps = {};
this._layerOrderChanged = false;
this.crossTileSymbolIndex = new ((this.crossTileSymbolIndex?.constructor) || Object)();
this.pauseablePlacement = void 0;
this.placement = void 0;
this.z = 0;
}
setGlobalStateProperty(name, value) {
this._checkLoaded();
const newValue = value === null ? this.stylesheet.state?.[name]?.default ?? null : value;
if (deepEqual(newValue, this._globalState[name])) return this;
this._globalState[name] = newValue;
this._applyGlobalStateChanges([name]);
}
getGlobalState() {
return this._globalState;
}
setGlobalState(newStylesheetState) {
this._checkLoaded();
const changedGlobalStateRefs = [];
for (const propertyName in newStylesheetState) if (!deepEqual(this._globalState[propertyName], newStylesheetState[propertyName].default)) {
changedGlobalStateRefs.push(propertyName);
this._globalState[propertyName] = newStylesheetState[propertyName].default;
}
this._applyGlobalStateChanges(changedGlobalStateRefs);
}
/**
* @internal
* Find all sources that are affected by the global state changes and reload them.
* Find all paint properties that are affected by the global state changes and update them.
* For example, if a layer filter uses global-state expression, this function will find the source id of that layer.
*/
_applyGlobalStateChanges(globalStateRefs) {
if (globalStateRefs.length === 0) return;
const sourceIdsToReload = /* @__PURE__ */ new Set();
const globalStateChange = {};
for (const ref of globalStateRefs) {
globalStateChange[ref] = this._globalState[ref];
for (const layerId in this._layers) {
const layer = this._layers[layerId];
const layoutAffectingGlobalStateRefs = layer.getLayoutAffectingGlobalStateRefs();
const paintAffectingGlobalStateRefs = layer.getPaintAffectingGlobalStateRefs();
const visibilityAffectingGlobalStateRefs = layer.getVisibilityAffectingGlobalStateRefs();
if (layoutAffectingGlobalStateRefs.has(ref)) sourceIdsToReload.add(layer.source);
if (paintAffectingGlobalStateRefs.has(ref)) for (const { name, value } of paintAffectingGlobalStateRefs.get(ref)) this._updatePaintProperty(layer, name, value);
if (visibilityAffectingGlobalStateRefs?.has(ref)) {
layer.recalculateVisibility();
this._updateLayer(layer);
}
}
}
this.dispatcher.broadcast("UGS", globalStateChange);
for (const id in this.tileManagers) if (sourceIdsToReload.has(id)) {
this._reloadSource(id);
this._changed = true;
}
}
async loadURL(url, options = {}, previousStyle) {
this.fire(new MapStyleDataEvent("dataloading"));
options.validate = typeof options.validate === "boolean" ? options.validate : true;
this._loadStyleRequest = new AbortController();
const abortController = this._loadStyleRequest;
try {
const request = await this.map._requestManager.transformRequest(url, "Style");
throwIfAborted(abortController.signal);
const response = await getJSON(request, abortController);
if (this._loadStyleRequest === abortController) this._loadStyleRequest = null;
this._load(response.data, options, previousStyle);
} catch (error) {
if (this._loadStyleRequest === abortController) this._loadStyleRequest = null;
if (error && !abortController.signal.aborted) this.fire(new ErrorEvent(ensureError(error)));
}
}
loadJSON(json, options = {}, previousStyle) {
this.fire(new MapStyleDataEvent("dataloading"));
this._frameRequest = new AbortController();
browser.frameAsync(this._frameRequest, this.map._ownerWindow).then(() => {
this._frameRequest = null;
options.validate = options.validate !== false;
this._load(json, options, previousStyle);
}).catch(() => {});
}
loadEmpty() {
this.fire(new MapStyleDataEvent("dataloading"));
this._load(empty, { validate: false });
}
_load(json, options, previousStyle) {
let nextState = options.transformStyle ? options.transformStyle(previousStyle, json) : json;
if (options.validate && validateStyleAndEmit(this, nextState)) return;
nextState = { ...nextState };
this._loaded = true;
this.stylesheet = nextState;
for (const id in nextState.sources) this.addSource(id, nextState.sources[id], { validate: false });
if (nextState.sprite) this._loadSprite(nextState.sprite);
else this.imageManager.setLoaded(true);
this.glyphManager.setURL(nextState.glyphs);
this._createLayers();
this.light = new Light(this.stylesheet.light ?? {}, this._globalState);
this._setProjectionInternal(this.stylesheet.projection?.type || "mercator");
this.sky = new Sky(this.stylesheet.sky, this._globalState);
this.map.setTerrain(this.stylesheet.terrain ?? null, { validate: false });
this.fire(new MapStyleDataEvent("data"));
this.fire(new MapStyleLoadEvent());
}
_createLayers() {
const dereferencedLayers = derefLayers(this.stylesheet.layers);
this.setGlobalState(this.stylesheet.state ?? null);
this.dispatcher.broadcast("SL", dereferencedLayers);
this._order = dereferencedLayers.map((layer) => layer.id);
this._layers = {};
this._serializedLayers = null;
for (const layer of dereferencedLayers) {
const styledLayer = createStyleLayer(layer, this._globalState);
styledLayer.setEventedParent(this, { layer: { id: layer.id } });
this._layers[layer.id] = styledLayer;
if (isRasterStyleLayer(styledLayer) && this.tileManagers[styledLayer.source]) {
const rasterFadeDuration = layer.paint?.["raster-fade-duration"] ?? styledLayer.paint.get("raster-fade-duration");
this.tileManagers[styledLayer.source].setRasterFadeDuration(rasterFadeDuration);
}
}
}
async _loadSprite(sprite, isUpdate = false, completion = void 0) {
this.imageManager.setLoaded(false);
const abortController = new AbortController();
this._spriteRequest = abortController;
let err;
try {
const images = await loadSprite(sprite, this.map._requestManager, this.map.getPixelRatio(), abortController);
if (!images) return;
for (const spriteId in images) {
const { loaded, removed } = this.imageManager.setSpriteImages(spriteId, images[spriteId]);
this._markImagesChanged(removed);
if (isUpdate) this._markImagesChanged(loaded);
}
} catch (error) {
err = error;
if (!abortController.signal.aborted) this.fire(new ErrorEvent(err));
} finally {
this._spriteRequest = null;
this.imageManager.setLoaded(true);
if (isUpdate) this._changed = true;
this.dispatcher.broadcast("SI", this.imageManager.listImages());
this.fire(new MapStyleDataEvent("data"));
completion?.(err);
}
}
_unloadSprite() {
this._markImagesChanged(this.imageManager.removeAllSpriteImages());
this._imagesListDirty = true;
this._changed = true;
this.fire(new MapStyleDataEvent("data"));
}
_validateLayer(layer) {
const tileManager = this.tileManagers[layer.source];
if (!tileManager) return;
const sourceLayer = layer.sourceLayer;
if (!sourceLayer) return;
const source = tileManager.getSource();
if (source.type === "geojson" || source.vectorLayerIds && !source.vectorLayerIds.includes(sourceLayer)) this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`Source layer "${sourceLayer}" does not exist on source "${source.id}" as specified by style layer "${layer.id}".`)));
}
loaded() {
if (!this._loaded) return false;
if (Object.keys(this._updatedSources).length) return false;
for (const id in this.tileManagers) if (!this.tileManagers[id].loaded()) return false;
return this.imageManager.isLoaded();
}
/**
* @hidden
* take an array of string IDs, and based on this._layers, generate an array of LayerSpecification
* @param ids - an array of string IDs, for which serialized layers will be generated. If omitted, all serialized layers will be returned
* @param returnClone - if true, return a clone of the layer object
* @returns generated result
*/
_serializeByIds(ids, returnClone = false) {
const serializedLayersDictionary = this._serializedAllLayers();
if (!ids || ids.length === 0) return returnClone ? Object.values(clone$2(serializedLayersDictionary)) : Object.values(serializedLayersDictionary);
const serializedLayers = [];
for (const id of ids) if (serializedLayersDictionary[id]) {
const toPush = returnClone ? clone$2(serializedLayersDictionary[id]) : serializedLayersDictionary[id];
serializedLayers.push(toPush);
}
return serializedLayers;
}
/**
* @hidden
* Lazy initialization of this._serializedLayers dictionary and return it
* @returns this._serializedLayers dictionary
*/
_serializedAllLayers() {
let serializedLayers = this._serializedLayers;
if (serializedLayers) return serializedLayers;
serializedLayers = this._serializedLayers = {};
const allLayerIds = Object.keys(this._layers);
for (const layerId of allLayerIds) {
const layer = this._layers[layerId];
if (layer.type !== "custom") serializedLayers[layerId] = layer.serialize();
}
return serializedLayers;
}
hasTransitions() {
if (this.light?.hasTransition()) return true;
if (this.sky?.hasTransition()) return true;
if (this.projection?.hasTransition()) return true;
for (const id in this.tileManagers) if (this.tileManagers[id].hasTransition()) return true;
for (const id in this._layers) if (this._layers[id].hasTransition()) return true;
return false;
}
_checkLoaded() {
if (!this._loaded) throw new Error("Style is not done loading.");
}
/**
* @internal
* Apply queued style updates in a batch and recalculate zoom-dependent paint properties.
*/
update(parameters) {
if (!this._loaded) return;
const changed = this._changed;
if (changed) {
if (this._imagesListDirty) {
this.dispatcher.broadcast("SI", this.imageManager.listImages());
this._imagesListDirty = false;
}
const updatedIds = Object.keys(this._updatedLayers);
const removedIds = Object.keys(this._removedLayers);
if (updatedIds.length || removedIds.length) this._updateWorkerLayers(updatedIds, removedIds);
for (const id in this._updatedSources) {
const action = this._updatedSources[id];
if (action === "reload") this._reloadSource(id);
else if (action === "clear") this._clearSource(id);
else throw new Error(`Invalid action ${action}`);
}
this._updateTilesForChangedImages();
this._updateTilesForChangedGlyphs();
for (const id in this._updatedPaintProps) this._layers[id].updateTransitions(parameters);
this.light.updateTransitions(parameters);
this.sky.updateTransitions(parameters);
this._resetUpdates();
}
const managersUsedBefore = {};
for (const id in this.tileManagers) {
const tileManager = this.tileManagers[id];
managersUsedBefore[id] = tileManager.used;
tileManager.used = false;
}
const availableImages = this.imageManager.listImages();
for (const layerId of this._order) {
const layer = this._layers[layerId];
layer.recalculate(parameters, availableImages);
if (!layer.isHidden(parameters.zoom) && layer.source) this.tileManagers[layer.source].used = true;
}
for (const id in managersUsedBefore) {
const tileManager = this.tileManagers[id];
if (!!managersUsedBefore[id] !== !!tileManager.used) tileManager.fire(new MapSourceDataEvent("data", {
sourceDataType: "visibility",
sourceId: id
}));
}
this.light.recalculate(parameters);
this.sky.recalculate(parameters);
this.projection.recalculate(parameters);
this.z = parameters.zoom;
if (changed) this.fire(new MapStyleDataEvent("data"));
}
_updateTilesForChangedImages() {
const changedImages = Object.keys(this._changedImages);
if (changedImages.length) {
for (const name in this.tileManagers) this.tileManagers[name].reloadTilesForDependencies(["icons", "patterns"], changedImages);
this._changedImages = {};
}
}
_updateTilesForChangedGlyphs() {
if (this._glyphsDidChange) {
for (const name in this.tileManagers) this.tileManagers[name].reloadTilesForDependencies(["glyphs"], [""]);
this._glyphsDidChange = false;
}
}
_updateWorkerLayers(updatedIds, removedIds) {
this.dispatcher.broadcast("UL", {
layers: this._serializeByIds(updatedIds, false),
removedIds
});
}
_resetUpdates() {
this._changed = false;
this._updatedLayers = {};
this._removedLayers = {};
this._updatedSources = {};
this._updatedPaintProps = {};
this._changedImages = {};
this._glyphsDidChange = false;
}
/**
* Update this style's state to match the given style JSON, performing only
* the necessary mutations.
*
* May throw an Error ('Unimplemented: METHOD') if the maplibre-gl-style-spec
* diff algorithm produces an operation that is not supported.
*
* @returns true if any changes were made; false otherwise
*/
setState(nextState, options = {}) {
this._checkLoaded();
const serializedStyle = this.serialize();
nextState = options.transformStyle ? options.transformStyle(serializedStyle, nextState) : nextState;
if ((options.validate ?? true) && validateStyleAndEmit(this, nextState)) return false;
nextState = clone$2(nextState);
nextState.layers = derefLayers(nextState.layers);
const changes = diff(serializedStyle, nextState);
const operations = this._getOperationsToPerform(changes);
if (operations.unimplemented.length > 0) throw new Error(`Unimplemented: ${operations.unimplemented.join(", ")}.`);
if (operations.operations.length === 0) return false;
for (const styleChangeOperation of operations.operations) styleChangeOperation();
this.stylesheet = nextState;
this._serializedLayers = null;
this.fire(new MapStyleLoadEvent({ style: this }));
return true;
}
_getOperationsToPerform(diff) {
const operations = [];
const unimplemented = [];
for (const op of diff) switch (op.command) {
case "setCenter":
case "setZoom":
case "setBearing":
case "setPitch":
case "setRoll": continue;
case "addLayer":
operations.push(() => this.addLayer.apply(this, op.args));
break;
case "removeLayer":
operations.push(() => this.removeLayer.apply(this, op.args));
break;
case "setPaintProperty":
operations.push(() => this.setPaintProperty.apply(this, op.args));
break;
case "setLayoutProperty":
operations.push(() => this.setLayoutProperty.apply(this, op.args));
break;
case "setFilter":
operations.push(() => this.setFilter.apply(this, op.args));
break;
case "addSource":
operations.push(() => this.addSource.apply(this, op.args));
break;
case "removeSource":
operations.push(() => this.removeSource.apply(this, op.args));
break;
case "setLayerZoomRange":
operations.push(() => this.setLayerZoomRange.apply(this, op.args));
break;
case "setLight":
operations.push(() => this.setLight.apply(this, op.args));
break;
case "setGeoJSONSourceData":
operations.push(() => this.setGeoJSONSourceData.apply(this, op.args));
break;
case "setGlyphs":
operations.push(() => this.setGlyphs.apply(this, op.args));
break;
case "setSprite":
operations.push(() => this.setSprite.apply(this, op.args));
break;
case "setTerrain":
operations.push(() => this.map.setTerrain.apply(this, op.args));
break;
case "setSky":
operations.push(() => this.setSky.apply(this, op.args));
break;
case "setProjection":
this.setProjection.apply(this, op.args);
break;
case "setGlobalState":
operations.push(() => this.setGlobalState.apply(this, op.args));
break;
case "setTransition":
operations.push(() => {});
break;
default: unimplemented.push(op.command);
}
return {
operations,
unimplemented
};
}
addImage(id, image) {
if (this.getImage(id)) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`An image named "${id}" already exists.`)));
return;
}
this.imageManager.addImage(id, image);
this._afterImageUpdated(id);
}
updateImage(id, image) {
this.imageManager.updateImage(id, image);
}
getImage(id) {
return this.imageManager.getImage(id);
}
setMissingImageResolver(resolver) {
this.imageManager.setMissingImageResolver(resolver);
}
removeImage(id) {
if (!this.getImage(id)) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`An image named "${id}" does not exist.`)));
return;
}
this.imageManager.removeImage(id);
this._afterImageUpdated(id);
}
/**
* Queues the tiles that depend on these images to be reloaded on the next update, which is
* needed whenever an image appears, disappears or changes size.
*/
_markImagesChanged(ids) {
for (const id of ids) this._changedImages[id] = true;
}
_afterImageUpdated(id) {
this._changedImages[id] = true;
this._imagesListDirty = true;
this._changed = true;
this.fire(new MapStyleDataEvent("data"));
}
listImages() {
this._checkLoaded();
return this.imageManager.listImages();
}
addSource(id, source, options = {}) {
this._checkLoaded();
if (this.tileManagers[id] !== void 0) throw new Error(`Source "${id}" already exists.`);
if (!source.type) throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(source).join(", ")}.`);
if (SPEC_SOURCE_TYPES.has(source.type) && this._validate(validateStyle.source, `sources.${id}`, source, null, options)) return;
if (this.map?._collectResourceTiming) source.collectResourceTiming = true;
const tileManager = this.tileManagers[id] = new TileManager(id, source, this.dispatcher);
tileManager.style = this;
tileManager.setEventedParent(this, () => ({
isSourceLoaded: tileManager.loaded(),
source: tileManager.serialize(),
sourceId: id
}));
tileManager.onAdd(this.map);
this._changed = true;
}
/**
* Remove a source from this stylesheet, given its id.
* @param id - id of the source to remove
* @throws if no source is found with the given ID
*/
removeSource(id) {
this._checkLoaded();
if (this.tileManagers[id] === void 0) throw new Error(`There is no source with this ID=${id}`);
for (const layerId in this._layers) if (this._layers[layerId].source === id) return this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`Source "${id}" cannot be removed while layer "${layerId}" is using it.`)));
const tileManager = this.tileManagers[id];
delete this.tileManagers[id];
delete this._updatedSources[id];
tileManager.fire(new MapSourceDataEvent("data", {
sourceDataType: "metadata",
sourceId: id
}));
tileManager.setEventedParent(null);
tileManager.onRemove(this.map);
this._changed = true;
}
/**
* Set the data of a GeoJSON source, given its id.
* @param id - id of the source
* @param data - GeoJSON source
*/
setGeoJSONSourceData(id, data) {
this._checkLoaded();
if (this.tileManagers[id] === void 0) throw new Error(`There is no source with this ID=${id}`);
const geojsonSource = this.tileManagers[id].getSource();
if (geojsonSource.type !== "geojson") throw new Error(`geojsonSource.type is ${geojsonSource.type}, which is !== 'geojson`);
geojsonSource.setData(data);
this._changed = true;
}
/**
* Get a source by ID.
* @param id - ID of the desired source
* @returns source
*/
getSource(id) {
return this.tileManagers[id]?.getSource();
}
/**
* Add a layer to the map style. The layer will be inserted before the layer with
* ID `before`, or appended if `before` is omitted.
* @param layerObject - The style layer to add.
* @param before - ID of an existing layer to insert before
* @param options - Style setter options.
*/
addLayer(layerObject, before, options = {}) {
this._checkLoaded();
const id = layerObject.id;
if (this.getLayer(id)) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`Layer "${id}" already exists on this map.`)));
return;
}
let layer;
if (layerObject.type === "custom") {
if (emitValidationErrors(this, validateCustomStyleLayer(layerObject))) return;
layer = createStyleLayer(layerObject, this._globalState);
} else {
if ("source" in layerObject && typeof layerObject.source === "object") {
this.addSource(id, layerObject.source);
layerObject = clone$2(layerObject);
layerObject = extend(layerObject, { source: id });
}
if (this._validate(validateStyle.layer, `layers.${id}`, layerObject, { arrayIndex: -1 }, options)) return;
layer = createStyleLayer(layerObject, this._globalState);
this._validateLayer(layer);
layer.setEventedParent(this, { layer: { id } });
}
const index = before ? this._order.indexOf(before) : this._order.length;
if (before && index === -1) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`Cannot add layer "${id}" before non-existing layer "${before}".`)));
return;
}
this._order.splice(index, 0, id);
this._layerOrderChanged = true;
this._layers[id] = layer;
if (this._removedLayers[id] && layer.source && layer.type !== "custom") {
const removed = this._removedLayers[id];
delete this._removedLayers[id];
if (removed.type !== layer.type) this._updatedSources[layer.source] = "clear";
else {
this._updatedSources[layer.source] = "reload";
this.tileManagers[layer.source].pause();
}
}
this._updateLayer(layer);
if (layer.onAdd) layer.onAdd(this.map);
}
/**
* Moves a layer to a different z-position. The layer will be inserted before the layer with
* ID `before`, or appended if `before` is omitted.
* @param id - ID of the layer to move
* @param before - ID of an existing layer to insert before
*/
moveLayer(id, before) {
this._checkLoaded();
this._changed = true;
if (!this._layers[id]) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`The layer '${id}' does not exist in the map's style and cannot be moved.`)));
return;
}
if (id === before) return;
const index = this._order.indexOf(id);
this._order.splice(index, 1);
const newIndex = before ? this._order.indexOf(before) : this._order.length;
if (before && newIndex === -1) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`Cannot move layer "${id}" before non-existing layer "${before}".`)));
return;
}
this._order.splice(newIndex, 0, id);
this._layerOrderChanged = true;
}
/**
* Remove the layer with the given id from the style.
* A {@link ErrorEvent} event will be fired if no such layer exists.
*
* @param id - id of the layer to remove
*/
removeLayer(id) {
this._checkLoaded();
const layer = this._layers[id];
if (!layer) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`Cannot remove non-existing layer "${id}".`)));
return;
}
layer.setEventedParent(null);
const index = this._order.indexOf(id);
this._order.splice(index, 1);
this._layerOrderChanged = true;
this._changed = true;
this._removedLayers[id] = layer;
delete this._layers[id];
if (this._serializedLayers) delete this._serializedLayers[id];
delete this._updatedLayers[id];
delete this._updatedPaintProps[id];
if (layer.onRemove) layer.onRemove(this.map);
}
/**
* Return the style layer object with the given `id`.
*
* @param id - id of the desired layer
* @returns a layer, if one with the given `id` exists
*/
getLayer(id) {
return this._layers[id];
}
/**
* Return the ids of all layers currently in the style, including custom layers, in order.
*
* @returns ids of layers, in order
*/
getLayersOrder() {
return [...this._order];
}
/**
* Checks if a specific layer is present within the style.
*
* @param id - the id of the desired layer
* @returns a boolean specifying if the given layer is present
*/
hasLayer(id) {
return id in this._layers;
}
setLayerZoomRange(layerId, minzoom, maxzoom) {
this._checkLoaded();
const layer = this.getLayer(layerId);
if (!layer) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`Cannot set the zoom range of non-existing layer "${layerId}".`)));
return;
}
if (layer.minzoom === minzoom && layer.maxzoom === maxzoom) return;
if (minzoom != null) layer.minzoom = minzoom;
if (maxzoom != null) layer.maxzoom = maxzoom;
this._updateLayer(layer);
}
setFilter(layerId, filter, options = {}) {
this._checkLoaded();
const layer = this.getLayer(layerId);
if (!layer) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`Cannot filter non-existing layer "${layerId}".`)));
return;
}
if (deepEqual(layer.filter, filter)) return;
if (filter === null || filter === void 0) {
layer.setFilter(void 0);
this._updateLayer(layer);
return;
}
if (this._validate(validateStyle.filter, `layers.${layer.id}.filter`, filter, null, options)) return;
layer.setFilter(clone$2(filter));
this._updateLayer(layer);
}
/**
* Get a layer's filter object
* @param layer - the layer to inspect
* @returns the layer's filter, if any
*/
getFilter(layer) {
return clone$2(this.getLayer(layer).filter);
}
setLayoutProperty(layerId, name, value, options = {}) {
this._checkLoaded();
const layer = this.getLayer(layerId);
if (!layer) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`Cannot style non-existing layer "${layerId}".`)));
return;
}
if (deepEqual(layer.getLayoutProperty(name), value)) return;
layer.setLayoutProperty(name, value, options);
this._updateLayer(layer);
}
/**
* Get a layout property's value from a given layer
* @param layerId - the layer to inspect
* @param name - the name of the layout property
* @returns the property value
*/
getLayoutProperty(layerId, name) {
const layer = this.getLayer(layerId);
if (!layer) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`Cannot get style of non-existing layer "${layerId}".`)));
return;
}
return layer.getLayoutProperty(name);
}
setPaintProperty(layerId, name, value, options = {}) {
this._checkLoaded();
const layer = this.getLayer(layerId);
if (!layer) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`Cannot style non-existing layer "${layerId}".`)));
return;
}
if (deepEqual(layer.getPaintProperty(name), value)) return;
this._updatePaintProperty(layer, name, value, options);
}
_updatePaintProperty(layer, name, value, options = {}) {
if (layer.setPaintProperty(name, value, options)) this._updateLayer(layer);
if (isRasterStyleLayer(layer) && name === "raster-fade-duration") this.tileManagers[layer.source].setRasterFadeDuration(value);
this._changed = true;
this._updatedPaintProps[layer.id] = true;
this._serializedLayers = null;
}
getPaintProperty(layer, name) {
return this.getLayer(layer).getPaintProperty(name);
}
setFeatureState(target, state) {
this._checkLoaded();
const sourceId = target.source;
const sourceLayer = target.sourceLayer;
const tileManager = this.tileManagers[sourceId];
if (tileManager === void 0) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`The source '${sourceId}' does not exist in the map's style.`)));
return;
}
const sourceType = tileManager.getSource().type;
if (sourceType === "geojson" && sourceLayer) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error("GeoJSON sources cannot have a sourceLayer parameter.")));
return;
}
if (sourceType === "vector" && !sourceLayer) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error("The sourceLayer parameter must be provided for vector source types.")));
return;
}
if (target.id === void 0) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error("The feature id parameter must be provided.")));
return;
}
const forbiddenStateKeys = [
"__proto__",
"constructor",
"prototype"
];
if (state && Object.keys(state).some((stateKey) => forbiddenStateKeys.includes(stateKey))) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`The feature state should not include one of the following keys: ${forbiddenStateKeys}`)));
return;
}
tileManager.setFeatureState(sourceLayer, target.id, state);
}
removeFeatureState(target, key) {
this._checkLoaded();
const sourceId = target.source;
const tileManager = this.tileManagers[sourceId];
if (tileManager === void 0) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`The source '${sourceId}' does not exist in the map's style.`)));
return;
}
const sourceType = tileManager.getSource().type;
const sourceLayer = sourceType === "vector" ? target.sourceLayer : void 0;
if (sourceType === "vector" && !sourceLayer) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error("The sourceLayer parameter must be provided for vector source types.")));
return;
}
if (key && typeof target.id !== "string" && typeof target.id !== "number") {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error("A feature id is required to remove its specific state property.")));
return;
}
tileManager.removeFeatureState(sourceLayer, target.id, key);
}
getFeatureState(target) {
this._checkLoaded();
const sourceId = target.source;
const sourceLayer = target.sourceLayer;
const tileManager = this.tileManagers[sourceId];
if (tileManager === void 0) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`The source '${sourceId}' does not exist in the map's style.`)));
return;
}
if (tileManager.getSource().type === "vector" && !sourceLayer) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error("The sourceLayer parameter must be provided for vector source types.")));
return;
}
if (target.id === void 0) this.fire(new ErrorEvent(/* @__PURE__ */ new Error("The feature id parameter must be provided.")));
return tileManager.getFeatureState(sourceLayer, target.id);
}
getTransition() {
return extend({
duration: 300,
delay: 0
}, this.stylesheet?.transition);
}
serialize() {
if (!this._loaded) return;
const sources = mapObject(this.tileManagers, (source) => source.serialize());
const layers = this._serializeByIds(this._order, true);
const terrain = this.map.getTerrain() || void 0;
const myStyleSheet = this.stylesheet;
return filterObject({
version: myStyleSheet.version,
name: myStyleSheet.name,
metadata: myStyleSheet.metadata,
light: myStyleSheet.light,
sky: myStyleSheet.sky,
center: myStyleSheet.center,
zoom: myStyleSheet.zoom,
bearing: myStyleSheet.bearing,
pitch: myStyleSheet.pitch,
sprite: myStyleSheet.sprite,
glyphs: myStyleSheet.glyphs,
transition: myStyleSheet.transition,
projection: myStyleSheet.projection,
sources,
layers,
terrain
}, (value) => value !== void 0);
}
_updateLayer(layer) {
this._updatedLayers[layer.id] = true;
if (layer.source && !this._updatedSources[layer.source] && this.tileManagers[layer.source].getSource().type !== "raster") {
this._updatedSources[layer.source] = "reload";
this.tileManagers[layer.source].pause();
}
this._serializedLayers = null;
this._changed = true;
}
_flattenAndSortRenderedFeatures(sourceResults) {
const isLayer3D = (layerId) => this._layers[layerId].type === "fill-extrusion";
const layerIndex = {};
const features3D = [];
for (let l = this._order.length - 1; l >= 0; l--) {
const layerId = this._order[l];
if (isLayer3D(layerId)) {
layerIndex[layerId] = l;
for (const sourceResult of sourceResults) {
const layerFeatures = sourceResult[layerId];
if (layerFeatures) for (const featureWrapper of layerFeatures) features3D.push(featureWrapper);
}
}
}
features3D.sort((a, b) => {
return b.intersectionZ - a.intersectionZ;
});
const features = [];
for (let l = this._order.length - 1; l >= 0; l--) {
const layerId = this._order[l];
if (isLayer3D(layerId)) for (let i = features3D.length - 1; i >= 0; i--) {
const topmost3D = features3D[i].feature;
if (layerIndex[topmost3D.layer.id] < l) break;
features.push(topmost3D);
features3D.pop();
}
else for (const sourceResult of sourceResults) {
const layerFeatures = sourceResult[layerId];
if (layerFeatures) for (const featureWrapper of layerFeatures) features.push(featureWrapper.feature);
}
}
return features;
}
queryRenderedFeatures(queryGeometry, params, transform) {
if (params?.filter) this._validate(validateStyle.filter, "queryRenderedFeatures.filter", params.filter, null, params);
const includedSources = {};
if (params?.layers) {
if (!(Array.isArray(params.layers) || params.layers instanceof Set)) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error("parameters.layers must be an Array or a Set of strings")));
return [];
}
for (const layerId of params.layers) {
const layer = this._layers[layerId];
if (!layer) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`The layer '${layerId}' does not exist in the map's style and cannot be queried for features.`)));
return [];
}
includedSources[layer.source] = true;
}
}
const sourceResults = [];
params.availableImages = this.imageManager.listImages();
const serializedLayers = this._serializedAllLayers();
const layersAsSet = params.layers instanceof Set ? params.layers : Array.isArray(params.layers) ? new Set(params.layers) : null;
const paramsStrict = {
...params,
layers: layersAsSet,
globalState: this._globalState
};
for (const id in this.tileManagers) {
if (params.layers && !includedSources[id]) continue;
sourceResults.push(queryRenderedFeatures(this.tileManagers[id], this._layers, serializedLayers, queryGeometry, paramsStrict, transform, this.map.terrain ? (id, x, y) => this.map.terrain.getElevation(id, x, y) : void 0));
}
if (this.placement) sourceResults.push(queryRenderedSymbols(this._layers, serializedLayers, this.tileManagers, queryGeometry, paramsStrict, this.placement.collisionIndex, this.placement.retainedQueryData));
return this._flattenAndSortRenderedFeatures(sourceResults);
}
querySourceFeatures(sourceID, params) {
if (params?.filter) this._validate(validateStyle.filter, "querySourceFeatures.filter", params.filter, null, params);
const tileManager = this.tileManagers[sourceID];
return tileManager ? querySourceFeatures(tileManager, params ? {
...params,
globalState: this._globalState
} : { globalState: this._globalState }) : [];
}
getLight() {
return this.light.getLight();
}
setLight(lightOptions, options = {}) {
this._checkLoaded();
const light = this.light.getLight();
let _update = false;
for (const key in lightOptions) if (!deepEqual(lightOptions[key], light[key])) {
_update = true;
break;
}
if (!_update) return;
const parameters = {
now: now(),
transition: extend({
duration: 300,
delay: 0
}, this.stylesheet.transition)
};
this.light.setLight(lightOptions, options);
this.light.updateTransitions(parameters);
}
getProjection() {
return this.stylesheet?.projection;
}
setProjection(projection) {
this._checkLoaded();
const resolvedProjection = projection ?? { type: "mercator" };
this.stylesheet.projection = projection;
if (this.projection) {
if (this.projection.name === resolvedProjection.type) return;
this.projection.destroy();
delete this.projection;
}
this._setProjectionInternal(resolvedProjection.type);
}
getSky() {
return this.stylesheet?.sky;
}
setSky(skyOptions, options = {}) {
this._checkLoaded();
const sky = this.getSky();
let update = false;
if (!skyOptions && !sky) return;
if (skyOptions && !sky) update = true;
else if (!skyOptions && sky) update = true;
else for (const key in skyOptions) if (!deepEqual(skyOptions[key], sky[key])) {
update = true;
break;
}
if (!update) return;
const parameters = {
now: now(),
transition: extend({
duration: 300,
delay: 0
}, this.stylesheet.transition)
};
this.stylesheet.sky = skyOptions;
this.sky.setSky(skyOptions, options);
this.sky.updateTransitions(parameters);
}
_setProjectionInternal(name) {
const projectionObjects = createProjectionFromName(name, this.map._camera?.transform.constrainOverride, this._globalState);
this.projection = projectionObjects.projection;
this.map.migrateProjection(projectionObjects.transform, projectionObjects.cameraHelper);
for (const key in this.tileManagers) this.tileManagers[key].reload();
}
_validate(validate, key, value, props, options = {}) {
return validateAndEmit(this, validate, {
key,
style: this.serialize(),
value,
...props
}, options);
}
_remove(mapRemoved = true) {
if (this._frameRequest) {
this._frameRequest.abort();
this._frameRequest = null;
}
if (this._loadStyleRequest) {
this._loadStyleRequest.abort();
this._loadStyleRequest = null;
}
if (this._spriteRequest) {
this._spriteRequest.abort();
this._spriteRequest = null;
}
rtlMainThreadPluginFactory().off(RTLPluginLoadedEventName, this._rtlPluginLoaded);
for (const layerId in this._layers) this._layers[layerId].setEventedParent(null);
for (const id in this.tileManagers) {
const tileManager = this.tileManagers[id];
tileManager.setEventedParent(null);
tileManager.onRemove(this.map);
}
this.imageManager.setEventedParent(null);
this.setEventedParent(null);
if (mapRemoved) this.dispatcher.broadcast("RM", void 0);
this.dispatcher.remove(mapRemoved);
}
_clearSource(id) {
this.tileManagers[id].clearTiles();
}
_reloadSource(id) {
this.tileManagers[id].resume();
this.tileManagers[id].reload();
}
_updateSources(transform) {
for (const id in this.tileManagers) this.tileManagers[id].update(transform, this.map.terrain);
}
_generateCollisionBoxes() {
for (const id in this.tileManagers) this._reloadSource(id);
}
_updatePlacement(transform, showCollisionBoxes, fadeDuration, crossSourceCollisions, forceFullPlacement = false) {
let symbolBucketsChanged = false;
let placementCommitted = false;
const layerTiles = {};
for (const layerID of this._order) {
const styleLayer = this._layers[layerID];
if (styleLayer.type !== "symbol") continue;
if (!layerTiles[styleLayer.source]) {
const tileManager = this.tileManagers[styleLayer.source];
layerTiles[styleLayer.source] = tileManager.getRenderableIds(true).map((id) => tileManager.getTileByID(id)).sort((a, b) => b.tileID.overscaledZ - a.tileID.overscaledZ || (a.tileID.isLessThan(b.tileID) ? -1 : 1));
}
const layerBucketsChanged = this.crossTileSymbolIndex.addLayer(styleLayer, layerTiles[styleLayer.source], transform.center.lng);
symbolBucketsChanged ||= layerBucketsChanged;
}
this.crossTileSymbolIndex.pruneUnusedLayers(this._order);
forceFullPlacement ||= this._layerOrderChanged || fadeDuration === 0;
if (forceFullPlacement || !this.pauseablePlacement || this.pauseablePlacement.isDone() && !this.placement.stillRecent(now(), transform.zoom)) {
this.pauseablePlacement = new PauseablePlacement(transform, this.map.terrain, this._order, forceFullPlacement, showCollisionBoxes, fadeDuration, crossSourceCollisions, this.placement);
this._layerOrderChanged = false;
}
if (this.pauseablePlacement.isDone()) this.placement.setStale();
else {
this.pauseablePlacement.continuePlacement(this._order, this._layers, layerTiles);
if (this.pauseablePlacement.isDone()) {
this.placement = this.pauseablePlacement.commit(now());
placementCommitted = true;
}
if (symbolBucketsChanged) this.pauseablePlacement.placement.setStale();
}
if (placementCommitted || symbolBucketsChanged) for (const layerID of this._order) {
const styleLayer = this._layers[layerID];
if (styleLayer.type !== "symbol") continue;
this.placement.updateLayerOpacities(styleLayer, layerTiles[styleLayer.source]);
}
return !this.pauseablePlacement.isDone() || this.placement.hasTransitions(now());
}
_releaseSymbolFadeTiles() {
for (const id in this.tileManagers) this.tileManagers[id].releaseSymbolFadeTiles();
}
async getImages(mapId, params) {
const images = await this.imageManager.getImages(params.icons);
this._updateTilesForChangedImages();
const tileManager = this.tileManagers[params.source];
if (tileManager) tileManager.setDependencies(params.tileID.key, params.type, params.icons);
return images;
}
async getGlyphs(mapId, params) {
const glyphs = await this.glyphManager.getGlyphs(params.stacks);
const tileManager = this.tileManagers[params.source];
if (tileManager) tileManager.setDependencies(params.tileID.key, params.type, [""]);
return glyphs;
}
getGlyphsUrl() {
return this.stylesheet.glyphs || null;
}
setGlyphs(glyphsUrl, options = {}) {
this._checkLoaded();
if (glyphsUrl && this._validate(validateStyle.glyphs, "glyphs", glyphsUrl, null, options)) return;
this._glyphsDidChange = true;
this.stylesheet.glyphs = glyphsUrl;
this.glyphManager.entries = {};
this.glyphManager.setURL(glyphsUrl);
}
async getDashes(mapId, params) {
const result = {};
for (const [key, dash] of Object.entries(params.dashes)) result[key] = this.lineAtlas.getDash(dash.dasharray, dash.round);
return result;
}
/**
* Add a sprite.
*
* @param id - The id of the desired sprite
* @param url - The url to load the desired sprite from
* @param options - The style setter options
* @param completion - The completion handler
*/
addSprite(id, url, options = {}, completion) {
this._checkLoaded();
const spriteToAdd = [{
id,
url
}];
const updatedSprite = [...coerceSpriteToArray(this.stylesheet.sprite), ...spriteToAdd];
if (this._validate(validateStyle.sprite, "sprite", updatedSprite, null, options)) return;
this.stylesheet.sprite = updatedSprite;
this._loadSprite(spriteToAdd, true, completion);
}
/**
* Remove a sprite by its id. When the last sprite is removed, the whole `this.stylesheet.sprite` object becomes
* `undefined`. This falsy `undefined` value later prevents attempts to load the sprite when it's absent.
*
* @param id - the id of the sprite to remove
*/
removeSprite(id) {
this._checkLoaded();
const internalSpriteRepresentation = coerceSpriteToArray(this.stylesheet.sprite);
if (!internalSpriteRepresentation.find((sprite) => sprite.id === id)) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`Sprite "${id}" doesn't exists on this map.`)));
return;
}
const changedImages = this.imageManager.removeSpriteImages(id);
this._markImagesChanged(changedImages);
internalSpriteRepresentation.splice(internalSpriteRepresentation.findIndex((sprite) => sprite.id === id), 1);
this.stylesheet.sprite = internalSpriteRepresentation.length > 0 ? internalSpriteRepresentation : void 0;
this._imagesListDirty = true;
this._changed = true;
this.fire(new MapStyleDataEvent("data"));
}
/**
* Get the current sprite value.
*
* @returns empty array when no sprite is set; id-url pairs otherwise
*/
getSprite() {
return coerceSpriteToArray(this.stylesheet.sprite);
}
/**
* Set a new value for the style's sprite.
*
* @param sprite - new sprite value
* @param options - style setter options
* @param completion - the completion handler
*/
setSprite(sprite, options = {}, completion) {
this._checkLoaded();
if (sprite && this._validate(validateStyle.sprite, "sprite", sprite, null, options)) return;
this.stylesheet.sprite = sprite;
if (sprite) this._loadSprite(sprite, true, completion);
else {
this._unloadSprite();
if (completion) completion(null);
}
}
/**
* Destroys all internal resources of the style (sources, images, layers, etc.)
*/
destroy() {
if (this._frameRequest) {
this._frameRequest.abort();
this._frameRequest = null;
}
if (this._loadStyleRequest) {
this._loadStyleRequest.abort();
this._loadStyleRequest = null;
}
if (this._spriteRequest) {
this._spriteRequest.abort();
this._spriteRequest = null;
}
for (const id in this.tileManagers) {
const tileManager = this.tileManagers[id];
tileManager.setEventedParent(null);
tileManager.onRemove(this.map);
}
this.tileManagers = {};
if (this.imageManager) {
this.imageManager.setEventedParent(null);
this.imageManager.destroy();
this.patternAtlas.destroy();
}
if (this.glyphManager) this.glyphManager.destroy();
for (const layerId in this._layers) {
const layer = this._layers[layerId];
layer.setEventedParent(null);
if (layer.onRemove) layer.onRemove(this.map);
}
this._setInitialValues();
this.setEventedParent(null);
this.dispatcher.unregisterMessageHandler("GG");
this.dispatcher.unregisterMessageHandler("GI");
this.dispatcher.unregisterMessageHandler("GDA");
this.dispatcher.remove(true);
this._listeners = {};
this._oneTimeListeners = {};
}
};
//#endregion
//#region src/data/raster_bounds_attributes.ts
const rasterBoundsAttributes = createLayout([{
name: "a_pos",
type: "Int16",
components: 2
}, {
name: "a_texture_pos",
type: "Int16",
components: 2
}]);
//#endregion
//#region src/webgl/vertex_array_object.ts
/**
* @internal
* A vertex array object used to pass data to the webgl code
*/
var VertexArrayObject = class {
constructor() {
this.boundProgram = null;
this.boundLayoutVertexBuffer = null;
this.boundPaintVertexBuffers = [];
this.boundIndexBuffer = null;
this.boundVertexOffset = null;
this.boundDynamicVertexBuffer = null;
this.vao = null;
}
bind(context, program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2, dynamicVertexBuffer3) {
this.context = context;
let paintBuffersDiffer = this.boundPaintVertexBuffers.length !== paintVertexBuffers.length;
for (let i = 0; !paintBuffersDiffer && i < paintVertexBuffers.length; i++) if (this.boundPaintVertexBuffers[i] !== paintVertexBuffers[i]) paintBuffersDiffer = true;
if (!this.vao || this.boundProgram !== program || this.boundLayoutVertexBuffer !== layoutVertexBuffer || paintBuffersDiffer || this.boundIndexBuffer !== indexBuffer || this.boundVertexOffset !== vertexOffset || this.boundDynamicVertexBuffer !== dynamicVertexBuffer || this.boundDynamicVertexBuffer2 !== dynamicVertexBuffer2 || this.boundDynamicVertexBuffer3 !== dynamicVertexBuffer3) this.freshBind(program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2, dynamicVertexBuffer3);
else {
context.bindVertexArray.set(this.vao);
if (dynamicVertexBuffer) dynamicVertexBuffer.bind();
if (indexBuffer?.dynamicDraw) indexBuffer.bind();
if (dynamicVertexBuffer2) dynamicVertexBuffer2.bind();
if (dynamicVertexBuffer3) dynamicVertexBuffer3.bind();
}
}
freshBind(program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2, dynamicVertexBuffer3) {
const numNextAttributes = program.numAttributes;
const context = this.context;
const gl = context.gl;
if (this.vao) this.destroy();
this.vao = context.createVertexArray();
context.bindVertexArray.set(this.vao);
this.boundProgram = program;
this.boundLayoutVertexBuffer = layoutVertexBuffer;
this.boundPaintVertexBuffers = paintVertexBuffers;
this.boundIndexBuffer = indexBuffer;
this.boundVertexOffset = vertexOffset;
this.boundDynamicVertexBuffer = dynamicVertexBuffer;
this.boundDynamicVertexBuffer2 = dynamicVertexBuffer2;
this.boundDynamicVertexBuffer3 = dynamicVertexBuffer3;
layoutVertexBuffer.enableAttributes(gl, program);
for (const vertexBuffer of paintVertexBuffers) vertexBuffer.enableAttributes(gl, program);
if (dynamicVertexBuffer) dynamicVertexBuffer.enableAttributes(gl, program);
if (dynamicVertexBuffer2) dynamicVertexBuffer2.enableAttributes(gl, program);
if (dynamicVertexBuffer3) dynamicVertexBuffer3.enableAttributes(gl, program);
layoutVertexBuffer.bind();
layoutVertexBuffer.setVertexAttribPointers(gl, program, vertexOffset);
for (const vertexBuffer of paintVertexBuffers) {
vertexBuffer.bind();
vertexBuffer.setVertexAttribPointers(gl, program, vertexOffset);
}
if (dynamicVertexBuffer) {
dynamicVertexBuffer.bind();
dynamicVertexBuffer.setVertexAttribPointers(gl, program, vertexOffset);
}
if (indexBuffer) indexBuffer.bind();
if (dynamicVertexBuffer2) {
dynamicVertexBuffer2.bind();
dynamicVertexBuffer2.setVertexAttribPointers(gl, program, vertexOffset);
}
if (dynamicVertexBuffer3) {
dynamicVertexBuffer3.bind();
dynamicVertexBuffer3.setVertexAttribPointers(gl, program, vertexOffset);
}
context.currentNumAttributes = numNextAttributes;
}
destroy() {
if (this.vao) {
this.context.deleteVertexArray(this.vao);
this.vao = null;
}
}
};
//#endregion
//#region src/webgl/program/terrain_program.ts
const terrainPreludeUniforms = (context, locations) => ({
"u_depth": new Uniform1i(context, locations.u_depth),
"u_terrain": new Uniform1i(context, locations.u_terrain),
"u_terrain_dim": new Uniform1f(context, locations.u_terrain_dim),
"u_terrain_matrix": new UniformMatrix4f(context, locations.u_terrain_matrix),
"u_terrain_unpack": new Uniform4f(context, locations.u_terrain_unpack),
"u_terrain_exaggeration": new Uniform1f(context, locations.u_terrain_exaggeration)
});
const terrainUniforms = (context, locations) => ({
"u_texture": new Uniform1i(context, locations.u_texture),
"u_ele_delta": new Uniform1f(context, locations.u_ele_delta),
"u_fog_matrix": new UniformMatrix4f(context, locations.u_fog_matrix),
"u_fog_color": new UniformColor(context, locations.u_fog_color),
"u_fog_ground_blend": new Uniform1f(context, locations.u_fog_ground_blend),
"u_fog_ground_blend_opacity": new Uniform1f(context, locations.u_fog_ground_blend_opacity),
"u_horizon_color": new UniformColor(context, locations.u_horizon_color),
"u_horizon_fog_blend": new Uniform1f(context, locations.u_horizon_fog_blend),
"u_is_globe_mode": new Uniform1f(context, locations.u_is_globe_mode)
});
const terrainDepthUniforms = (context, locations) => ({ "u_ele_delta": new Uniform1f(context, locations.u_ele_delta) });
const terrainCoordsUniforms = (context, locations) => ({
"u_texture": new Uniform1i(context, locations.u_texture),
"u_terrain_coords_id": new Uniform1f(context, locations.u_terrain_coords_id),
"u_ele_delta": new Uniform1f(context, locations.u_ele_delta)
});
const terrainUniformValues = (eleDelta, fogMatrix, sky, pitch, isGlobeMode) => ({
"u_texture": 0,
"u_ele_delta": eleDelta,
"u_fog_matrix": fogMatrix,
"u_fog_color": sky ? sky.properties.get("fog-color") : Color.white,
"u_fog_ground_blend": sky ? sky.properties.get("fog-ground-blend") : 1,
"u_fog_ground_blend_opacity": isGlobeMode ? 0 : sky ? sky.calculateFogBlendOpacity(pitch) : 0,
"u_horizon_color": sky ? sky.properties.get("horizon-color") : Color.white,
"u_horizon_fog_blend": sky ? sky.properties.get("horizon-fog-blend") : 1,
"u_is_globe_mode": isGlobeMode ? 1 : 0
});
const terrainDepthUniformValues = (eleDelta) => ({ "u_ele_delta": eleDelta });
const terrainCoordsUniformValues = (coordsId, eleDelta) => ({
"u_terrain_coords_id": coordsId / 255,
"u_texture": 0,
"u_ele_delta": eleDelta
});
//#endregion
//#region src/webgl/program/projection_program.ts
const projectionUniforms = (context, locations) => ({
"u_projection_matrix": new UniformMatrix4f(context, locations.u_projection_matrix),
"u_projection_tile_mercator_coords": new Uniform4f(context, locations.u_projection_tile_mercator_coords),
"u_projection_clipping_plane": new Uniform4f(context, locations.u_projection_clipping_plane),
"u_projection_transition": new Uniform1f(context, locations.u_projection_transition),
"u_projection_fallback_matrix": new UniformMatrix4f(context, locations.u_projection_fallback_matrix),
"u_projection_clip_antimeridian": new Uniform1i(context, locations.u_projection_clip_antimeridian)
});
/**
* Converts a {@link ProjectionData} object into the values expected by the projection prelude's uniforms.
*/
const projectionUniformValues = (projectionData) => ({
"u_projection_matrix": projectionData.mainMatrix,
"u_projection_tile_mercator_coords": projectionData.tileMercatorCoords,
"u_projection_clipping_plane": projectionData.clippingPlane,
"u_projection_transition": projectionData.projectionTransition,
"u_projection_fallback_matrix": projectionData.fallbackMatrix,
"u_projection_clip_antimeridian": projectionData.clipAntimeridian ? 1 : 0
});
//#endregion
//#region src/webgl/program.ts
function getTokenizedAttributesAndUniforms(array) {
const result = [];
for (const entry of array) {
if (entry === null) continue;
const token = entry.split(" ");
result.push(token.pop());
}
return result;
}
function getIntegerAttributeNames(gl, program) {
const integerTypes = /* @__PURE__ */ new Set([
gl.INT,
gl.INT_VEC2,
gl.INT_VEC3,
gl.INT_VEC4,
gl.UNSIGNED_INT,
gl.UNSIGNED_INT_VEC2,
gl.UNSIGNED_INT_VEC3,
gl.UNSIGNED_INT_VEC4
]);
const names = /* @__PURE__ */ new Set();
const numActiveAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
for (let i = 0; i < numActiveAttributes; i++) {
const attribute = gl.getActiveAttrib(program, i);
if (attribute && integerTypes.has(attribute.type)) names.add(attribute.name);
}
return names;
}
/**
* @internal
* A webgl program to execute in the GPU space
*/
var Program = class {
constructor(context, source, configuration, fixedUniforms, showOverdrawInspector, useTerrain, projectionPrelude, projectionDefine, extraDefines = []) {
const gl = context.gl;
this.program = gl.createProgram();
const staticAttrInfo = getTokenizedAttributesAndUniforms(source.staticAttributes);
const dynamicAttrInfo = configuration ? configuration.getBinderAttributes() : [];
const allAttrInfo = staticAttrInfo.concat(dynamicAttrInfo);
const preludeUniformsInfo = shaders.prelude.staticUniforms ? getTokenizedAttributesAndUniforms(shaders.prelude.staticUniforms) : [];
const projectionPreludeUniformsInfo = projectionPrelude.staticUniforms ? getTokenizedAttributesAndUniforms(projectionPrelude.staticUniforms) : [];
const staticUniformsInfo = source.staticUniforms ? getTokenizedAttributesAndUniforms(source.staticUniforms) : [];
const dynamicUniformsInfo = configuration ? configuration.getBinderUniforms() : [];
const uniformList = preludeUniformsInfo.concat(projectionPreludeUniformsInfo).concat(staticUniformsInfo).concat(dynamicUniformsInfo);
const allUniformsInfo = [];
for (const uniform of uniformList) if (!allUniformsInfo.includes(uniform)) allUniformsInfo.push(uniform);
const defines = configuration ? configuration.defines() : [];
defines.unshift("#version 300 es");
if (showOverdrawInspector) defines.push("#define OVERDRAW_INSPECTOR;");
if (useTerrain) defines.push("#define TERRAIN3D;");
if (projectionDefine) defines.push(projectionDefine);
if (extraDefines) defines.push(...extraDefines);
const fragmentSource = defines.concat(shaders.prelude.fragmentSource, projectionPrelude.fragmentSource, source.fragmentSource).join("\n");
const vertexSource = defines.concat(shaders.prelude.vertexSource, projectionPrelude.vertexSource, source.vertexSource).join("\n");
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
if (gl.isContextLost()) {
this.failedToCreate = true;
return;
}
gl.shaderSource(fragmentShader, fragmentSource);
gl.compileShader(fragmentShader);
if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) throw new Error(`Could not compile fragment shader: ${gl.getShaderInfoLog(fragmentShader)}`);
gl.attachShader(this.program, fragmentShader);
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
if (gl.isContextLost()) {
this.failedToCreate = true;
return;
}
gl.shaderSource(vertexShader, vertexSource);
gl.compileShader(vertexShader);
if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) throw new Error(`Could not compile vertex shader: ${gl.getShaderInfoLog(vertexShader)}`);
gl.attachShader(this.program, vertexShader);
this.attributes = {};
const uniformLocations = {};
this.numAttributes = allAttrInfo.length;
gl.linkProgram(this.program);
if (!gl.getProgramParameter(this.program, gl.LINK_STATUS)) throw new Error(`Program failed to link: ${gl.getProgramInfoLog(this.program)}`);
const integerAttributeNames = getIntegerAttributeNames(gl, this.program);
for (const name of allAttrInfo) {
if (!name) continue;
const location = gl.getAttribLocation(this.program, name);
if (location >= 0) this.attributes[name] = {
location,
isInteger: integerAttributeNames.has(name)
};
}
gl.deleteShader(vertexShader);
gl.deleteShader(fragmentShader);
for (const uniform of allUniformsInfo) if (uniform && !uniformLocations[uniform]) {
const uniformLocation = gl.getUniformLocation(this.program, uniform);
if (uniformLocation) uniformLocations[uniform] = uniformLocation;
}
this.fixedUniforms = fixedUniforms(context, uniformLocations);
this.terrainUniforms = terrainPreludeUniforms(context, uniformLocations);
this.projectionUniforms = projectionUniforms(context, uniformLocations);
this.binderUniforms = configuration ? configuration.getUniforms(context, uniformLocations) : [];
}
draw(context, drawMode, depthMode, stencilMode, colorMode, cullFaceMode, uniformValues, terrain, projectionData, layerID, layoutVertexBuffer, indexBuffer, segments, currentProperties, zoom, configuration, dynamicLayoutBuffer, dynamicLayoutBuffer2, dynamicLayoutBuffer3) {
const gl = context.gl;
if (this.failedToCreate) return;
context.program.set(this.program);
context.setDepthMode(depthMode);
context.setStencilMode(stencilMode);
context.setColorMode(colorMode);
context.setCullFace(cullFaceMode);
if (terrain) {
context.activeTexture.set(gl.TEXTURE2);
gl.bindTexture(gl.TEXTURE_2D, terrain.depthTexture);
context.activeTexture.set(gl.TEXTURE3);
gl.bindTexture(gl.TEXTURE_2D, terrain.texture);
for (const name in this.terrainUniforms) this.terrainUniforms[name].set(terrain[name]);
}
if (projectionData) {
const values = projectionUniformValues(projectionData);
for (const name in this.projectionUniforms) this.projectionUniforms[name].set(values[name]);
}
if (uniformValues) for (const name in this.fixedUniforms) this.fixedUniforms[name].set(uniformValues[name]);
if (configuration) configuration.setUniforms(context, this.binderUniforms, currentProperties, { zoom });
let primitiveSize = 0;
switch (drawMode) {
case gl.LINES:
primitiveSize = 2;
break;
case gl.TRIANGLES:
primitiveSize = 3;
break;
case gl.LINE_STRIP: primitiveSize = 1;
}
for (const segment of segments.get()) {
segment.vaos ||= {};
segment.vaos[layerID] ||= new VertexArrayObject();
segment.vaos[layerID].bind(context, this, layoutVertexBuffer, configuration ? configuration.getPaintVertexBuffers() : [], indexBuffer, segment.vertexOffset, dynamicLayoutBuffer, dynamicLayoutBuffer2, dynamicLayoutBuffer3);
gl.drawElements(drawMode, segment.primitiveLength * primitiveSize, gl.UNSIGNED_SHORT, segment.primitiveOffset * primitiveSize * 2);
}
}
};
//#endregion
//#region src/webgl/program/pattern.ts
function patternUniformValues(crossfade, painter, tile) {
const tileRatio = 1 / pixelsToTileUnits(tile, 1, painter.transform.tileZoom);
const numTiles = Math.pow(2, tile.tileID.overscaledZ);
const tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, painter.transform.tileZoom) / numTiles;
const pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles);
const pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y;
return {
"u_image": 0,
"u_texsize": tile.imageAtlasTexture.size,
"u_scale": [
tileRatio,
crossfade.fromScale,
crossfade.toScale
],
"u_fade": crossfade.t,
"u_pixel_coord_upper": [pixelX >> 16, pixelY >> 16],
"u_pixel_coord_lower": [pixelX & 65535, pixelY & 65535]
};
}
function bgPatternUniformValues(image, crossfade, painter, tile) {
const imagePosA = painter.patternAtlas.getPattern(image.from.toString());
const imagePosB = painter.patternAtlas.getPattern(image.to.toString());
const { width, height } = painter.patternAtlas.getPixelSize();
const numTiles = Math.pow(2, tile.tileID.overscaledZ);
const tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, painter.transform.tileZoom) / numTiles;
const pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles);
const pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y;
return {
"u_image": 0,
"u_pattern_tl_a": imagePosA.tl,
"u_pattern_br_a": imagePosA.br,
"u_pattern_tl_b": imagePosB.tl,
"u_pattern_br_b": imagePosB.br,
"u_texsize": [width, height],
"u_mix": crossfade.t,
"u_pattern_size_a": imagePosA.displaySize,
"u_pattern_size_b": imagePosB.displaySize,
"u_scale_a": crossfade.fromScale,
"u_scale_b": crossfade.toScale,
"u_tile_units_to_pixels": 1 / pixelsToTileUnits(tile, 1, painter.transform.tileZoom),
"u_pixel_coord_upper": [pixelX >> 16, pixelY >> 16],
"u_pixel_coord_lower": [pixelX & 65535, pixelY & 65535]
};
}
//#endregion
//#region src/webgl/program/fill_extrusion_program.ts
const fillExtrusionUniforms = (context, locations) => ({
"u_lightpos": new Uniform3f(context, locations.u_lightpos),
"u_lightpos_globe": new Uniform3f(context, locations.u_lightpos_globe),
"u_lightintensity": new Uniform1f(context, locations.u_lightintensity),
"u_lightcolor": new Uniform3f(context, locations.u_lightcolor),
"u_vertical_gradient": new Uniform1f(context, locations.u_vertical_gradient),
"u_opacity": new Uniform1f(context, locations.u_opacity),
"u_fill_translate": new Uniform2f(context, locations.u_fill_translate)
});
const fillExtrusionPatternUniforms = (context, locations) => ({
"u_lightpos": new Uniform3f(context, locations.u_lightpos),
"u_lightpos_globe": new Uniform3f(context, locations.u_lightpos_globe),
"u_lightintensity": new Uniform1f(context, locations.u_lightintensity),
"u_lightcolor": new Uniform3f(context, locations.u_lightcolor),
"u_vertical_gradient": new Uniform1f(context, locations.u_vertical_gradient),
"u_height_factor": new Uniform1f(context, locations.u_height_factor),
"u_opacity": new Uniform1f(context, locations.u_opacity),
"u_fill_translate": new Uniform2f(context, locations.u_fill_translate),
"u_image": new Uniform1i(context, locations.u_image),
"u_texsize": new Uniform2f(context, locations.u_texsize),
"u_pixel_coord_upper": new Uniform2f(context, locations.u_pixel_coord_upper),
"u_pixel_coord_lower": new Uniform2f(context, locations.u_pixel_coord_lower),
"u_scale": new Uniform3f(context, locations.u_scale),
"u_fade": new Uniform1f(context, locations.u_fade)
});
const fillExtrusionUniformValues = (painter, shouldUseVerticalGradient, opacity, translate) => {
const light = painter.style.light;
const lightPos = light.getCartesianPosition();
const lightMat = create$4();
if (light.properties.get("anchor") === "viewport") fromRotation(lightMat, painter.transform.bearingInRadians);
transformMat3(lightPos, lightPos, lightMat);
const transformedLightPos = painter.transform.transformLightDirection(lightPos);
const lightColor = light.properties.get("color");
return {
"u_lightpos": lightPos,
"u_lightpos_globe": transformedLightPos,
"u_lightintensity": light.properties.get("intensity"),
"u_lightcolor": [
lightColor.r,
lightColor.g,
lightColor.b
],
"u_vertical_gradient": +shouldUseVerticalGradient,
"u_opacity": opacity,
"u_fill_translate": translate
};
};
const fillExtrusionPatternUniformValues = (painter, shouldUseVerticalGradient, opacity, translate, coord, crossfade, tile) => {
return extend(fillExtrusionUniformValues(painter, shouldUseVerticalGradient, opacity, translate), patternUniformValues(crossfade, painter, tile), { "u_height_factor": -Math.pow(2, coord.overscaledZ) / tile.tileSize / 8 });
};
//#endregion
//#region src/webgl/program/fill_program.ts
const fillUniforms = (context, locations) => ({ "u_fill_translate": new Uniform2f(context, locations.u_fill_translate) });
const fillPatternUniforms = (context, locations) => ({
"u_image": new Uniform1i(context, locations.u_image),
"u_texsize": new Uniform2f(context, locations.u_texsize),
"u_pixel_coord_upper": new Uniform2f(context, locations.u_pixel_coord_upper),
"u_pixel_coord_lower": new Uniform2f(context, locations.u_pixel_coord_lower),
"u_scale": new Uniform3f(context, locations.u_scale),
"u_fade": new Uniform1f(context, locations.u_fade),
"u_fill_translate": new Uniform2f(context, locations.u_fill_translate)
});
const fillOutlineUniforms = (context, locations) => ({
"u_world": new Uniform2f(context, locations.u_world),
"u_fill_translate": new Uniform2f(context, locations.u_fill_translate)
});
const fillOutlinePatternUniforms = (context, locations) => ({
"u_world": new Uniform2f(context, locations.u_world),
"u_image": new Uniform1i(context, locations.u_image),
"u_texsize": new Uniform2f(context, locations.u_texsize),
"u_pixel_coord_upper": new Uniform2f(context, locations.u_pixel_coord_upper),
"u_pixel_coord_lower": new Uniform2f(context, locations.u_pixel_coord_lower),
"u_scale": new Uniform3f(context, locations.u_scale),
"u_fade": new Uniform1f(context, locations.u_fade),
"u_fill_translate": new Uniform2f(context, locations.u_fill_translate)
});
const fillPatternUniformValues = (painter, crossfade, tile, translate) => extend(patternUniformValues(crossfade, painter, tile), { "u_fill_translate": translate });
const fillUniformValues = (translate) => ({ "u_fill_translate": translate });
const fillOutlineUniformValues = (drawingBufferSize, translate) => ({
"u_world": drawingBufferSize,
"u_fill_translate": translate
});
const fillOutlinePatternUniformValues = (painter, crossfade, tile, drawingBufferSize, translate) => extend(fillPatternUniformValues(painter, crossfade, tile, translate), { "u_world": drawingBufferSize });
//#endregion
//#region src/webgl/program/circle_program.ts
const circleUniforms = (context, locations) => ({
"u_camera_to_center_distance": new Uniform1f(context, locations.u_camera_to_center_distance),
"u_scale_with_map": new Uniform1i(context, locations.u_scale_with_map),
"u_pitch_with_map": new Uniform1i(context, locations.u_pitch_with_map),
"u_extrude_scale": new Uniform2f(context, locations.u_extrude_scale),
"u_device_pixel_ratio": new Uniform1f(context, locations.u_device_pixel_ratio),
"u_globe_extrude_scale": new Uniform1f(context, locations.u_globe_extrude_scale),
"u_translate": new Uniform2f(context, locations.u_translate)
});
const circleUniformValues = (painter, tile, layer, translate, radiusCorrectionFactor) => {
const transform = painter.transform;
let pitchWithMap, extrudeScale;
let globeExtrudeScale = 0;
if (layer.paint.get("circle-pitch-alignment") === "map") {
const pixelRatio = pixelsToTileUnits(tile, 1, transform.zoom);
pitchWithMap = true;
extrudeScale = [pixelRatio, pixelRatio];
globeExtrudeScale = pixelRatio / (EXTENT * Math.pow(2, tile.tileID.overscaledZ)) * 2 * Math.PI * radiusCorrectionFactor;
} else {
pitchWithMap = false;
extrudeScale = transform.pixelsToGLUnits;
}
return {
"u_camera_to_center_distance": transform.cameraToCenterDistance,
"u_scale_with_map": +(layer.paint.get("circle-pitch-scale") === "map"),
"u_pitch_with_map": +pitchWithMap,
"u_device_pixel_ratio": painter.pixelRatio,
"u_extrude_scale": extrudeScale,
"u_globe_extrude_scale": globeExtrudeScale,
"u_translate": translate
};
};
//#endregion
//#region src/webgl/program/collision_program.ts
const collisionUniforms = (context, locations) => ({ "u_pixel_extrude_scale": new Uniform2f(context, locations.u_pixel_extrude_scale) });
const collisionCircleUniforms = (context, locations) => ({ "u_viewport_size": new Uniform2f(context, locations.u_viewport_size) });
const collisionUniformValues = (transform) => {
return { "u_pixel_extrude_scale": [1 / transform.width, 1 / transform.height] };
};
const collisionCircleUniformValues = (transform) => {
return { "u_viewport_size": [transform.width, transform.height] };
};
//#endregion
//#region src/webgl/program/debug_program.ts
const debugUniforms = (context, locations) => ({
"u_color": new UniformColor(context, locations.u_color),
"u_overlay": new Uniform1i(context, locations.u_overlay),
"u_overlay_scale": new Uniform1f(context, locations.u_overlay_scale)
});
const debugUniformValues = (color, scaleRatio = 1) => ({
"u_color": color,
"u_overlay": 0,
"u_overlay_scale": scaleRatio
});
//#endregion
//#region src/webgl/program/heatmap_program.ts
const heatmapUniforms = (context, locations) => ({
"u_extrude_scale": new Uniform1f(context, locations.u_extrude_scale),
"u_intensity": new Uniform1f(context, locations.u_intensity),
"u_globe_extrude_scale": new Uniform1f(context, locations.u_globe_extrude_scale)
});
const heatmapTextureUniforms = (context, locations) => ({
"u_matrix": new UniformMatrix4f(context, locations.u_matrix),
"u_world": new Uniform2f(context, locations.u_world),
"u_image": new Uniform1i(context, locations.u_image),
"u_color_ramp": new Uniform1i(context, locations.u_color_ramp),
"u_opacity": new Uniform1f(context, locations.u_opacity)
});
const heatmapUniformValues = (tile, zoom, intensity, radiusCorrectionFactor) => {
const globeExtrudeScale = pixelsToTileUnits(tile, 1, zoom) / (EXTENT * Math.pow(2, tile.tileID.overscaledZ)) * 2 * Math.PI * radiusCorrectionFactor;
return {
"u_extrude_scale": pixelsToTileUnits(tile, 1, zoom),
"u_intensity": intensity,
"u_globe_extrude_scale": globeExtrudeScale
};
};
const heatmapTextureUniformValues = (painter, layer, textureUnit, colorRampUnit) => {
const matrix = create$1();
ortho(matrix, 0, painter.width, painter.height, 0, 0, 1);
const gl = painter.context.gl;
return {
"u_matrix": matrix,
"u_world": [gl.drawingBufferWidth, gl.drawingBufferHeight],
"u_image": textureUnit,
"u_color_ramp": colorRampUnit,
"u_opacity": layer.paint.get("heatmap-opacity")
};
};
//#endregion
//#region src/webgl/program/hillshade_program.ts
const hillshadeUniforms = (context, locations) => ({
"u_image": new Uniform1i(context, locations.u_image),
"u_latrange": new Uniform2f(context, locations.u_latrange),
"u_exaggeration": new Uniform1f(context, locations.u_exaggeration),
"u_altitudes": new UniformFloatArray(context, locations.u_altitudes),
"u_azimuths": new UniformFloatArray(context, locations.u_azimuths),
"u_accent": new UniformColor(context, locations.u_accent),
"u_method": new Uniform1i(context, locations.u_method),
"u_shadows": new UniformColorArray(context, locations.u_shadows),
"u_highlights": new UniformColorArray(context, locations.u_highlights)
});
const hillshadePrepareUniforms = (context, locations) => ({
"u_matrix": new UniformMatrix4f(context, locations.u_matrix),
"u_image": new Uniform1i(context, locations.u_image),
"u_dimension": new Uniform2f(context, locations.u_dimension),
"u_zoom": new Uniform1f(context, locations.u_zoom),
"u_unpack": new Uniform4f(context, locations.u_unpack)
});
const hillshadeUniformValues = (painter, tile, layer) => {
const accent = layer.paint.get("hillshade-accent-color");
let method;
switch (layer.paint.get("hillshade-method")) {
case "basic":
method = 4;
break;
case "combined":
method = 1;
break;
case "igor":
method = 2;
break;
case "multidirectional":
method = 3;
break;
default: method = 0;
}
const illumination = layer.getIlluminationProperties();
for (let i = 0; i < illumination.directionRadians.length; i++) if (layer.paint.get("hillshade-illumination-anchor") === "viewport") illumination.directionRadians[i] += painter.transform.bearingInRadians;
return {
"u_image": 0,
"u_latrange": getTileLatRange(painter, tile.tileID),
"u_exaggeration": layer.paint.get("hillshade-exaggeration"),
"u_altitudes": illumination.altitudeRadians,
"u_azimuths": illumination.directionRadians,
"u_accent": accent,
"u_method": method,
"u_highlights": illumination.highlightColor,
"u_shadows": illumination.shadowColor
};
};
const hillshadeUniformPrepareValues = (tileID, dem) => {
const stride = dem.stride;
const matrix = create$1();
ortho(matrix, 0, EXTENT, -EXTENT, 0, 0, 1);
translate(matrix, matrix, [
0,
-EXTENT,
0
]);
return {
"u_matrix": matrix,
"u_image": 1,
"u_dimension": [stride, stride],
"u_zoom": tileID.overscaledZ,
"u_unpack": dem.getUnpackVector()
};
};
function getTileLatRange(painter, tileID) {
const tilesAtZoom = Math.pow(2, tileID.canonical.z);
const y = tileID.canonical.y;
return [new MercatorCoordinate(0, y / tilesAtZoom).toLngLat().lat, new MercatorCoordinate(0, (y + 1) / tilesAtZoom).toLngLat().lat];
}
//#endregion
//#region src/webgl/program/color_relief_program.ts
const colorReliefUniforms = (context, locations) => ({
"u_image": new Uniform1i(context, locations.u_image),
"u_unpack": new Uniform4f(context, locations.u_unpack),
"u_dimension": new Uniform2f(context, locations.u_dimension),
"u_elevation_stops": new Uniform1i(context, locations.u_elevation_stops),
"u_color_stops": new Uniform1i(context, locations.u_color_stops),
"u_color_ramp_size": new Uniform1i(context, locations.u_color_ramp_size),
"u_opacity": new Uniform1f(context, locations.u_opacity)
});
const colorReliefUniformValues = (layer, dem, colorRampSize = 0) => {
return {
"u_image": 0,
"u_unpack": dem.getUnpackVector(),
"u_dimension": [dem.stride, dem.stride],
"u_elevation_stops": 1,
"u_color_stops": 4,
"u_color_ramp_size": colorRampSize,
"u_opacity": layer.paint.get("color-relief-opacity")
};
};
//#endregion
//#region src/webgl/program/line_program.ts
const lineUniforms = (context, locations) => ({
"u_translation": new Uniform2f(context, locations.u_translation),
"u_ratio": new Uniform1f(context, locations.u_ratio),
"u_device_pixel_ratio": new Uniform1f(context, locations.u_device_pixel_ratio),
"u_units_to_pixels": new Uniform2f(context, locations.u_units_to_pixels)
});
const lineGradientUniforms = (context, locations) => ({
"u_translation": new Uniform2f(context, locations.u_translation),
"u_ratio": new Uniform1f(context, locations.u_ratio),
"u_device_pixel_ratio": new Uniform1f(context, locations.u_device_pixel_ratio),
"u_units_to_pixels": new Uniform2f(context, locations.u_units_to_pixels),
"u_image": new Uniform1i(context, locations.u_image),
"u_image_height": new Uniform1f(context, locations.u_image_height)
});
const linePatternUniforms = (context, locations) => ({
"u_translation": new Uniform2f(context, locations.u_translation),
"u_texsize": new Uniform2f(context, locations.u_texsize),
"u_ratio": new Uniform1f(context, locations.u_ratio),
"u_device_pixel_ratio": new Uniform1f(context, locations.u_device_pixel_ratio),
"u_image": new Uniform1i(context, locations.u_image),
"u_units_to_pixels": new Uniform2f(context, locations.u_units_to_pixels),
"u_scale": new Uniform3f(context, locations.u_scale),
"u_fade": new Uniform1f(context, locations.u_fade)
});
const lineSDFUniforms = (context, locations) => ({
"u_translation": new Uniform2f(context, locations.u_translation),
"u_ratio": new Uniform1f(context, locations.u_ratio),
"u_device_pixel_ratio": new Uniform1f(context, locations.u_device_pixel_ratio),
"u_units_to_pixels": new Uniform2f(context, locations.u_units_to_pixels),
"u_image": new Uniform1i(context, locations.u_image),
"u_mix": new Uniform1f(context, locations.u_mix),
"u_tileratio": new Uniform1f(context, locations.u_tileratio),
"u_crossfade_from": new Uniform1f(context, locations.u_crossfade_from),
"u_crossfade_to": new Uniform1f(context, locations.u_crossfade_to),
"u_lineatlas_width": new Uniform1f(context, locations.u_lineatlas_width),
"u_lineatlas_height": new Uniform1f(context, locations.u_lineatlas_height)
});
const lineGradientSDFUniforms = (context, locations) => ({
"u_translation": new Uniform2f(context, locations.u_translation),
"u_ratio": new Uniform1f(context, locations.u_ratio),
"u_device_pixel_ratio": new Uniform1f(context, locations.u_device_pixel_ratio),
"u_units_to_pixels": new Uniform2f(context, locations.u_units_to_pixels),
"u_image": new Uniform1i(context, locations.u_image),
"u_image_height": new Uniform1f(context, locations.u_image_height),
"u_tileratio": new Uniform1f(context, locations.u_tileratio),
"u_crossfade_from": new Uniform1f(context, locations.u_crossfade_from),
"u_crossfade_to": new Uniform1f(context, locations.u_crossfade_to),
"u_image_dash": new Uniform1i(context, locations.u_image_dash),
"u_mix": new Uniform1f(context, locations.u_mix),
"u_lineatlas_width": new Uniform1f(context, locations.u_lineatlas_width),
"u_lineatlas_height": new Uniform1f(context, locations.u_lineatlas_height)
});
const lineUniformValues = (painter, tile, layer, ratioScale) => {
const transform = painter.transform;
return {
"u_translation": calculateTranslation(painter, tile, layer),
"u_ratio": ratioScale / pixelsToTileUnits(tile, 1, transform.zoom),
"u_device_pixel_ratio": painter.pixelRatio,
"u_units_to_pixels": [1 / transform.pixelsToGLUnits[0], 1 / transform.pixelsToGLUnits[1]]
};
};
const lineGradientUniformValues = (painter, tile, layer, ratioScale, imageHeight) => {
return extend(lineUniformValues(painter, tile, layer, ratioScale), {
"u_image": 0,
"u_image_height": imageHeight
});
};
const linePatternUniformValues = (painter, tile, layer, ratioScale, crossfade) => {
const transform = painter.transform;
const tileZoomRatio = calculateTileRatio(tile, transform);
return {
"u_translation": calculateTranslation(painter, tile, layer),
"u_texsize": tile.imageAtlasTexture.size,
"u_ratio": ratioScale / pixelsToTileUnits(tile, 1, transform.zoom),
"u_device_pixel_ratio": painter.pixelRatio,
"u_image": 0,
"u_scale": [
tileZoomRatio,
crossfade.fromScale,
crossfade.toScale
],
"u_fade": crossfade.t,
"u_units_to_pixels": [1 / transform.pixelsToGLUnits[0], 1 / transform.pixelsToGLUnits[1]]
};
};
const lineSDFUniformValues = (painter, tile, layer, ratioScale, crossfade) => {
const transform = painter.transform;
const tileRatio = calculateTileRatio(tile, transform);
return extend(lineUniformValues(painter, tile, layer, ratioScale), {
"u_tileratio": tileRatio,
"u_crossfade_from": crossfade.fromScale,
"u_crossfade_to": crossfade.toScale,
"u_image": 0,
"u_mix": crossfade.t,
"u_lineatlas_width": painter.lineAtlas.width,
"u_lineatlas_height": painter.lineAtlas.height
});
};
const lineGradientSDFUniformValues = (painter, tile, layer, ratioScale, crossfade, imageHeight) => {
const transform = painter.transform;
const tileRatio = calculateTileRatio(tile, transform);
return extend(lineUniformValues(painter, tile, layer, ratioScale), {
"u_image": 0,
"u_image_height": imageHeight,
"u_tileratio": tileRatio,
"u_crossfade_from": crossfade.fromScale,
"u_crossfade_to": crossfade.toScale,
"u_image_dash": 1,
"u_mix": crossfade.t,
"u_lineatlas_width": painter.lineAtlas.width,
"u_lineatlas_height": painter.lineAtlas.height
});
};
function calculateTileRatio(tile, transform) {
return 1 / pixelsToTileUnits(tile, 1, transform.tileZoom);
}
function calculateTranslation(painter, tile, layer) {
return translatePosition(painter.transform, tile, layer.paint.get("line-translate"), layer.paint.get("line-translate-anchor"));
}
//#endregion
//#region src/webgl/program/layer_opacity_program.ts
const layerOpacityUniforms = (context, locations) => ({
"u_image": new Uniform1i(context, locations.u_image),
"u_opacity": new Uniform1f(context, locations.u_opacity)
});
const layerOpacityUniformValues = (opacity, textureUnit) => ({
"u_image": textureUnit,
"u_opacity": opacity
});
//#endregion
//#region src/webgl/program/symbol_program.ts
const symbolIconUniforms = (context, locations) => ({
"u_is_size_zoom_constant": new Uniform1i(context, locations.u_is_size_zoom_constant),
"u_is_size_feature_constant": new Uniform1i(context, locations.u_is_size_feature_constant),
"u_size_t": new Uniform1f(context, locations.u_size_t),
"u_size": new Uniform1f(context, locations.u_size),
"u_camera_to_center_distance": new Uniform1f(context, locations.u_camera_to_center_distance),
"u_pitch": new Uniform1f(context, locations.u_pitch),
"u_rotate_symbol": new Uniform1i(context, locations.u_rotate_symbol),
"u_aspect_ratio": new Uniform1f(context, locations.u_aspect_ratio),
"u_fade_change": new Uniform1f(context, locations.u_fade_change),
"u_label_plane_matrix": new UniformMatrix4f(context, locations.u_label_plane_matrix),
"u_coord_matrix": new UniformMatrix4f(context, locations.u_coord_matrix),
"u_is_text": new Uniform1i(context, locations.u_is_text),
"u_pitch_with_map": new Uniform1i(context, locations.u_pitch_with_map),
"u_is_along_line": new Uniform1i(context, locations.u_is_along_line),
"u_is_variable_anchor": new Uniform1i(context, locations.u_is_variable_anchor),
"u_texsize": new Uniform2f(context, locations.u_texsize),
"u_texture": new Uniform1i(context, locations.u_texture),
"u_translation": new Uniform2f(context, locations.u_translation),
"u_pitched_scale": new Uniform1f(context, locations.u_pitched_scale),
"u_is_offset": new Uniform1i(context, locations.u_is_offset)
});
const symbolSDFUniforms = (context, locations) => ({
"u_is_size_zoom_constant": new Uniform1i(context, locations.u_is_size_zoom_constant),
"u_is_size_feature_constant": new Uniform1i(context, locations.u_is_size_feature_constant),
"u_size_t": new Uniform1f(context, locations.u_size_t),
"u_size": new Uniform1f(context, locations.u_size),
"u_camera_to_center_distance": new Uniform1f(context, locations.u_camera_to_center_distance),
"u_pitch": new Uniform1f(context, locations.u_pitch),
"u_rotate_symbol": new Uniform1i(context, locations.u_rotate_symbol),
"u_aspect_ratio": new Uniform1f(context, locations.u_aspect_ratio),
"u_fade_change": new Uniform1f(context, locations.u_fade_change),
"u_label_plane_matrix": new UniformMatrix4f(context, locations.u_label_plane_matrix),
"u_coord_matrix": new UniformMatrix4f(context, locations.u_coord_matrix),
"u_is_text": new Uniform1i(context, locations.u_is_text),
"u_pitch_with_map": new Uniform1i(context, locations.u_pitch_with_map),
"u_is_along_line": new Uniform1i(context, locations.u_is_along_line),
"u_is_variable_anchor": new Uniform1i(context, locations.u_is_variable_anchor),
"u_texsize": new Uniform2f(context, locations.u_texsize),
"u_texture": new Uniform1i(context, locations.u_texture),
"u_gamma_scale": new Uniform1f(context, locations.u_gamma_scale),
"u_device_pixel_ratio": new Uniform1f(context, locations.u_device_pixel_ratio),
"u_is_halo": new Uniform1i(context, locations.u_is_halo),
"u_is_plain": new Uniform1i(context, locations.u_is_plain),
"u_translation": new Uniform2f(context, locations.u_translation),
"u_pitched_scale": new Uniform1f(context, locations.u_pitched_scale),
"u_is_offset": new Uniform1i(context, locations.u_is_offset)
});
const symbolTextAndIconUniforms = (context, locations) => ({
"u_is_size_zoom_constant": new Uniform1i(context, locations.u_is_size_zoom_constant),
"u_is_size_feature_constant": new Uniform1i(context, locations.u_is_size_feature_constant),
"u_size_t": new Uniform1f(context, locations.u_size_t),
"u_size": new Uniform1f(context, locations.u_size),
"u_camera_to_center_distance": new Uniform1f(context, locations.u_camera_to_center_distance),
"u_pitch": new Uniform1f(context, locations.u_pitch),
"u_rotate_symbol": new Uniform1i(context, locations.u_rotate_symbol),
"u_aspect_ratio": new Uniform1f(context, locations.u_aspect_ratio),
"u_fade_change": new Uniform1f(context, locations.u_fade_change),
"u_label_plane_matrix": new UniformMatrix4f(context, locations.u_label_plane_matrix),
"u_coord_matrix": new UniformMatrix4f(context, locations.u_coord_matrix),
"u_is_text": new Uniform1i(context, locations.u_is_text),
"u_pitch_with_map": new Uniform1i(context, locations.u_pitch_with_map),
"u_is_along_line": new Uniform1i(context, locations.u_is_along_line),
"u_is_variable_anchor": new Uniform1i(context, locations.u_is_variable_anchor),
"u_texsize": new Uniform2f(context, locations.u_texsize),
"u_texsize_icon": new Uniform2f(context, locations.u_texsize_icon),
"u_texture": new Uniform1i(context, locations.u_texture),
"u_texture_icon": new Uniform1i(context, locations.u_texture_icon),
"u_gamma_scale": new Uniform1f(context, locations.u_gamma_scale),
"u_device_pixel_ratio": new Uniform1f(context, locations.u_device_pixel_ratio),
"u_is_halo": new Uniform1i(context, locations.u_is_halo),
"u_translation": new Uniform2f(context, locations.u_translation),
"u_pitched_scale": new Uniform1f(context, locations.u_pitched_scale),
"u_is_offset": new Uniform1i(context, locations.u_is_offset)
});
const symbolIconUniformValues = (functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, labelPlaneMatrix, glCoordMatrix, translation, isText, texSize, pitchedScale, isOffset) => {
const transform = painter.transform;
return {
"u_is_size_zoom_constant": +(functionType === "constant" || functionType === "source"),
"u_is_size_feature_constant": +(functionType === "constant" || functionType === "camera"),
"u_size_t": size ? size.uSizeT : 0,
"u_size": size ? size.uSize : 0,
"u_camera_to_center_distance": transform.cameraToCenterDistance,
"u_pitch": transform.pitch / 360 * 2 * Math.PI,
"u_rotate_symbol": +rotateInShader,
"u_aspect_ratio": transform.width / transform.height,
"u_fade_change": painter.options.fadeDuration ? painter.symbolFadeChange : 1,
"u_label_plane_matrix": labelPlaneMatrix,
"u_coord_matrix": glCoordMatrix,
"u_is_text": +isText,
"u_pitch_with_map": +pitchWithMap,
"u_is_along_line": isAlongLine,
"u_is_variable_anchor": isVariableAnchor,
"u_texsize": texSize,
"u_texture": 0,
"u_translation": translation,
"u_pitched_scale": pitchedScale,
"u_is_offset": isOffset
};
};
const symbolSDFUniformValues = (functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, labelPlaneMatrix, glCoordMatrix, translation, isText, texSize, isHalo, pitchedScale, isOffset) => {
const transform = painter.transform;
return extend(symbolIconUniformValues(functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, labelPlaneMatrix, glCoordMatrix, translation, isText, texSize, pitchedScale, isOffset), {
"u_gamma_scale": pitchWithMap ? Math.cos(transform.pitch * Math.PI / 180) * transform.cameraToCenterDistance : 1,
"u_device_pixel_ratio": painter.pixelRatio,
"u_is_halo": isHalo ? 1 : 0,
"u_is_plain": 1
});
};
const symbolTextAndIconUniformValues = (functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, labelPlaneMatrix, glCoordMatrix, translation, texSizeSDF, texSizeIcon, pitchedScale, isOffset) => {
return extend(symbolSDFUniformValues(functionType, size, rotateInShader, pitchWithMap, isAlongLine, isVariableAnchor, painter, labelPlaneMatrix, glCoordMatrix, translation, true, texSizeSDF, true, pitchedScale, isOffset), {
"u_texsize_icon": texSizeIcon,
"u_texture_icon": 1
});
};
//#endregion
//#region src/webgl/program/background_program.ts
const backgroundUniforms = (context, locations) => ({
"u_opacity": new Uniform1f(context, locations.u_opacity),
"u_color": new UniformColor(context, locations.u_color)
});
const backgroundPatternUniforms = (context, locations) => ({
"u_opacity": new Uniform1f(context, locations.u_opacity),
"u_image": new Uniform1i(context, locations.u_image),
"u_pattern_tl_a": new Uniform2f(context, locations.u_pattern_tl_a),
"u_pattern_br_a": new Uniform2f(context, locations.u_pattern_br_a),
"u_pattern_tl_b": new Uniform2f(context, locations.u_pattern_tl_b),
"u_pattern_br_b": new Uniform2f(context, locations.u_pattern_br_b),
"u_texsize": new Uniform2f(context, locations.u_texsize),
"u_mix": new Uniform1f(context, locations.u_mix),
"u_pattern_size_a": new Uniform2f(context, locations.u_pattern_size_a),
"u_pattern_size_b": new Uniform2f(context, locations.u_pattern_size_b),
"u_scale_a": new Uniform1f(context, locations.u_scale_a),
"u_scale_b": new Uniform1f(context, locations.u_scale_b),
"u_pixel_coord_upper": new Uniform2f(context, locations.u_pixel_coord_upper),
"u_pixel_coord_lower": new Uniform2f(context, locations.u_pixel_coord_lower),
"u_tile_units_to_pixels": new Uniform1f(context, locations.u_tile_units_to_pixels)
});
const backgroundUniformValues = (opacity, color) => ({
"u_opacity": opacity,
"u_color": color
});
const backgroundPatternUniformValues = (opacity, painter, image, tile, crossfade) => extend(bgPatternUniformValues(image, crossfade, painter, tile), { "u_opacity": opacity });
//#endregion
//#region src/webgl/program/atmosphere_program.ts
const atmosphereUniforms = (context, locations) => ({
"u_sun_pos": new Uniform3f(context, locations.u_sun_pos),
"u_atmosphere_blend": new Uniform1f(context, locations.u_atmosphere_blend),
"u_globe_position": new Uniform3f(context, locations.u_globe_position),
"u_globe_radius": new Uniform1f(context, locations.u_globe_radius),
"u_inv_proj_matrix": new UniformMatrix4f(context, locations.u_inv_proj_matrix)
});
const atmosphereUniformValues = (sunPos, atmosphereBlend, globePosition, globeRadius, invProjMatrix) => ({
"u_sun_pos": sunPos,
"u_atmosphere_blend": atmosphereBlend,
"u_globe_position": globePosition,
"u_globe_radius": globeRadius,
"u_inv_proj_matrix": invProjMatrix
});
//#endregion
//#region src/webgl/program/sky_program.ts
const skyUniforms = (context, locations) => ({
"u_sky_color": new UniformColor(context, locations.u_sky_color),
"u_horizon_color": new UniformColor(context, locations.u_horizon_color),
"u_horizon": new Uniform2f(context, locations.u_horizon),
"u_horizon_normal": new Uniform2f(context, locations.u_horizon_normal),
"u_sky_horizon_blend": new Uniform1f(context, locations.u_sky_horizon_blend),
"u_sky_blend": new Uniform1f(context, locations.u_sky_blend)
});
const skyUniformValues = (sky, transform, pixelRatio) => {
const cosRoll = Math.cos(transform.rollInRadians);
const sinRoll = Math.sin(transform.rollInRadians);
const mercatorHorizon = getMercatorHorizon(transform);
const skyBlend = transform.getProjectionData({
overscaledTileID: null,
applyGlobeMatrix: true,
applyTerrainMatrix: true
}).projectionTransition;
return {
"u_sky_color": sky.properties.get("sky-color"),
"u_horizon_color": sky.properties.get("horizon-color"),
"u_horizon": [(transform.width / 2 - mercatorHorizon * sinRoll) * pixelRatio, (transform.height / 2 + mercatorHorizon * cosRoll) * pixelRatio],
"u_horizon_normal": [-sinRoll, cosRoll],
"u_sky_horizon_blend": sky.properties.get("sky-horizon-blend") * transform.height / 2 * pixelRatio,
"u_sky_blend": skyBlend
};
};
//#endregion
//#region src/webgl/program/program_uniforms.ts
const emptyUniforms = (_, __) => {};
const programUniforms = {
fillExtrusion: fillExtrusionUniforms,
fillExtrusionPattern: fillExtrusionPatternUniforms,
fill: fillUniforms,
fillPattern: fillPatternUniforms,
fillOutline: fillOutlineUniforms,
fillOutlinePattern: fillOutlinePatternUniforms,
circle: circleUniforms,
collisionBox: collisionUniforms,
collisionCircle: collisionCircleUniforms,
debug: debugUniforms,
depth: emptyUniforms,
clippingMask: emptyUniforms,
heatmap: heatmapUniforms,
heatmapTexture: heatmapTextureUniforms,
hillshade: hillshadeUniforms,
hillshadePrepare: hillshadePrepareUniforms,
colorRelief: colorReliefUniforms,
line: lineUniforms,
lineGradient: lineGradientUniforms,
linePattern: linePatternUniforms,
lineSDF: lineSDFUniforms,
lineGradientSDF: lineGradientSDFUniforms,
layerOpacity: layerOpacityUniforms,
raster: rasterUniforms,
symbolIcon: symbolIconUniforms,
symbolSDF: symbolSDFUniforms,
symbolTextAndIcon: symbolTextAndIconUniforms,
background: backgroundUniforms,
backgroundPattern: backgroundPatternUniforms,
terrain: terrainUniforms,
terrainDepth: terrainDepthUniforms,
terrainCoords: terrainCoordsUniforms,
atmosphere: atmosphereUniforms,
sky: skyUniforms
};
//#endregion
//#region src/webgl/index_buffer.ts
/**
* @internal
* an index buffer class
*/
var IndexBuffer = class {
constructor(context, array, dynamicDraw) {
this.context = context;
const gl = context.gl;
this.buffer = gl.createBuffer();
this.dynamicDraw = Boolean(dynamicDraw);
this.context.unbindVAO();
context.bindElementBuffer.set(this.buffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW);
if (!this.dynamicDraw) array.freeBufferAfterUpload();
}
bind() {
this.context.bindElementBuffer.set(this.buffer);
}
updateData(array) {
const gl = this.context.gl;
if (!this.dynamicDraw) throw new Error("Attempted to update data while not in dynamic mode.");
this.context.unbindVAO();
this.bind();
gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, 0, array.arrayBuffer);
}
destroy() {
const gl = this.context.gl;
if (this.buffer) {
gl.deleteBuffer(this.buffer);
delete this.buffer;
}
}
};
//#endregion
//#region src/webgl/vertex_buffer.ts
/**
* An Enum for AttributeType
*/
const AttributeType = {
Int8: "BYTE",
Uint8: "UNSIGNED_BYTE",
Int16: "SHORT",
Uint16: "UNSIGNED_SHORT",
Int32: "INT",
Uint32: "UNSIGNED_INT",
Float32: "FLOAT"
};
/**
* @internal
* The `VertexBuffer` class turns a `StructArray` into a WebGL buffer. Each member of the StructArray's
* Struct type is converted to a WebGL attribute.
*/
var VertexBuffer = class {
/**
* @param dynamicDraw - Whether this buffer will be repeatedly updated.
*/
constructor(context, array, attributes, dynamicDraw) {
this.length = array.length;
this.attributes = attributes;
this.itemSize = array.bytesPerElement;
this.dynamicDraw = dynamicDraw;
this.context = context;
const gl = context.gl;
this.buffer = gl.createBuffer();
context.bindVertexBuffer.set(this.buffer);
gl.bufferData(gl.ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW);
if (!this.dynamicDraw) array.freeBufferAfterUpload();
}
bind() {
this.context.bindVertexBuffer.set(this.buffer);
}
updateData(array) {
if (array.length !== this.length) throw new Error(`Length of new data is ${array.length}, which doesn't match current length of ${this.length}`);
const gl = this.context.gl;
this.bind();
gl.bufferSubData(gl.ARRAY_BUFFER, 0, array.arrayBuffer);
}
enableAttributes(gl, program) {
for (const member of this.attributes) {
const attribute = program.attributes[member.name];
if (attribute !== void 0) gl.enableVertexAttribArray(attribute.location);
}
}
/**
* Set the attribute pointers in a WebGL context
* @param gl - The WebGL context
* @param program - The active WebGL program
* @param vertexOffset - Index of the starting vertex of the segment
*/
setVertexAttribPointers(gl, program, vertexOffset) {
for (const member of this.attributes) {
const attribute = program.attributes[member.name];
if (attribute !== void 0) {
const offset = member.offset + this.itemSize * (vertexOffset || 0);
if (attribute.isInteger) gl.vertexAttribIPointer(attribute.location, member.components, gl[AttributeType[member.type]], this.itemSize, offset);
else gl.vertexAttribPointer(attribute.location, member.components, gl[AttributeType[member.type]], false, this.itemSize, offset);
}
}
}
/**
* Destroy the GL buffer bound to the given WebGL context
*/
destroy() {
const gl = this.context.gl;
if (this.buffer) {
gl.deleteBuffer(this.buffer);
delete this.buffer;
}
}
};
//#endregion
//#region src/webgl/value.ts
var BaseValue = class {
constructor(context) {
this.gl = context.gl;
this.default = this.getDefault();
this.current = this.default;
this.dirty = false;
}
get() {
return this.current;
}
set(value) {}
getDefault() {
return this.default;
}
setDefault() {
this.set(this.default);
}
};
var ClearColor = class extends BaseValue {
getDefault() {
return Color.transparent;
}
set(v) {
const c = this.current;
if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) return;
this.gl.clearColor(v.r, v.g, v.b, v.a);
this.current = v;
this.dirty = false;
}
};
var ClearDepth = class extends BaseValue {
getDefault() {
return 1;
}
set(v) {
if (v === this.current && !this.dirty) return;
this.gl.clearDepth(v);
this.current = v;
this.dirty = false;
}
};
var ClearStencil = class extends BaseValue {
getDefault() {
return 0;
}
set(v) {
if (v === this.current && !this.dirty) return;
this.gl.clearStencil(v);
this.current = v;
this.dirty = false;
}
};
var ColorMask = class extends BaseValue {
getDefault() {
return [
true,
true,
true,
true
];
}
set(v) {
const c = this.current;
if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) return;
this.gl.colorMask(v[0], v[1], v[2], v[3]);
this.current = v;
this.dirty = false;
}
};
var DepthMask = class extends BaseValue {
getDefault() {
return true;
}
set(v) {
if (v === this.current && !this.dirty) return;
this.gl.depthMask(v);
this.current = v;
this.dirty = false;
}
};
var StencilMask = class extends BaseValue {
getDefault() {
return 255;
}
set(v) {
if (v === this.current && !this.dirty) return;
this.gl.stencilMask(v);
this.current = v;
this.dirty = false;
}
};
var StencilFunc = class extends BaseValue {
getDefault() {
return {
func: this.gl.ALWAYS,
ref: 0,
mask: 255
};
}
set(v) {
const c = this.current;
if (v.func === c.func && v.ref === c.ref && v.mask === c.mask && !this.dirty) return;
this.gl.stencilFunc(v.func, v.ref, v.mask);
this.current = v;
this.dirty = false;
}
};
var StencilOp = class extends BaseValue {
getDefault() {
const gl = this.gl;
return [
gl.KEEP,
gl.KEEP,
gl.KEEP
];
}
set(v) {
const c = this.current;
if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && !this.dirty) return;
this.gl.stencilOp(v[0], v[1], v[2]);
this.current = v;
this.dirty = false;
}
};
var StencilTest = class extends BaseValue {
getDefault() {
return false;
}
set(v) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
if (v) gl.enable(gl.STENCIL_TEST);
else gl.disable(gl.STENCIL_TEST);
this.current = v;
this.dirty = false;
}
};
var DepthRange = class extends BaseValue {
getDefault() {
return [0, 1];
}
set(v) {
const c = this.current;
if (v[0] === c[0] && v[1] === c[1] && !this.dirty) return;
this.gl.depthRange(v[0], v[1]);
this.current = v;
this.dirty = false;
}
};
var DepthTest = class extends BaseValue {
getDefault() {
return false;
}
set(v) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
if (v) gl.enable(gl.DEPTH_TEST);
else gl.disable(gl.DEPTH_TEST);
this.current = v;
this.dirty = false;
}
};
var DepthFunc = class extends BaseValue {
getDefault() {
return this.gl.LESS;
}
set(v) {
if (v === this.current && !this.dirty) return;
this.gl.depthFunc(v);
this.current = v;
this.dirty = false;
}
};
var Blend = class extends BaseValue {
getDefault() {
return false;
}
set(v) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
if (v) gl.enable(gl.BLEND);
else gl.disable(gl.BLEND);
this.current = v;
this.dirty = false;
}
};
var BlendFunc = class extends BaseValue {
getDefault() {
const gl = this.gl;
return [gl.ONE, gl.ZERO];
}
set(v) {
const c = this.current;
if (v[0] === c[0] && v[1] === c[1] && !this.dirty) return;
this.gl.blendFunc(v[0], v[1]);
this.current = v;
this.dirty = false;
}
};
var BlendColor = class extends BaseValue {
getDefault() {
return Color.transparent;
}
set(v) {
const c = this.current;
if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) return;
this.gl.blendColor(v.r, v.g, v.b, v.a);
this.current = v;
this.dirty = false;
}
};
var BlendEquation = class extends BaseValue {
getDefault() {
return this.gl.FUNC_ADD;
}
set(v) {
if (v === this.current && !this.dirty) return;
this.gl.blendEquation(v);
this.current = v;
this.dirty = false;
}
};
var CullFace = class extends BaseValue {
getDefault() {
return false;
}
set(v) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
if (v) gl.enable(gl.CULL_FACE);
else gl.disable(gl.CULL_FACE);
this.current = v;
this.dirty = false;
}
};
var CullFaceSide = class extends BaseValue {
getDefault() {
return this.gl.BACK;
}
set(v) {
if (v === this.current && !this.dirty) return;
this.gl.cullFace(v);
this.current = v;
this.dirty = false;
}
};
var FrontFace = class extends BaseValue {
getDefault() {
return this.gl.CCW;
}
set(v) {
if (v === this.current && !this.dirty) return;
this.gl.frontFace(v);
this.current = v;
this.dirty = false;
}
};
var ProgramValue = class extends BaseValue {
getDefault() {
return null;
}
set(v) {
if (v === this.current && !this.dirty) return;
this.gl.useProgram(v);
this.current = v;
this.dirty = false;
}
};
var ActiveTextureUnit = class extends BaseValue {
getDefault() {
return this.gl.TEXTURE0;
}
set(v) {
if (v === this.current && !this.dirty) return;
this.gl.activeTexture(v);
this.current = v;
this.dirty = false;
}
};
var Viewport = class extends BaseValue {
getDefault() {
const gl = this.gl;
return [
0,
0,
gl.drawingBufferWidth,
gl.drawingBufferHeight
];
}
set(v) {
const c = this.current;
if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) return;
this.gl.viewport(v[0], v[1], v[2], v[3]);
this.current = v;
this.dirty = false;
}
};
var BindFramebuffer = class extends BaseValue {
getDefault() {
return null;
}
set(v) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
gl.bindFramebuffer(gl.FRAMEBUFFER, v);
this.current = v;
this.dirty = false;
}
};
var BindRenderbuffer = class extends BaseValue {
getDefault() {
return null;
}
set(v) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
gl.bindRenderbuffer(gl.RENDERBUFFER, v);
this.current = v;
this.dirty = false;
}
};
var BindTexture = class extends BaseValue {
getDefault() {
return null;
}
set(v) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
gl.bindTexture(gl.TEXTURE_2D, v);
this.current = v;
this.dirty = false;
}
};
var BindVertexBuffer = class extends BaseValue {
getDefault() {
return null;
}
set(v) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
gl.bindBuffer(gl.ARRAY_BUFFER, v);
this.current = v;
this.dirty = false;
}
};
var BindElementBuffer = class extends BaseValue {
getDefault() {
return null;
}
set(v) {
const gl = this.gl;
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, v);
this.current = v;
this.dirty = false;
}
};
var BindVertexArray = class extends BaseValue {
getDefault() {
return null;
}
set(v) {
if (v === this.current && !this.dirty) return;
this.gl.bindVertexArray(v);
this.current = v;
this.dirty = false;
}
};
var PixelStoreUnpack = class extends BaseValue {
getDefault() {
return 4;
}
set(v) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
gl.pixelStorei(gl.UNPACK_ALIGNMENT, v);
this.current = v;
this.dirty = false;
}
};
var PixelStoreUnpackPremultiplyAlpha = class extends BaseValue {
getDefault() {
return false;
}
set(v) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, v);
this.current = v;
this.dirty = false;
}
};
var PixelStoreUnpackFlipY = class extends BaseValue {
getDefault() {
return false;
}
set(v) {
if (v === this.current && !this.dirty) return;
const gl = this.gl;
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, v);
this.current = v;
this.dirty = false;
}
};
var FramebufferAttachment = class extends BaseValue {
constructor(context, parent) {
super(context);
this.context = context;
this.parent = parent;
}
getDefault() {
return null;
}
};
var ColorAttachment = class extends FramebufferAttachment {
setDirty() {
this.dirty = true;
}
set(v) {
if (v === this.current && !this.dirty) return;
this.context.bindFramebuffer.set(this.parent);
const gl = this.gl;
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, v, 0);
this.current = v;
this.dirty = false;
}
};
var DepthAttachment = class extends FramebufferAttachment {
set(v) {
if (v === this.current && !this.dirty) return;
this.context.bindFramebuffer.set(this.parent);
const gl = this.gl;
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, v);
this.current = v;
this.dirty = false;
}
};
var DepthStencilAttachment = class extends FramebufferAttachment {
set(v) {
if (v === this.current && !this.dirty) return;
this.context.bindFramebuffer.set(this.parent);
const gl = this.gl;
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, v);
this.current = v;
this.dirty = false;
}
};
//#endregion
//#region src/webgl/framebuffer.ts
/**
* @internal
* A framebuffer holder object
*/
var Framebuffer = class {
constructor(context, width, height, hasDepth, hasStencil) {
this.context = context;
this.width = width;
this.height = height;
const gl = context.gl;
const fbo = this.framebuffer = gl.createFramebuffer();
this.colorAttachment = new ColorAttachment(context, fbo);
if (hasDepth) this.depthAttachment = hasStencil ? new DepthStencilAttachment(context, fbo) : new DepthAttachment(context, fbo);
else if (hasStencil) throw new Error("Stencil cannot be set without depth");
}
destroy() {
const gl = this.context.gl;
const texture = this.colorAttachment.get();
if (texture) gl.deleteTexture(texture);
if (this.depthAttachment) {
const renderbuffer = this.depthAttachment.get();
if (renderbuffer) gl.deleteRenderbuffer(renderbuffer);
}
gl.deleteFramebuffer(this.framebuffer);
}
};
//#endregion
//#region src/webgl/color_mode.ts
const ZERO = 0;
const ONE = 1;
const ONE_MINUS_SRC_ALPHA = 771;
var ColorMode = class {
constructor(blendFunction, blendColor, mask) {
this.blendFunction = blendFunction;
this.blendColor = blendColor;
this.mask = mask;
}
};
ColorMode.Replace = [ONE, ZERO];
ColorMode.disabled = new ColorMode(ColorMode.Replace, Color.transparent, [
false,
false,
false,
false
]);
ColorMode.unblended = new ColorMode(ColorMode.Replace, Color.transparent, [
true,
true,
true,
true
]);
ColorMode.alphaBlended = new ColorMode([ONE, ONE_MINUS_SRC_ALPHA], Color.transparent, [
true,
true,
true,
true
]);
//#endregion
//#region src/webgl/context.ts
/**
* @internal
* A webgl wrapper class to allow injection, mocking and abstraction
*/
var Context = class {
constructor(gl) {
this.gl = gl;
this.clearColor = new ClearColor(this);
this.clearDepth = new ClearDepth(this);
this.clearStencil = new ClearStencil(this);
this.colorMask = new ColorMask(this);
this.depthMask = new DepthMask(this);
this.stencilMask = new StencilMask(this);
this.stencilFunc = new StencilFunc(this);
this.stencilOp = new StencilOp(this);
this.stencilTest = new StencilTest(this);
this.depthRange = new DepthRange(this);
this.depthTest = new DepthTest(this);
this.depthFunc = new DepthFunc(this);
this.blend = new Blend(this);
this.blendFunc = new BlendFunc(this);
this.blendColor = new BlendColor(this);
this.blendEquation = new BlendEquation(this);
this.cullFace = new CullFace(this);
this.cullFaceSide = new CullFaceSide(this);
this.frontFace = new FrontFace(this);
this.program = new ProgramValue(this);
this.activeTexture = new ActiveTextureUnit(this);
this.viewport = new Viewport(this);
this.bindFramebuffer = new BindFramebuffer(this);
this.bindRenderbuffer = new BindRenderbuffer(this);
this.bindTexture = new BindTexture(this);
this.bindVertexBuffer = new BindVertexBuffer(this);
this.bindElementBuffer = new BindElementBuffer(this);
this.bindVertexArray = new BindVertexArray(this);
this.pixelStoreUnpack = new PixelStoreUnpack(this);
this.pixelStoreUnpackPremultiplyAlpha = new PixelStoreUnpackPremultiplyAlpha(this);
this.pixelStoreUnpackFlipY = new PixelStoreUnpackFlipY(this);
this.extTextureFilterAnisotropic = gl.getExtension("EXT_texture_filter_anisotropic");
if (this.extTextureFilterAnisotropic) this.extTextureFilterAnisotropicMax = gl.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
this.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
gl.getExtension("EXT_color_buffer_half_float");
gl.getExtension("EXT_color_buffer_float");
}
setDefault() {
this.unbindVAO();
this.clearColor.setDefault();
this.clearDepth.setDefault();
this.clearStencil.setDefault();
this.colorMask.setDefault();
this.depthMask.setDefault();
this.stencilMask.setDefault();
this.stencilFunc.setDefault();
this.stencilOp.setDefault();
this.stencilTest.setDefault();
this.depthRange.setDefault();
this.depthTest.setDefault();
this.depthFunc.setDefault();
this.blend.setDefault();
this.blendFunc.setDefault();
this.blendColor.setDefault();
this.blendEquation.setDefault();
this.cullFace.setDefault();
this.cullFaceSide.setDefault();
this.frontFace.setDefault();
this.program.setDefault();
this.activeTexture.setDefault();
this.bindFramebuffer.setDefault();
this.pixelStoreUnpack.setDefault();
this.pixelStoreUnpackPremultiplyAlpha.setDefault();
this.pixelStoreUnpackFlipY.setDefault();
}
setDirty() {
this.clearColor.dirty = true;
this.clearDepth.dirty = true;
this.clearStencil.dirty = true;
this.colorMask.dirty = true;
this.depthMask.dirty = true;
this.stencilMask.dirty = true;
this.stencilFunc.dirty = true;
this.stencilOp.dirty = true;
this.stencilTest.dirty = true;
this.depthRange.dirty = true;
this.depthTest.dirty = true;
this.depthFunc.dirty = true;
this.blend.dirty = true;
this.blendFunc.dirty = true;
this.blendColor.dirty = true;
this.blendEquation.dirty = true;
this.cullFace.dirty = true;
this.cullFaceSide.dirty = true;
this.frontFace.dirty = true;
this.program.dirty = true;
this.activeTexture.dirty = true;
this.viewport.dirty = true;
this.bindFramebuffer.dirty = true;
this.bindRenderbuffer.dirty = true;
this.bindTexture.dirty = true;
this.bindVertexBuffer.dirty = true;
this.bindElementBuffer.dirty = true;
this.bindVertexArray.dirty = true;
this.pixelStoreUnpack.dirty = true;
this.pixelStoreUnpackPremultiplyAlpha.dirty = true;
this.pixelStoreUnpackFlipY.dirty = true;
}
/**
* Reset some GL state to default values before handing users the raw context, as we do for
* custom layers and WebGL style images, to avoid hard-to-debug bugs in their code.
*
* MapLibre restores all of its own state afterwards, so the only state worth resetting first
* is state users would be surprised to find dirty: `CULL_FACE`, `TEXTURE0` and the three
* `UNPACK_` settings, whose defaults are meaningful enough that most code assumes them.
* The vertex array is unbound rather than reset, so that MapLibre never has to track it and
* a user's `vertexAttribPointer` calls cannot land on one of ours.
*/
setCustomLayerDefaults() {
this.unbindVAO();
this.cullFace.setDefault();
this.activeTexture.setDefault();
this.pixelStoreUnpack.setDefault();
this.pixelStoreUnpackPremultiplyAlpha.setDefault();
this.pixelStoreUnpackFlipY.setDefault();
}
createIndexBuffer(array, dynamicDraw) {
return new IndexBuffer(this, array, dynamicDraw);
}
createVertexBuffer(array, attributes, dynamicDraw) {
return new VertexBuffer(this, array, attributes, dynamicDraw);
}
createRenderbuffer(storageFormat, width, height) {
const gl = this.gl;
const rbo = gl.createRenderbuffer();
this.bindRenderbuffer.set(rbo);
gl.renderbufferStorage(gl.RENDERBUFFER, storageFormat, width, height);
this.bindRenderbuffer.set(null);
return rbo;
}
createFramebuffer(width, height, hasDepth, hasStencil) {
return new Framebuffer(this, width, height, hasDepth, hasStencil);
}
clear({ color, depth, stencil }) {
const gl = this.gl;
let mask = 0;
if (color) {
mask |= gl.COLOR_BUFFER_BIT;
this.clearColor.set(color);
this.colorMask.set([
true,
true,
true,
true
]);
}
if (typeof depth !== "undefined") {
mask |= gl.DEPTH_BUFFER_BIT;
this.depthRange.set([0, 1]);
this.clearDepth.set(depth);
this.depthMask.set(true);
}
if (typeof stencil !== "undefined") {
mask |= gl.STENCIL_BUFFER_BIT;
this.clearStencil.set(stencil);
this.stencilMask.set(255);
}
gl.clear(mask);
}
setCullFace(cullFaceMode) {
if (cullFaceMode.enable === false) this.cullFace.set(false);
else {
this.cullFace.set(true);
this.cullFaceSide.set(cullFaceMode.mode);
this.frontFace.set(cullFaceMode.frontFace);
}
}
setDepthMode(depthMode) {
if (depthMode.func === this.gl.ALWAYS && !depthMode.mask) this.depthTest.set(false);
else {
this.depthTest.set(true);
this.depthFunc.set(depthMode.func);
this.depthMask.set(depthMode.mask);
this.depthRange.set(depthMode.range);
}
}
setStencilMode(stencilMode) {
if (stencilMode.test.func === this.gl.ALWAYS && !stencilMode.mask) this.stencilTest.set(false);
else {
this.stencilTest.set(true);
this.stencilMask.set(stencilMode.mask);
this.stencilOp.set([
stencilMode.fail,
stencilMode.depthFail,
stencilMode.pass
]);
this.stencilFunc.set({
func: stencilMode.test.func,
ref: stencilMode.ref,
mask: stencilMode.test.mask
});
}
}
setColorMode(colorMode) {
if (deepEqual(colorMode.blendFunction, ColorMode.Replace)) this.blend.set(false);
else {
this.blend.set(true);
this.blendFunc.set(colorMode.blendFunction);
this.blendColor.set(colorMode.blendColor);
}
this.colorMask.set(colorMode.mask);
}
createVertexArray() {
return this.gl.createVertexArray();
}
deleteVertexArray(x) {
this.gl.deleteVertexArray(x);
}
unbindVAO() {
this.bindVertexArray.set(null);
}
};
//#endregion
//#region src/webgl/depth_mode.ts
const ALWAYS$1 = 519;
var DepthMode = class {
constructor(depthFunc, depthMask, depthRange) {
this.func = depthFunc;
this.mask = depthMask;
this.range = depthRange;
}
};
DepthMode.ReadOnly = false;
DepthMode.ReadWrite = true;
DepthMode.disabled = new DepthMode(ALWAYS$1, DepthMode.ReadOnly, [0, 1]);
//#endregion
//#region src/webgl/stencil_mode.ts
const ALWAYS = 519;
const KEEP = 7680;
var StencilMode = class {
constructor(test, ref, mask, fail, depthFail, pass) {
this.test = test;
this.ref = ref;
this.mask = mask;
this.fail = fail;
this.depthFail = depthFail;
this.pass = pass;
}
};
StencilMode.disabled = new StencilMode({
func: ALWAYS,
mask: 0
}, 0, 0, KEEP, KEEP, KEEP);
//#endregion
//#region src/webgl/cull_face_mode.ts
const FRONT = 1028;
const BACK = 1029;
const CCW = 2305;
var CullFaceMode = class {
constructor(enable, mode, frontFace) {
this.enable = enable;
this.mode = mode;
this.frontFace = frontFace;
}
};
CullFaceMode.disabled = new CullFaceMode(false, BACK, CCW);
CullFaceMode.backCCW = new CullFaceMode(true, BACK, CCW);
CullFaceMode.frontCCW = new CullFaceMode(true, FRONT, CCW);
//#endregion
//#region src/webgl/draw/draw_collision_debug.ts
let quadTriangles;
function drawCollisionDebug(painter, tileManager, layer, coords, isText) {
const context = painter.context;
const transform = painter.transform;
const gl = context.gl;
const program = painter.useProgram("collisionBox");
const tileBatches = [];
let circleCount = 0;
let circleOffset = 0;
for (const coord of coords) {
const bucket = tileManager.getTile(coord).getBucket(layer);
if (!bucket) continue;
const buffers = isText ? bucket.textCollisionBox : bucket.iconCollisionBox;
const circleArray = bucket.collisionCircleArray;
if (circleArray.length > 0) {
tileBatches.push({
circleArray,
circleOffset,
coord
});
circleCount += circleArray.length / 4;
circleOffset = circleCount;
}
if (!buffers) continue;
program.draw(context, gl.LINES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, collisionUniformValues(painter.transform), painter.style.map.terrain?.getTerrainData(coord), transform.getProjectionData({
overscaledTileID: coord,
applyGlobeMatrix: true,
applyTerrainMatrix: true
}), layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer, buffers.segments, null, painter.transform.zoom, null, null, buffers.collisionVertexBuffer);
}
if (!isText || !tileBatches.length) return;
const circleProgram = painter.useProgram("collisionCircle");
const vertexData = new CollisionCircleLayoutArray();
vertexData.resize(circleCount * 4);
vertexData._trim();
let vertexOffset = 0;
for (const batch of tileBatches) for (let i = 0; i < batch.circleArray.length / 4; i++) {
const circleIdx = i * 4;
const x = batch.circleArray[circleIdx + 0];
const y = batch.circleArray[circleIdx + 1];
const radius = batch.circleArray[circleIdx + 2];
const collision = batch.circleArray[circleIdx + 3];
vertexData.emplace(vertexOffset++, x, y, radius, collision, 0);
vertexData.emplace(vertexOffset++, x, y, radius, collision, 1);
vertexData.emplace(vertexOffset++, x, y, radius, collision, 2);
vertexData.emplace(vertexOffset++, x, y, radius, collision, 3);
}
if (!quadTriangles || quadTriangles.length < circleCount * 2) quadTriangles = createQuadTriangles(circleCount);
const indexBuffer = context.createIndexBuffer(quadTriangles, true);
const vertexBuffer = context.createVertexBuffer(vertexData, collisionCircleLayout.members, true);
for (const batch of tileBatches) {
const uniforms = collisionCircleUniformValues(painter.transform);
circleProgram.draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, uniforms, painter.style.map.terrain?.getTerrainData(batch.coord), null, layer.id, vertexBuffer, indexBuffer, SegmentVector.simpleSegment(0, batch.circleOffset * 2, batch.circleArray.length, batch.circleArray.length / 2), null, painter.transform.zoom, null, null, null);
}
vertexBuffer.destroy();
indexBuffer.destroy();
}
function createQuadTriangles(quadCount) {
const triCount = quadCount * 2;
const array = new QuadTriangleArray();
array.resize(triCount);
array._trim();
for (let i = 0; i < triCount; i++) {
const idx = i * 6;
array.uint16[idx + 0] = i * 4 + 0;
array.uint16[idx + 1] = i * 4 + 1;
array.uint16[idx + 2] = i * 4 + 2;
array.uint16[idx + 3] = i * 4 + 2;
array.uint16[idx + 4] = i * 4 + 3;
array.uint16[idx + 5] = i * 4 + 0;
}
return array;
}
//#endregion
//#region src/webgl/draw/draw_symbol.ts
const identityMat4 = identity(/* @__PURE__ */ new Float32Array(16));
function drawSymbols(painter, tileManager, layer, coords, variableOffsets, renderOptions) {
if (painter.renderPass !== "translucent") return;
const { isRenderingToTexture } = renderOptions;
const stencilMode = StencilMode.disabled;
const colorMode = painter.colorModeForRenderPass();
if (layer._unevaluatedLayout.hasValue("text-variable-anchor") || layer._unevaluatedLayout.hasValue("text-variable-anchor-offset")) updateVariableAnchors(coords, painter, layer, tileManager, layer.layout.get("text-rotation-alignment"), layer.layout.get("text-pitch-alignment"), layer.paint.get("text-translate"), layer.paint.get("text-translate-anchor"), variableOffsets);
if (layer.paint.get("icon-opacity").constantOr(1) !== 0) drawLayerSymbols(painter, tileManager, layer, coords, false, layer.paint.get("icon-translate"), layer.paint.get("icon-translate-anchor"), layer.layout.get("icon-rotation-alignment"), layer.layout.get("icon-pitch-alignment"), layer.layout.get("icon-keep-upright"), stencilMode, colorMode, isRenderingToTexture);
if (layer.paint.get("text-opacity").constantOr(1) !== 0) drawLayerSymbols(painter, tileManager, layer, coords, true, layer.paint.get("text-translate"), layer.paint.get("text-translate-anchor"), layer.layout.get("text-rotation-alignment"), layer.layout.get("text-pitch-alignment"), layer.layout.get("text-keep-upright"), stencilMode, colorMode, isRenderingToTexture);
if (tileManager.map.showCollisionBoxes) {
drawCollisionDebug(painter, tileManager, layer, coords, true);
drawCollisionDebug(painter, tileManager, layer, coords, false);
}
}
function calculateVariableRenderShift(anchor, width, height, textOffset, textBoxScale, renderTextSize) {
const { horizontalAlign, verticalAlign } = getAnchorAlignment(anchor);
const shiftX = -(horizontalAlign - .5) * width;
const shiftY = -(verticalAlign - .5) * height;
return new Point((shiftX / textBoxScale + textOffset[0]) * renderTextSize, (shiftY / textBoxScale + textOffset[1]) * renderTextSize);
}
function updateVariableAnchors(coords, painter, layer, tileManager, rotationAlignment, pitchAlignment, translate, translateAnchor, variableOffsets) {
const transform = painter.transform;
const terrain = painter.style.map.terrain;
const rotateWithMap = rotationAlignment === "map";
const pitchWithMap = pitchAlignment === "map";
for (const coord of coords) {
const tile = tileManager.getTile(coord);
const bucket = tile.getBucket(layer);
if (!bucket?.text?.segments.get().length) continue;
const sizeData = bucket.textSizeData;
const size = evaluateSizeForZoom(sizeData, transform.zoom);
const pixelToTileScale = pixelsToTileUnits(tile, 1, painter.transform.zoom);
const pitchedLabelPlaneMatrix = getPitchedLabelPlaneMatrix(rotateWithMap, painter.transform, pixelToTileScale);
const updateTextFitIcon = layer.layout.get("icon-text-fit") !== "none" && bucket.hasIconData();
if (size) {
const tileScale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ);
const getElevation = terrain ? (x, y) => terrain.getElevation(coord, x, y) : null;
updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, transform, pitchedLabelPlaneMatrix, tileScale, size, updateTextFitIcon, translatePosition(transform, tile, translate, translateAnchor), coord.toUnwrapped(), getElevation);
}
}
}
function getShiftedAnchor(projectedAnchorPoint, projectionContext, rotateWithMap, shift, transformAngle, pitchedTextShiftCorrection) {
const translatedAnchor = projectionContext.tileAnchorPoint.add(new Point(projectionContext.translation[0], projectionContext.translation[1]));
if (projectionContext.pitchWithMap) {
let adjustedShift = shift.mult(pitchedTextShiftCorrection);
if (!rotateWithMap) adjustedShift = adjustedShift.rotate(-transformAngle);
const tileAnchorShifted = translatedAnchor.add(adjustedShift);
return projectWithMatrix(tileAnchorShifted.x, tileAnchorShifted.y, projectionContext.pitchedLabelPlaneMatrix, projectionContext.getElevation).point;
} else if (rotateWithMap) {
const east = projectTileCoordinatesToLabelPlane(projectionContext.tileAnchorPoint.x + 1, projectionContext.tileAnchorPoint.y, projectionContext).point.sub(projectedAnchorPoint);
const angle = Math.atan(east.y / east.x) + (east.x < 0 ? Math.PI : 0);
return projectedAnchorPoint.add(shift.rotate(angle));
} else return projectedAnchorPoint.add(shift);
}
function updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, transform, pitchedLabelPlaneMatrix, tileScale, size, updateTextFitIcon, translation, unwrappedTileID, getElevation) {
const placedSymbols = bucket.text.placedSymbolArray;
const dynamicTextLayoutVertexArray = bucket.text.dynamicLayoutVertexArray;
const dynamicIconLayoutVertexArray = bucket.icon.dynamicLayoutVertexArray;
const placedTextShifts = {};
dynamicTextLayoutVertexArray.clear();
for (let s = 0; s < placedSymbols.length; s++) {
const symbol = placedSymbols.get(s);
const skipOrientation = bucket.allowVerticalPlacement && !symbol.placedOrientation;
const variableOffset = !symbol.hidden && symbol.crossTileID && !skipOrientation ? variableOffsets[symbol.crossTileID] : null;
if (!variableOffset) hideGlyphs(symbol.numGlyphs, dynamicTextLayoutVertexArray);
else {
const tileAnchor = new Point(symbol.anchorX, symbol.anchorY);
const projectionContext = {
getElevation,
width: transform.width,
height: transform.height,
pitchedLabelPlaneMatrix,
lineVertexArray: null,
pitchWithMap,
transform,
projectionCache: null,
tileAnchorPoint: tileAnchor,
translation,
unwrappedTileID
};
const projectedAnchor = pitchWithMap ? projectTileCoordinatesToClipSpace(tileAnchor.x, tileAnchor.y, projectionContext) : projectTileCoordinatesToLabelPlane(tileAnchor.x, tileAnchor.y, projectionContext);
const perspectiveRatio = getPerspectiveRatio(transform.cameraToCenterDistance, projectedAnchor.signedDistanceFromCamera);
let renderTextSize = evaluateSizeForFeature(bucket.textSizeData, size, symbol) * perspectiveRatio / 24;
if (pitchWithMap) renderTextSize *= bucket.tilePixelRatio / tileScale;
const { width, height, anchor, textOffset, textBoxScale } = variableOffset;
const shift = calculateVariableRenderShift(anchor, width, height, textOffset, textBoxScale, renderTextSize);
const pitchedTextCorrection = transform.getPitchedTextCorrection(tileAnchor.x + translation[0], tileAnchor.y + translation[1], unwrappedTileID);
const shiftedAnchor = getShiftedAnchor(projectedAnchor.point, projectionContext, rotateWithMap, shift, -transform.bearingInRadians, pitchedTextCorrection);
const angle = bucket.allowVerticalPlacement && symbol.placedOrientation === 2 ? Math.PI / 2 : 0;
for (let g = 0; g < symbol.numGlyphs; g++) addDynamicAttributes(dynamicTextLayoutVertexArray, shiftedAnchor, angle);
if (updateTextFitIcon && symbol.associatedIconIndex >= 0) placedTextShifts[symbol.associatedIconIndex] = {
shiftedAnchor,
angle
};
}
}
if (updateTextFitIcon) {
dynamicIconLayoutVertexArray.clear();
const placedIcons = bucket.icon.placedSymbolArray;
for (let i = 0; i < placedIcons.length; i++) {
const placedIcon = placedIcons.get(i);
if (placedIcon.hidden) hideGlyphs(placedIcon.numGlyphs, dynamicIconLayoutVertexArray);
else {
const shift = placedTextShifts[i];
if (!shift) hideGlyphs(placedIcon.numGlyphs, dynamicIconLayoutVertexArray);
else for (let g = 0; g < placedIcon.numGlyphs; g++) addDynamicAttributes(dynamicIconLayoutVertexArray, shift.shiftedAnchor, shift.angle);
}
}
bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicIconLayoutVertexArray);
}
bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicTextLayoutVertexArray);
}
function getSymbolProgramName(isSDF, isText, bucket) {
if (bucket.iconsInText && isText) return "symbolTextAndIcon";
else if (isSDF) return "symbolSDF";
else return "symbolIcon";
}
function drawLayerSymbols(painter, tileManager, layer, coords, isText, translate, translateAnchor, rotationAlignment, pitchAlignment, keepUpright, stencilMode, colorMode, isRenderingToTexture) {
const context = painter.context;
const gl = context.gl;
const transform = painter.transform;
const rotateWithMap = rotationAlignment === "map";
const pitchWithMap = pitchAlignment === "map";
const alongLine = rotationAlignment !== "viewport" && layer.layout.get("symbol-placement") !== "point";
const rotateInShader = rotateWithMap && !pitchWithMap && !alongLine;
const hasSortKey = !layer.layout.get("symbol-sort-key").isConstant();
let sortFeaturesByKey = false;
const depthMode = painter.getDepthModeForSublayer(0, DepthMode.ReadOnly);
const hasVariablePlacement = layer._unevaluatedLayout.hasValue("text-variable-anchor") || layer._unevaluatedLayout.hasValue("text-variable-anchor-offset");
const tileRenderState = [];
const pitchedTextRescaling = transform.getCircleRadiusCorrection();
for (const coord of coords) {
const tile = tileManager.getTile(coord);
const bucket = tile.getBucket(layer);
if (!bucket) continue;
const buffers = isText ? bucket.text : bucket.icon;
if (!buffers?.segments.get().length || !buffers.hasVisibleVertices) continue;
const programConfiguration = buffers.programConfigurations.get(layer.id);
const isSDF = isText || bucket.sdfIcons;
const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData;
const transformed = pitchWithMap || transform.pitch !== 0;
const program = painter.useProgram(getSymbolProgramName(isSDF, isText, bucket), programConfiguration);
const size = evaluateSizeForZoom(sizeData, transform.zoom);
const terrainData = painter.style.map.terrain?.getTerrainData(coord);
let texSize;
let texSizeIcon = [0, 0];
let atlasTexture;
let atlasInterpolation;
let atlasTextureIcon = null;
let atlasInterpolationIcon;
if (isText) {
atlasTexture = tile.glyphAtlasTexture;
atlasInterpolation = gl.LINEAR;
texSize = tile.glyphAtlasTexture.size;
if (bucket.iconsInText) {
texSizeIcon = tile.imageAtlasTexture.size;
atlasTextureIcon = tile.imageAtlasTexture;
const zoomDependentSize = sizeData.kind === "composite" || sizeData.kind === "camera";
atlasInterpolationIcon = transformed || painter.options.rotating || painter.options.zooming || zoomDependentSize ? gl.LINEAR : gl.NEAREST;
}
} else {
const iconScaled = layer.layout.get("icon-size").constantOr(0) !== 1 || bucket.iconsNeedLinear;
atlasTexture = tile.imageAtlasTexture;
atlasInterpolation = isSDF || painter.options.rotating || painter.options.zooming || iconScaled || transformed ? gl.LINEAR : gl.NEAREST;
texSize = tile.imageAtlasTexture.size;
}
const s = pixelsToTileUnits(tile, 1, painter.transform.zoom);
const pitchedLabelPlaneMatrix = getPitchedLabelPlaneMatrix(rotateWithMap, painter.transform, s);
const glCoordMatrixForShader = getGlCoordMatrix(pitchWithMap, rotateWithMap, painter.transform, s);
const translation = translatePosition(transform, tile, translate, translateAnchor);
const projectionData = transform.getProjectionData({
overscaledTileID: coord,
applyGlobeMatrix: !isRenderingToTexture,
applyTerrainMatrix: true
});
const hasVariableAnchors = hasVariablePlacement && bucket.hasTextData();
const updateTextFitIcon = layer.layout.get("icon-text-fit") !== "none" && hasVariableAnchors && bucket.hasIconData();
const isOffset = layer._unevaluatedLayout.hasValue("icon-offset");
if (alongLine) {
const pitchedLabelPlaneMatrixInverse = create$1();
fastInvertTransformMat4(pitchedLabelPlaneMatrixInverse, pitchedLabelPlaneMatrix);
const getElevation = painter.style.map.terrain ? (x, y) => painter.style.map.terrain.getElevation(coord, x, y) : null;
updateLineLabels(bucket, painter, isText, pitchedLabelPlaneMatrix, pitchedLabelPlaneMatrixInverse, pitchWithMap, keepUpright, layer.layout.get("text-rotation-alignment") === "map", coord.toUnwrapped(), transform.width, transform.height, translation, getElevation);
}
const shaderVariableAnchor = isText && hasVariablePlacement || updateTextFitIcon;
const combinedLabelPlaneMatrix = pitchWithMap ? pitchedLabelPlaneMatrix : painter.transform.clipSpaceToPixelsMatrix;
const uLabelPlaneMatrix = alongLine || shaderVariableAnchor ? identityMat4 : combinedLabelPlaneMatrix;
const hasHalo = isSDF && layer.paint.get(isText ? "text-halo-width" : "icon-halo-width").constantOr(1) !== 0;
let uniformValues;
if (isSDF) {
if (!bucket.iconsInText) uniformValues = symbolSDFUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, uLabelPlaneMatrix, glCoordMatrixForShader, translation, isText, texSize, hasHalo, pitchedTextRescaling, isOffset);
else uniformValues = symbolTextAndIconUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, uLabelPlaneMatrix, glCoordMatrixForShader, translation, texSize, texSizeIcon, pitchedTextRescaling, isOffset);
} else uniformValues = symbolIconUniformValues(sizeData.kind, size, rotateInShader, pitchWithMap, alongLine, shaderVariableAnchor, painter, uLabelPlaneMatrix, glCoordMatrixForShader, translation, isText, texSize, pitchedTextRescaling, isOffset);
const state = {
program,
buffers,
uniformValues,
projectionData,
atlasTexture,
atlasTextureIcon,
atlasInterpolation,
atlasInterpolationIcon,
isSDF,
hasHalo
};
if (hasSortKey && bucket.canOverlap) {
sortFeaturesByKey = true;
const oldSegments = buffers.segments.get();
for (const segment of oldSegments) tileRenderState.push({
segments: new SegmentVector([segment]),
sortKey: segment.sortKey,
state,
terrainData
});
} else tileRenderState.push({
segments: buffers.segments,
sortKey: 0,
state,
terrainData
});
}
if (sortFeaturesByKey) tileRenderState.sort((a, b) => a.sortKey - b.sortKey);
const haloWidth = layer.paint.get(isText ? "text-halo-width" : "icon-halo-width").constantOr(null) ?? Infinity;
const isGlyphOverlap = layer.layout.get("text-letter-spacing").constantOr(0) * 24 < 0 || haloWidth > 1;
for (const segmentState of tileRenderState) {
const state = segmentState.state;
context.activeTexture.set(gl.TEXTURE0);
state.atlasTexture.bind(state.atlasInterpolation, gl.CLAMP_TO_EDGE);
if (state.atlasTextureIcon) {
context.activeTexture.set(gl.TEXTURE1);
if (state.atlasTextureIcon) state.atlasTextureIcon.bind(state.atlasInterpolationIcon, gl.CLAMP_TO_EDGE);
}
const isHalo = state.isSDF && state.hasHalo;
if (isHalo) {
const uniformValues = state.uniformValues;
uniformValues["u_is_halo"] = 1;
if (isGlyphOverlap) {
uniformValues["u_is_plain"] = 0;
drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, uniformValues, state.projectionData, segmentState.terrainData);
uniformValues["u_is_halo"] = 0;
uniformValues["u_is_plain"] = 1;
}
}
drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, state.uniformValues, state.projectionData, segmentState.terrainData);
if (isHalo && !isGlyphOverlap) state.uniformValues["u_is_halo"] = 0;
}
}
function drawSymbolElements(buffers, segments, layer, painter, program, depthMode, stencilMode, colorMode, uniformValues, projectionData, terrainData) {
const context = painter.context;
const gl = context.gl;
program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer, segments, layer.paint, painter.transform.zoom, buffers.programConfigurations.get(layer.id), buffers.dynamicLayoutVertexBuffer, buffers.opacityVertexBuffer);
}
//#endregion
//#region src/webgl/draw/draw_circle.ts
function drawCircles(painter, tileManager, layer, coords, renderOptions) {
if (painter.renderPass !== "translucent") return;
const { isRenderingToTexture } = renderOptions;
const opacity = layer.paint.get("circle-opacity");
const strokeWidth = layer.paint.get("circle-stroke-width");
const strokeOpacity = layer.paint.get("circle-stroke-opacity");
const sortFeaturesByKey = !layer.layout.get("circle-sort-key").isConstant();
if (opacity.constantOr(1) === 0 && (strokeWidth.constantOr(1) === 0 || strokeOpacity.constantOr(1) === 0)) return;
const context = painter.context;
const gl = context.gl;
const transform = painter.transform;
const depthMode = painter.getDepthModeForSublayer(0, DepthMode.ReadOnly);
const stencilMode = StencilMode.disabled;
const colorMode = painter.colorModeForRenderPass();
const segmentsRenderStates = [];
const radiusCorrectionFactor = transform.getCircleRadiusCorrection();
for (const coord of coords) {
const tile = tileManager.getTile(coord);
const bucket = tile.getBucket(layer);
if (!bucket) continue;
const styleTranslate = layer.paint.get("circle-translate");
const styleTranslateAnchor = layer.paint.get("circle-translate-anchor");
const translateForUniforms = translatePosition(transform, tile, styleTranslate, styleTranslateAnchor);
const programConfiguration = bucket.programConfigurations.get(layer.id);
const program = painter.useProgram("circle", programConfiguration);
const layoutVertexBuffer = bucket.layoutVertexBuffer;
const indexBuffer = bucket.indexBuffer;
const terrainData = painter.style.map.terrain?.getTerrainData(coord);
const state = {
programConfiguration,
program,
layoutVertexBuffer,
indexBuffer,
uniformValues: circleUniformValues(painter, tile, layer, translateForUniforms, radiusCorrectionFactor),
terrainData,
projectionData: transform.getProjectionData({
overscaledTileID: coord,
applyGlobeMatrix: !isRenderingToTexture,
applyTerrainMatrix: true
})
};
if (sortFeaturesByKey) {
const oldSegments = bucket.segments.get();
for (const segment of oldSegments) segmentsRenderStates.push({
segments: new SegmentVector([segment]),
sortKey: segment.sortKey,
state
});
} else segmentsRenderStates.push({
segments: bucket.segments,
sortKey: 0,
state
});
}
if (sortFeaturesByKey) segmentsRenderStates.sort((a, b) => a.sortKey - b.sortKey);
for (const segmentsState of segmentsRenderStates) {
const { programConfiguration, program, layoutVertexBuffer, indexBuffer, uniformValues, terrainData, projectionData } = segmentsState.state;
const segments = segmentsState.segments;
program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, layer.id, layoutVertexBuffer, indexBuffer, segments, layer.paint, painter.transform.zoom, programConfiguration);
}
}
//#endregion
//#region src/webgl/draw/draw_heatmap.ts
function drawHeatmap(painter, tileManager, layer, tileIDs, renderOptions) {
if (layer.paint.get("heatmap-opacity") === 0) return;
const context = painter.context;
const { isRenderingToTexture, isRenderingGlobe } = renderOptions;
if (painter.style.map.terrain) {
for (const coord of tileIDs) {
const tile = tileManager.getTile(coord);
if (tileManager.hasRenderableParent(coord)) continue;
if (painter.renderPass === "offscreen") prepareHeatmapTerrain(painter, tile, layer, coord, isRenderingGlobe);
else if (painter.renderPass === "translucent") renderHeatmapTerrain(painter, layer, coord, isRenderingToTexture, isRenderingGlobe);
}
context.viewport.set([
0,
0,
painter.width,
painter.height
]);
} else if (painter.renderPass === "offscreen") prepareHeatmapFlat(painter, tileManager, layer, tileIDs);
else if (painter.renderPass === "translucent") renderHeatmapFlat(painter, layer);
}
function prepareHeatmapFlat(painter, tileManager, layer, coords) {
const context = painter.context;
const gl = context.gl;
const transform = painter.transform;
const stencilMode = StencilMode.disabled;
const colorMode = new ColorMode([gl.ONE, gl.ONE], Color.transparent, [
true,
true,
true,
true
]);
bindFramebuffer(context, painter, layer);
context.clear({ color: Color.transparent });
for (const coord of coords) {
if (tileManager.hasRenderableParent(coord)) continue;
const tile = tileManager.getTile(coord);
const bucket = tile.getBucket(layer);
if (!bucket) continue;
const programConfiguration = bucket.programConfigurations.get(layer.id);
const program = painter.useProgram("heatmap", programConfiguration);
const projectionData = transform.getProjectionData({
overscaledTileID: coord,
applyGlobeMatrix: true,
applyTerrainMatrix: false
});
const radiusCorrectionFactor = transform.getCircleRadiusCorrection();
program.draw(context, gl.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, CullFaceMode.backCCW, heatmapUniformValues(tile, transform.zoom, layer.paint.get("heatmap-intensity"), radiusCorrectionFactor), null, projectionData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, transform.zoom, programConfiguration);
}
context.viewport.set([
0,
0,
painter.width,
painter.height
]);
}
function renderHeatmapFlat(painter, layer) {
const context = painter.context;
const gl = context.gl;
context.setColorMode(painter.colorModeForRenderPass());
const fbo = layer.heatmapFbos.get(HEATMAP_FULL_RENDER_FBO_KEY);
if (!fbo) return;
context.activeTexture.set(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());
context.activeTexture.set(gl.TEXTURE1);
getColorRampTexture(context, layer).bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
painter.useProgram("heatmapTexture").draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, heatmapTextureUniformValues(painter, layer, 0, 1), null, null, layer.id, painter.viewportBuffer, painter.quadTriangleIndexBuffer, painter.viewportSegments, layer.paint, painter.transform.zoom);
}
function prepareHeatmapTerrain(painter, tile, layer, coord, isRenderingGlobe) {
const context = painter.context;
const gl = context.gl;
const stencilMode = StencilMode.disabled;
const colorMode = new ColorMode([gl.ONE, gl.ONE], Color.transparent, [
true,
true,
true,
true
]);
const bucket = tile.getBucket(layer);
if (!bucket) return;
const tileKey = coord.key;
let fbo = layer.heatmapFbos.get(tileKey);
if (!fbo) {
fbo = createHeatmapFbo(context, tile.tileSize, tile.tileSize);
layer.heatmapFbos.set(tileKey, fbo);
}
context.bindFramebuffer.set(fbo.framebuffer);
context.viewport.set([
0,
0,
tile.tileSize,
tile.tileSize
]);
context.clear({ color: Color.transparent });
const programConfiguration = bucket.programConfigurations.get(layer.id);
const program = painter.useProgram("heatmap", programConfiguration, !isRenderingGlobe);
const projectionData = painter.transform.getProjectionData({
overscaledTileID: tile.tileID,
applyGlobeMatrix: true,
applyTerrainMatrix: true
});
const terrainData = painter.style.map.terrain.getTerrainData(coord);
program.draw(context, gl.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, CullFaceMode.disabled, heatmapUniformValues(tile, painter.transform.zoom, layer.paint.get("heatmap-intensity"), 1), terrainData, projectionData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration);
}
function renderHeatmapTerrain(painter, layer, coord, isRenderingToTexture, isRenderingGlobe) {
const context = painter.context;
const gl = context.gl;
const transform = painter.transform;
context.setColorMode(painter.colorModeForRenderPass());
const colorRampTexture = getColorRampTexture(context, layer);
const tileKey = coord.key;
const fbo = layer.heatmapFbos.get(tileKey);
if (!fbo) return;
context.activeTexture.set(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());
context.activeTexture.set(gl.TEXTURE1);
colorRampTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
const projectionData = transform.getProjectionData({
overscaledTileID: coord,
applyTerrainMatrix: isRenderingGlobe,
applyGlobeMatrix: !isRenderingToTexture
});
painter.useProgram("heatmapTexture").draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, heatmapTextureUniformValues(painter, layer, 0, 1), null, projectionData, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments, layer.paint, transform.zoom);
fbo.destroy();
layer.heatmapFbos.delete(tileKey);
}
function bindFramebuffer(context, painter, layer) {
const gl = context.gl;
context.activeTexture.set(gl.TEXTURE1);
context.viewport.set([
0,
0,
painter.width / 4,
painter.height / 4
]);
let fbo = layer.heatmapFbos.get(HEATMAP_FULL_RENDER_FBO_KEY);
if (!fbo) {
fbo = createHeatmapFbo(context, painter.width / 4, painter.height / 4);
layer.heatmapFbos.set(HEATMAP_FULL_RENDER_FBO_KEY, fbo);
} else {
gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());
context.bindFramebuffer.set(fbo.framebuffer);
}
}
function createHeatmapFbo(context, width, height) {
const gl = context.gl;
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA16F, width, height);
const fbo = context.createFramebuffer(width, height, false, false);
fbo.colorAttachment.set(texture);
return fbo;
}
function getColorRampTexture(context, layer) {
layer.colorRampTexture ||= new Texture(context, layer.colorRamp, context.gl.RGBA);
return layer.colorRampTexture;
}
//#endregion
//#region src/webgl/draw/draw_layer_opacity.ts
/**
* Partial line-layer-opacity
* render the whole layer to a scratch FBO, then composite with `layerOpacity`.
* Applies opacity uniformly to the layer instead of accumulating alpha across overlapping segments.
*/
function prepareDrawLayerOpacity(painter, layer, coords, terrain) {
const context = painter.context;
const compositeTarget = context.bindFramebuffer.get();
const compositeViewport = context.viewport.get();
const [, , width, height] = compositeViewport;
bindLayerOpacity(painter, width, height);
context.viewport.set([
0,
0,
width,
height
]);
context.clear({
color: Color.transparent,
depth: 1,
stencil: 0
});
painter.currentStencilSource = void 0;
painter.renderTileClippingMasks(layer, coords, terrain);
return {
compositeTarget,
compositeViewport
};
}
function bindLayerOpacity(painter, width, height) {
const gl = painter.context.gl;
if (!painter.layerOpacityFbo) {
const fbo = painter.context.createFramebuffer(width, height, true, true);
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
fbo.colorAttachment.set(texture);
fbo.depthAttachment.set(painter.context.createRenderbuffer(gl.DEPTH_STENCIL, width, height));
painter.layerOpacityFbo = fbo;
painter.context.bindFramebuffer.set(painter.layerOpacityFbo.framebuffer);
return;
}
if (painter.layerOpacityFbo.width === width && painter.layerOpacityFbo.height === height) {
painter.context.bindFramebuffer.set(painter.layerOpacityFbo.framebuffer);
return;
}
const fbo = painter.layerOpacityFbo;
gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
painter.context.bindRenderbuffer.set(fbo.depthAttachment.get());
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
painter.context.bindRenderbuffer.set(null);
fbo.width = width;
fbo.height = height;
painter.context.bindFramebuffer.set(fbo.framebuffer);
}
function drawLayerOpacity(painter, opacity, prepareDrawLayerOpacityResult, layer) {
const context = painter.context;
const gl = context.gl;
context.bindFramebuffer.set(prepareDrawLayerOpacityResult.compositeTarget);
context.viewport.set(prepareDrawLayerOpacityResult.compositeViewport);
context.activeTexture.set(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, painter.layerOpacityFbo.colorAttachment.get());
painter.useProgram("layerOpacity").draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled, layerOpacityUniformValues(opacity, 0), null, null, layer.id, painter.viewportBuffer, painter.quadTriangleIndexBuffer, painter.viewportSegments, layer.paint, painter.transform.zoom);
painter.currentStencilSource = void 0;
}
//#endregion
//#region src/webgl/draw/draw_line.ts
function updateGradientTexture(painter, tileManager, context, gl, layer, bucket, coord, layerGradient) {
let textureResolution = 256;
if (layer.stepInterpolant) {
const sourceMaxZoom = tileManager.getSource().maxzoom;
const potentialOverzoom = coord.canonical.z === sourceMaxZoom ? Math.ceil(1 << painter.transform.maxZoom - coord.canonical.z) : 1;
const maxTextureCoverage = bucket.maxLineLength / EXTENT * 1024 * potentialOverzoom;
textureResolution = clamp(nextPowerOfTwo(maxTextureCoverage), 256, context.maxTextureSize);
}
layerGradient.gradient = renderColorRamp({
expression: layer.gradientExpression(),
evaluationKey: "lineProgress",
resolution: textureResolution,
image: layerGradient.gradient || void 0,
clips: bucket.lineClipsArray
});
if (layerGradient.texture) layerGradient.texture.update(layerGradient.gradient);
else layerGradient.texture = new Texture(context, layerGradient.gradient, gl.RGBA);
layerGradient.version = layer.gradientVersion;
return layerGradient.texture;
}
function bindImagePatternTextures(context, gl, tile, programConfiguration, crossfade) {
context.activeTexture.set(gl.TEXTURE0);
tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
programConfiguration.updatePaintBuffers(crossfade);
}
function bindDasharrayTextures(painter, context, gl, programConfiguration, programChanged, crossfade) {
if (programChanged || painter.lineAtlas.dirty) {
context.activeTexture.set(gl.TEXTURE0);
painter.lineAtlas.bind(context);
}
programConfiguration.updatePaintBuffers(crossfade);
}
function bindGradientTextures(painter, tileManager, context, gl, layer, bucket, coord) {
const layerGradient = bucket.gradients[layer.id];
let gradientTexture = layerGradient.texture;
if (layer.gradientVersion !== layerGradient.version) gradientTexture = updateGradientTexture(painter, tileManager, context, gl, layer, bucket, coord, layerGradient);
context.activeTexture.set(gl.TEXTURE0);
gradientTexture.bind(layer.stepInterpolant ? gl.NEAREST : gl.LINEAR, gl.CLAMP_TO_EDGE);
}
function bindGradientAndDashTextures(painter, tileManager, context, gl, layer, bucket, coord, programConfiguration, crossfade) {
const layerGradient = bucket.gradients[layer.id];
let gradientTexture = layerGradient.texture;
if (layer.gradientVersion !== layerGradient.version) gradientTexture = updateGradientTexture(painter, tileManager, context, gl, layer, bucket, coord, layerGradient);
context.activeTexture.set(gl.TEXTURE0);
gradientTexture.bind(layer.stepInterpolant ? gl.NEAREST : gl.LINEAR, gl.CLAMP_TO_EDGE);
context.activeTexture.set(gl.TEXTURE1);
painter.lineAtlas.bind(context);
programConfiguration.updatePaintBuffers(crossfade);
}
function drawLine(painter, tileManager, layer, coords, renderOptions) {
if (painter.renderPass !== "translucent") return;
const opacity = layer.paint.get("line-opacity");
const width = layer.paint.get("line-width");
const layerOpacity = layer.paint.get("line-layer-opacity");
if (opacity.constantOr(1) === 0 || width.constantOr(1) === 0 || layerOpacity === 0) return;
const useTerrain = !!painter.style.map.terrain;
if (layerOpacity < 1) {
const results = prepareDrawLayerOpacity(painter, layer, coords, useTerrain);
drawLineTiles(painter, tileManager, layer, coords, renderOptions, useTerrain);
drawLayerOpacity(painter, layerOpacity, results, layer);
return;
}
drawLineTiles(painter, tileManager, layer, coords, renderOptions, useTerrain);
}
function drawLineTiles(painter, tileManager, layer, coords, renderOptions, useTerrain) {
const { isRenderingToTexture } = renderOptions;
const depthMode = painter.getDepthModeForSublayer(0, DepthMode.ReadOnly);
const colorMode = painter.colorModeForRenderPass();
const dasharrayProperty = layer.paint.get("line-dasharray");
const dasharray = dasharrayProperty.constantOr(1);
const patternProperty = layer.paint.get("line-pattern");
const image = patternProperty.constantOr(1);
const gradient = layer.paint.get("line-gradient");
const crossfade = layer.getCrossfadeParameters();
let programId;
if (image) programId = "linePattern";
else if (dasharray && gradient) programId = "lineGradientSDF";
else if (dasharray) programId = "lineSDF";
else if (gradient) programId = "lineGradient";
else programId = "line";
const context = painter.context;
const gl = context.gl;
const transform = painter.transform;
let firstTile = true;
for (const coord of coords) {
const tile = tileManager.getTile(coord);
if (image && !tile.patternsLoaded()) continue;
const bucket = tile.getBucket(layer);
if (!bucket) continue;
const programConfiguration = bucket.programConfigurations.get(layer.id);
const prevProgram = painter.context.program.get();
const program = painter.useProgram(programId, programConfiguration);
const programChanged = firstTile || program.program !== prevProgram;
const terrainData = useTerrain ? painter.getTerrainDataForTile(coord, isRenderingToTexture) : null;
const constantPattern = patternProperty.constantOr(null);
const constantDasharray = dasharrayProperty?.constantOr(null);
if (constantPattern && tile.imageAtlas) {
const atlas = tile.imageAtlas;
const posTo = atlas.patternPositions[constantPattern.to.toString()];
const posFrom = atlas.patternPositions[constantPattern.from.toString()];
if (posTo && posFrom) programConfiguration.setConstantPatternPositions(posTo, posFrom);
} else if (constantDasharray) {
const round = layer.layout.get("line-cap").constantOr(null) === "round";
const dashTo = painter.lineAtlas.getDash(constantDasharray.to, round);
const dashFrom = painter.lineAtlas.getDash(constantDasharray.from, round);
programConfiguration.setConstantDashPositions(dashTo, dashFrom);
}
const projectionData = transform.getProjectionData({
overscaledTileID: coord,
applyGlobeMatrix: !isRenderingToTexture,
applyTerrainMatrix: true
});
const pixelRatio = transform.getPixelScale();
let uniformValues;
if (image) {
uniformValues = linePatternUniformValues(painter, tile, layer, pixelRatio, crossfade);
bindImagePatternTextures(context, gl, tile, programConfiguration, crossfade);
} else if (dasharray && gradient) {
uniformValues = lineGradientSDFUniformValues(painter, tile, layer, pixelRatio, crossfade, bucket.lineClipsArray.length);
bindGradientAndDashTextures(painter, tileManager, context, gl, layer, bucket, coord, programConfiguration, crossfade);
} else if (dasharray) {
uniformValues = lineSDFUniformValues(painter, tile, layer, pixelRatio, crossfade);
bindDasharrayTextures(painter, context, gl, programConfiguration, programChanged, crossfade);
} else if (gradient) {
uniformValues = lineGradientUniformValues(painter, tile, layer, pixelRatio, bucket.lineClipsArray.length);
bindGradientTextures(painter, tileManager, context, gl, layer, bucket, coord);
} else uniformValues = lineUniformValues(painter, tile, layer, pixelRatio);
const stencil = painter.stencilModeForClipping(coord);
program.draw(context, gl.TRIANGLES, depthMode, stencil, colorMode, CullFaceMode.disabled, uniformValues, terrainData, projectionData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration, bucket.layoutVertexBuffer2);
firstTile = false;
}
}
//#endregion
//#region src/render/update_pattern_positions_in_program.ts
/**
* A simple helper shared by draw_fill and draw_fill_extrusions to find the correct pattern positions AND update program.
* For transitionable properties, especially 'fill-pattern' and 'fill-extrusion-pattern', while rendering certain frames
* tile.imageAtlas has been updated by worker to hold the new pattern only, but rendering code is still looking for the previous image.
* The mismatch was causing setConstantPatternPositions method not being called and pixelRatio was always the
* default of 1, instead of actual values set by original map.addImage.
*
* @param programConfiguration - to be used to set pattern position and device pixel ratio.
* @param propertyName - 'fill-pattern' or 'fill-extrusion-pattern' property key
* @param constantPattern - either 'fill-pattern' or 'fill-extrusion-pattern' property value
* @param tile - current tile being drawn
* @param layer - current layer being rendered
*/
function updatePatternPositionsInProgram(programConfiguration, propertyName, constantPattern, tile, layer) {
if (!constantPattern || !tile?.imageAtlas) return;
const patternPositions = tile.imageAtlas.patternPositions;
let posTo = patternPositions[constantPattern.to.toString()];
let posFrom = patternPositions[constantPattern.from.toString()];
if (!posTo && posFrom) posTo = posFrom;
if (!posFrom && posTo) posFrom = posTo;
if (!posTo || !posFrom) {
const transitioned = layer.getPaintProperty(propertyName);
posTo = patternPositions[transitioned];
posFrom = patternPositions[transitioned];
}
if (posTo && posFrom) programConfiguration.setConstantPatternPositions(posTo, posFrom);
}
//#endregion
//#region src/webgl/draw/draw_fill.ts
function drawFill(painter, tileManager, layer, coords, renderOptions) {
const color = layer.paint.get("fill-color");
const opacity = layer.paint.get("fill-opacity");
const layerOpacity = layer.paint.get("fill-layer-opacity");
if (opacity.constantOr(1) === 0 || layerOpacity === 0) return;
if (layerOpacity < 1) {
if (painter.renderPass !== "translucent") return;
const results = prepareDrawLayerOpacity(painter, layer, coords, !!painter.style.map.terrain);
drawFillAndOutline(painter, tileManager, layer, coords, renderOptions);
drawLayerOpacity(painter, layerOpacity, results, layer);
return;
}
const pattern = layer.paint.get("fill-pattern");
const fillEligibleForOpaque = painter.opaquePassEnabledForLayer() && !pattern.constantOr(1) && color.constantOr(Color.transparent).a === 1 && opacity.constantOr(0) === 1;
if (fillEligibleForOpaque && painter.renderPass === "opaque") {
const { isRenderingToTexture } = renderOptions;
const colorMode = painter.colorModeForRenderPass();
drawFillTiles(painter, tileManager, layer, coords, painter.getDepthModeForSublayer(1, DepthMode.ReadWrite), colorMode, false, isRenderingToTexture);
return;
}
if (fillEligibleForOpaque && painter.renderPass === "translucent") {
drawOutline(painter, tileManager, layer, coords, renderOptions);
return;
}
if (painter.renderPass === "translucent") drawFillAndOutline(painter, tileManager, layer, coords, renderOptions);
}
/**
* Draw fill + outline in a single translucent pass with ReadOnly depth.
* Shared by the layer-opacity subpass (always) and the normal translucent path
* (when the fill is not opaque-pass-eligible).
*/
function drawFillAndOutline(painter, tileManager, layer, coords, renderOptions) {
const { isRenderingToTexture } = renderOptions;
const colorMode = painter.colorModeForRenderPass();
drawFillTiles(painter, tileManager, layer, coords, painter.getDepthModeForSublayer(1, DepthMode.ReadOnly), colorMode, false, isRenderingToTexture);
drawOutline(painter, tileManager, layer, coords, renderOptions);
}
function drawOutline(painter, tileManager, layer, coords, renderOptions) {
if (!layer.paint.get("fill-antialias")) return;
const { isRenderingToTexture } = renderOptions;
const colorMode = painter.colorModeForRenderPass();
drawFillTiles(painter, tileManager, layer, coords, painter.getDepthModeForSublayer(layer.getPaintProperty("fill-outline-color") ? 2 : 0, DepthMode.ReadOnly), colorMode, true, isRenderingToTexture);
}
function drawFillTiles(painter, tileManager, layer, coords, depthMode, colorMode, isOutline, isRenderingToTexture) {
const gl = painter.context.gl;
const fillPropertyName = "fill-pattern";
const patternProperty = layer.paint.get(fillPropertyName);
const image = patternProperty?.constantOr(1);
const crossfade = layer.getCrossfadeParameters();
let drawMode, programName, uniformValues, indexBuffer, segments;
const transform = painter.transform;
const propertyFillTranslate = layer.paint.get("fill-translate");
const propertyFillTranslateAnchor = layer.paint.get("fill-translate-anchor");
if (!isOutline) {
programName = image ? "fillPattern" : "fill";
drawMode = gl.TRIANGLES;
} else {
programName = image && !layer.getPaintProperty("fill-outline-color") ? "fillOutlinePattern" : "fillOutline";
drawMode = gl.LINES;
}
const constantPattern = patternProperty.constantOr(null);
for (const coord of coords) {
const tile = tileManager.getTile(coord);
if (image && !tile.patternsLoaded()) continue;
const bucket = tile.getBucket(layer);
if (!bucket) continue;
const programConfiguration = bucket.programConfigurations.get(layer.id);
const program = painter.useProgram(programName, programConfiguration);
const terrainData = painter.getTerrainDataForTile(coord, isRenderingToTexture);
if (image) {
painter.context.activeTexture.set(gl.TEXTURE0);
tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
programConfiguration.updatePaintBuffers(crossfade);
}
updatePatternPositionsInProgram(programConfiguration, fillPropertyName, constantPattern, tile, layer);
const projectionData = transform.getProjectionData({
overscaledTileID: coord,
applyGlobeMatrix: !isRenderingToTexture,
applyTerrainMatrix: true
});
const translateForUniforms = translatePosition(transform, tile, propertyFillTranslate, propertyFillTranslateAnchor);
if (!isOutline) {
indexBuffer = bucket.indexBuffer;
segments = bucket.segments;
uniformValues = image ? fillPatternUniformValues(painter, crossfade, tile, translateForUniforms) : fillUniformValues(translateForUniforms);
} else {
indexBuffer = bucket.indexBuffer2;
segments = bucket.segments2;
const drawingBufferSize = [gl.drawingBufferWidth, gl.drawingBufferHeight];
uniformValues = programName === "fillOutlinePattern" && image ? fillOutlinePatternUniformValues(painter, crossfade, tile, drawingBufferSize, translateForUniforms) : fillOutlineUniformValues(drawingBufferSize, translateForUniforms);
}
const stencil = painter.stencilModeForClipping(coord);
program.draw(painter.context, drawMode, depthMode, stencil, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, layer.id, bucket.layoutVertexBuffer, indexBuffer, segments, layer.paint, painter.transform.zoom, programConfiguration);
}
}
//#endregion
//#region src/webgl/draw/draw_fill_extrusion.ts
function drawFillExtrusion(painter, tileManager, layer, coords, renderOptions) {
const opacity = layer.paint.get("fill-extrusion-opacity");
if (opacity === 0) return;
const { isRenderingToTexture } = renderOptions;
if (painter.renderPass === "translucent") {
const depthMode = new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);
if (opacity === 1 && !layer.paint.get("fill-extrusion-pattern").constantOr(1)) {
const colorMode = painter.colorModeForRenderPass();
drawExtrusionTiles(painter, tileManager, layer, coords, depthMode, StencilMode.disabled, colorMode, isRenderingToTexture);
} else {
drawExtrusionTiles(painter, tileManager, layer, coords, depthMode, StencilMode.disabled, ColorMode.disabled, isRenderingToTexture);
drawExtrusionTiles(painter, tileManager, layer, coords, depthMode, painter.stencilModeFor3D(), painter.colorModeForRenderPass(), isRenderingToTexture);
}
}
}
function drawExtrusionTiles(painter, tileManager, layer, coords, depthMode, stencilMode, colorMode, isRenderingToTexture) {
const context = painter.context;
const gl = context.gl;
const fillPropertyName = "fill-extrusion-pattern";
const patternProperty = layer.paint.get(fillPropertyName);
const image = patternProperty.constantOr(1);
const crossfade = layer.getCrossfadeParameters();
const opacity = layer.paint.get("fill-extrusion-opacity");
const constantPattern = patternProperty.constantOr(null);
const transform = painter.transform;
for (const coord of coords) {
const tile = tileManager.getTile(coord);
const bucket = tile.getBucket(layer);
if (!bucket) continue;
const terrainData = painter.style.map.terrain?.getTerrainData(coord);
const programConfiguration = bucket.programConfigurations.get(layer.id);
const program = painter.useProgram(image ? "fillExtrusionPattern" : "fillExtrusion", programConfiguration);
if (image) {
painter.context.activeTexture.set(gl.TEXTURE0);
tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
programConfiguration.updatePaintBuffers(crossfade);
}
const projectionData = transform.getProjectionData({
overscaledTileID: coord,
applyGlobeMatrix: !isRenderingToTexture,
applyTerrainMatrix: true
});
updatePatternPositionsInProgram(programConfiguration, fillPropertyName, constantPattern, tile, layer);
const translate = translatePosition(transform, tile, layer.paint.get("fill-extrusion-translate"), layer.paint.get("fill-extrusion-translate-anchor"));
const shouldUseVerticalGradient = layer.paint.get("fill-extrusion-vertical-gradient");
const uniformValues = image ? fillExtrusionPatternUniformValues(painter, shouldUseVerticalGradient, opacity, translate, coord, crossfade, tile) : fillExtrusionUniformValues(painter, shouldUseVerticalGradient, opacity, translate);
program.draw(context, context.gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments, layer.paint, painter.transform.zoom, programConfiguration, painter.style.map.terrain && bucket.centroidVertexBuffer);
}
}
//#endregion
//#region src/webgl/draw/draw_hillshade.ts
function drawHillshade(painter, tileManager, layer, tileIDs, renderOptions) {
if (painter.renderPass !== "offscreen" && painter.renderPass !== "translucent") return;
const { isRenderingToTexture } = renderOptions;
const context = painter.context;
const useSubdivision = painter.style.projection.useSubdivision;
const depthMode = painter.getDepthModeForSublayer(0, DepthMode.ReadOnly);
const colorMode = painter.colorModeForRenderPass();
if (painter.renderPass === "offscreen") {
prepareHillshade(painter, tileManager, tileIDs, layer, depthMode, StencilMode.disabled, colorMode);
context.viewport.set([
0,
0,
painter.width,
painter.height
]);
} else if (painter.renderPass === "translucent") {
if (useSubdivision) {
const [stencilBorderless, stencilBorders, coords] = painter.stencilConfigForOverlapTwoPass(tileIDs);
renderHillshade(painter, tileManager, layer, coords, stencilBorderless, depthMode, colorMode, false, isRenderingToTexture);
renderHillshade(painter, tileManager, layer, coords, stencilBorders, depthMode, colorMode, true, isRenderingToTexture);
} else {
const [stencil, coords] = painter.getStencilConfigForOverlapAndUpdateStencilID(tileIDs);
renderHillshade(painter, tileManager, layer, coords, stencil, depthMode, colorMode, false, isRenderingToTexture);
}
}
}
function renderHillshade(painter, tileManager, layer, coords, stencilModes, depthMode, colorMode, useBorder, isRenderingToTexture) {
const projection = painter.style.projection;
const context = painter.context;
const transform = painter.transform;
const gl = context.gl;
const defines = [`#define NUM_ILLUMINATION_SOURCES ${layer.paint.get("hillshade-highlight-color").values.length}`];
const program = painter.useProgram("hillshade", null, false, defines);
const align = !painter.options.moving;
for (const coord of coords) {
const tile = tileManager.getTile(coord);
const fbo = tile.fbo;
if (!fbo) continue;
const mesh = projection.getMeshFromTileID(context, coord.canonical, useBorder, true, "raster");
const terrainData = painter.getTerrainDataForTile(coord, isRenderingToTexture);
context.activeTexture.set(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());
const projectionData = transform.getProjectionData({
overscaledTileID: coord,
aligned: align,
applyGlobeMatrix: !isRenderingToTexture,
applyTerrainMatrix: true
});
program.draw(context, gl.TRIANGLES, depthMode, stencilModes[coord.overscaledZ], colorMode, CullFaceMode.backCCW, hillshadeUniformValues(painter, tile, layer), terrainData, projectionData, layer.id, mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
}
}
function prepareHillshade(painter, tileManager, tileIDs, layer, depthMode, stencilMode, colorMode) {
const context = painter.context;
const gl = context.gl;
const textureFilter = layer.paint.get("resampling") === "nearest" ? gl.NEAREST : gl.LINEAR;
for (const coord of tileIDs) {
const tile = tileManager.getTile(coord);
const dem = tile.dem;
if (!dem?.data) continue;
if (!tile.needsHillshadePrepare) continue;
const tileSize = dem.dim;
const textureStride = dem.stride;
const pixelData = dem.getPixels();
context.activeTexture.set(gl.TEXTURE1);
context.pixelStoreUnpackPremultiplyAlpha.set(false);
tile.demTexture ||= painter.getTileTexture(textureStride);
if (tile.demTexture) {
const demTexture = tile.demTexture;
demTexture.update(pixelData, { premultiply: false });
demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);
} else {
tile.demTexture = new Texture(context, pixelData, gl.RGBA, { premultiply: false });
tile.demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);
}
context.activeTexture.set(gl.TEXTURE0);
let fbo = tile.fbo;
if (!fbo) {
const renderTexture = new Texture(context, {
width: tileSize,
height: tileSize,
data: null
}, gl.RGBA);
renderTexture.bind(textureFilter, gl.CLAMP_TO_EDGE);
fbo = tile.fbo = context.createFramebuffer(tileSize, tileSize, true, false);
fbo.colorAttachment.set(renderTexture.texture);
}
context.bindFramebuffer.set(fbo.framebuffer);
context.viewport.set([
0,
0,
tileSize,
tileSize
]);
painter.useProgram("hillshadePrepare").draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, hillshadeUniformPrepareValues(tile.tileID, dem), null, null, layer.id, painter.rasterBoundsBuffer, painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments);
tile.needsHillshadePrepare = false;
}
}
//#endregion
//#region src/webgl/draw/draw_color_relief.ts
function drawColorRelief(painter, tileManager, layer, tileIDs, renderOptions) {
if (painter.renderPass !== "translucent") return;
if (!tileIDs.length) return;
const { isRenderingToTexture } = renderOptions;
const useSubdivision = painter.style.projection.useSubdivision;
const depthMode = painter.getDepthModeForSublayer(0, DepthMode.ReadOnly);
const colorMode = painter.colorModeForRenderPass();
if (useSubdivision) {
const [stencilBorderless, stencilBorders, coords] = painter.stencilConfigForOverlapTwoPass(tileIDs);
renderColorRelief(painter, tileManager, layer, coords, stencilBorderless, depthMode, colorMode, false, isRenderingToTexture);
renderColorRelief(painter, tileManager, layer, coords, stencilBorders, depthMode, colorMode, true, isRenderingToTexture);
} else {
const [stencil, coords] = painter.getStencilConfigForOverlapAndUpdateStencilID(tileIDs);
renderColorRelief(painter, tileManager, layer, coords, stencil, depthMode, colorMode, false, isRenderingToTexture);
}
}
let textureMaxSize = 0;
function renderColorRelief(painter, tileManager, layer, coords, stencilModes, depthMode, colorMode, useBorder, isRenderingToTexture) {
const projection = painter.style.projection;
const context = painter.context;
const transform = painter.transform;
const gl = context.gl;
const program = painter.useProgram("colorRelief");
const align = !painter.options.moving;
const textureFilter = layer.paint.get("resampling") === "nearest" ? gl.NEAREST : gl.LINEAR;
let firstTile = true;
let colorRampSize = 0;
for (const coord of coords) {
const tile = tileManager.getTile(coord);
const dem = tile.dem;
if (firstTile) {
textureMaxSize ||= gl.getParameter(gl.MAX_TEXTURE_SIZE);
const maxLength = textureMaxSize;
const { elevationTexture, colorTexture } = layer.getColorRampTextures(context, maxLength, dem.getUnpackVector());
context.activeTexture.set(gl.TEXTURE1);
elevationTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);
context.activeTexture.set(gl.TEXTURE4);
colorTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
firstTile = false;
colorRampSize = elevationTexture.size[0];
}
if (!dem?.data) continue;
const textureStride = dem.stride;
const pixelData = dem.getPixels();
context.activeTexture.set(gl.TEXTURE0);
context.pixelStoreUnpackPremultiplyAlpha.set(false);
tile.demTexture ||= painter.getTileTexture(textureStride);
if (tile.demTexture) {
const demTexture = tile.demTexture;
demTexture.update(pixelData, { premultiply: false });
demTexture.bind(textureFilter, gl.CLAMP_TO_EDGE);
} else {
tile.demTexture = new Texture(context, pixelData, gl.RGBA, { premultiply: false });
tile.demTexture.bind(textureFilter, gl.CLAMP_TO_EDGE);
}
const mesh = projection.getMeshFromTileID(context, coord.canonical, useBorder, true, "raster");
const terrainData = painter.getTerrainDataForTile(coord, isRenderingToTexture);
const projectionData = transform.getProjectionData({
overscaledTileID: coord,
aligned: align,
applyGlobeMatrix: !isRenderingToTexture,
applyTerrainMatrix: true
});
program.draw(context, gl.TRIANGLES, depthMode, stencilModes[coord.overscaledZ], colorMode, CullFaceMode.backCCW, colorReliefUniformValues(layer, tile.dem, colorRampSize), terrainData, projectionData, layer.id, mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
}
}
//#endregion
//#region src/webgl/draw/draw_raster.ts
const cornerCoords = [
new Point(0, 0),
new Point(EXTENT, 0),
new Point(EXTENT, EXTENT),
new Point(0, EXTENT)
];
function drawRaster(painter, tileManager, layer, tileIDs, renderOptions) {
if (painter.renderPass !== "translucent") return;
if (layer.paint.get("raster-opacity") === 0) return;
if (!tileIDs.length) return;
const { isRenderingToTexture } = renderOptions;
const source = tileManager.getSource();
const useSubdivision = painter.style.projection.useSubdivision;
if (source instanceof ImageSource) drawTiles(painter, tileManager, layer, tileIDs, null, false, false, source.tileCoords, source.imageWarp, source.flippedWindingOrder, isRenderingToTexture, source.getMesh(painter.context, useSubdivision));
else if (useSubdivision) {
const [stencilBorderless, stencilBorders, coords] = painter.stencilConfigForOverlapTwoPass(tileIDs);
drawTiles(painter, tileManager, layer, coords, stencilBorderless, false, true, cornerCoords, bilinearImageWarp, false, isRenderingToTexture);
drawTiles(painter, tileManager, layer, coords, stencilBorders, true, true, cornerCoords, bilinearImageWarp, false, isRenderingToTexture);
} else {
const [stencil, coords] = painter.getStencilConfigForOverlapAndUpdateStencilID(tileIDs);
drawTiles(painter, tileManager, layer, coords, stencil, false, true, cornerCoords, bilinearImageWarp, false, isRenderingToTexture);
}
}
function drawTiles(painter, tileManager, layer, coords, stencilModes, useBorder, allowPoles, corners, imageWarp, flipCullfaceMode = false, isRenderingToTexture = false, sourceMesh = null) {
const minTileZ = coords[coords.length - 1].overscaledZ;
const context = painter.context;
const gl = context.gl;
const program = painter.useProgram("raster");
const transform = painter.transform;
const projection = painter.style.projection;
const colorMode = painter.colorModeForRenderPass();
const align = !painter.options.moving;
const rasterOpacity = layer.paint.get("raster-opacity");
const textureFilter = layer.paint.get("resampling") === "nearest" || layer.paint.get("raster-resampling") === "nearest" ? gl.NEAREST : gl.LINEAR;
const fadeDuration = layer.paint.get("raster-fade-duration");
const isTerrain = !!painter.style.map.terrain;
for (const coord of coords) {
const depthMode = painter.getDepthModeForSublayer(coord.overscaledZ - minTileZ, rasterOpacity === 1 ? DepthMode.ReadWrite : DepthMode.ReadOnly, gl.LESS);
const tile = tileManager.getTile(coord);
context.activeTexture.set(gl.TEXTURE0);
tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);
context.activeTexture.set(gl.TEXTURE1);
const { parentTile, parentScaleBy, parentTopLeft, fadeValues } = getFadeProperties(tile, tileManager, fadeDuration, isTerrain);
tile.fadeOpacity = fadeValues.tileOpacity;
if (parentTile) {
parentTile.fadeOpacity = fadeValues.parentTileOpacity;
parentTile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);
} else tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);
if (tile.texture.useMipmap && context.extTextureFilterAnisotropic && painter.transform.pitch > painter.options.anisotropicFilterPitch) gl.texParameterf(gl.TEXTURE_2D, context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, context.extTextureFilterAnisotropicMax);
const terrainData = painter.getTerrainDataForTile(coord, isRenderingToTexture);
const projectionData = transform.getProjectionData({
overscaledTileID: coord,
aligned: align,
applyGlobeMatrix: !isRenderingToTexture,
applyTerrainMatrix: true
});
const uniformValues = rasterUniformValues(parentTopLeft, parentScaleBy, fadeValues.fadeMix, layer, corners, imageWarp);
const mesh = sourceMesh ?? projection.getMeshFromTileID(context, coord.canonical, useBorder, allowPoles, "raster");
const stencilMode = stencilModes ? stencilModes[coord.overscaledZ] : StencilMode.disabled;
program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, flipCullfaceMode ? CullFaceMode.frontCCW : CullFaceMode.backCCW, uniformValues, terrainData, projectionData, layer.id, mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
}
}
/**
* Get fade properties for current tile - either cross-fading or self-fading properties.
*/
function getFadeProperties(tile, tileManager, fadeDuration, isTerrain) {
const defaults = {
parentTile: null,
parentScaleBy: 1,
parentTopLeft: [0, 0],
fadeValues: {
tileOpacity: 1,
parentTileOpacity: 1,
fadeMix: {
opacity: 1,
mix: 0
}
}
};
if (fadeDuration === 0 || isTerrain) return defaults;
if (tile.fadingParentID) {
const parentTile = tileManager.getLoadedTile(tile.fadingParentID);
if (!parentTile) return defaults;
const parentScaleBy = Math.pow(2, parentTile.tileID.overscaledZ - tile.tileID.overscaledZ);
return {
parentTile,
parentScaleBy,
parentTopLeft: [tile.tileID.canonical.x * parentScaleBy % 1, tile.tileID.canonical.y * parentScaleBy % 1],
fadeValues: getCrossFadeValues(tile, parentTile, fadeDuration)
};
}
if (tile.selfFading) return {
parentTile: null,
parentScaleBy: 1,
parentTopLeft: [0, 0],
fadeValues: getSelfFadeValues(tile, fadeDuration)
};
return defaults;
}
/**
* Cross-fade values for a base tile with a parent tile (for zooming in/out)
*/
function getCrossFadeValues(tile, parentTile, fadeDuration) {
const currentTime = now();
const timeSinceTile = (currentTime - tile.timeAdded) / fadeDuration;
const timeSinceParent = (currentTime - parentTile.timeAdded) / fadeDuration;
const doFadeIn = tile.fadingDirection === 1;
const opacity1 = clamp(timeSinceTile, 0, 1);
const opacity2 = clamp(1 - timeSinceParent, 0, 1);
const tileOpacity = doFadeIn ? opacity1 : opacity2;
return {
tileOpacity,
parentTileOpacity: doFadeIn ? opacity2 : opacity1,
fadeMix: {
opacity: 1,
mix: 1 - tileOpacity
}
};
}
/**
* Simple fade-in values for tile without a parent (i.e. edge tiles)
*/
function getSelfFadeValues(tile, fadeDuration) {
const timeSinceTile = (now() - tile.timeAdded) / fadeDuration;
const tileOpacity = clamp(timeSinceTile, 0, 1);
return {
tileOpacity,
fadeMix: {
opacity: tileOpacity,
mix: 0
}
};
}
//#endregion
//#region src/webgl/draw/draw_background.ts
function drawBackground(painter, tileManager, layer, coords, renderOptions) {
const color = layer.paint.get("background-color");
const opacity = layer.paint.get("background-opacity");
if (opacity === 0) return;
const { isRenderingToTexture } = renderOptions;
const context = painter.context;
const gl = context.gl;
const projection = painter.style.projection;
const transform = painter.transform;
const tileSize = transform.tileSize;
const image = layer.paint.get("background-pattern");
if (painter.isPatternMissing(image)) return;
const pass = !image && color.a === 1 && opacity === 1 && painter.opaquePassEnabledForLayer() ? "opaque" : "translucent";
if (painter.renderPass !== pass) return;
const stencilMode = StencilMode.disabled;
const depthMode = painter.getDepthModeForSublayer(0, pass === "opaque" ? DepthMode.ReadWrite : DepthMode.ReadOnly);
const colorMode = painter.colorModeForRenderPass();
const program = painter.useProgram(image ? "backgroundPattern" : "background");
const tileIDs = coords ? coords : coveringTiles(transform, {
tileSize,
terrain: painter.style.map.terrain
});
if (image) {
context.activeTexture.set(gl.TEXTURE0);
painter.patternAtlas.bind(painter.context);
}
const crossfade = layer.getCrossfadeParameters();
for (const tileID of tileIDs) {
const projectionData = transform.getProjectionData({
overscaledTileID: tileID,
applyGlobeMatrix: !isRenderingToTexture,
applyTerrainMatrix: true
});
const uniformValues = image ? backgroundPatternUniformValues(opacity, painter, image, {
tileID,
tileSize
}, crossfade) : backgroundUniformValues(opacity, color);
const terrainData = painter.getTerrainDataForTile(tileID, isRenderingToTexture);
const mesh = projection.getMeshFromTileID(context, tileID.canonical, false, true, "raster");
program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, layer.id, mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
}
}
//#endregion
//#region src/webgl/draw/draw_debug.ts
const topColor = new Color(1, 0, 0, 1);
const btmColor = new Color(0, 1, 0, 1);
const leftColor = new Color(0, 0, 1, 1);
const rightColor = new Color(1, 0, 1, 1);
const centerColor = new Color(0, 1, 1, 1);
function drawDebugPadding(painter) {
const padding = painter.transform.padding;
const lineWidth = 3;
drawHorizontalLine(painter, painter.transform.height - (padding.top || 0), lineWidth, topColor);
drawHorizontalLine(painter, padding.bottom || 0, lineWidth, btmColor);
drawVerticalLine(painter, padding.left || 0, lineWidth, leftColor);
drawVerticalLine(painter, painter.transform.width - (padding.right || 0), lineWidth, rightColor);
const center = painter.transform.centerPoint;
drawCrosshair(painter, center.x, painter.transform.height - center.y, centerColor);
}
function drawCrosshair(painter, x, y, color) {
const size = 20;
const lineWidth = 2;
drawDebugSSRect(painter, x - lineWidth / 2, y - size / 2, lineWidth, size, color);
drawDebugSSRect(painter, x - size / 2, y - lineWidth / 2, size, lineWidth, color);
}
function drawHorizontalLine(painter, y, lineWidth, color) {
drawDebugSSRect(painter, 0, y + lineWidth / 2, painter.transform.width, lineWidth, color);
}
function drawVerticalLine(painter, x, lineWidth, color) {
drawDebugSSRect(painter, x - lineWidth / 2, 0, lineWidth, painter.transform.height, color);
}
function drawDebugSSRect(painter, x, y, width, height, color) {
const context = painter.context;
const gl = context.gl;
gl.enable(gl.SCISSOR_TEST);
gl.scissor(x * painter.pixelRatio, y * painter.pixelRatio, width * painter.pixelRatio, height * painter.pixelRatio);
context.clear({ color });
gl.disable(gl.SCISSOR_TEST);
}
function drawDebug(painter, tileManager, coords) {
for (const coord of coords) drawDebugTile(painter, tileManager, coord);
}
function drawDebugTile(painter, tileManager, coord) {
const context = painter.context;
const gl = context.gl;
const program = painter.useProgram("debug");
const depthMode = DepthMode.disabled;
const stencilMode = StencilMode.disabled;
const colorMode = painter.colorModeForRenderPass();
const id = "$debug";
const terrainData = painter.style.map.terrain?.getTerrainData(coord);
context.activeTexture.set(gl.TEXTURE0);
const tileByteLength = tileManager.getTileByID(coord.key).latestRawTileData?.byteLength || 0;
const tileSizeKb = Math.floor(tileByteLength / 1024);
const tileSize = tileManager.getTile(coord).tileSize;
const scaleRatio = 512 / Math.min(tileSize, 512) * (coord.overscaledZ / painter.transform.zoom) * .5;
let tileIdText = coord.canonical.toString();
if (coord.overscaledZ !== coord.canonical.z) tileIdText += ` => ${coord.overscaledZ}`;
drawTextToOverlay(painter, `${tileIdText} ${tileSizeKb}kB`);
const projectionData = painter.transform.getProjectionData({
overscaledTileID: coord,
applyGlobeMatrix: true,
applyTerrainMatrix: true
});
program.draw(context, gl.TRIANGLES, depthMode, stencilMode, ColorMode.alphaBlended, CullFaceMode.disabled, debugUniformValues(Color.transparent, scaleRatio), null, projectionData, id, painter.debugBuffer, painter.quadTriangleIndexBuffer, painter.debugSegments);
program.draw(context, gl.LINE_STRIP, depthMode, stencilMode, colorMode, CullFaceMode.disabled, debugUniformValues(Color.red), terrainData, projectionData, id, painter.debugBuffer, painter.tileBorderIndexBuffer, painter.debugSegments);
}
function drawTextToOverlay(painter, text) {
painter.initDebugOverlayCanvas();
const canvas = painter.debugOverlayCanvas;
const gl = painter.context.gl;
const ctx2d = painter.debugOverlayCanvas.getContext("2d");
ctx2d.clearRect(0, 0, canvas.width, canvas.height);
ctx2d.shadowColor = "white";
ctx2d.shadowBlur = 2;
ctx2d.lineWidth = 1.5;
ctx2d.strokeStyle = "white";
ctx2d.textBaseline = "top";
ctx2d.font = `bold 36px Open Sans, sans-serif`;
ctx2d.fillText(text, 5, 5);
ctx2d.strokeText(text, 5, 5);
painter.debugOverlayTexture.update(canvas);
painter.debugOverlayTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
}
function selectDebugSource(style, zoom) {
let selectedSource = null;
const sources = Object.values(style._layers).flatMap((layer) => {
if (layer.source && !layer.isHidden(zoom)) return [style.tileManagers[layer.source]];
else return [];
});
const vectorSources = sources.filter((source) => source.getSource().type === "vector");
const otherSources = sources.filter((source) => source.getSource().type !== "vector");
const considerSource = (source) => {
if (!selectedSource || selectedSource.getSource().maxzoom < source.getSource().maxzoom) selectedSource = source;
};
for (const source of vectorSources) considerSource(source);
if (!selectedSource) for (const source of otherSources) considerSource(source);
return selectedSource;
}
//#endregion
//#region src/webgl/draw/draw_custom.ts
function drawCustom(painter, tileManager, layer, renderOptions) {
const { isRenderingGlobe } = renderOptions;
const context = painter.context;
const implementation = layer.implementation;
const projection = painter.style.projection;
const transform = painter.transform;
const projectionData = transform.getProjectionDataForCustomLayer(isRenderingGlobe);
const customLayerArgs = {
farZ: transform.farZ,
nearZ: transform.nearZ,
fov: transform.fov * Math.PI / 180,
modelViewProjectionMatrix: transform.modelViewProjectionMatrix,
projectionMatrix: transform.projectionMatrix,
shaderData: {
variantName: projection.shaderVariantName,
vertexShaderPrelude: `const float PI = 3.141592653589793;\nuniform mat4 u_projection_matrix;\n${projection.shaderPreludeCode.vertexSource}`,
define: projection.shaderDefine
},
defaultProjectionData: projectionData,
getProjectionData: (params) => {
return transform.getProjectionData({
overscaledTileID: new OverscaledTileID(params.tileID.canonical.z, params.tileID.wrap ?? 0, params.tileID.canonical.z, params.tileID.canonical.x, params.tileID.canonical.y),
aligned: params.aligned,
applyGlobeMatrix: params.applyGlobeMatrix,
applyTerrainMatrix: params.applyTerrainMatrix
});
}
};
const renderingMode = implementation.renderingMode ? implementation.renderingMode : "2d";
if (painter.renderPass === "offscreen") {
const prerender = implementation.prerender;
if (prerender) {
painter.setCustomLayerDefaults();
context.setColorMode(painter.colorModeForRenderPass());
prerender.call(implementation, context.gl, customLayerArgs);
context.setDirty();
painter.setBaseState();
}
} else if (painter.renderPass === "translucent") {
painter.setCustomLayerDefaults();
context.setColorMode(painter.colorModeForRenderPass());
context.setStencilMode(StencilMode.disabled);
const depthMode = renderingMode === "3d" ? painter.getDepthModeFor3D() : painter.getDepthModeForSublayer(0, DepthMode.ReadOnly);
context.setDepthMode(depthMode);
implementation.render(context.gl, customLayerArgs);
context.setDirty();
painter.setBaseState();
context.bindFramebuffer.set(null);
}
}
//#endregion
//#region src/webgl/draw/draw_terrain.ts
/**
* Redraw the Depth Framebuffer
* @param painter - the painter
* @param terrain - the terrain
*/
function drawDepth(painter, terrain) {
const context = painter.context;
const gl = context.gl;
const tr = painter.transform;
const colorMode = ColorMode.unblended;
const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]);
const tiles = terrain.tileManager.getRenderableTiles();
const program = painter.useProgram("terrainDepth");
context.bindFramebuffer.set(terrain.getFramebuffer("depth").framebuffer);
context.viewport.set([
0,
0,
painter.width / devicePixelRatio,
painter.height / devicePixelRatio
]);
context.clear({
color: Color.transparent,
depth: 1
});
for (const tile of tiles) {
const mesh = terrain.getTerrainMesh(tile.tileID);
const terrainData = terrain.getTerrainData(tile.tileID);
const projectionData = tr.getProjectionData({
overscaledTileID: tile.tileID,
applyTerrainMatrix: false,
applyGlobeMatrix: true
});
const uniformValues = terrainDepthUniformValues(terrain.getSkirtLength(tr.zoom));
program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, "terrain", mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
}
context.bindFramebuffer.set(null);
context.viewport.set([
0,
0,
painter.width,
painter.height
]);
}
/**
* Redraw the Coords Framebuffers
* @param painter - the painter
* @param terrain - the terrain
*/
function drawCoords(painter, terrain) {
const context = painter.context;
const gl = context.gl;
const tr = painter.transform;
const colorMode = ColorMode.unblended;
const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]);
const coords = terrain.getCoordsTexture();
const tiles = terrain.tileManager.getRenderableTiles();
const program = painter.useProgram("terrainCoords");
context.bindFramebuffer.set(terrain.getFramebuffer("coords").framebuffer);
context.viewport.set([
0,
0,
painter.width / devicePixelRatio,
painter.height / devicePixelRatio
]);
context.clear({
color: Color.transparent,
depth: 1
});
terrain.coordsIndex = [];
for (const tile of tiles) {
const mesh = terrain.getTerrainMesh(tile.tileID);
const terrainData = terrain.getTerrainData(tile.tileID);
context.activeTexture.set(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, coords.texture);
const uniformValues = terrainCoordsUniformValues(255 - terrain.coordsIndex.length, terrain.getSkirtLength(tr.zoom));
const projectionData = tr.getProjectionData({
overscaledTileID: tile.tileID,
applyTerrainMatrix: false,
applyGlobeMatrix: true
});
program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, "terrain", mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
terrain.coordsIndex.push(tile.tileID.key);
}
context.bindFramebuffer.set(null);
context.viewport.set([
0,
0,
painter.width,
painter.height
]);
}
function drawTerrain(painter, terrain, tiles, renderOptions) {
const { isRenderingGlobe } = renderOptions;
const context = painter.context;
const gl = context.gl;
const tr = painter.transform;
const colorMode = painter.colorModeForRenderPass();
const depthMode = painter.getDepthModeFor3D();
const program = painter.useProgram("terrain");
context.bindFramebuffer.set(null);
context.viewport.set([
0,
0,
painter.width,
painter.height
]);
for (const tile of tiles) {
const mesh = terrain.getTerrainMesh(tile.tileID);
const texture = painter.renderToTexture.getTexture(tile);
const terrainData = terrain.getTerrainData(tile.tileID);
context.activeTexture.set(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture.texture);
const eleDelta = terrain.getSkirtLength(tr.zoom);
const fogMatrix = tr.calculateFogMatrix(tile.tileID.toUnwrapped());
const uniformValues = terrainUniformValues(eleDelta, fogMatrix, painter.style.sky, tr.pitch, isRenderingGlobe);
const projectionData = tr.getProjectionData({
overscaledTileID: tile.tileID,
applyTerrainMatrix: false,
applyGlobeMatrix: true
});
program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.backCCW, uniformValues, terrainData, projectionData, "terrain", mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
}
}
//#endregion
//#region src/webgl/draw/draw_sky.ts
function getMesh(context, sky) {
if (!sky.mesh) {
const vertexArray = new PosArray();
vertexArray.emplaceBack(-1, -1);
vertexArray.emplaceBack(1, -1);
vertexArray.emplaceBack(1, 1);
vertexArray.emplaceBack(-1, 1);
const indexArray = new TriangleIndexArray();
indexArray.emplaceBack(0, 1, 2);
indexArray.emplaceBack(0, 2, 3);
sky.mesh = new Mesh(context.createVertexBuffer(vertexArray, posAttributes.members), context.createIndexBuffer(indexArray), SegmentVector.simpleSegment(0, 0, vertexArray.length, indexArray.length));
}
return sky.mesh;
}
function drawSky(painter, sky) {
const context = painter.context;
const gl = context.gl;
const skyUniforms = skyUniformValues(sky, painter.transform, painter.pixelRatio);
const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, [0, 1]);
const stencilMode = StencilMode.disabled;
const colorMode = painter.colorModeForRenderPass();
const program = painter.useProgram("sky");
const mesh = getMesh(context, sky);
program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled, skyUniforms, null, void 0, "sky", mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
}
function getSunPos(light, transform) {
const lightPos = light.getCartesianPosition();
negate(lightPos, lightPos);
const lightMat = identity(/* @__PURE__ */ new Float64Array(16));
if (light.properties.get("anchor") === "map") {
rotateZ(lightMat, lightMat, transform.rollInRadians);
rotateX(lightMat, lightMat, -transform.pitchInRadians);
rotateZ(lightMat, lightMat, transform.bearingInRadians);
rotateX(lightMat, lightMat, transform.center.lat * Math.PI / 180);
rotateY$1(lightMat, lightMat, -transform.center.lng * Math.PI / 180);
}
transformMat4$1(lightPos, lightPos, lightMat);
return lightPos;
}
function drawAtmosphere(painter, sky, light) {
const context = painter.context;
const gl = context.gl;
const program = painter.useProgram("atmosphere");
const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadOnly, [0, 1]);
const transform = painter.transform;
const sunPos = getSunPos(light, painter.transform);
const projectionData = transform.getProjectionData({
overscaledTileID: null,
applyGlobeMatrix: true,
applyTerrainMatrix: true
});
const atmosphereBlend = sky.properties.get("atmosphere-blend") * projectionData.projectionTransition;
if (atmosphereBlend === 0) return;
const globeRadius = getGlobeRadiusPixels(transform.worldSize, transform.center.lat);
const invProjMatrix = transform.inverseProjectionMatrix;
const vec = /* @__PURE__ */ new Float64Array(4);
vec[3] = 1;
transformMat4(vec, vec, transform.modelViewProjectionMatrix);
vec[0] /= vec[3];
vec[1] /= vec[3];
vec[2] /= vec[3];
vec[3] = 1;
transformMat4(vec, vec, invProjMatrix);
vec[0] /= vec[3];
vec[1] /= vec[3];
vec[2] /= vec[3];
vec[3] = 1;
const globePosition = [
vec[0],
vec[1],
vec[2]
];
const uniformValues = atmosphereUniformValues(sunPos, atmosphereBlend, globePosition, globeRadius, invProjMatrix);
const mesh = getMesh(context, sky);
program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, ColorMode.alphaBlended, CullFaceMode.disabled, uniformValues, null, null, "atmosphere", mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
}
//#endregion
//#region src/webgl/draw/index.ts
const webglDrawFunctions = {
symbol: drawSymbols,
circle: drawCircles,
heatmap: drawHeatmap,
line: drawLine,
fill: drawFill,
fillExtrusion: drawFillExtrusion,
hillshade: drawHillshade,
colorRelief: drawColorRelief,
raster: drawRaster,
background: drawBackground,
sky: drawSky,
atmosphere: drawAtmosphere,
custom: drawCustom,
debug: drawDebug,
debugPadding: drawDebugPadding,
terrainDepth: drawDepth,
terrainCoords: drawCoords
};
//#endregion
//#region src/render/painter.ts
/**
* @internal
* Initialize a new painter object.
*/
var Painter = class Painter {
constructor(gl, transform) {
this.drawFunctions = webglDrawFunctions;
this.context = new Context(gl);
this.transform = transform;
this.layerOpacityFbo = null;
this._tileTextures = {};
this._rttObjectRecyclePool = [];
this._rttSharedFbo = null;
this.terrainFacilitator = {
depthDirty: true,
coordsDirty: false,
matrix: identity(/* @__PURE__ */ new Float64Array(16)),
renderTime: 0
};
this.setup();
this.numSublayers = TileManager.maxOverzooming + TileManager.maxUnderzooming + 1;
this.depthEpsilon = 1 / Math.pow(2, 16);
this.crossTileSymbolIndex = new CrossTileSymbolIndex();
}
resize(width, height, pixelRatio) {
this.width = Math.floor(width * pixelRatio);
this.height = Math.floor(height * pixelRatio);
this.pixelRatio = pixelRatio;
this.context.viewport.set([
0,
0,
this.width,
this.height
]);
if (this.style) for (const layerId of this.style._order) this.style._layers[layerId].resize();
}
setup() {
const context = this.context;
const tileExtentArray = new PosArray();
tileExtentArray.emplaceBack(0, 0);
tileExtentArray.emplaceBack(EXTENT, 0);
tileExtentArray.emplaceBack(0, EXTENT);
tileExtentArray.emplaceBack(EXTENT, EXTENT);
this.tileExtentBuffer = context.createVertexBuffer(tileExtentArray, posAttributes.members);
this.tileExtentSegments = SegmentVector.simpleSegment(0, 0, 4, 2);
const debugArray = new PosArray();
debugArray.emplaceBack(0, 0);
debugArray.emplaceBack(EXTENT, 0);
debugArray.emplaceBack(0, EXTENT);
debugArray.emplaceBack(EXTENT, EXTENT);
this.debugBuffer = context.createVertexBuffer(debugArray, posAttributes.members);
this.debugSegments = SegmentVector.simpleSegment(0, 0, 4, 5);
const rasterBoundsArray = new RasterBoundsArray();
rasterBoundsArray.emplaceBack(0, 0, 0, 0);
rasterBoundsArray.emplaceBack(EXTENT, 0, EXTENT, 0);
rasterBoundsArray.emplaceBack(0, EXTENT, 0, EXTENT);
rasterBoundsArray.emplaceBack(EXTENT, EXTENT, EXTENT, EXTENT);
this.rasterBoundsBuffer = context.createVertexBuffer(rasterBoundsArray, rasterBoundsAttributes.members);
this.rasterBoundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2);
const rasterBoundsArrayPosOnly = new PosArray();
rasterBoundsArrayPosOnly.emplaceBack(0, 0);
rasterBoundsArrayPosOnly.emplaceBack(EXTENT, 0);
rasterBoundsArrayPosOnly.emplaceBack(0, EXTENT);
rasterBoundsArrayPosOnly.emplaceBack(EXTENT, EXTENT);
this.rasterBoundsBufferPosOnly = context.createVertexBuffer(rasterBoundsArrayPosOnly, posAttributes.members);
this.rasterBoundsSegmentsPosOnly = SegmentVector.simpleSegment(0, 0, 4, 5);
const viewportArray = new PosArray();
viewportArray.emplaceBack(0, 0);
viewportArray.emplaceBack(1, 0);
viewportArray.emplaceBack(0, 1);
viewportArray.emplaceBack(1, 1);
this.viewportBuffer = context.createVertexBuffer(viewportArray, posAttributes.members);
this.viewportSegments = SegmentVector.simpleSegment(0, 0, 4, 2);
const tileLineStripIndices = new LineStripIndexArray();
tileLineStripIndices.emplaceBack(0);
tileLineStripIndices.emplaceBack(1);
tileLineStripIndices.emplaceBack(3);
tileLineStripIndices.emplaceBack(2);
tileLineStripIndices.emplaceBack(0);
this.tileBorderIndexBuffer = context.createIndexBuffer(tileLineStripIndices);
const quadTriangleIndices = new TriangleIndexArray();
quadTriangleIndices.emplaceBack(1, 0, 2);
quadTriangleIndices.emplaceBack(1, 2, 3);
this.quadTriangleIndexBuffer = context.createIndexBuffer(quadTriangleIndices);
const gl = this.context.gl;
this.stencilClearMode = new StencilMode({
func: gl.ALWAYS,
mask: 0
}, 0, 255, gl.ZERO, gl.ZERO, gl.ZERO);
this.tileExtentMesh = new Mesh(this.tileExtentBuffer, this.quadTriangleIndexBuffer, this.tileExtentSegments);
}
clearStencil() {
const context = this.context;
const gl = context.gl;
this.nextStencilID = 1;
this.currentStencilSource = void 0;
const matrix = create$1();
ortho(matrix, 0, this.width, this.height, 0, 0, 1);
scale(matrix, matrix, [
gl.drawingBufferWidth,
gl.drawingBufferHeight,
0
]);
const projectionData = {
mainMatrix: matrix,
tileMercatorCoords: [
0,
0,
1,
1
],
clippingPlane: [
0,
0,
0,
0
],
projectionTransition: 0,
fallbackMatrix: matrix,
clipAntimeridian: false
};
this.useProgram("clippingMask", null, true).draw(context, gl.TRIANGLES, DepthMode.disabled, this.stencilClearMode, ColorMode.disabled, CullFaceMode.disabled, null, null, projectionData, "$clipping", this.viewportBuffer, this.quadTriangleIndexBuffer, this.viewportSegments);
}
renderTileClippingMasks(layer, tileIDs, renderToTexture) {
if (this.currentStencilSource === layer.source || !layer.isTileClipped() || !tileIDs?.length) return;
this.currentStencilSource = layer.source;
if (this.nextStencilID + tileIDs.length > 256) this.clearStencil();
const context = this.context;
context.setColorMode(ColorMode.disabled);
context.setDepthMode(DepthMode.disabled);
const stencilRefs = {};
for (const tileID of tileIDs) stencilRefs[tileID.key] = this.nextStencilID++;
if (this.style.projection.useSubdivision) this._renderTileMasks(stencilRefs, tileIDs, renderToTexture, true);
this._renderTileMasks(stencilRefs, tileIDs, renderToTexture, false);
this._tileClippingMaskIDs = stencilRefs;
}
_renderTileMasks(tileStencilRefs, tileIDs, renderToTexture, useBorders) {
const context = this.context;
const gl = context.gl;
const projection = this.style.projection;
const transform = this.transform;
const program = this.useProgram("clippingMask");
for (const tileID of tileIDs) {
const stencilRef = tileStencilRefs[tileID.key];
const terrainData = this.getTerrainDataForTile(tileID, renderToTexture);
const mesh = projection.getMeshFromTileID(this.context, tileID.canonical, useBorders, true, "stencil");
const projectionData = transform.getProjectionData({
overscaledTileID: tileID,
applyGlobeMatrix: !renderToTexture,
applyTerrainMatrix: true
});
program.draw(context, gl.TRIANGLES, DepthMode.disabled, new StencilMode({
func: gl.ALWAYS,
mask: 0
}, stencilRef, 255, gl.KEEP, gl.KEEP, gl.REPLACE), ColorMode.disabled, renderToTexture ? CullFaceMode.disabled : CullFaceMode.backCCW, null, terrainData, projectionData, "$clipping", mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
}
}
getTerrainDataForTile(tileID, isRenderingToTexture) {
if (isRenderingToTexture && this.style.projection?.name === "mercator") return null;
return this.style.map.terrain?.getTerrainData(tileID) || null;
}
/**
* Fills the depth buffer with the geometry of all supplied tiles.
* Does not change the color buffer or the stencil buffer.
*/
_renderTilesDepthBuffer() {
const context = this.context;
const gl = context.gl;
const projection = this.style.projection;
const transform = this.transform;
const program = this.useProgram("depth");
const depthMode = this.getDepthModeFor3D();
const tileIDs = coveringTiles(transform, { tileSize: transform.tileSize });
for (const tileID of tileIDs) {
const terrainData = this.style.map.terrain?.getTerrainData(tileID);
const mesh = projection.getMeshFromTileID(this.context, tileID.canonical, true, true, "raster");
const projectionData = transform.getProjectionData({
overscaledTileID: tileID,
applyGlobeMatrix: true,
applyTerrainMatrix: true
});
program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, ColorMode.disabled, CullFaceMode.backCCW, null, terrainData, projectionData, "$clipping", mesh.vertexBuffer, mesh.indexBuffer, mesh.segments);
}
}
stencilModeFor3D() {
this.currentStencilSource = void 0;
if (this.nextStencilID + 1 > 256) this.clearStencil();
const id = this.nextStencilID++;
const gl = this.context.gl;
return new StencilMode({
func: gl.NOTEQUAL,
mask: 255
}, id, 255, gl.KEEP, gl.KEEP, gl.REPLACE);
}
stencilModeForClipping(tileID) {
const gl = this.context.gl;
return new StencilMode({
func: gl.EQUAL,
mask: 255
}, this._tileClippingMaskIDs[tileID.key], 0, gl.KEEP, gl.KEEP, gl.REPLACE);
}
getStencilConfigForOverlapAndUpdateStencilID(tileIDs) {
const gl = this.context.gl;
const coords = tileIDs.sort((a, b) => b.overscaledZ - a.overscaledZ);
const minTileZ = coords[coords.length - 1].overscaledZ;
const stencilValues = coords[0].overscaledZ - minTileZ + 1;
if (stencilValues > 1) {
this.currentStencilSource = void 0;
if (this.nextStencilID + stencilValues > 256) this.clearStencil();
const zToStencilMode = {};
for (let i = 0; i < stencilValues; i++) zToStencilMode[i + minTileZ] = new StencilMode({
func: gl.GEQUAL,
mask: 255
}, i + this.nextStencilID, 255, gl.KEEP, gl.KEEP, gl.REPLACE);
this.nextStencilID += stencilValues;
return [zToStencilMode, coords];
}
return [{ [minTileZ]: StencilMode.disabled }, coords];
}
stencilConfigForOverlapTwoPass(tileIDs) {
const gl = this.context.gl;
const coords = tileIDs.sort((a, b) => b.overscaledZ - a.overscaledZ);
const minTileZ = coords[coords.length - 1].overscaledZ;
const stencilValues = coords[0].overscaledZ - minTileZ + 1;
this.clearStencil();
if (stencilValues > 1) {
const zToStencilModeHigh = {};
const zToStencilModeLow = {};
for (let i = 0; i < stencilValues; i++) {
zToStencilModeHigh[i + minTileZ] = new StencilMode({
func: gl.GREATER,
mask: 255
}, stencilValues + 1 + i, 255, gl.KEEP, gl.KEEP, gl.REPLACE);
zToStencilModeLow[i + minTileZ] = new StencilMode({
func: gl.GREATER,
mask: 255
}, 1 + i, 255, gl.KEEP, gl.KEEP, gl.REPLACE);
}
this.nextStencilID = stencilValues * 2 + 1;
return [
zToStencilModeHigh,
zToStencilModeLow,
coords
];
} else {
this.nextStencilID = 3;
return [
{ [minTileZ]: new StencilMode({
func: gl.GREATER,
mask: 255
}, 2, 255, gl.KEEP, gl.KEEP, gl.REPLACE) },
{ [minTileZ]: new StencilMode({
func: gl.GREATER,
mask: 255
}, 1, 255, gl.KEEP, gl.KEEP, gl.REPLACE) },
coords
];
}
}
colorModeForRenderPass() {
const gl = this.context.gl;
if (this._showOverdrawInspector) {
const a = 1 / 8;
return new ColorMode([gl.CONSTANT_COLOR, gl.ONE], new Color(a, a, a, 0), [
true,
true,
true,
true
]);
} else if (this.renderPass === "opaque") return ColorMode.unblended;
else return ColorMode.alphaBlended;
}
getDepthModeForSublayer(n, mask, func) {
if (!this.opaquePassEnabledForLayer()) return DepthMode.disabled;
const depth = 1 - ((1 + this.currentLayer) * this.numSublayers + n) * this.depthEpsilon;
return new DepthMode(func || this.context.gl.LEQUAL, mask, [depth, depth]);
}
getDepthModeFor3D() {
return new DepthMode(this.context.gl.LEQUAL, DepthMode.ReadWrite, this.depthRangeFor3D);
}
opaquePassEnabledForLayer() {
return this.currentLayer < this.opaquePassCutoff;
}
render(style, options) {
this.style = style;
this.options = options;
this.lineAtlas = style.lineAtlas;
this.imageManager = style.imageManager;
this.patternAtlas = style.patternAtlas;
this.glyphManager = style.glyphManager;
this.symbolFadeChange = style.placement.symbolFadeChange(now());
this.imageManager.beginFrame();
const layerIds = this.style._order;
const tileManagers = this.style.tileManagers;
const coordsAscending = {};
const coordsDescending = {};
const coordsDescendingSymbol = {};
const renderOptions = {
isRenderingToTexture: false,
isRenderingGlobe: style.projection?.transitionState > 0
};
for (const id in tileManagers) {
const tileManager = tileManagers[id];
if (tileManager.used) tileManager.prepare(this.context);
coordsAscending[id] = tileManager.getVisibleCoordinates(false);
coordsDescending[id] = coordsAscending[id].slice().reverse();
coordsDescendingSymbol[id] = tileManager.getVisibleCoordinates(true).reverse();
}
this.opaquePassCutoff = Infinity;
for (let i = 0; i < layerIds.length; i++) {
const layerId = layerIds[i];
if (this.style._layers[layerId].is3D()) {
this.opaquePassCutoff = i;
break;
}
}
this.maybeDrawDepth(false);
if (this.renderToTexture) {
this.renderToTexture.prepareForRender(this.style, this.transform.zoom);
this.opaquePassCutoff = 0;
}
this.renderPass = "offscreen";
for (const layerId of layerIds) {
const layer = this.style._layers[layerId];
if (!layer.hasOffscreenPass() || layer.isHidden(this.transform.zoom)) continue;
const coords = coordsDescending[layer.source];
if (layer.type !== "custom" && !coords.length) continue;
this.renderLayer(this, tileManagers[layer.source], layer, coords, renderOptions);
}
this.context.viewport.set([
0,
0,
this.width,
this.height
]);
this.context.bindFramebuffer.set(null);
this.context.clear({
color: options.showOverdrawInspector ? Color.black : Color.transparent,
depth: 1
});
this.clearStencil();
if (this.style.sky) this.drawFunctions.sky(this, this.style.sky);
this._showOverdrawInspector = options.showOverdrawInspector;
this.depthRangeFor3D = [0, 1 - (style._order.length + 2) * this.numSublayers * this.depthEpsilon];
if (!this.renderToTexture) {
this.renderPass = "opaque";
for (this.currentLayer = layerIds.length - 1; this.currentLayer >= 0; this.currentLayer--) {
const layer = this.style._layers[layerIds[this.currentLayer]];
const tileManager = tileManagers[layer.source];
const coords = coordsAscending[layer.source];
this.renderTileClippingMasks(layer, coords, false);
this.renderLayer(this, tileManager, layer, coords, renderOptions);
}
}
this.renderPass = "translucent";
let globeDepthRendered = false;
for (this.currentLayer = 0; this.currentLayer < layerIds.length; this.currentLayer++) {
const layer = this.style._layers[layerIds[this.currentLayer]];
const tileManager = tileManagers[layer.source];
if (this.renderToTexture?.renderLayer(layer, renderOptions)) continue;
if (!this.opaquePassEnabledForLayer() && !globeDepthRendered) {
globeDepthRendered = true;
if (renderOptions.isRenderingGlobe && !this.style.map.terrain) this._renderTilesDepthBuffer();
}
const coords = (layer.type === "symbol" ? coordsDescendingSymbol : coordsDescending)[layer.source];
this.renderTileClippingMasks(layer, coordsAscending[layer.source], !!this.renderToTexture);
this.renderLayer(this, tileManager, layer, coords, renderOptions);
}
if (renderOptions.isRenderingGlobe) this.drawFunctions.atmosphere(this, this.style.sky, this.style.light);
if (this.options.showTileBoundaries) {
const selectedSource = selectDebugSource(this.style, this.transform.zoom);
if (selectedSource) this.drawFunctions.debug(this, selectedSource, selectedSource.getVisibleCoordinates());
}
if (this.options.showPadding) this.drawFunctions.debugPadding(this);
this.context.setDefault();
}
/**
* Update the depth framebuffer if the camera has moved or tiles have reloaded.
* Marks coords as depthDirty so they are re-rendered on next demand.
*/
maybeDrawDepth(requireExact) {
if (!this.style?.map?.terrain) return;
const prevMatrix = this.terrainFacilitator.matrix;
const currMatrix = this.transform.modelViewProjectionMatrix;
let doUpdate = this.terrainFacilitator.depthDirty;
doUpdate ||= requireExact ? !exactEquals(prevMatrix, currMatrix) : !equals(prevMatrix, currMatrix);
doUpdate ||= this.style.map.terrain.tileManager.anyTilesAfterTime(this.terrainFacilitator.renderTime);
if (!doUpdate) return;
copy(prevMatrix, currMatrix);
this.terrainFacilitator.renderTime = now();
this.terrainFacilitator.depthDirty = false;
this.terrainFacilitator.coordsDirty = true;
this.drawFunctions.terrainDepth(this, this.style.map.terrain);
}
/**
* Render the coords framebuffer if it is coordsDirty
*/
maybeDrawCoords() {
if (!this.style?.map?.terrain || !this.terrainFacilitator.coordsDirty) return;
this.terrainFacilitator.coordsDirty = false;
this.drawFunctions.terrainCoords(this, this.style.map.terrain);
}
renderLayer(painter, tileManager, layer, coords, renderOptions) {
if (layer.isHidden(this.transform.zoom)) return;
if (layer.type !== "background" && layer.type !== "custom" && !(coords || []).length) return;
this.id = layer.id;
const draw = this.drawFunctions;
if (isSymbolStyleLayer(layer)) draw.symbol(painter, tileManager, layer, coords, this.style.placement.variableOffsets, renderOptions);
else if (isCircleStyleLayer(layer)) draw.circle(painter, tileManager, layer, coords, renderOptions);
else if (isHeatmapStyleLayer(layer)) draw.heatmap(painter, tileManager, layer, coords, renderOptions);
else if (isLineStyleLayer(layer)) draw.line(painter, tileManager, layer, coords, renderOptions);
else if (isFillStyleLayer(layer)) draw.fill(painter, tileManager, layer, coords, renderOptions);
else if (isFillExtrusionStyleLayer(layer)) draw.fillExtrusion(painter, tileManager, layer, coords, renderOptions);
else if (isHillshadeStyleLayer(layer)) draw.hillshade(painter, tileManager, layer, coords, renderOptions);
else if (isColorReliefStyleLayer(layer)) draw.colorRelief(painter, tileManager, layer, coords, renderOptions);
else if (isRasterStyleLayer(layer)) draw.raster(painter, tileManager, layer, coords, renderOptions);
else if (isBackgroundStyleLayer(layer)) draw.background(painter, tileManager, layer, coords, renderOptions);
else if (isCustomStyleLayer(layer)) draw.custom(painter, tileManager, layer, renderOptions);
}
static {
this.MAX_TEXTURE_POOL_SIZE_PER_BUCKET = 50;
}
saveTileTexture(texture) {
const textures = this._tileTextures[texture.size[0]];
if (!textures) this._tileTextures[texture.size[0]] = [texture];
else if (textures.length < Painter.MAX_TEXTURE_POOL_SIZE_PER_BUCKET) textures.push(texture);
else texture.destroy();
}
getTileTexture(size) {
const textures = this._tileTextures[size];
return textures && textures.length > 0 ? textures.pop() : null;
}
acquireRTT(size) {
const gl = this.context.gl;
const obj = this._rttObjectRecyclePool.pop();
if (obj) {
if (obj.size !== size) {
gl.bindTexture(gl.TEXTURE_2D, obj.texture.texture);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
obj.texture.size = [size, size];
obj.size = size;
}
return obj;
}
const texture = new Texture(this.context, {
width: size,
height: size,
data: null
}, gl.RGBA);
texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);
if (this.context.extTextureFilterAnisotropic) gl.texParameterf(gl.TEXTURE_2D, this.context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, this.context.extTextureFilterAnisotropicMax);
return {
texture,
size
};
}
/**
* Binds the shared RTT FBO with the given RTTObject's texture attached
* as color target. Creates / resizes the shared FBO and depth-stencil
* renderbuffer lazily.
*/
bindRTT(obj) {
const gl = this.context.gl;
const size = obj.size;
if (!this._rttSharedFbo) {
const fbo = this.context.createFramebuffer(size, size, true, true);
const depthRenderbuffer = this.context.createRenderbuffer(gl.DEPTH_STENCIL, size, size);
fbo.depthAttachment.set(depthRenderbuffer);
this._rttSharedFbo = {
fbo,
depthRenderbuffer,
size
};
}
if (this._rttSharedFbo.size !== size) {
this.context.bindRenderbuffer.set(this._rttSharedFbo.depthRenderbuffer);
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
this.context.bindRenderbuffer.set(null);
this._rttSharedFbo.fbo.width = size;
this._rttSharedFbo.fbo.height = size;
this._rttSharedFbo.size = size;
}
this._rttSharedFbo.fbo.colorAttachment.set(obj.texture.texture);
this.context.bindFramebuffer.set(this._rttSharedFbo.fbo.framebuffer);
}
releaseRTT(obj) {
this._rttObjectRecyclePool.push(obj);
}
/**
* Checks whether a pattern image is needed, and if it is, whether it is not loaded.
*
* @returns true if a needed image is missing and rendering needs to be skipped.
*/
isPatternMissing(image) {
if (!image) return false;
if (!image.from || !image.to) return true;
const imagePosA = this.patternAtlas.getPattern(image.from.toString());
const imagePosB = this.patternAtlas.getPattern(image.to.toString());
return !imagePosA || !imagePosB;
}
/**
* Finds the required shader and its variant (base/terrain/globe, etc.) and binds it, compiling a new shader if required.
* @param name - Name of the desired shader.
* @param programConfiguration - Configuration of shader's inputs.
* @param forceSimpleProjection - Whether to force the use of a shader variant with simple mercator projection vertex shader.
* @param defines - Additional macros to be injected at the beginning of the shader. Expected format is `['#define XYZ']`, etc.
* False by default. Use true when drawing with a simple projection matrix is desired, eg. when drawing a fullscreen quad.
* @returns
*/
useProgram(name, programConfiguration, forceSimpleProjection = false, defines = []) {
this.cache ||= {};
const useTerrain = !!this.style.map.terrain;
const projection = this.style.projection;
const projectionPrelude = forceSimpleProjection ? shaders.projectionMercator : projection.shaderPreludeCode;
const projectionDefine = forceSimpleProjection ? MercatorShaderDefine : projection.shaderDefine;
const projectionKey = `/${forceSimpleProjection ? MercatorShaderVariantKey : projection.shaderVariantName}`;
const configurationKey = programConfiguration ? programConfiguration.cacheKey : "";
const overdrawKey = this._showOverdrawInspector ? "/overdraw" : "";
const terrainKey = useTerrain ? "/terrain" : "";
const definesKey = defines ? `/${defines.join("/")}` : "";
const key = name + configurationKey + projectionKey + overdrawKey + terrainKey + definesKey;
this.cache[key] ||= new Program(this.context, shaders[name], programConfiguration, programUniforms[name], this._showOverdrawInspector, useTerrain, projectionPrelude, projectionDefine, defines);
return this.cache[key];
}
setCustomLayerDefaults() {
this.context.setCustomLayerDefaults();
}
setBaseState() {
const gl = this.context.gl;
this.context.cullFace.set(false);
this.context.viewport.set([
0,
0,
this.width,
this.height
]);
this.context.blendEquation.set(gl.FUNC_ADD);
}
initDebugOverlayCanvas() {
if (this.debugOverlayCanvas == null) {
this.debugOverlayCanvas = document.createElement("canvas");
this.debugOverlayCanvas.width = 512;
this.debugOverlayCanvas.height = 512;
const gl = this.context.gl;
this.debugOverlayTexture = new Texture(this.context, this.debugOverlayCanvas, gl.RGBA);
}
}
destroy() {
if (this._tileTextures) {
for (const size in this._tileTextures) {
const textures = this._tileTextures[size];
if (textures) for (const texture of textures) texture.destroy();
}
this._tileTextures = {};
}
for (const obj of this._rttObjectRecyclePool) obj.texture.destroy();
this._rttObjectRecyclePool = [];
if (this._rttSharedFbo) {
this._rttSharedFbo.fbo.colorAttachment.set(null);
this._rttSharedFbo.fbo.depthAttachment.set(null);
const gl = this.context.gl;
gl.deleteRenderbuffer(this._rttSharedFbo.depthRenderbuffer);
gl.deleteFramebuffer(this._rttSharedFbo.fbo.framebuffer);
this._rttSharedFbo = null;
}
this.layerOpacityFbo?.destroy();
this.layerOpacityFbo = null;
if (this.tileExtentBuffer) this.tileExtentBuffer.destroy();
if (this.debugBuffer) this.debugBuffer.destroy();
if (this.rasterBoundsBuffer) this.rasterBoundsBuffer.destroy();
if (this.rasterBoundsBufferPosOnly) this.rasterBoundsBufferPosOnly.destroy();
if (this.viewportBuffer) this.viewportBuffer.destroy();
if (this.tileBorderIndexBuffer) this.tileBorderIndexBuffer.destroy();
if (this.quadTriangleIndexBuffer) this.quadTriangleIndexBuffer.destroy();
if (this.tileExtentMesh) this.tileExtentMesh.vertexBuffer?.destroy();
if (this.tileExtentMesh) this.tileExtentMesh.indexBuffer?.destroy();
if (this.debugOverlayTexture) this.debugOverlayTexture.destroy();
if (this.cache) {
for (const key in this.cache) {
const program = this.cache[key];
if (program?.program) this.context.gl.deleteProgram(program.program);
}
this.cache = {};
}
if (this.context) this.context.setDefault();
}
overLimit() {
const { drawingBufferWidth, drawingBufferHeight } = this.context.gl;
return this.width !== drawingBufferWidth || this.height !== drawingBufferHeight;
}
};
//#endregion
//#region src/util/gpu_initialization_error.ts
/**
* Thrown (via the map's `error` event) when a GPU rendering context cannot be created.
*
* Carries the canvas attributes that were requested and, when the browser provided one,
* the originating `webglcontextcreationerror` `statusMessage`.
* Consumers can branch on `instanceof GPUInitializationError` and inspect the cause programmatically.
* @see https://wiki.openstreetmap.org/wiki/This_map_requires_WebGL
*/
var GPUInitializationError = class extends Error {
constructor(requestedAttributes, creationEvent) {
super("WebGL2 is required to display this map. We are sorry, but it seems that your browser does not support WebGL2, a technology for rendering 3D graphics on the web. Read more on https://wiki.openstreetmap.org/wiki/This_map_requires_WebGL");
this.name = "GPUInitializationError";
this.requestedAttributes = requestedAttributes;
this.statusMessage = creationEvent?.statusMessage ?? null;
}
};
//#endregion
//#region src/util/throttle.ts
/**
* Throttle the given function to run at most every `period` milliseconds.
*/
function throttle(fn, time) {
let pending = false;
let timerId = null;
let lastCallArgs;
const later = () => {
timerId = null;
if (pending) {
fn(...lastCallArgs);
timerId = setTimeout(later, time);
pending = false;
}
};
return (...args) => {
pending = true;
lastCallArgs = args;
if (!timerId) later();
return timerId;
};
}
//#endregion
//#region src/ui/hash.ts
/**
* Adds the map's position to its page's location hash.
* Passed as an option to the map object.
*
* @group Markers and Controls
*/
var Hash = class {
constructor(hashName) {
this._getHashParams = () => {
return new URLSearchParams(window.location.hash.replace("#", ""));
};
this._getCurrentHash = () => {
const params = this._getHashParams();
if (this._hashName) return (params.get(this._hashName) || "").split("/");
return ([...params.keys()][0] ?? "").split("/");
};
this._onHashChange = () => {
const hash = this._getCurrentHash();
if (!this._isValidHash(hash)) return false;
const bearing = this._map.dragRotate.isEnabled() && this._map.touchZoomRotate.isEnabled() ? +(hash[3] || 0) : this._map.getBearing();
this._map.jumpTo({
center: [+hash[2], +hash[1]],
zoom: +hash[0],
bearing,
pitch: +(hash[4] || 0)
});
return true;
};
this._updateHashUnthrottled = () => {
const location = window.location.href.replace(/(#.*)?$/, this.getHashString());
window.history.replaceState(window.history.state, null, location);
};
this._removeHash = () => {
const params = this._getHashParams();
if (this._hashName) params.delete(this._hashName);
else {
const keys = Array.from(params.keys());
if (keys.length > 0) params.delete(keys[0]);
}
const newHash = decodeURIComponent(params.toString()).replace(/=&/g, "&").replace(/=$/g, "");
const replaceString = newHash ? `#${newHash}` : "";
let location = window.location.href.replace(/(#.+)?$/, replaceString);
location = location.replace("&&", "&");
window.history.replaceState(window.history.state, null, location);
};
this._updateHash = throttle(this._updateHashUnthrottled, 300);
this._hashName = hashName && encodeURIComponent(hashName);
}
/**
* Map element to listen for coordinate changes
*
* @param map - The map object
*/
addTo(map) {
this._map = map;
addEventListener("hashchange", this._onHashChange, false);
this._map.on("moveend", this._updateHash);
return this;
}
/**
* Removes hash
*/
remove() {
removeEventListener("hashchange", this._onHashChange, false);
this._map.off("moveend", this._updateHash);
clearTimeout(this._updateHash());
this._removeHash();
delete this._map;
return this;
}
getHashString(mapFeedback) {
const center = this._map.getCenter(), zoom = Math.round(this._map.getZoom() * 100) / 100, precision = Math.ceil((zoom * Math.LN2 + Math.log(512 / 360 / .5)) / Math.LN10), m = Math.pow(10, precision), lng = Math.round(center.lng * m) / m, lat = Math.round(center.lat * m) / m, bearing = this._map.getBearing(), pitch = this._map.getPitch();
let hash = "";
if (mapFeedback) hash += `/${lng}/${lat}/${zoom}`;
else hash += `${zoom}/${lat}/${lng}`;
if (bearing || pitch) hash += `/${Math.round(bearing * 10) / 10}`;
if (pitch) hash += `/${Math.round(pitch)}`;
if (this._hashName) {
const params = this._getHashParams();
params.set(this._hashName, hash);
return `#${decodeURIComponent(params.toString()).replace(/=&/g, "&").replace(/=$/g, "")}`;
}
return `#${hash}`;
}
_isValidHash(hash) {
if (hash.length < 3 || hash.some((h) => isNaN(+h))) return false;
try {
new LngLat(+hash[2], +hash[1]);
} catch {
return false;
}
const zoom = +hash[0];
const bearing = +(hash[3] || 0);
const pitch = +(hash[4] || 0);
return zoom >= this._map.getMinZoom() && zoom <= this._map.getMaxZoom() && bearing >= -180 && bearing <= 180 && pitch >= this._map.getMinPitch() && pitch <= this._map.getMaxPitch();
}
};
//#endregion
//#region src/ui/handler_inertia.ts
const defaultInertiaOptions = {
linearity: .3,
easing: bezier(0, 0, .3, 1)
};
const defaultPanInertiaOptions = extend({
deceleration: 2500,
maxSpeed: 1400
}, defaultInertiaOptions);
const defaultZoomInertiaOptions = extend({
deceleration: 20,
maxSpeed: 1400
}, defaultInertiaOptions);
const defaultBearingInertiaOptions = extend({
deceleration: 1e3,
maxSpeed: 360
}, defaultInertiaOptions);
const defaultPitchInertiaOptions = extend({
deceleration: 1e3,
maxSpeed: 90
}, defaultInertiaOptions);
const defaultRollInertiaOptions = extend({
deceleration: 1e3,
maxSpeed: 360
}, defaultInertiaOptions);
/**
* The maximum age of a recorded gesture update, in milliseconds.
*/
const BUFFER_CUTOFF = 160;
/**
* The time window the gesture velocity is measured over, in milliseconds.
*/
const VELOCITY_WINDOW = 60;
var HandlerInertia = class {
constructor(map) {
this._map = map;
this.clear();
}
clear() {
this._inertiaBuffer = [];
}
record(settings) {
this._drainInertiaBuffer();
this._inertiaBuffer.push({
time: now(),
settings
});
}
_drainInertiaBuffer() {
const inertia = this._inertiaBuffer, currentTime = now();
while (inertia.length > 0 && currentTime - inertia[0].time > BUFFER_CUTOFF) inertia.shift();
}
/**
* Returns the entries the velocity is measured from: everything recorded within
* {@link VELOCITY_WINDOW} before now, but never fewer than the last two, so that
* inertia also works below two recorded updates per window.
*/
_getVelocityEntries() {
const inertia = this._inertiaBuffer;
const windowStart = now() - VELOCITY_WINDOW;
let firstIndex = Math.max(0, inertia.length - 2);
while (firstIndex > 0 && inertia[firstIndex - 1].time >= windowStart) firstIndex--;
return inertia.slice(firstIndex);
}
/**
* Returns the ease which continues the gesture that has just ended.
*
* The velocity is measured over the time up to the release and not up to the last
* recorded movement, so that a gesture held still before being released has a lower
* velocity, down to no inertia at all. The delta of an entry happened before it was
* recorded, so the first entry only marks the start of the measured interval; anchors
* are the exception, as they describe the state at the moment of their entry.
*
* @param panInertiaOptions - overrides for the pan inertia defaults
* @returns the ease options, or `undefined` when the measured interval holds no
* movement, which terrain gestures produce by recording updates without any delta
*/
_onMoveEnd(panInertiaOptions) {
this._drainInertiaBuffer();
const entries = this._getVelocityEntries();
if (entries.length < 2) {
this.clear();
return;
}
const deltas = {
zoom: 0,
bearing: 0,
pitch: 0,
roll: 0,
pan: new Point(0, 0),
pinchAround: void 0,
around: void 0
};
for (const { settings } of entries) {
if (settings.around) deltas.around = settings.around;
if (settings.pinchAround) deltas.pinchAround = settings.pinchAround;
}
for (const { settings } of entries.slice(1)) {
deltas.zoom += settings.zoomDelta || 0;
deltas.bearing += settings.bearingDelta || 0;
deltas.pitch += settings.pitchDelta || 0;
deltas.roll += settings.rollDelta || 0;
if (settings.panDelta) deltas.pan._add(settings.panDelta);
}
if (!deltas.pan.mag() && !deltas.zoom && !deltas.bearing && !deltas.pitch && !deltas.roll) {
this.clear();
return;
}
const duration = now() - entries[0].time;
const easeOptions = {};
if (deltas.pan.mag()) {
const result = calculateEasing(deltas.pan.mag(), duration, extend({}, defaultPanInertiaOptions, panInertiaOptions || {}));
const finalPan = deltas.pan.mult(result.amount / deltas.pan.mag());
const computedEaseOptions = this._map._camera.cameraHelper.handlePanInertia(finalPan, this._map._camera.transform);
easeOptions.center = computedEaseOptions.easingCenter;
easeOptions.offset = computedEaseOptions.easingOffset;
extendDuration(easeOptions, result);
}
if (deltas.zoom) {
const result = calculateEasing(deltas.zoom, duration, defaultZoomInertiaOptions);
easeOptions.zoom = evaluateZoomSnap(this._map.getZoom() + result.amount, this._map.getZoomSnap(), result.amount);
extendDuration(easeOptions, result);
}
if (deltas.bearing) {
const result = calculateEasing(deltas.bearing, duration, defaultBearingInertiaOptions);
easeOptions.bearing = this._map.getBearing() + clamp(result.amount, -179, 179);
extendDuration(easeOptions, result);
}
if (deltas.pitch) {
const result = calculateEasing(deltas.pitch, duration, defaultPitchInertiaOptions);
easeOptions.pitch = this._map.getPitch() + result.amount;
extendDuration(easeOptions, result);
}
if (deltas.roll) {
const result = calculateEasing(deltas.roll, duration, defaultRollInertiaOptions);
easeOptions.roll = this._map.getRoll() + clamp(result.amount, -179, 179);
extendDuration(easeOptions, result);
}
if (easeOptions.zoom || easeOptions.bearing) {
const last = deltas.pinchAround === void 0 ? deltas.around : deltas.pinchAround;
easeOptions.around = last ? this._map.unproject(last) : this._map.getCenter();
}
this.clear();
return extend(easeOptions, { noMoveStart: true });
}
};
function extendDuration(easeOptions, result) {
if (!easeOptions.duration || easeOptions.duration < result.duration) {
easeOptions.duration = result.duration;
easeOptions.easing = result.easing;
}
}
function calculateEasing(amount, inertiaDuration, inertiaOptions) {
const { maxSpeed, linearity, deceleration } = inertiaOptions;
const speed = clamp(amount * linearity / (inertiaDuration / 1e3), -maxSpeed, maxSpeed);
const duration = Math.abs(speed) / (deceleration * linearity);
return {
easing: inertiaOptions.easing,
duration: duration * 1e3,
amount: speed * (duration / 2)
};
}
//#endregion
//#region src/ui/handler/map_event.ts
var MapEventHandler = class {
constructor(map, options) {
this._map = map;
this._clickTolerance = options.clickTolerance;
}
reset() {
delete this._mousedownPos;
}
wheel(e) {
return this._firePreventable(new MapWheelEvent(this._map, e));
}
mousedown(e, point) {
this._mousedownPos = point;
return this._firePreventable(new MapMouseEvent(e.type, this._map, e));
}
mouseup(e) {
this._map.fire(new MapMouseEvent(e.type, this._map, e));
}
click(e, point) {
if (this._mousedownPos && this._mousedownPos.dist(point) >= this._clickTolerance) return;
this._map.fire(new MapMouseEvent(e.type, this._map, e));
}
dblclick(e) {
return this._firePreventable(new MapMouseEvent(e.type, this._map, e));
}
mouseover(e) {
this._map.fire(new MapMouseEvent(e.type, this._map, e));
}
mouseout(e) {
this._map.fire(new MapMouseEvent(e.type, this._map, e));
}
touchstart(e) {
return this._firePreventable(new MapTouchEvent(e.type, this._map, e));
}
touchmove(e) {
this._map.fire(new MapTouchEvent(e.type, this._map, e));
}
touchend(e) {
this._map.fire(new MapTouchEvent(e.type, this._map, e));
}
touchcancel(e) {
this._map.fire(new MapTouchEvent(e.type, this._map, e));
}
_firePreventable(mapEvent) {
this._map.fire(mapEvent);
if (mapEvent.defaultPrevented) return {};
}
isEnabled() {
return true;
}
isActive() {
return false;
}
enable() {}
disable() {}
};
var BlockableMapEventHandler = class {
constructor(map) {
this._map = map;
}
reset() {
this._delayContextMenu = false;
this._ignoreContextMenu = true;
delete this._contextMenuEvent;
}
mousemove(e) {
this._map.fire(new MapMouseEvent(e.type, this._map, e));
}
mousedown() {
this._delayContextMenu = true;
this._ignoreContextMenu = false;
}
mouseup() {
this._delayContextMenu = false;
if (this._contextMenuEvent) {
this._map.fire(new MapMouseEvent("contextmenu", this._map, this._contextMenuEvent));
delete this._contextMenuEvent;
}
}
contextmenu(e) {
if (this._delayContextMenu) this._contextMenuEvent = e;
else if (!this._ignoreContextMenu) this._map.fire(new MapMouseEvent(e.type, this._map, e));
if (this._map.listens("contextmenu")) e.preventDefault();
}
isEnabled() {
return true;
}
isActive() {
return false;
}
enable() {}
disable() {}
};
//#endregion
//#region src/ui/handler/box_zoom.ts
/**
* The `BoxZoomHandler` allows the user to zoom the map to fit within a bounding box.
* The bounding box is defined by clicking and holding `shift` while dragging the cursor.
*
* @group Handlers
*/
var BoxZoomHandler = class {
/** @internal */
constructor(map, options, transformProvider) {
this._map = map;
this._tr = transformProvider;
this._el = map.getCanvasContainer();
this._container = map.getContainer();
this._clickTolerance = options.clickTolerance || 1;
if (options.boxZoom && typeof options.boxZoom === "object") this._boxZoomEnd = options.boxZoom.boxZoomEnd;
}
/**
* Returns a Boolean indicating whether the "box zoom" interaction is enabled.
*
* @returns `true` if the "box zoom" interaction is enabled.
*/
isEnabled() {
return !!this._enabled;
}
/**
* Returns a Boolean indicating whether the "box zoom" interaction is active, i.e. currently being used.
*
* @returns `true` if the "box zoom" interaction is active.
*/
isActive() {
return !!this._active;
}
/**
* Enables the "box zoom" interaction.
*
* @example
* ```ts
* map.boxZoom.enable();
* ```
*/
enable() {
if (this.isEnabled()) return;
this._enabled = true;
}
/**
* Disables the "box zoom" interaction.
*
* @example
* ```ts
* map.boxZoom.disable();
* ```
*/
disable() {
if (!this.isEnabled()) return;
this._enabled = false;
}
mousedown(e, point) {
if (!this.isEnabled()) return;
if (!(e.shiftKey && e.button === 0)) return;
DOM.disableDrag();
this._startPos = this._lastPos = point;
this._active = true;
}
mousemoveWindow(e, point) {
if (!this._active) return;
const pos = point;
if (this._lastPos.equals(pos) || !this._box && pos.dist(this._startPos) < this._clickTolerance) return;
const p0 = this._startPos;
this._lastPos = pos;
if (!this._box) {
this._box = DOM.create("div", "maplibregl-boxzoom", this._container);
this._container.classList.add("maplibregl-crosshair");
this._fireEvent("boxzoomstart", e);
}
const minX = Math.min(p0.x, pos.x), maxX = Math.max(p0.x, pos.x), minY = Math.min(p0.y, pos.y), maxY = Math.max(p0.y, pos.y);
this._box.style.transform = `translate(${minX}px,${minY}px)`;
this._box.style.width = `${maxX - minX}px`;
this._box.style.height = `${maxY - minY}px`;
}
mouseupWindow(e, point) {
if (!this._active) return;
if (e.button !== 0) return;
const p0 = this._startPos, p1 = point;
this.reset();
DOM.suppressClick();
if (p0.x === p1.x && p0.y === p1.y) this._fireEvent("boxzoomcancel", e);
else {
this._map.fire(new MapBoxZoomEvent("boxzoomend", { originalEvent: e }));
if (this._boxZoomEnd) {
this._boxZoomEnd(this._map, p0, p1, e);
return;
}
return { cameraAnimation: (map) => map.fitScreenCoordinates(p0, p1, this._tr.bearing, { linear: true }) };
}
}
keydown(e) {
if (!this._active) return;
if (e.keyCode === 27) {
this.reset();
this._fireEvent("boxzoomcancel", e);
}
}
reset() {
this._active = false;
this._container.classList.remove("maplibregl-crosshair");
if (this._box) {
this._box.remove();
this._box = null;
}
DOM.enableDrag();
delete this._startPos;
delete this._lastPos;
}
_fireEvent(type, e) {
return this._map.fire(new MapBoxZoomEvent(type, { originalEvent: e }));
}
};
//#endregion
//#region src/ui/handler/handler_util.ts
function indexTouches(touches, points) {
if (touches.length !== points.length) throw new Error(`The number of touches and points are not equal - touches ${touches.length}, points ${points.length}`);
const obj = {};
for (let i = 0; i < touches.length; i++) obj[touches[i].identifier] = points[i];
return obj;
}
//#endregion
//#region src/ui/handler/tap_recognizer.ts
function getCentroid(points) {
const sum = new Point(0, 0);
for (const point of points) sum._add(point);
return sum.div(points.length);
}
const MAX_TOUCH_TIME = 500;
var SingleTapRecognizer = class {
constructor(options) {
this.reset();
this.numTouches = options.numTouches;
}
reset() {
delete this.centroid;
delete this.startTime;
delete this.touches;
this.aborted = false;
}
touchstart(e, points, mapTouches) {
if (this.centroid || mapTouches.length > this.numTouches) this.aborted = true;
if (this.aborted) return;
if (this.startTime === void 0) this.startTime = e.timeStamp;
if (mapTouches.length === this.numTouches) {
this.centroid = getCentroid(points);
this.touches = indexTouches(mapTouches, points);
}
}
touchmove(e, points, mapTouches) {
if (this.aborted || !this.centroid) return;
const newTouches = indexTouches(mapTouches, points);
for (const id in this.touches) {
const prevPos = this.touches[id];
const pos = newTouches[id];
if (!pos || pos.dist(prevPos) > 30) this.aborted = true;
}
}
touchend(e, points, mapTouches) {
if (!this.centroid || e.timeStamp - this.startTime > MAX_TOUCH_TIME) this.aborted = true;
if (mapTouches.length === 0) {
const centroid = !this.aborted && this.centroid;
this.reset();
if (centroid) return centroid;
}
}
};
var TapRecognizer = class {
constructor(options) {
this.singleTap = new SingleTapRecognizer(options);
this.numTaps = options.numTaps;
this.reset();
}
reset() {
this.lastTime = Infinity;
delete this.lastTap;
this.count = 0;
this.singleTap.reset();
}
touchstart(e, points, mapTouches) {
this.singleTap.touchstart(e, points, mapTouches);
}
touchmove(e, points, mapTouches) {
this.singleTap.touchmove(e, points, mapTouches);
}
touchend(e, points, mapTouches) {
const tap = this.singleTap.touchend(e, points, mapTouches);
if (tap) {
const soonEnough = e.timeStamp - this.lastTime < 500;
const closeEnough = !this.lastTap || this.lastTap.dist(tap) < 30;
if (!soonEnough || !closeEnough) this.reset();
this.count++;
this.lastTime = e.timeStamp;
this.lastTap = tap;
if (this.count === this.numTaps) {
this.reset();
return tap;
}
}
}
};
//#endregion
//#region src/ui/handler/tap_zoom.ts
/**
* A `TapZoomHandler` allows the user to zoom the map at a point by double tapping
*/
var TapZoomHandler = class {
constructor(map, transformProvider) {
this._tr = transformProvider;
this._zoomIn = new TapRecognizer({
numTouches: 1,
numTaps: 2
});
this._zoomOut = new TapRecognizer({
numTouches: 2,
numTaps: 1
});
this.reset();
}
reset() {
this._active = false;
this._zoomIn.reset();
this._zoomOut.reset();
}
touchstart(e, points, mapTouches) {
this._zoomIn.touchstart(e, points, mapTouches);
this._zoomOut.touchstart(e, points, mapTouches);
}
touchmove(e, points, mapTouches) {
this._zoomIn.touchmove(e, points, mapTouches);
this._zoomOut.touchmove(e, points, mapTouches);
}
touchend(e, points, mapTouches) {
const zoomInPoint = this._zoomIn.touchend(e, points, mapTouches);
const zoomOutPoint = this._zoomOut.touchend(e, points, mapTouches);
const tr = this._tr;
if (zoomInPoint) {
this._active = true;
e.preventDefault();
setTimeout(() => this.reset(), 0);
return { cameraAnimation: (map) => map.easeTo({
duration: 300,
zoom: evaluateZoomSnap(tr.zoom + 1, map.getZoomSnap()),
around: tr.unproject(zoomInPoint)
}, { originalEvent: e }) };
} else if (zoomOutPoint) {
this._active = true;
e.preventDefault();
setTimeout(() => this.reset(), 0);
return { cameraAnimation: (map) => map.easeTo({
duration: 300,
zoom: evaluateZoomSnap(tr.zoom - 1, map.getZoomSnap()),
around: tr.unproject(zoomOutPoint)
}, { originalEvent: e }) };
}
}
touchcancel() {
this.reset();
}
enable() {
this._enabled = true;
}
disable() {
this._enabled = false;
this.reset();
}
isEnabled() {
return this._enabled;
}
isActive() {
return this._active;
}
};
//#endregion
//#region src/ui/handler/drag_handler.ts
/**
* A generic class to create handlers for drag events, from both mouse and touch events.
*/
var DragHandler = class {
constructor(options) {
this._enabled = !!options.enable;
this._moveStateManager = options.moveStateManager;
this._clickTolerance = options.clickTolerance || 1;
this._moveFunction = options.move;
this._activateOnStart = !!options.activateOnStart;
options.assignEvents(this);
this.reset();
}
reset(e) {
this._active = false;
this._moved = false;
delete this._lastPoint;
this._moveStateManager.endMove(e);
}
_move(...params) {
const move = this._moveFunction(...params);
if (move.bearingDelta || move.pitchDelta || move.rollDelta || move.around || move.panDelta) {
this._active = true;
return move;
}
}
dragStart(e, point) {
if (!this.isEnabled() || this._lastPoint) return;
if (!this._moveStateManager.isValidStartEvent(e)) return;
this._moveStateManager.startMove(e);
this._lastPoint = Array.isArray(point) ? point[0] : point;
if (this._activateOnStart && this._lastPoint) this._active = true;
}
dragMove(e, point) {
if (!this.isEnabled()) return;
const lastPoint = this._lastPoint;
if (!lastPoint) return;
e.preventDefault();
if (!this._moveStateManager.isValidMoveEvent(e)) {
this.reset(e);
return;
}
const movePoint = Array.isArray(point) ? point[0] : point;
if (!this._moved && movePoint.dist(lastPoint) < this._clickTolerance) return;
this._moved = true;
this._lastPoint = movePoint;
return this._move(lastPoint, movePoint);
}
dragEnd(e) {
if (!this.isEnabled() || !this._lastPoint) return;
if (!this._moveStateManager.isValidEndEvent(e)) return;
if (this._moved) DOM.suppressClick();
this.reset(e);
}
enable() {
this._enabled = true;
}
disable() {
this._enabled = false;
this.reset();
}
isEnabled() {
return this._enabled;
}
isActive() {
return this._active;
}
getClickTolerance() {
return this._clickTolerance;
}
};
//#endregion
//#region src/ui/handler/drag_move_state_manager.ts
const LEFT_BUTTON$1 = 0;
const RIGHT_BUTTON$1 = 2;
const BUTTONS_FLAGS = {
[LEFT_BUTTON$1]: 1,
[RIGHT_BUTTON$1]: 2
};
function buttonNoLongerPressed(e, button) {
const flag = BUTTONS_FLAGS[button];
return e.buttons === void 0 || (e.buttons & flag) !== flag;
}
var MouseMoveStateManager = class {
constructor(options) {
this._correctEvent = options.checkCorrectEvent;
}
startMove(e) {
this._eventButton = e.button;
}
endMove(_e) {
delete this._eventButton;
}
isValidStartEvent(e) {
return this._correctEvent(e);
}
isValidMoveEvent(e) {
return !buttonNoLongerPressed(e, this._eventButton);
}
isValidEndEvent(e) {
return e.button === this._eventButton;
}
};
var OneFingerTouchMoveStateManager = class {
constructor() {
this._firstTouch = void 0;
}
_isOneFingerTouch(e) {
return e.targetTouches.length === 1;
}
_isSameTouchEvent(e) {
return e.targetTouches[0].identifier === this._firstTouch;
}
startMove(e) {
this._firstTouch = e.targetTouches[0].identifier;
}
endMove(_e) {
delete this._firstTouch;
}
isValidStartEvent(e) {
return this._isOneFingerTouch(e);
}
isValidMoveEvent(e) {
return this._isOneFingerTouch(e) && this._isSameTouchEvent(e);
}
isValidEndEvent(e) {
return this._isOneFingerTouch(e) && this._isSameTouchEvent(e);
}
};
var MouseOrTouchMoveStateManager = class {
constructor(mouseMoveStateManager = new MouseMoveStateManager({ checkCorrectEvent: () => true }), oneFingerTouchMoveStateManager = new OneFingerTouchMoveStateManager()) {
this.mouseMoveStateManager = mouseMoveStateManager;
this.oneFingerTouchMoveStateManager = oneFingerTouchMoveStateManager;
}
_executeRelevantHandler(e, onMouseEvent, onTouchEvent) {
if (e instanceof MouseEvent) return onMouseEvent(e);
if (typeof TouchEvent !== "undefined" && e instanceof TouchEvent) return onTouchEvent(e);
}
startMove(e) {
this._executeRelevantHandler(e, (e) => {
this.mouseMoveStateManager.startMove(e);
}, (e) => {
this.oneFingerTouchMoveStateManager.startMove(e);
});
}
endMove(e) {
this._executeRelevantHandler(e, (e) => {
this.mouseMoveStateManager.endMove(e);
}, (e) => {
this.oneFingerTouchMoveStateManager.endMove(e);
});
}
isValidStartEvent(e) {
return !!this._executeRelevantHandler(e, (e) => this.mouseMoveStateManager.isValidStartEvent(e), (e) => this.oneFingerTouchMoveStateManager.isValidStartEvent(e));
}
isValidMoveEvent(e) {
return !!this._executeRelevantHandler(e, (e) => this.mouseMoveStateManager.isValidMoveEvent(e), (e) => this.oneFingerTouchMoveStateManager.isValidMoveEvent(e));
}
isValidEndEvent(e) {
return !!this._executeRelevantHandler(e, (e) => this.mouseMoveStateManager.isValidEndEvent(e), (e) => this.oneFingerTouchMoveStateManager.isValidEndEvent(e));
}
};
//#endregion
//#region src/ui/handler/mouse.ts
const LEFT_BUTTON = 0;
const RIGHT_BUTTON = 2;
const assignEvents = (handler) => {
handler.mousedown = handler.dragStart;
handler.mousemoveWindow = handler.dragMove;
handler.mouseup = handler.dragEnd;
handler.contextmenu = (e) => {
e.preventDefault();
};
};
function generateMousePanHandler({ enable, clickTolerance }) {
return new DragHandler({
clickTolerance,
move: (lastPoint, point) => ({
around: point,
panDelta: point.sub(lastPoint)
}),
activateOnStart: true,
moveStateManager: new MouseMoveStateManager({ checkCorrectEvent: (e) => e.button === LEFT_BUTTON && !e.ctrlKey }),
enable,
assignEvents
});
}
function generateMouseRotationHandler({ enable, clickTolerance, aroundCenter = true, minPixelCenterThreshold = 100, rotateSpeed = .8 }, getCenter) {
return new DragHandler({
clickTolerance,
move: (lastPoint, currentPoint) => {
const center = getCenter();
if (aroundCenter && Math.abs(center.y - lastPoint.y) > minPixelCenterThreshold) return { bearingDelta: getAngleDelta(new Point(lastPoint.x, currentPoint.y), currentPoint, center) };
let bearingDelta = (currentPoint.x - lastPoint.x) * rotateSpeed;
if (aroundCenter && currentPoint.y < center.y) bearingDelta = -bearingDelta;
return { bearingDelta };
},
moveStateManager: new MouseMoveStateManager({ checkCorrectEvent: (e) => e.button === LEFT_BUTTON && e.ctrlKey || e.button === RIGHT_BUTTON && !e.ctrlKey }),
enable,
assignEvents
});
}
function generateMousePitchHandler({ enable, clickTolerance, pitchSpeed = -.5 }) {
return new DragHandler({
clickTolerance,
move: (lastPoint, point) => ({ pitchDelta: (point.y - lastPoint.y) * pitchSpeed }),
moveStateManager: new MouseMoveStateManager({ checkCorrectEvent: (e) => e.button === LEFT_BUTTON && e.ctrlKey || e.button === RIGHT_BUTTON }),
enable,
assignEvents
});
}
function generateMouseRollHandler({ enable, clickTolerance, rollDegreesPerPixelMoved = .3 }, getCenter) {
return new DragHandler({
clickTolerance,
move: (lastPoint, currentPoint) => {
const center = getCenter();
let rollDelta = (currentPoint.x - lastPoint.x) * rollDegreesPerPixelMoved;
if (currentPoint.y < center.y) rollDelta = -rollDelta;
return { rollDelta };
},
moveStateManager: new MouseMoveStateManager({ checkCorrectEvent: (e) => e.button === RIGHT_BUTTON && e.ctrlKey }),
enable,
assignEvents
});
}
//#endregion
//#region src/ui/handler/touch_pan.ts
/**
* A `TouchPanHandler` allows the user to pan the map using touch gestures.
*/
var TouchPanHandler = class {
constructor(options, map) {
this._clickTolerance = options.clickTolerance || 1;
this._map = map;
this.reset();
}
reset() {
this._active = false;
this._touches = {};
this._sum = new Point(0, 0);
}
_shouldBePrevented(touchesCount) {
return touchesCount < (this._map.cooperativeGestures.isEnabled() ? 2 : 1);
}
touchstart(e, points, mapTouches) {
return this._calculateTransform(e, points, mapTouches);
}
touchmove(e, points, mapTouches) {
if (!this._active) return;
if (this._shouldBePrevented(mapTouches.length)) {
this._map.cooperativeGestures.notifyGestureBlocked("touch_pan", e);
return;
}
e.preventDefault();
return this._calculateTransform(e, points, mapTouches);
}
touchend(e, points, mapTouches) {
this._calculateTransform(e, points, mapTouches);
if (this._active && this._shouldBePrevented(mapTouches.length)) this.reset();
}
touchcancel() {
this.reset();
}
_calculateTransform(e, points, mapTouches) {
if (mapTouches.length > 0) this._active = true;
const touches = indexTouches(mapTouches, points);
const touchPointSum = new Point(0, 0);
const touchDeltaSum = new Point(0, 0);
let touchDeltaCount = 0;
for (const identifier in touches) {
const point = touches[identifier];
const prevPoint = this._touches[identifier];
if (prevPoint) {
touchPointSum._add(point);
touchDeltaSum._add(point.sub(prevPoint));
touchDeltaCount++;
touches[identifier] = point;
}
}
this._touches = touches;
if (this._shouldBePrevented(touchDeltaCount) || !touchDeltaSum.mag()) return;
const panDelta = touchDeltaSum.div(touchDeltaCount);
this._sum._add(panDelta);
if (this._sum.mag() < this._clickTolerance) return;
return {
around: touchPointSum.div(touchDeltaCount),
panDelta
};
}
enable() {
this._enabled = true;
}
disable() {
this._enabled = false;
this.reset();
}
isEnabled() {
return this._enabled;
}
isActive() {
return this._active;
}
};
//#endregion
//#region src/ui/handler/two_fingers_touch.ts
/**
* The `TwoFingersTouchHandler`s allows the user to zoom, pitch and rotate the map using two fingers
*
*/
var TwoFingersTouchHandler = class {
/** @internal */
constructor() {
this.reset();
}
reset() {
this._active = false;
delete this._firstTwoTouches;
}
touchstart(e, points, mapTouches) {
if (this._firstTwoTouches || mapTouches.length < 2) return;
this._firstTwoTouches = [mapTouches[0].identifier, mapTouches[1].identifier];
this._start([points[0], points[1]]);
}
touchmove(e, points, mapTouches) {
if (!this._firstTwoTouches) return;
e.preventDefault();
const [idA, idB] = this._firstTwoTouches;
const a = getTouchById(mapTouches, points, idA);
const b = getTouchById(mapTouches, points, idB);
if (!a || !b) return;
const pinchAround = this._aroundCenter ? null : a.add(b).div(2);
return this._move([a, b], pinchAround, e);
}
touchend(e, points, mapTouches) {
if (!this._firstTwoTouches) return;
const [idA, idB] = this._firstTwoTouches;
const a = getTouchById(mapTouches, points, idA);
const b = getTouchById(mapTouches, points, idB);
if (a && b) return;
if (this._active) DOM.suppressClick();
this.reset();
}
touchcancel() {
this.reset();
}
/**
* Enables the "drag to pitch" interaction.
*
* @example
* ```ts
* map.touchPitch.enable();
* ```
*/
enable(options) {
this._enabled = true;
this._aroundCenter = !!options && options.around === "center";
}
/**
* Disables the "drag to pitch" interaction.
*
* @example
* ```ts
* map.touchPitch.disable();
* ```
*/
disable() {
this._enabled = false;
this.reset();
}
/**
* Returns a Boolean indicating whether the "drag to pitch" interaction is enabled.
*
* @returns `true` if the "drag to pitch" interaction is enabled.
*/
isEnabled() {
return !!this._enabled;
}
/**
* Returns a Boolean indicating whether the "drag to pitch" interaction is active, i.e. currently being used.
*
* @returns `true` if the "drag to pitch" interaction is active.
*/
isActive() {
return !!this._active;
}
};
function getTouchById(mapTouches, points, identifier) {
for (let i = 0; i < mapTouches.length; i++) if (mapTouches[i].identifier === identifier) return points[i];
}
const defaultZoomRate$2 = 1;
const defaultZoomThreshold = .1;
function getZoomDelta(distance, lastDistance) {
return Math.log(distance / lastDistance) / Math.LN2;
}
/**
* The `TwoFingersTouchHandler`s allows the user to zoom the map two fingers
*
* @group Handlers
*/
var TwoFingersTouchZoomHandler = class extends TwoFingersTouchHandler {
constructor() {
super();
this._zoomRate = defaultZoomRate$2;
this._zoomThreshold = defaultZoomThreshold;
}
/**
* Sets the zoom rate of touch gestures.
* @param zoomRate - 1 The rate used to scale touch movement to a zoom value. Set to `undefined` to restore the default.
* @example
* Slow down touch zoom
* ```ts
* map.touchZoomRotate.setZoomRate(0.5);
* ```
*/
setZoomRate(zoomRate) {
this._zoomRate = zoomRate ?? defaultZoomRate$2;
}
/**
* Sets the threshold before a pinch gesture starts zooming.
* @param zoomThreshold - 0.1 The minimum zoom delta before the pinch gesture becomes active. Set to `undefined` to restore the default.
* @example
* Make pinch zoom less sensitive
* ```ts
* map.touchZoomRotate.setZoomThreshold(0.3);
* ```
*/
setZoomThreshold(zoomThreshold) {
this._zoomThreshold = zoomThreshold ?? defaultZoomThreshold;
}
reset() {
super.reset();
delete this._distance;
delete this._startDistance;
}
_start(points) {
this._startDistance = this._distance = points[0].dist(points[1]);
}
_move(points, pinchAround) {
const lastDistance = this._distance;
this._distance = points[0].dist(points[1]);
if (!this._active && Math.abs(getZoomDelta(this._distance, this._startDistance)) < this._zoomThreshold) return;
this._active = true;
return {
zoomDelta: getZoomDelta(this._distance, lastDistance) * this._zoomRate,
pinchAround
};
}
};
const ROTATION_THRESHOLD = 25;
function getBearingDelta(a, b) {
return a.angleWith(b) * 180 / Math.PI;
}
/**
* The `TwoFingersTouchHandler`s allows the user to rotate the map two fingers
*
* @group Handlers
*/
var TwoFingersTouchRotateHandler = class extends TwoFingersTouchHandler {
reset() {
super.reset();
delete this._minDiameter;
delete this._startVector;
delete this._vector;
}
_start(points) {
this._startVector = this._vector = points[0].sub(points[1]);
this._minDiameter = points[0].dist(points[1]);
}
_move(points, pinchAround, _e) {
const lastVector = this._vector;
this._vector = points[0].sub(points[1]);
if (!this._active && this._isBelowThreshold(this._vector)) return;
this._active = true;
return {
bearingDelta: getBearingDelta(this._vector, lastVector),
pinchAround
};
}
_isBelowThreshold(vector) {
this._minDiameter = Math.min(this._minDiameter, vector.mag());
const circumference = Math.PI * this._minDiameter;
const threshold = ROTATION_THRESHOLD / circumference * 360;
const bearingDeltaSinceStart = getBearingDelta(vector, this._startVector);
return Math.abs(bearingDeltaSinceStart) < threshold;
}
};
function isVertical(vector) {
return Math.abs(vector.y) > Math.abs(vector.x);
}
const ALLOWED_SINGLE_TOUCH_TIME = 100;
/**
* The `TwoFingersTouchPitchHandler` allows the user to pitch the map by dragging up and down with two fingers.
*
* @group Handlers
*/
var TwoFingersTouchPitchHandler = class extends TwoFingersTouchHandler {
constructor(map) {
super();
this._currentTouchCount = 0;
this._map = map;
}
reset() {
super.reset();
this._valid = void 0;
delete this._firstMove;
delete this._lastPoints;
}
touchstart(e, points, mapTouches) {
super.touchstart(e, points, mapTouches);
this._currentTouchCount = mapTouches.length;
}
_start(points) {
this._lastPoints = points;
if (isVertical(points[0].sub(points[1]))) this._valid = false;
}
_move(points, center, e) {
if (this._map.cooperativeGestures.isEnabled() && this._currentTouchCount < 3) return;
const vectorA = points[0].sub(this._lastPoints[0]);
const vectorB = points[1].sub(this._lastPoints[1]);
this._valid = this.gestureBeginsVertically(vectorA, vectorB, e.timeStamp);
if (!this._valid) return;
this._lastPoints = points;
this._active = true;
return { pitchDelta: (vectorA.y + vectorB.y) / 2 * -.5 };
}
gestureBeginsVertically(vectorA, vectorB, timeStamp) {
if (this._valid !== void 0) return this._valid;
const threshold = 2;
const movedA = vectorA.mag() >= threshold;
const movedB = vectorB.mag() >= threshold;
if (!movedA && !movedB) return;
if (!movedA || !movedB) {
if (this._firstMove === void 0) this._firstMove = timeStamp;
if (timeStamp - this._firstMove < ALLOWED_SINGLE_TOUCH_TIME) return;
else return false;
}
const isSameDirection = vectorA.y > 0 === vectorB.y > 0;
return isVertical(vectorA) && isVertical(vectorB) && isSameDirection;
}
};
//#endregion
//#region src/ui/handler/keyboard.ts
const defaultOptions$5 = {
panStep: 100,
bearingStep: 15,
pitchStep: 10
};
/**
* The `KeyboardHandler` allows the user to zoom, rotate, and pan the map using
* the following keyboard shortcuts:
*
* - `=` / `+`: Increase the zoom level by 1.
* - `Shift-=` / `Shift-+`: Increase the zoom level by 2.
* - `-`: Decrease the zoom level by 1.
* - `Shift--`: Decrease the zoom level by 2.
* - Arrow keys: Pan by 100 pixels.
* - `Shift+⇢`: Increase the rotation by 15 degrees.
* - `Shift+⇠`: Decrease the rotation by 15 degrees.
* - `Shift+⇡`: Increase the pitch by 10 degrees.
* - `Shift+⇣`: Decrease the pitch by 10 degrees.
*
* @group Handlers
*/
var KeyboardHandler = class {
/** @internal */
constructor(map, transformProvider) {
this._tr = transformProvider;
const stepOptions = defaultOptions$5;
this._panStep = stepOptions.panStep;
this._bearingStep = stepOptions.bearingStep;
this._pitchStep = stepOptions.pitchStep;
this._rotationDisabled = false;
}
reset() {
this._active = false;
}
keydown(e) {
if (e.altKey || e.ctrlKey || e.metaKey) return;
let zoomDir = 0;
let bearingDir = 0;
let pitchDir = 0;
let xDir = 0;
let yDir = 0;
switch (e.keyCode) {
case 61:
case 107:
case 171:
case 187:
zoomDir = 1;
break;
case 189:
case 109:
case 173:
zoomDir = -1;
break;
case 37:
if (e.shiftKey) bearingDir = -1;
else {
e.preventDefault();
xDir = -1;
}
break;
case 39:
if (e.shiftKey) bearingDir = 1;
else {
e.preventDefault();
xDir = 1;
}
break;
case 38:
if (e.shiftKey) pitchDir = 1;
else {
e.preventDefault();
yDir = -1;
}
break;
case 40:
if (e.shiftKey) pitchDir = -1;
else {
e.preventDefault();
yDir = 1;
}
break;
default: return;
}
if (this._rotationDisabled) {
bearingDir = 0;
pitchDir = 0;
}
return { cameraAnimation: (map) => {
const tr = this._tr;
map.easeTo({
duration: 300,
easeId: "keyboardHandler",
easing: easeOut,
zoom: zoomDir ? evaluateZoomSnap(tr.zoom + zoomDir * (e.shiftKey ? 2 : 1), map.getZoomSnap()) : tr.zoom,
bearing: tr.bearing + bearingDir * this._bearingStep,
pitch: tr.pitch + pitchDir * this._pitchStep,
offset: [-xDir * this._panStep, -yDir * this._panStep],
center: tr.center
}, { originalEvent: e });
} };
}
/**
* Enables the "keyboard rotate and zoom" interaction.
*
* @example
* ```ts
* map.keyboard.enable();
* ```
*/
enable() {
this._enabled = true;
}
/**
* Disables the "keyboard rotate and zoom" interaction.
*
* @example
* ```ts
* map.keyboard.disable();
* ```
*/
disable() {
this._enabled = false;
this.reset();
}
/**
* Returns a Boolean indicating whether the "keyboard rotate and zoom"
* interaction is enabled.
*
* @returns `true` if the "keyboard rotate and zoom"
* interaction is enabled.
*/
isEnabled() {
return this._enabled;
}
/**
* Returns true if the handler is enabled and has detected the start of a
* zoom/rotate gesture.
*
* @returns `true` if the handler is enabled and has detected the
* start of a zoom/rotate gesture.
*/
isActive() {
return this._active;
}
/**
* Disables the "keyboard pan/rotate" interaction, leaving the
* "keyboard zoom" interaction enabled.
*
* @example
* ```ts
* map.keyboard.disableRotation();
* ```
*/
disableRotation() {
this._rotationDisabled = true;
}
/**
* Enables the "keyboard pan/rotate" interaction.
*
* @example
* ```ts
* map.keyboard.enable();
* map.keyboard.enableRotation();
* ```
*/
enableRotation() {
this._rotationDisabled = false;
}
};
function easeOut(t) {
return t * (2 - t);
}
//#endregion
//#region src/ui/handler/scroll_zoom.ts
const wheelZoomDelta = 4.000244140625;
const defaultZoomRate$1 = 1 / 100;
const wheelZoomRate = 1 / 450;
const maxScalePerFrame = 2;
const wheelEventTimeDiffAdjustment = 5;
/**
* The `ScrollZoomHandler` allows the user to zoom the map by scrolling.
*
* @group Handlers
*/
var ScrollZoomHandler = class {
/** @internal */
constructor(map, triggerRenderFrame, transformProvider) {
this._onTimeout = (initialEvent) => {
this._type = "wheel";
this._delta -= this._lastValue;
if (!this._active) this._start(initialEvent);
};
this._map = map;
this._tr = transformProvider;
this._triggerRenderFrame = triggerRenderFrame;
this._delta = 0;
this._defaultZoomRate = defaultZoomRate$1;
this._wheelZoomRate = wheelZoomRate;
}
/**
* Set the zoom rate of a trackpad
* @param zoomRate - 1/100 The rate used to scale trackpad movement to a zoom value.
* @example
* Speed up trackpad zoom
* ```ts
* map.scrollZoom.setZoomRate(1/25);
* ```
*/
setZoomRate(zoomRate) {
this._defaultZoomRate = zoomRate;
}
/**
* Set the zoom rate of a mouse wheel
* @param wheelZoomRate - 1/450 The rate used to scale mouse wheel movement to a zoom value.
* @example
* Slow down zoom of mouse wheel
* ```ts
* map.scrollZoom.setWheelZoomRate(1/600);
* ```
*/
setWheelZoomRate(wheelZoomRate) {
this._wheelZoomRate = wheelZoomRate;
}
/**
* Returns a Boolean indicating whether the "scroll to zoom" interaction is enabled.
* @returns `true` if the "scroll to zoom" interaction is enabled.
*/
isEnabled() {
return !!this._enabled;
}
isActive() {
return !!this._active || this._finishTimeout !== void 0;
}
isZooming() {
return !!this._zooming;
}
/**
* Enables the "scroll to zoom" interaction.
*
* @param options - Options object.
* @example
* ```ts
* map.scrollZoom.enable();
* map.scrollZoom.enable({ around: 'center' })
* ```
*/
enable(options) {
if (this.isEnabled()) return;
this._enabled = true;
this._aroundCenter = !!options && options.around === "center";
}
/**
* Disables the "scroll to zoom" interaction.
*
* @example
* ```ts
* map.scrollZoom.disable();
* ```
*/
disable() {
if (!this.isEnabled()) return;
this._enabled = false;
}
/**
* Determines whether or not the gesture is blocked due to cooperativeGestures.
*/
_shouldBePrevented(e) {
if (!this._map.cooperativeGestures.isEnabled()) return false;
return !(e.ctrlKey || this._map.cooperativeGestures.isBypassed(e));
}
wheel(e) {
if (!this.isEnabled()) return;
if (this._shouldBePrevented(e)) {
this._map.cooperativeGestures.notifyGestureBlocked("wheel_zoom", e);
return;
}
let value = e.deltaMode === WheelEvent.DOM_DELTA_LINE ? e.deltaY * 40 : e.deltaY;
const currentTime = now(), timeDelta = currentTime - (this._lastWheelEventTime || 0);
this._lastWheelEventTime = currentTime;
if (value !== 0 && value % wheelZoomDelta === 0) this._type = "wheel";
else if (value !== 0 && Math.abs(value) < 4) this._type = "trackpad";
else if (timeDelta > 400) {
this._type = null;
this._lastValue = value;
this._timeout = setTimeout(this._onTimeout, 40, e);
} else if (!this._type) {
this._type = Math.abs(timeDelta * value) < 200 ? "trackpad" : "wheel";
if (this._timeout) {
clearTimeout(this._timeout);
this._timeout = null;
value += this._lastValue;
}
}
if (e.shiftKey && value) value = value / 4;
if (this._type) {
this._lastWheelEvent = e;
this._delta -= value;
if (!this._active) this._start(e);
}
e.preventDefault();
}
_start(e) {
if (!this._delta) return;
this._needsRerender = false;
this._active = true;
if (!this.isZooming()) this._zooming = true;
if (this._finishTimeout) {
clearTimeout(this._finishTimeout);
delete this._finishTimeout;
}
const pos = DOM.mousePos(this._map.getCanvas(), e);
const tr = this._tr;
if (this._aroundCenter) this._aroundPoint = tr.transform.locationToScreenPoint(LngLat.convert(tr.center));
else this._aroundPoint = pos;
if (!this._needsRerender) {
this._needsRerender = true;
this._triggerRenderFrame();
}
}
renderFrame() {
if (!this._needsRerender) return;
this._needsRerender = false;
if (!this.isActive()) return;
const tr = this._tr.transform;
if (typeof this._lastExpectedZoom === "number") {
const externalZoomChange = tr.zoom - this._lastExpectedZoom;
if (typeof this._startZoom === "number") this._startZoom += externalZoomChange;
if (typeof this._targetZoom === "number") this._targetZoom += externalZoomChange;
}
if (this._delta !== 0) {
const zoomRate = this._type === "wheel" && Math.abs(this._delta) > wheelZoomDelta ? this._wheelZoomRate : this._defaultZoomRate;
let scale = maxScalePerFrame / (1 + Math.exp(-Math.abs(this._delta * zoomRate)));
if (this._delta < 0 && scale !== 0) scale = 1 / scale;
const fromScale = typeof this._targetZoom !== "number" ? tr.scale : zoomScale(this._targetZoom);
const target = tr.applyConstrain(tr.getCameraLngLat(), scaleZoom(fromScale * scale)).zoom;
const zoomSnap = this._map.getZoomSnap();
if (this._type === "wheel" && zoomSnap > 0) {
const currentSnapped = evaluateZoomSnap(tr.zoom, zoomSnap);
this._targetZoom = evaluateZoomSnap(target, zoomSnap, target - currentSnapped);
} else this._targetZoom = target;
if (this._type === "wheel") {
this._startZoom = tr.zoom;
this._easing = this._smoothOutEasing(200);
}
this._delta = 0;
}
const targetZoom = typeof this._targetZoom !== "number" ? tr.zoom : this._targetZoom;
const startZoom = this._startZoom;
const easing = this._easing;
let finished = false;
let zoom;
if (this._type === "wheel" && startZoom && easing) {
const lastWheelEventTimeDiff = now() - this._lastWheelEventTime;
const t = Math.min((lastWheelEventTimeDiff + wheelEventTimeDiffAdjustment) / 200, 1);
const k = easing(t);
zoom = interpolateFactory.number(startZoom, targetZoom, k);
if (t < 1) this._needsRerender = true;
else finished = true;
} else {
zoom = targetZoom;
finished = true;
}
this._active = true;
if (finished) {
this._active = false;
this._finishTimeout = setTimeout(() => {
this._zooming = false;
this._triggerRenderFrame();
delete this._targetZoom;
delete this._lastExpectedZoom;
delete this._finishTimeout;
}, 200);
}
this._lastExpectedZoom = zoom;
return {
noInertia: true,
needsRenderFrame: !finished,
zoomDelta: zoom - tr.zoom,
around: this._aroundPoint,
originalEvent: this._lastWheelEvent
};
}
_smoothOutEasing(duration) {
let easing = defaultEasing;
if (this._prevEase) {
const currentEase = this._prevEase;
const t = (now() - currentEase.start) / currentEase.duration;
const speed = currentEase.easing(t + .01) - currentEase.easing(t);
const x = .27 / Math.sqrt(speed * speed + 1e-4) * .01;
const y = Math.sqrt(.0729 - x * x);
easing = bezier(x, y, .25, 1);
}
this._prevEase = {
start: now(),
duration,
easing
};
return easing;
}
reset() {
this._active = false;
this._zooming = false;
delete this._targetZoom;
delete this._lastExpectedZoom;
if (this._finishTimeout) {
clearTimeout(this._finishTimeout);
delete this._finishTimeout;
}
}
};
//#endregion
//#region src/ui/handler/shim/dblclick_zoom.ts
/**
* The `DoubleClickZoomHandler` allows the user to zoom the map at a point by
* double clicking or double tapping.
*
* @group Handlers
*/
var DoubleClickZoomHandler = class {
/** @internal */
constructor(clickZoom, TapZoom) {
this._clickZoom = clickZoom;
this._tapZoom = TapZoom;
}
/**
* Enables the "double click to zoom" interaction.
*
* @example
* ```ts
* map.doubleClickZoom.enable();
* ```
*/
enable() {
this._clickZoom.enable();
this._tapZoom.enable();
}
/**
* Disables the "double click to zoom" interaction.
*
* @example
* ```ts
* map.doubleClickZoom.disable();
* ```
*/
disable() {
this._clickZoom.disable();
this._tapZoom.disable();
}
/**
* Returns a Boolean indicating whether the "double click to zoom" interaction is enabled.
*
* @returns `true` if the "double click to zoom" interaction is enabled.
*/
isEnabled() {
return this._clickZoom.isEnabled() && this._tapZoom.isEnabled();
}
/**
* Returns a Boolean indicating whether the "double click to zoom" interaction is active, i.e. currently being used.
*
* @returns `true` if the "double click to zoom" interaction is active.
*/
isActive() {
return this._clickZoom.isActive() || this._tapZoom.isActive();
}
};
//#endregion
//#region src/ui/handler/click_zoom.ts
/**
* The `ClickZoomHandler` allows the user to zoom the map at a point by double clicking
* It is used by other handlers
*/
var ClickZoomHandler = class {
/** @internal */
constructor(map, transformProvider) {
this._tr = transformProvider;
this.reset();
}
reset() {
this._active = false;
}
dblclick(e, point) {
e.preventDefault();
return { cameraAnimation: (map) => {
map.easeTo({
duration: 300,
zoom: evaluateZoomSnap(this._tr.zoom + (e.shiftKey ? -1 : 1), map.getZoomSnap()),
around: this._tr.unproject(point)
}, { originalEvent: e });
} };
}
enable() {
this._enabled = true;
}
disable() {
this._enabled = false;
this.reset();
}
isEnabled() {
return this._enabled;
}
isActive() {
return this._active;
}
};
//#endregion
//#region src/ui/handler/tap_drag_zoom.ts
const defaultZoomRate = 1;
/**
* A `TapDragZoomHandler` allows the user to zoom the map at a point by double tapping. It also allows the user pan the map by dragging.
*/
var TapDragZoomHandler = class {
constructor() {
this._tap = new TapRecognizer({
numTouches: 1,
numTaps: 1
});
this._zoomRate = defaultZoomRate;
this.reset();
}
setZoomRate(zoomRate) {
this._zoomRate = zoomRate ?? defaultZoomRate;
}
reset() {
this._active = false;
delete this._swipePoint;
delete this._swipeTouch;
delete this._tapTime;
delete this._tapPoint;
this._tap.reset();
}
touchstart(e, points, mapTouches) {
if (this._swipePoint) return;
if (!this._tapTime) this._tap.touchstart(e, points, mapTouches);
else {
const swipePoint = points[0];
const soonEnough = e.timeStamp - this._tapTime < 500;
const closeEnough = this._tapPoint.dist(swipePoint) < 30;
if (!soonEnough || !closeEnough) this.reset();
else if (mapTouches.length > 0) {
this._swipePoint = swipePoint;
this._swipeTouch = mapTouches[0].identifier;
}
}
}
touchmove(e, points, mapTouches) {
if (!this._tapTime) this._tap.touchmove(e, points, mapTouches);
else if (this._swipePoint) {
if (mapTouches[0].identifier !== this._swipeTouch) return;
const newSwipePoint = points[0];
const dist = newSwipePoint.y - this._swipePoint.y;
this._swipePoint = newSwipePoint;
e.preventDefault();
this._active = true;
return { zoomDelta: dist / 128 * this._zoomRate };
}
}
touchend(e, points, mapTouches) {
if (!this._tapTime) {
const point = this._tap.touchend(e, points, mapTouches);
if (point) {
this._tapTime = e.timeStamp;
this._tapPoint = point;
}
} else if (this._swipePoint) {
if (mapTouches.length === 0) this.reset();
}
}
touchcancel() {
this.reset();
}
enable() {
this._enabled = true;
}
disable() {
this._enabled = false;
this.reset();
}
isEnabled() {
return this._enabled;
}
isActive() {
return this._active;
}
};
//#endregion
//#region src/ui/handler/shim/drag_pan.ts
/**
* The `DragPanHandler` allows the user to pan the map by clicking and dragging
* the cursor.
*
* @group Handlers
*/
var DragPanHandler = class {
/** @internal */
constructor(el, mousePan, touchPan) {
this._el = el;
this._mousePan = mousePan;
this._touchPan = touchPan;
}
/**
* Enables the "drag to pan" interaction.
*
* @param options - Options object
* @example
* ```ts
* map.dragPan.enable();
* map.dragPan.enable({
* linearity: 0.3,
* easing: bezier(0, 0, 0.3, 1),
* maxSpeed: 1400,
* deceleration: 2500,
* });
* ```
*/
enable(options) {
this._inertiaOptions = options || {};
this._mousePan.enable();
this._touchPan.enable();
this._el.classList.add("maplibregl-touch-drag-pan");
}
/**
* Disables the "drag to pan" interaction.
*
* @example
* ```ts
* map.dragPan.disable();
* ```
*/
disable() {
this._mousePan.disable();
this._touchPan.disable();
this._el.classList.remove("maplibregl-touch-drag-pan");
}
/**
* Returns a Boolean indicating whether the "drag to pan" interaction is enabled.
*
* @returns `true` if the "drag to pan" interaction is enabled.
*/
isEnabled() {
return this._mousePan.isEnabled() && this._touchPan.isEnabled();
}
/**
* Returns a Boolean indicating whether the "drag to pan" interaction is active, i.e. currently being used.
*
* @returns `true` if the "drag to pan" interaction is active.
*/
isActive() {
return this._mousePan.isActive() || this._touchPan.isActive();
}
};
//#endregion
//#region src/ui/handler/shim/drag_rotate.ts
/**
* The `DragRotateHandler` allows the user to rotate the map by clicking and
* dragging the cursor while holding the right mouse button or `ctrl` key.
*
* @group Handlers
*/
var DragRotateHandler = class {
/** @internal */
constructor(options, mouseRotate, mousePitch, mouseRoll) {
this._pitchWithRotate = options.pitchWithRotate;
this._rollEnabled = options.rollEnabled;
this._mouseRotate = mouseRotate;
this._mousePitch = mousePitch;
this._mouseRoll = mouseRoll;
}
/**
* Enables the "drag to rotate" interaction.
*
* @example
* ```ts
* map.dragRotate.enable();
* ```
*/
enable() {
this._mouseRotate.enable();
if (this._pitchWithRotate) this._mousePitch.enable();
if (this._rollEnabled) this._mouseRoll.enable();
}
/**
* Disables the "drag to rotate" interaction.
*
* @example
* ```ts
* map.dragRotate.disable();
* ```
*/
disable() {
this._mouseRotate.disable();
this._mousePitch.disable();
this._mouseRoll.disable();
}
/**
* Returns a Boolean indicating whether the "drag to rotate" interaction is enabled.
*
* @returns `true` if the "drag to rotate" interaction is enabled.
*/
isEnabled() {
return this._mouseRotate.isEnabled() && (!this._pitchWithRotate || this._mousePitch.isEnabled()) && (!this._rollEnabled || this._mouseRoll.isEnabled());
}
/**
* Returns a Boolean indicating whether the "drag to rotate" interaction is active, i.e. currently being used.
*
* @returns `true` if the "drag to rotate" interaction is active.
*/
isActive() {
return this._mouseRotate.isActive() || this._mousePitch.isActive() || this._mouseRoll.isActive();
}
};
//#endregion
//#region src/ui/handler/shim/two_fingers_touch.ts
/**
* The `TwoFingersTouchZoomRotateHandler` allows the user to zoom and rotate the map by
* pinching on a touchscreen.
*
* They can zoom with one finger by double tapping and dragging. On the second tap,
* hold the finger down and drag up or down to zoom in or out.
*
* @group Handlers
*/
var TwoFingersTouchZoomRotateHandler = class {
/** @internal */
constructor(el, touchZoom, touchRotate, tapDragZoom) {
this._el = el;
this._touchZoom = touchZoom;
this._touchRotate = touchRotate;
this._tapDragZoom = tapDragZoom;
this._rotationDisabled = false;
this._enabled = true;
}
/**
* Enables the "pinch to rotate and zoom" interaction.
*
* @param options - Options object.
*
* @example
* ```ts
* map.touchZoomRotate.enable();
* map.touchZoomRotate.enable({ around: 'center' });
* ```
*/
enable(options) {
this._touchZoom.enable(options);
if (!this._rotationDisabled) this._touchRotate.enable(options);
this._tapDragZoom.enable();
this._el.classList.add("maplibregl-touch-zoom-rotate");
}
/**
* Disables the "pinch to rotate and zoom" interaction.
*
* @example
* ```ts
* map.touchZoomRotate.disable();
* ```
*/
disable() {
this._touchZoom.disable();
this._touchRotate.disable();
this._tapDragZoom.disable();
this._el.classList.remove("maplibregl-touch-zoom-rotate");
}
/**
* Returns a Boolean indicating whether the "pinch to rotate and zoom" interaction is enabled.
*
* @returns `true` if the "pinch to rotate and zoom" interaction is enabled.
*/
isEnabled() {
return this._touchZoom.isEnabled() && (this._rotationDisabled || this._touchRotate.isEnabled()) && this._tapDragZoom.isEnabled();
}
/**
* Returns true if the handler is enabled and has detected the start of a zoom/rotate gesture.
*
* @returns `true` if the handler is active, `false` otherwise
*/
isActive() {
return this._touchZoom.isActive() || this._touchRotate.isActive() || this._tapDragZoom.isActive();
}
/**
* Sets the zoom rate of touch gestures.
* @param zoomRate - 1 The rate used to scale touch movement to a zoom value. Set to `undefined` to restore the default.
* @example
* Slow down touch zoom
* ```ts
* map.touchZoomRotate.setZoomRate(0.5);
* ```
*/
setZoomRate(zoomRate) {
this._touchZoom.setZoomRate(zoomRate);
this._tapDragZoom.setZoomRate(zoomRate);
}
/**
* Sets the threshold before a pinch gesture starts zooming.
* @param zoomThreshold - 0.1 The minimum zoom delta before the pinch gesture becomes active. Set to `undefined` to restore the default.
* @example
* Make pinch zoom less sensitive
* ```ts
* map.touchZoomRotate.setZoomThreshold(0.3);
* ```
*/
setZoomThreshold(zoomThreshold) {
this._touchZoom.setZoomThreshold(zoomThreshold);
}
/**
* Disables the "pinch to rotate" interaction, leaving the "pinch to zoom"
* interaction enabled.
*
* @example
* ```ts
* map.touchZoomRotate.disableRotation();
* ```
*/
disableRotation() {
this._rotationDisabled = true;
this._touchRotate.disable();
}
/**
* Enables the "pinch to rotate" interaction.
*
* @example
* ```ts
* map.touchZoomRotate.enable();
* map.touchZoomRotate.enableRotation();
* ```
*/
enableRotation() {
this._rotationDisabled = false;
if (this._touchZoom.isEnabled()) this._touchRotate.enable();
}
};
//#endregion
//#region src/ui/handler/cooperative_gestures.ts
/**
* A `CooperativeGestureHandler` is a control that adds cooperative gesture info when user tries to zoom in/out.
*
* When the CooperativeGestureHandler blocks a gesture, it will emit a `cooperativegestureprevented` event.
*
* @group Handlers
*
* @example
* ```ts
* const map = new Map({
* cooperativeGestures: true
* });
* ```
* @see [Example: cooperative gestures](https://maplibre.org/maplibre-gl-js/docs/examples/cooperative-gestures/)
**/
var CooperativeGesturesHandler = class {
constructor(map, options) {
this._bypassKey = navigator.userAgent.includes("Mac") ? "metaKey" : "ctrlKey";
this._map = map;
this._options = options;
this._enabled = false;
}
isActive() {
return false;
}
reset() {}
_setupUI() {
if (this._container) return;
const mapCanvasContainer = this._map.getCanvasContainer();
mapCanvasContainer.classList.add("maplibregl-cooperative-gestures");
this._container = DOM.create("div", "maplibregl-cooperative-gesture-screen", mapCanvasContainer);
let desktopMessage = this._map._getUIString("CooperativeGesturesHandler.WindowsHelpText");
if (this._bypassKey === "metaKey") desktopMessage = this._map._getUIString("CooperativeGesturesHandler.MacHelpText");
const mobileMessage = this._map._getUIString("CooperativeGesturesHandler.MobileHelpText");
const desktopDiv = document.createElement("div");
desktopDiv.className = "maplibregl-desktop-message";
desktopDiv.textContent = desktopMessage;
this._container.appendChild(desktopDiv);
const mobileDiv = document.createElement("div");
mobileDiv.className = "maplibregl-mobile-message";
mobileDiv.textContent = mobileMessage;
this._container.appendChild(mobileDiv);
this._container.setAttribute("aria-hidden", "true");
}
_destroyUI() {
if (this._container) {
this._container.remove();
this._map.getCanvasContainer().classList.remove("maplibregl-cooperative-gestures");
}
delete this._container;
}
enable() {
this._setupUI();
this._enabled = true;
}
disable() {
this._enabled = false;
this._destroyUI();
}
isEnabled() {
return this._enabled;
}
isBypassed(event) {
return event[this._bypassKey];
}
notifyGestureBlocked(gestureType, originalEvent) {
if (!this._enabled) return;
this._map.fire(new MapLibreEvent("cooperativegestureprevented", {
gestureType,
originalEvent
}));
this._container.classList.add("maplibregl-show");
setTimeout(() => {
this._container.classList.remove("maplibregl-show");
}, 100);
}
};
//#endregion
//#region src/ui/handler/transform-provider.ts
/**
* @internal
* Shared utilities for the Handler classes to access the correct camera state.
* If Camera.transformCameraUpdate is specified or terrain is enabled, the
* "desired state" of camera may differ from the state used for rendering. The
* handlers need the "desired state" to track accumulated changes.
*/
var TransformProvider = class {
constructor(camera) {
this._camera = camera;
}
get transform() {
return this._camera._requestedCameraState || this._camera.transform;
}
get center() {
return {
lng: this.transform.center.lng,
lat: this.transform.center.lat
};
}
get zoom() {
return this.transform.zoom;
}
get pitch() {
return this.transform.pitch;
}
get bearing() {
return this.transform.bearing;
}
unproject(point) {
return this.transform.screenPointToLocation(Point.convert(point), this._camera.terrain);
}
};
//#endregion
//#region src/ui/handler_manager.ts
const isMoving = (p) => p.zoom || p.drag || p.roll || p.pitch || p.rotate;
/**
* A terrain gesture's anchor plane must stay below this fraction of the camera's
* altitude over the center-elevation plane, or the ray-plane solve degenerates.
*/
const TERRAIN_ANCHOR_MAX_CAMERA_ALTITUDE_FRACTION = .9;
var RenderFrameEvent = class extends Event {};
function hasChange(result) {
return result.panDelta?.mag() || result.zoomDelta || result.bearingDelta || result.pitchDelta || result.rollDelta;
}
var HandlerManager = class {
/**
* @internal
* The document that contains the map container element, for cross-window support.
*/
get _ownerDocument() {
return this._el?.ownerDocument || document;
}
/**
* @internal
* The window that contains the map container element, for cross-window support.
*/
get _ownerWindow() {
return this._el?.ownerDocument?.defaultView || window;
}
constructor(map, camera, options) {
this._terrainGestureAnchorElevation = null;
this.handleWindowEvent = (e) => {
this.handleEvent(e, `${e.type}Window`);
};
this.handleEvent = (e, eventName) => {
if (e.type === "blur") {
this.stop(true);
return;
}
this._updatingCamera = true;
const inputEvent = e.type === "renderFrame" ? void 0 : e;
const mergedHandlerResult = { needsRenderFrame: false };
const eventsInProgress = {};
const activeHandlers = {};
for (const { handlerName, handler, allowed } of this._handlers) {
if (!handler.isEnabled()) continue;
let data;
if (this._blockedByActive(activeHandlers, allowed, handlerName)) handler.reset();
else if (handler[eventName || e.type]) {
if (isPointableEvent(e, eventName || e.type)) {
const point = DOM.mousePos(this._map.getCanvas(), e);
data = handler[eventName || e.type](e, point);
} else if (isTouchableEvent(e, eventName || e.type)) {
const eventTouches = e.touches;
const mapTouches = this._getMapTouches(eventTouches);
const points = DOM.touchPos(this._map.getCanvas(), mapTouches);
data = handler[eventName || e.type](e, points, mapTouches);
} else if (!isTouchableOrPointableType(eventName || e.type)) data = handler[eventName || e.type](e);
this.mergeHandlerResult(mergedHandlerResult, eventsInProgress, data, handlerName, inputEvent);
if (data?.needsRenderFrame) this._triggerRenderFrame();
}
if (data || handler.isActive()) activeHandlers[handlerName] = handler;
}
const deactivatedHandlers = {};
for (const name in this._previousActiveHandlers) if (!activeHandlers[name]) deactivatedHandlers[name] = inputEvent;
this._previousActiveHandlers = activeHandlers;
if (Object.keys(deactivatedHandlers).length || hasChange(mergedHandlerResult)) {
this._changes.push([
mergedHandlerResult,
eventsInProgress,
deactivatedHandlers
]);
this._triggerRenderFrame();
}
if (Object.keys(activeHandlers).length || hasChange(mergedHandlerResult)) this._camera.stop(true);
this._updatingCamera = false;
const { cameraAnimation } = mergedHandlerResult;
if (cameraAnimation) {
this._inertia.clear();
this._fireEvents({}, {}, true);
this._changes = [];
cameraAnimation(this._map);
}
};
this._map = map;
this._camera = camera;
this._transformProvider = new TransformProvider(this._camera);
this._el = this._map.getCanvasContainer();
this._handlers = [];
this._handlersById = {};
this._changes = [];
this._inertia = new HandlerInertia(map);
this._bearingSnap = options.bearingSnap;
this._previousActiveHandlers = {};
this._eventsInProgress = {};
this._addDefaultHandlers(options);
const el = this._el;
this._listeners = [
[
el,
"touchstart",
{ passive: true }
],
[
el,
"touchmove",
{ passive: false }
],
[
el,
"touchend",
void 0
],
[
el,
"touchcancel",
void 0
],
[
el,
"mousedown",
void 0
],
[
el,
"mousemove",
void 0
],
[
el,
"mouseup",
void 0
],
[
this._ownerDocument,
"mousemove",
{ capture: true }
],
[
this._ownerDocument,
"mouseup",
void 0
],
[
el,
"mouseover",
void 0
],
[
el,
"mouseout",
void 0
],
[
el,
"dblclick",
void 0
],
[
el,
"click",
void 0
],
[
el,
"keydown",
{ capture: false }
],
[
el,
"keyup",
void 0
],
[
el,
"wheel",
{ passive: false }
],
[
el,
"contextmenu",
void 0
],
[
this._ownerWindow,
"blur",
void 0
]
];
for (const [target, type, listenerOptions] of this._listeners) target.addEventListener(type, target === this._ownerDocument ? this.handleWindowEvent : this.handleEvent, listenerOptions);
}
destroy() {
for (const [target, type, listenerOptions] of this._listeners) target.removeEventListener(type, target === this._ownerDocument ? this.handleWindowEvent : this.handleEvent, listenerOptions);
}
_addDefaultHandlers(options) {
const map = this._map;
const el = map.getCanvasContainer();
this._add("mapEvent", new MapEventHandler(map, options));
const boxZoom = map.boxZoom = new BoxZoomHandler(map, options, this._transformProvider);
this._add("boxZoom", boxZoom);
if (options.interactive && options.boxZoom) boxZoom.enable();
const cooperativeGestures = map.cooperativeGestures = new CooperativeGesturesHandler(map, options.cooperativeGestures);
this._add("cooperativeGestures", cooperativeGestures);
if (options.cooperativeGestures) cooperativeGestures.enable();
const tapZoom = new TapZoomHandler(map, this._transformProvider);
const clickZoom = new ClickZoomHandler(map, this._transformProvider);
map.doubleClickZoom = new DoubleClickZoomHandler(clickZoom, tapZoom);
this._add("tapZoom", tapZoom);
this._add("clickZoom", clickZoom);
if (options.interactive && options.doubleClickZoom) map.doubleClickZoom.enable();
const tapDragZoom = new TapDragZoomHandler();
this._add("tapDragZoom", tapDragZoom);
const touchPitch = map.touchPitch = new TwoFingersTouchPitchHandler(map);
this._add("touchPitch", touchPitch);
if (options.interactive && options.touchPitch) map.touchPitch.enable(options.touchPitch);
const getCenter = () => map.project(map.getCenter());
const mouseRotate = generateMouseRotationHandler(options, getCenter);
const mousePitch = generateMousePitchHandler(options);
const mouseRoll = generateMouseRollHandler(options, getCenter);
map.dragRotate = new DragRotateHandler(options, mouseRotate, mousePitch, mouseRoll);
this._add("mouseRotate", mouseRotate, ["mousePitch"]);
this._add("mousePitch", mousePitch, ["mouseRotate", "mouseRoll"]);
this._add("mouseRoll", mouseRoll, ["mousePitch"]);
if (options.interactive && options.dragRotate) map.dragRotate.enable();
const mousePan = generateMousePanHandler(options);
const touchPan = new TouchPanHandler(options, map);
map.dragPan = new DragPanHandler(el, mousePan, touchPan);
this._add("mousePan", mousePan);
this._add("touchPan", touchPan, ["touchZoom", "touchRotate"]);
if (options.interactive && options.dragPan) map.dragPan.enable(options.dragPan);
const touchRotate = new TwoFingersTouchRotateHandler();
const touchZoom = new TwoFingersTouchZoomHandler();
map.touchZoomRotate = new TwoFingersTouchZoomRotateHandler(el, touchZoom, touchRotate, tapDragZoom);
this._add("touchRotate", touchRotate, ["touchPan", "touchZoom"]);
this._add("touchZoom", touchZoom, ["touchPan", "touchRotate"]);
if (options.interactive && options.touchZoomRotate) map.touchZoomRotate.enable(options.touchZoomRotate);
this._add("blockableMapEvent", new BlockableMapEventHandler(map));
const scrollZoom = map.scrollZoom = new ScrollZoomHandler(map, () => this._triggerRenderFrame(), this._transformProvider);
this._add("scrollZoom", scrollZoom, ["mousePan"]);
if (options.interactive && options.scrollZoom) map.scrollZoom.enable(options.scrollZoom);
const keyboard = map.keyboard = new KeyboardHandler(map, this._transformProvider);
this._add("keyboard", keyboard);
if (options.interactive && options.keyboard) map.keyboard.enable();
}
_add(handlerName, handler, allowed) {
this._handlers.push({
handlerName,
handler,
allowed
});
this._handlersById[handlerName] = handler;
}
stop(allowEndAnimation) {
if (this._updatingCamera) return;
for (const { handler } of this._handlers) handler.reset();
this._inertia.clear();
this._fireEvents({}, {}, allowEndAnimation);
this._changes = [];
}
isActive() {
for (const { handler } of this._handlers) if (handler.isActive()) return true;
return false;
}
isZooming() {
return !!this._eventsInProgress.zoom || this._map.scrollZoom.isZooming();
}
isRotating() {
return !!this._eventsInProgress.rotate;
}
isMoving() {
return Boolean(isMoving(this._eventsInProgress)) || this.isZooming();
}
_blockedByActive(activeHandlers, allowed, myName) {
for (const name in activeHandlers) {
if (name === myName) continue;
if (!allowed?.includes(name)) return true;
}
return false;
}
_getMapTouches(touches) {
const mapTouches = [];
for (const t of touches) {
const target = t.target;
if (this._el.contains(target)) mapTouches.push(t);
}
return mapTouches;
}
mergeHandlerResult(mergedHandlerResult, eventsInProgress, handlerResult, name, e) {
if (!handlerResult) return;
extend(mergedHandlerResult, handlerResult);
const eventData = {
handlerName: name,
originalEvent: handlerResult.originalEvent || e
};
if (handlerResult.zoomDelta !== void 0) eventsInProgress.zoom = eventData;
if (handlerResult.panDelta !== void 0) eventsInProgress.drag = eventData;
if (handlerResult.rollDelta !== void 0) eventsInProgress.roll = eventData;
if (handlerResult.pitchDelta !== void 0) eventsInProgress.pitch = eventData;
if (handlerResult.bearingDelta !== void 0) eventsInProgress.rotate = eventData;
}
_applyChanges() {
const combined = {};
const combinedEventsInProgress = {};
const combinedDeactivatedHandlers = {};
for (const [change, eventsInProgress, deactivatedHandlers] of this._changes) {
if (change.panDelta) combined.panDelta = (combined.panDelta || new Point(0, 0))._add(change.panDelta);
if (change.zoomDelta) combined.zoomDelta = (combined.zoomDelta || 0) + change.zoomDelta;
if (change.bearingDelta) combined.bearingDelta = (combined.bearingDelta || 0) + change.bearingDelta;
if (change.pitchDelta) combined.pitchDelta = (combined.pitchDelta || 0) + change.pitchDelta;
if (change.rollDelta) combined.rollDelta = (combined.rollDelta || 0) + change.rollDelta;
if (change.around !== void 0) combined.around = change.around;
if (change.pinchAround !== void 0) combined.pinchAround = change.pinchAround;
if (change.noInertia) combined.noInertia = change.noInertia;
extend(combinedEventsInProgress, eventsInProgress);
extend(combinedDeactivatedHandlers, deactivatedHandlers);
}
this._updateMapTransform(combined, combinedEventsInProgress, combinedDeactivatedHandlers);
this._changes = [];
}
_updateMapTransform(combinedResult, combinedEventsInProgress, deactivatedHandlers) {
const map = this._map;
const tr = this._camera.getTransformForUpdate();
const terrain = map.terrain;
if (!hasChange(combinedResult) && !(terrain && this._terrainMovement)) {
this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true);
return;
}
this._camera.stop(true);
const { panDelta, zoomDelta, bearingDelta, pitchDelta, rollDelta } = combinedResult;
let { around, aroundOnSurface } = this._resolveAround(combinedResult, terrain, tr);
const aroundElevation = terrain ? this._terrainGestureElevation(terrain, around, aroundOnSurface, tr, combinedEventsInProgress) : void 0;
const deltasForHelper = {
panDelta,
zoomDelta,
rollDelta,
pitchDelta,
bearingDelta,
around,
aroundElevation
};
if (this._camera.cameraHelper.useGlobeControls && !tr.isPointOnMapSurface(around)) around = tr.centerPoint;
const preZoomAroundLoc = this._computePreZoomAroundLoc(tr, around, panDelta, aroundElevation);
this._handleMapControls({
terrain,
tr,
deltasForHelper,
preZoomAroundLoc,
combinedEventsInProgress,
panDelta
});
this._camera.applyUpdatedTransform(tr);
this._map._update();
if (!combinedResult.noInertia) this._inertia.record(combinedResult);
this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true);
}
/**
* The gesture's anchor point: the pinch midpoint when pinching, otherwise the
* pan's anchor, clamped to the center point when it does not lie on the map.
*/
_resolveAround(combinedResult, terrain, tr) {
let around = combinedResult.pinchAround !== void 0 ? combinedResult.pinchAround : combinedResult.around;
around ||= this._camera.transform.centerPoint;
if (terrain && !tr.isPointOnMapSurface(around)) return {
around: tr.centerPoint,
aroundOnSurface: false
};
return {
around,
aroundOnSurface: true
};
}
/**
* The elevation of the plane a terrain gesture is solved on: the elevation of the
* terrain point grabbed at gesture start, captured here on the gesture's first
* frame. Undefined means the gesture is solved at the center's elevation instead —
* when the grabbed terrain is not loaded, the anchor is the center point (a
* center-point anchor is skipped by the camera helper and would lose the pan), or
* the anchor plane is too close to the camera for a stable ray-plane solve.
*/
_terrainGestureElevation(terrain, around, aroundOnSurface, tr, combinedEventsInProgress) {
if (!aroundOnSurface) return;
if (!this._terrainMovement && (combinedEventsInProgress.drag || combinedEventsInProgress.zoom)) {
const anchor = terrain.pointCoordinate(around);
this._terrainGestureAnchorElevation = anchor ? anchor.z : null;
}
if (this._terrainGestureAnchorElevation === null) return;
const elevation = this._terrainGestureAnchorElevation;
if (around.distSqr(tr.centerPoint) < .01) return;
if (elevation - tr.elevation >= TERRAIN_ANCHOR_MAX_CAMERA_ALTITUDE_FRACTION * (tr.getCameraAltitude() - tr.elevation)) return;
return elevation;
}
/**
* The location that was under `around` before this frame's deltas — the point the
* camera helper re-anchors after zooming — solved at `aroundElevation` when a
* terrain gesture provides one. When rotating about the center point, the
* transform's center is used directly to avoid numerical issues near the horizon.
*/
_computePreZoomAroundLoc(tr, around, panDelta, aroundElevation) {
if (around.distSqr(tr.centerPoint) < .01) return tr.center;
const aroundPreviousPoint = panDelta ? around.sub(panDelta) : around;
if (aroundElevation !== void 0) return tr.screenPointToLocationAtElevation(aroundPreviousPoint, aroundElevation);
return tr.screenPointToLocation(aroundPreviousPoint);
}
_handleMapControls({ terrain, tr, deltasForHelper, preZoomAroundLoc, combinedEventsInProgress, panDelta }) {
const cameraHelper = this._camera.cameraHelper;
cameraHelper.handleMapControlsRollPitchBearingZoom(deltasForHelper, tr);
if (!terrain) {
cameraHelper.handleMapControlsPan(deltasForHelper, tr, preZoomAroundLoc);
return;
}
if (cameraHelper.useGlobeControls) {
if (!this._terrainMovement && (combinedEventsInProgress.drag || combinedEventsInProgress.zoom)) {
this._terrainMovement = true;
this._camera.elevationFreeze = true;
}
cameraHelper.handleMapControlsPan(deltasForHelper, tr, preZoomAroundLoc);
return;
}
if (!this._terrainMovement && (combinedEventsInProgress.drag || combinedEventsInProgress.zoom)) {
this._terrainMovement = true;
this._camera.elevationFreeze = true;
cameraHelper.handleMapControlsPan(deltasForHelper, tr, preZoomAroundLoc);
return;
}
if (deltasForHelper.aroundElevation === void 0 && combinedEventsInProgress.drag && this._terrainMovement && panDelta) {
tr.setCenter(tr.screenPointToLocation(tr.centerPoint.sub(panDelta)));
return;
}
cameraHelper.handleMapControlsPan(deltasForHelper, tr, preZoomAroundLoc);
}
_fireEvents(newEventsInProgress, deactivatedHandlers, allowEndAnimation) {
const wasMoving = isMoving(this._eventsInProgress);
const nowMoving = isMoving(newEventsInProgress);
const startEvents = {};
for (const eventName in newEventsInProgress) {
const { originalEvent } = newEventsInProgress[eventName];
if (!this._eventsInProgress[eventName]) startEvents[`${eventName}start`] = originalEvent;
this._eventsInProgress[eventName] = newEventsInProgress[eventName];
}
if (!wasMoving && nowMoving) this._fireEvent("movestart", nowMoving.originalEvent);
for (const name in startEvents) this._fireEvent(name, startEvents[name]);
if (nowMoving) this._fireEvent("move", nowMoving.originalEvent);
for (const eventName in newEventsInProgress) {
const { originalEvent } = newEventsInProgress[eventName];
this._fireEvent(eventName, originalEvent);
}
const endEvents = {};
let originalEndEvent;
for (const eventName in this._eventsInProgress) {
const { handlerName, originalEvent } = this._eventsInProgress[eventName];
if (!this._handlersById[handlerName].isActive()) {
delete this._eventsInProgress[eventName];
originalEndEvent = deactivatedHandlers[handlerName] || originalEvent;
endEvents[`${eventName}end`] = originalEndEvent;
}
}
for (const name in endEvents) this._fireEvent(name, endEvents[name]);
const stillMoving = isMoving(this._eventsInProgress);
const finishedMoving = (wasMoving || nowMoving) && !stillMoving;
if (finishedMoving && this._terrainMovement) {
this._camera.elevationFreeze = false;
this._terrainMovement = false;
this._terrainGestureAnchorElevation = null;
const tr = this._camera.getTransformForUpdate();
if (this._map.getCenterClampedToGround()) tr.recalculateZoomAndCenter(this._map.terrain);
this._camera.applyUpdatedTransform(tr);
}
if (allowEndAnimation && finishedMoving) {
this._updatingCamera = true;
const inertialEase = this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions);
const shouldSnapToNorth = (bearing) => bearing !== 0 && -this._bearingSnap < bearing && bearing < this._bearingSnap;
if (inertialEase && (inertialEase.essential || !browser.prefersReducedMotion)) {
if (shouldSnapToNorth(inertialEase.bearing || this._map.getBearing())) inertialEase.bearing = 0;
inertialEase.freezeElevation = true;
this._map.easeTo(inertialEase, { originalEvent: originalEndEvent });
} else {
this._map.fire(new MapMovementEvent("moveend", { originalEvent: originalEndEvent }));
if (shouldSnapToNorth(this._map.getBearing())) this._map.resetNorth();
}
this._updatingCamera = false;
}
}
_fireEvent(type, e) {
this._map.fire(new MapMovementEvent(type, e ? { originalEvent: e } : {}));
}
_requestFrame() {
this._map.triggerRepaint();
return this._map._renderTaskQueue.add((timeStamp) => {
delete this._frameId;
this.handleEvent(new RenderFrameEvent("renderFrame", { timeStamp }));
this._applyChanges();
});
}
_triggerRenderFrame() {
if (this._frameId === void 0) this._frameId = this._requestFrame();
}
};
//#endregion
//#region src/ui/camera.ts
var Camera = class extends Evented {
constructor(options) {
super();
this._renderFrameCallback = () => {
const t = Math.min((now() - this._easeStart) / this._easeOptions.duration, 1);
this._onEaseFrame(this._easeOptions.easing(t));
if (t < 1 && this._easeFrameId) this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback);
else this.stop();
};
this.transform = new MercatorTransform();
this.cameraHelper = new MercatorCameraHelper();
if (options.minZoom !== void 0) this.transform.setMinZoom(options.minZoom);
if (options.maxZoom !== void 0) this.transform.setMaxZoom(options.maxZoom);
if (options.minPitch !== void 0) this.transform.setMinPitch(options.minPitch);
if (options.maxPitch !== void 0) this.transform.setMaxPitch(options.maxPitch);
if (options.renderWorldCopies !== void 0) this.transform.setRenderWorldCopies(options.renderWorldCopies);
if (options.transformConstrain !== null) this.transform.setConstrainOverride(options.transformConstrain);
this._moving = false;
this._zooming = false;
this._bearingSnap = options.bearingSnap;
this._zoomSnap = options.zoomSnap;
this._requestRenderFrame = options.requestRenderFrame;
this._cancelRenderFrame = options.cancelRenderFrame;
this.terrain = options.terrain;
this._centerClampedToGround = options.centerClampedToGround ?? true;
this.transformCameraUpdate = options.transformCameraUpdate ?? null;
this._stopHandlers = options.stopHandlers ?? (() => {});
this.on("moveend", () => {
delete this._requestedCameraState;
});
}
migrateProjection(newTransform, newCameraHelper) {
newTransform.apply(this.transform, true);
this.transform = newTransform;
this.cameraHelper = newCameraHelper;
}
getCenter() {
return new LngLat(this.transform.center.lng, this.transform.center.lat);
}
setCenter(center, eventData) {
return this.jumpTo({ center }, eventData);
}
getCenterElevation() {
return this.transform.elevation;
}
setCenterElevation(elevation, eventData) {
this.jumpTo({ elevation }, eventData);
return this;
}
getCenterClampedToGround() {
return this._centerClampedToGround;
}
setCenterClampedToGround(centerClampedToGround) {
this._centerClampedToGround = centerClampedToGround;
}
panBy(offset, options, eventData) {
offset = Point.convert(offset).mult(-1);
return this.panTo(this.transform.center, extend({ offset }, options), eventData);
}
panTo(lnglat, options, eventData) {
return this.easeTo(extend({ center: lnglat }, options), eventData);
}
getZoom() {
return this.transform.zoom;
}
setZoom(zoom, eventData) {
this.jumpTo({ zoom }, eventData);
return this;
}
zoomTo(zoom, options, eventData) {
return this.easeTo(extend({ zoom }, options), eventData);
}
zoomIn(options, eventData) {
this.zoomTo(evaluateZoomSnap(this.getZoom() + 1, this._zoomSnap), options, eventData);
return this;
}
zoomOut(options, eventData) {
this.zoomTo(evaluateZoomSnap(this.getZoom() - 1, this._zoomSnap), options, eventData);
return this;
}
getVerticalFieldOfView() {
return this.transform.fov;
}
setVerticalFieldOfView(fov, eventData) {
if (fov != this.transform.fov) {
this.transform.setFov(fov);
this.fire(new MapMovementEvent("movestart", eventData)).fire(new MapMovementEvent("move", eventData)).fire(new MapMovementEvent("moveend", eventData));
}
return this;
}
getBearing() {
return this.transform.bearing;
}
setZoomSnap(snap) {
this._zoomSnap = snap;
return this;
}
getZoomSnap() {
return this._zoomSnap;
}
setBearing(bearing, eventData) {
this.jumpTo({ bearing }, eventData);
return this;
}
getPadding() {
return this.transform.padding;
}
setPadding(padding, eventData) {
this.jumpTo({ padding }, eventData);
return this;
}
rotateTo(bearing, options, eventData) {
return this.easeTo(extend({ bearing }, options), eventData);
}
resetNorth(options, eventData) {
this.rotateTo(0, extend({ duration: 1e3 }, options), eventData);
return this;
}
resetNorthPitch(options, eventData) {
this.easeTo(extend({
bearing: 0,
pitch: 0,
roll: 0,
duration: 1e3
}, options), eventData);
return this;
}
snapToNorth(options, eventData) {
if (Math.abs(this.getBearing()) < this._bearingSnap) return this.resetNorth(options, eventData);
return this;
}
getPitch() {
return this.transform.pitch;
}
setPitch(pitch, eventData) {
this.jumpTo({ pitch }, eventData);
return this;
}
getRoll() {
return this.transform.roll;
}
setRoll(roll, eventData) {
this.jumpTo({ roll }, eventData);
return this;
}
cameraForBounds(bounds, options) {
bounds = LngLatBounds.convert(bounds).adjustAntiMeridian();
const bearing = options?.bearing || 0;
return this._cameraForBoxAndBearing(bounds.getNorthWest(), bounds.getSouthEast(), bearing, options);
}
/**
* @internal
* Calculate the center of these two points in the viewport and use
* the highest zoom level up to and including {@link Map.getMaxZoom} that fits
* the AABB defined by these points in the viewport at the specified bearing.
* @param p0 - First point
* @param p1 - Second point
* @param bearing - Desired map bearing at end of animation, in degrees
* @param options - the camera options
* @returns If map is able to fit to provided bounds, returns `center`, `zoom`, and `bearing`.
* If map is unable to fit, method will warn and return undefined.
* @example
* ```ts
* let p0 = [-79, 43];
* let p1 = [-73, 45];
* let bearing = 90;
* let newCameraTransform = map._cameraForBoxAndBearing(p0, p1, bearing, {
* padding: {top: 10, bottom:25, left: 15, right: 5}
* });
* ```
*/
_cameraForBoxAndBearing(p0, p1, bearing, options) {
const defaultPadding = {
top: 0,
bottom: 0,
right: 0,
left: 0
};
options = extend({
padding: defaultPadding,
offset: [0, 0],
maxZoom: this.transform.maxZoom
}, options);
if (typeof options.padding === "number") {
const p = options.padding;
options.padding = {
top: p,
bottom: p,
right: p,
left: p
};
}
const padding = extend(defaultPadding, options.padding);
options.padding = padding;
const tr = this.transform;
const bounds = new LngLatBounds(p0, p1);
const result = this.cameraHelper.cameraForBoxAndBearing(options, padding, bounds, bearing, tr);
if (result && this._zoomSnap) result.zoom = evaluateZoomSnap(result.zoom, this._zoomSnap, -1);
return result;
}
fitBounds(bounds, options, eventData) {
return this._fitInternal(this.cameraForBounds(bounds, options), options, eventData);
}
fitScreenCoordinates(p0, p1, bearing, options, eventData) {
return this._fitInternal(this._cameraForBoxAndBearing(this.transform.screenPointToLocation(Point.convert(p0)), this.transform.screenPointToLocation(Point.convert(p1)), bearing, options), options, eventData);
}
_fitInternal(calculatedOptions, options, eventData) {
if (!calculatedOptions) return this;
options = extend(calculatedOptions, options);
delete options.padding;
return options.linear ? this.easeTo(options, eventData) : this.flyTo(options, eventData);
}
jumpTo(options, eventData) {
this.stop();
if ("zoom" in options && this._zoomSnap) options.zoom = evaluateZoomSnap(options.zoom, this._zoomSnap);
const tr = this.getTransformForUpdate();
let bearingChanged = false, pitchChanged = false;
let rollChanged = false;
const oldZoom = tr.zoom;
if (this.terrain) tr.setElevation(this.terrain.getElevationForLngLatZoom(options.center ? LngLat.convert(options.center) : tr.center, options.zoom || tr.tileZoom));
this.cameraHelper.handleJumpToCenterZoom(tr, options);
const zoomChanged = tr.zoom !== oldZoom;
if ("elevation" in options && tr.elevation !== +options.elevation) tr.setElevation(+options.elevation);
if ("bearing" in options && tr.bearing !== +options.bearing) {
bearingChanged = true;
tr.setBearing(+options.bearing);
}
if ("pitch" in options && tr.pitch !== +options.pitch) {
pitchChanged = true;
tr.setPitch(+options.pitch);
}
if ("roll" in options && tr.roll !== +options.roll) {
rollChanged = true;
tr.setRoll(+options.roll);
}
if (options.padding != null && !tr.isPaddingEqual(options.padding)) tr.setPadding(options.padding);
this.applyUpdatedTransform(tr);
this.fire(new MapMovementEvent("movestart", eventData)).fire(new MapMovementEvent("move", eventData));
if (zoomChanged) this.fire(new MapMovementEvent("zoomstart", eventData)).fire(new MapMovementEvent("zoom", eventData)).fire(new MapMovementEvent("zoomend", eventData));
if (bearingChanged) this.fire(new MapMovementEvent("rotatestart", eventData)).fire(new MapMovementEvent("rotate", eventData)).fire(new MapMovementEvent("rotateend", eventData));
if (pitchChanged) this.fire(new MapMovementEvent("pitchstart", eventData)).fire(new MapMovementEvent("pitch", eventData)).fire(new MapMovementEvent("pitchend", eventData));
if (rollChanged) this.fire(new MapMovementEvent("rollstart", eventData)).fire(new MapMovementEvent("roll", eventData)).fire(new MapMovementEvent("rollend", eventData));
return this.fire(new MapMovementEvent("moveend", eventData));
}
calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo = 0) {
const fromMercator = MercatorCoordinate.fromLngLat(from, altitudeFrom);
const toMercator = MercatorCoordinate.fromLngLat(to, altitudeTo);
const dx = toMercator.x - fromMercator.x;
const dy = toMercator.y - fromMercator.y;
const dz = toMercator.z - fromMercator.z;
const distance3D = Math.hypot(dx, dy, dz);
if (distance3D === 0) throw new Error("Can't calculate camera options with same From and To");
const groundDistance = Math.hypot(dx, dy);
const zoom = scaleZoom(this.transform.cameraToCenterDistance / distance3D / this.transform.tileSize);
const bearing = Math.atan2(dx, -dy) * 180 / Math.PI;
let pitch = Math.acos(groundDistance / distance3D) * 180 / Math.PI;
pitch = dz < 0 ? 90 - pitch : 90 + pitch;
return {
center: toMercator.toLngLat(),
elevation: altitudeTo,
zoom,
pitch,
bearing
};
}
calculateCameraOptionsFromCameraLngLatAltRotation(cameraLngLat, cameraAlt, bearing, pitch, roll) {
const centerInfo = this.transform.calculateCenterFromCameraLngLatAlt(cameraLngLat, cameraAlt, bearing, pitch);
return {
center: centerInfo.center,
elevation: centerInfo.elevation,
zoom: centerInfo.zoom,
bearing,
pitch,
roll
};
}
easeTo(options, eventData) {
this._stop(false, options.easeId);
options = extend({
offset: [0, 0],
duration: 500,
easing: defaultEasing
}, options);
if ("zoom" in options && this._zoomSnap) options.zoom = evaluateZoomSnap(options.zoom, this._zoomSnap);
if (options.animate === false || !options.essential && browser.prefersReducedMotion) options.duration = 0;
const tr = this.getTransformForUpdate();
const startBearing = this.getBearing(), startPitch = tr.pitch, startRoll = tr.roll, bearing = "bearing" in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing, pitch = "pitch" in options ? +options.pitch : startPitch, roll = "roll" in options ? this._normalizeBearing(options.roll, startRoll) : startRoll, padding = "padding" in options ? options.padding : tr.padding;
const offsetAsPoint = Point.convert(options.offset);
let around, aroundPoint;
if (options.around) {
around = LngLat.convert(options.around);
aroundPoint = tr.locationToScreenPoint(around);
}
const currently = {
moving: this._moving,
zooming: this._zooming,
rotating: this._rotating,
pitching: this._pitching,
rolling: this._rolling
};
const easeHandler = this.cameraHelper.handleEaseTo(tr, {
bearing,
pitch,
roll,
padding,
around,
aroundPoint,
offsetAsPoint,
offset: options.offset,
zoom: options.zoom,
center: options.center
});
this._rotating ||= startBearing !== bearing;
this._pitching ||= pitch !== startPitch;
this._rolling ||= roll !== startRoll;
this._padding = !tr.isPaddingEqual(padding);
this._zooming ||= easeHandler.isZooming;
this._easeId = options.easeId;
this._prepareEase(eventData, options.noMoveStart, currently);
if (this.terrain) this._prepareElevation(easeHandler.elevationCenter);
this._ease((k) => {
easeHandler.easeFunc(k);
if (this.terrain && !options.freezeElevation) this._updateElevation(k);
this.applyUpdatedTransform(tr);
this._fireMoveEvents(eventData);
}, (interruptingEaseId) => {
if (this.terrain && options.freezeElevation) this._finalizeElevation();
this._afterEase(eventData, interruptingEaseId);
}, options);
return this;
}
_prepareEase(eventData, noMoveStart, currently = {}) {
this._moving = true;
if (!noMoveStart && !currently.moving) this.fire(new MapMovementEvent("movestart", eventData));
if (this._zooming && !currently.zooming) this.fire(new MapMovementEvent("zoomstart", eventData));
if (this._rotating && !currently.rotating) this.fire(new MapMovementEvent("rotatestart", eventData));
if (this._pitching && !currently.pitching) this.fire(new MapMovementEvent("pitchstart", eventData));
if (this._rolling && !currently.rolling) this.fire(new MapMovementEvent("rollstart", eventData));
}
_prepareElevation(center) {
this._elevationCenter = center;
this._elevationStart = this.transform.elevation;
this._elevationTarget = this.terrain.getElevationForLngLatZoom(center, this.transform.tileZoom);
this.elevationFreeze = true;
}
_updateElevation(k) {
if (this._elevationStart === void 0 || this._elevationCenter === void 0) this._prepareElevation(this.transform.center);
this.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._elevationCenter, this.transform.tileZoom));
const elevation = this.terrain.getElevationForLngLatZoom(this._elevationCenter, this.transform.tileZoom);
if (k < 1 && elevation !== this._elevationTarget) {
const pitch1 = this._elevationTarget - this._elevationStart;
const pitch2 = (elevation - (pitch1 * k + this._elevationStart)) / (1 - k);
this._elevationStart += k * (pitch1 - pitch2);
this._elevationTarget = elevation;
}
this.transform.setElevation(interpolateFactory.number(this._elevationStart, this._elevationTarget, k));
}
_finalizeElevation() {
this.elevationFreeze = false;
if (this.getCenterClampedToGround()) this.transform.recalculateZoomAndCenter(this.terrain);
}
/**
* @internal
* Called when the camera is about to be manipulated.
* If `transformCameraUpdate` is specified or terrain is enabled, a copy of
* the current transform is created to track the accumulated changes.
* This underlying transform represents the "desired state" proposed by input handlers / animations / UI controls.
* It may differ from the state used for rendering (`this.transform`).
* @returns Transform to apply changes to
*/
getTransformForUpdate() {
if (!this.transformCameraUpdate && !this.terrain) return this.transform;
this._requestedCameraState ||= this.transform.clone();
return this._requestedCameraState;
}
/**
* @internal
* Checks the given transform for the camera being below terrain surface and
* returns new pitch and zoom to fix that.
*
* With the new pitch and zoom, the camera will be at the same ground
* position but at higher altitude. It will still point to the same spot on
* the map.
*
* @param tr - The transform to check.
*/
_elevateCameraIfInsideTerrain(tr) {
if (!this.terrain && tr.elevation >= 0 && tr.pitch <= 90) return {};
const cameraLngLat = tr.getCameraLngLat();
const cameraAltitude = tr.getCameraAltitude();
const minAltitude = this.terrain ? this.terrain.getElevationForLngLatZoom(cameraLngLat, tr.zoom) : 0;
if (cameraAltitude < minAltitude) {
const newCamera = this.calculateCameraOptionsFromTo(cameraLngLat, minAltitude, tr.center, tr.elevation);
return {
pitch: newCamera.pitch,
zoom: newCamera.zoom
};
}
return {};
}
/**
* @internal
* Called after the camera is done being manipulated.
* @param tr - the requested camera end state
* If the camera is inside terrain, it gets elevated.
* Call `transformCameraUpdate` if present, and then apply the "approved" changes.
*/
applyUpdatedTransform(tr) {
const modifiers = [];
modifiers.push((tr) => this._elevateCameraIfInsideTerrain(tr));
if (this.transformCameraUpdate) modifiers.push((tr) => this.transformCameraUpdate(tr));
if (!modifiers.length) return;
const finalTransform = tr.clone();
for (const modifier of modifiers) {
const nextTransform = finalTransform.clone();
const { center, zoom, roll, pitch, bearing, elevation } = modifier(nextTransform);
if (center) nextTransform.setCenter(center);
if (elevation !== void 0) nextTransform.setElevation(elevation);
if (zoom !== void 0) nextTransform.setZoom(zoom);
if (roll !== void 0) nextTransform.setRoll(roll);
if (pitch !== void 0) nextTransform.setPitch(pitch);
if (bearing !== void 0) nextTransform.setBearing(bearing);
finalTransform.apply(nextTransform, false);
}
this.transform.apply(finalTransform, false);
}
_fireMoveEvents(eventData) {
this.fire(new MapMovementEvent("move", eventData));
if (this._zooming) this.fire(new MapMovementEvent("zoom", eventData));
if (this._rotating) this.fire(new MapMovementEvent("rotate", eventData));
if (this._pitching) this.fire(new MapMovementEvent("pitch", eventData));
if (this._rolling) this.fire(new MapMovementEvent("roll", eventData));
}
_afterEase(eventData, easeId) {
if (this._easeId && easeId && this._easeId === easeId) return;
delete this._easeId;
const wasZooming = this._zooming;
const wasRotating = this._rotating;
const wasPitching = this._pitching;
const wasRolling = this._rolling;
this._moving = false;
this._zooming = false;
this._rotating = false;
this._pitching = false;
this._rolling = false;
this._padding = false;
if (wasZooming) this.fire(new MapMovementEvent("zoomend", eventData));
if (wasRotating) this.fire(new MapMovementEvent("rotateend", eventData));
if (wasPitching) this.fire(new MapMovementEvent("pitchend", eventData));
if (wasRolling) this.fire(new MapMovementEvent("rollend", eventData));
this.fire(new MapMovementEvent("moveend", eventData));
}
flyTo(options, eventData) {
if (!options.essential && browser.prefersReducedMotion) {
const coercedOptions = pick(options, [
"center",
"zoom",
"bearing",
"pitch",
"roll",
"elevation",
"padding"
]);
return this.jumpTo(coercedOptions, eventData);
}
this.stop();
options = extend({
offset: [0, 0],
speed: 1.2,
curve: 1.42,
easing: defaultEasing
}, options);
if ("zoom" in options && this._zoomSnap) options.zoom = evaluateZoomSnap(options.zoom, this._zoomSnap);
const tr = this.getTransformForUpdate(), startBearing = tr.bearing, startPitch = tr.pitch, startRoll = tr.roll, startPadding = tr.padding;
const bearing = "bearing" in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing;
const pitch = "pitch" in options ? +options.pitch : startPitch;
const roll = "roll" in options ? this._normalizeBearing(options.roll, startRoll) : startRoll;
const padding = "padding" in options ? options.padding : tr.padding;
const offsetAsPoint = Point.convert(options.offset);
let pointAtOffset = tr.centerPoint.add(offsetAsPoint);
const locationAtOffset = tr.screenPointToLocation(pointAtOffset);
const flyToHandler = this.cameraHelper.handleFlyTo(tr, {
bearing,
pitch,
roll,
padding,
locationAtOffset,
offsetAsPoint,
center: options.center,
minZoom: options.minZoom,
zoom: options.zoom
});
let rho = options.curve;
const w0 = Math.max(tr.width, tr.height);
const w1 = w0 / flyToHandler.scaleOfZoom;
const u1 = flyToHandler.pixelPathLength;
const wMax = w0 / flyToHandler.scaleOfMinZoom;
rho = Math.min(rho, Math.sqrt(wMax / u1 * 2));
const rho2 = rho * rho;
/**
* rᵢ: Returns the zoom-out factor at one end of the animation.
*
* @param descent - `true` for the descent, `false` for the ascent
*/
function zoomOutFactor(descent) {
const b = (w1 * w1 - w0 * w0 + (descent ? -1 : 1) * rho2 * rho2 * u1 * u1) / (2 * (descent ? w1 : w0) * rho2 * u1);
return Math.log(Math.sqrt(b * b + 1) - b);
}
function sinh(n) {
return (Math.exp(n) - Math.exp(-n)) / 2;
}
function cosh(n) {
return (Math.exp(n) + Math.exp(-n)) / 2;
}
function tanh(n) {
return sinh(n) / cosh(n);
}
const r0 = zoomOutFactor(false);
let w = function(s) {
return cosh(r0) / cosh(r0 + rho * s);
};
let u = function(s) {
return w0 * ((cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2) / u1;
};
let S = (zoomOutFactor(true) - r0) / rho;
if (Math.abs(u1) < 2e-6 || !isFinite(S)) {
if (Math.abs(w0 - w1) < 1e-6) return this.easeTo(options, eventData);
const k = w1 < w0 ? -1 : 1;
S = Math.abs(Math.log(w1 / w0)) / rho;
u = () => 0;
w = (s) => Math.exp(k * rho * s);
}
if ("duration" in options) options.duration = +options.duration;
else {
const V = "screenSpeed" in options ? +options.screenSpeed / rho : +options.speed;
options.duration = 1e3 * S / V;
}
if (options.maxDuration && options.duration > options.maxDuration) options.duration = 0;
this._zooming = true;
this._rotating = startBearing !== bearing;
this._pitching = pitch !== startPitch;
this._rolling = roll !== startRoll;
this._padding = !tr.isPaddingEqual(padding);
this._prepareEase(eventData, false);
if (this.terrain) this._prepareElevation(flyToHandler.targetCenter);
this._ease((k) => {
const s = k * S;
const scale = 1 / w(s);
const centerFactor = u(s);
if (this._rotating) tr.setBearing(interpolateFactory.number(startBearing, bearing, k));
if (this._pitching) tr.setPitch(interpolateFactory.number(startPitch, pitch, k));
if (this._rolling) tr.setRoll(interpolateFactory.number(startRoll, roll, k));
if (this._padding) {
tr.interpolatePadding(startPadding, padding, k);
pointAtOffset = tr.centerPoint.add(offsetAsPoint);
}
flyToHandler.easeFunc(k, scale, centerFactor, pointAtOffset);
if (this.terrain && !options.freezeElevation) this._updateElevation(k);
this.applyUpdatedTransform(tr);
this._fireMoveEvents(eventData);
}, () => {
if (this.terrain && options.freezeElevation) this._finalizeElevation();
this._afterEase(eventData);
}, options);
return this;
}
isEasing() {
return !!this._easeFrameId;
}
stop(allowGestures) {
return this._stop(allowGestures);
}
_stop(allowGestures, easeId) {
if (this._easeFrameId) {
this._cancelRenderFrame(this._easeFrameId);
delete this._easeFrameId;
delete this._onEaseFrame;
}
if (this._onEaseEnd) {
const onEaseEnd = this._onEaseEnd;
delete this._onEaseEnd;
onEaseEnd.call(this, easeId);
}
if (!allowGestures) this._stopHandlers();
return this;
}
_ease(frame, finish, options) {
if (options.animate === false || options.duration === 0) {
frame(1);
finish();
} else {
this._easeStart = now();
this._easeOptions = options;
this._onEaseFrame = frame;
this._onEaseEnd = finish;
this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback);
}
}
_normalizeBearing(bearing, currentBearing) {
bearing = wrap(bearing, -180, 180);
const diff = Math.abs(bearing - currentBearing);
if (Math.abs(bearing - 360 - currentBearing) < diff) bearing -= 360;
if (Math.abs(bearing + 360 - currentBearing) < diff) bearing += 360;
return bearing;
}
isMoving() {
return this._moving;
}
isZooming() {
return this._zooming;
}
isRotating() {
return this._rotating;
}
};
//#endregion
//#region src/ui/control/attribution_control.ts
const defaultAttributionControlOptions = {
compact: true,
customAttribution: "<a href=\"https://maplibre.org/\" target=\"_blank\">MapLibre</a>"
};
/**
* An `AttributionControl` control presents the map's attribution information. By default, the attribution control is expanded (regardless of map width).
* @group Markers and Controls
* @example
* ```ts
* let map = new Map({attributionControl: false})
* .addControl(new AttributionControl({
* compact: true
* }));
* ```
* @see [Change the default position for attribution](https://maplibre.org/maplibre-gl-js/docs/examples/change-the-default-position-for-attribution/)
*/
var AttributionControl = class {
/**
* @param options - the attribution options
*/
constructor(options = defaultAttributionControlOptions) {
this._toggleAttribution = () => {
if (this._container.classList.contains("maplibregl-compact")) {
if (this._container.classList.contains("maplibregl-compact-show")) {
this._container.setAttribute("open", "");
this._container.classList.remove("maplibregl-compact-show");
} else {
this._container.classList.add("maplibregl-compact-show");
this._container.removeAttribute("open");
}
}
};
this._updateData = (e) => {
if (e && (e.type === "terrain" || e.dataType === "style" || e.dataType === "source" && (e.sourceDataType === "metadata" || e.sourceDataType === "visibility"))) this._updateAttributions();
};
this._updateCompact = () => {
if (this._map.getCanvasContainer().offsetWidth <= 640 || this._compact) {
if (this._compact === false) this._container.setAttribute("open", "");
else if (!this._container.classList.contains("maplibregl-compact") && !this._container.classList.contains("maplibregl-attrib-empty")) {
this._container.setAttribute("open", "");
this._container.classList.add("maplibregl-compact", "maplibregl-compact-show");
}
} else {
this._container.setAttribute("open", "");
if (this._container.classList.contains("maplibregl-compact")) this._container.classList.remove("maplibregl-compact", "maplibregl-compact-show");
}
};
this._updateCompactMinimize = () => {
if (this._container.classList.contains("maplibregl-compact")) {
if (this._container.classList.contains("maplibregl-compact-show")) this._container.classList.remove("maplibregl-compact-show");
}
};
this.options = options;
}
getDefaultPosition() {
return "bottom-right";
}
/** {@inheritDoc IControl.onAdd} */
onAdd(map) {
this._map = map;
this._compact = this.options.compact;
this._container = DOM.create("details", "maplibregl-ctrl maplibregl-ctrl-attrib");
this._compactButton = DOM.create("summary", "maplibregl-ctrl-attrib-button", this._container);
this._compactButton.addEventListener("click", this._toggleAttribution);
this._setElementTitle(this._compactButton, "ToggleAttribution");
this._innerContainer = DOM.create("div", "maplibregl-ctrl-attrib-inner", this._container);
this._updateAttributions();
this._updateCompact();
this._map.on("styledata", this._updateData);
this._map.on("sourcedata", this._updateData);
this._map.on("terrain", this._updateData);
this._map.on("resize", this._updateCompact);
this._map.on("drag", this._updateCompactMinimize);
return this._container;
}
/** {@inheritDoc IControl.onRemove} */
onRemove() {
this._container.remove();
this._map.off("styledata", this._updateData);
this._map.off("sourcedata", this._updateData);
this._map.off("terrain", this._updateData);
this._map.off("resize", this._updateCompact);
this._map.off("drag", this._updateCompactMinimize);
this._map = void 0;
this._compact = void 0;
this._attribHTML = void 0;
}
_setElementTitle(element, title) {
const str = this._map._getUIString(`AttributionControl.${title}`);
element.title = str;
element.setAttribute("aria-label", str);
}
_updateAttributions() {
if (!this._map.style) return;
let attributions = [];
if (this.options.customAttribution) {
if (Array.isArray(this.options.customAttribution)) attributions = attributions.concat(this.options.customAttribution.map((attribution) => {
if (typeof attribution !== "string") return "";
return attribution;
}));
else if (typeof this.options.customAttribution === "string") attributions.push(this.options.customAttribution);
}
if (this._map.style.stylesheet) {
const stylesheet = this._map.style.stylesheet;
this.styleOwner = stylesheet.owner;
this.styleId = stylesheet.id;
}
const tileManagers = this._map.style.tileManagers;
for (const id in tileManagers) {
const tileManager = tileManagers[id];
if (tileManager.used || tileManager.usedForTerrain) {
const source = tileManager.getSource();
if (source.attribution && !attributions.includes(source.attribution)) attributions.push(source.attribution);
}
}
attributions = attributions.filter((e) => String(e).trim());
attributions.sort((a, b) => a.length - b.length);
attributions = attributions.filter((attrib, i) => {
for (let j = i + 1; j < attributions.length; j++) if (attributions[j].includes(attrib)) return false;
return true;
});
const attribHTML = attributions.join(" | ");
if (attribHTML === this._attribHTML) return;
this._attribHTML = attribHTML;
if (attributions.length) {
this._innerContainer.innerHTML = DOM.sanitize(attribHTML);
this._container.classList.remove("maplibregl-attrib-empty");
} else this._container.classList.add("maplibregl-attrib-empty");
this._updateCompact();
this._editLink = null;
}
};
//#endregion
//#region src/ui/control/logo_control.ts
/**
* A `LogoControl` is a control that adds the watermark.
*
* @group Markers and Controls
*
* @example
* ```ts
* map.addControl(new LogoControl({compact: false}));
* ```
**/
var LogoControl = class {
/**
* @param options - the control's options
*/
constructor(options = {}) {
this._updateCompact = () => {
const containerChildren = this._container.children;
if (containerChildren.length) {
const anchor = containerChildren[0];
if (this._map.getCanvasContainer().offsetWidth <= 640 || this._compact) {
if (this._compact !== false) anchor.classList.add("maplibregl-compact");
} else anchor.classList.remove("maplibregl-compact");
}
};
this.options = options;
}
getDefaultPosition() {
return "bottom-left";
}
/** {@inheritDoc IControl.onAdd} */
onAdd(map) {
this._map = map;
this._compact = this.options?.compact;
this._container = DOM.create("div", "maplibregl-ctrl");
const anchor = DOM.create("a", "maplibregl-ctrl-logo");
anchor.target = "_blank";
anchor.rel = "noopener nofollow";
anchor.href = "https://maplibre.org/";
anchor.setAttribute("aria-label", this._map._getUIString("LogoControl.Title"));
anchor.setAttribute("rel", "noopener nofollow");
this._container.appendChild(anchor);
this._container.style.display = "block";
this._map.on("resize", this._updateCompact);
this._updateCompact();
return this._container;
}
/** {@inheritDoc IControl.onRemove} */
onRemove() {
this._container.remove();
this._map.off("resize", this._updateCompact);
this._map = void 0;
this._compact = void 0;
}
};
//#endregion
//#region src/util/task_queue.ts
var TaskQueue = class {
constructor() {
this._queue = [];
this._id = 0;
this._cleared = false;
this._currentlyRunning = false;
}
add(callback) {
const id = ++this._id;
this._queue.push({
callback,
id,
cancelled: false
});
return id;
}
remove(id) {
const running = this._currentlyRunning;
const queue = running ? this._queue.concat(running) : this._queue;
for (const task of queue) if (task.id === id) {
task.cancelled = true;
return;
}
}
run(timeStamp = 0) {
if (this._currentlyRunning) throw new Error("Attempting to run(), but is already running.");
const queue = this._currentlyRunning = this._queue;
this._queue = [];
for (const task of queue) {
if (task.cancelled) continue;
task.callback(timeStamp);
if (this._cleared) break;
}
this._cleared = false;
this._currentlyRunning = false;
}
clear() {
if (this._currentlyRunning) this._cleared = true;
this._queue = [];
}
};
//#endregion
//#region src/data/pos3d_attributes.ts
const pos3dAttributes = createLayout([{
name: "a_pos3d",
type: "Int16",
components: 3
}]);
//#endregion
//#region src/tile/terrain_tile_manager.ts
/**
* @internal
* This class is a helper for the Terrain-class, it:
*
* - loads raster-dem tiles
* - manages all renderToTexture tiles.
* - caches previous rendered tiles.
* - finds all necessary renderToTexture tiles for a OverscaledTileID area
* - finds the corresponding raster-dem tile for OverscaledTileID
*/
var TerrainTileManager = class extends Evented {
constructor(tileManager) {
super();
this._lastTilesetChange = now();
this.tileManager = tileManager;
this._tiles = {};
this._renderableTilesKeys = [];
this._sourceTileCache = {};
this.minzoom = 0;
this.maxzoom = 22;
this.deltaZoom = 1;
this.tileSize = tileManager._source.tileSize * 2 ** this.deltaZoom;
tileManager.usedForTerrain = true;
tileManager.tileSize = this.tileSize;
}
destruct() {
this.tileManager.usedForTerrain = false;
this.tileManager.tileSize = null;
this.releaseAllRTT();
}
getSource() {
return this.tileManager._source;
}
/**
* Load Terrain Tiles, create internal render-to-texture tiles, free GPU memory.
* @param transform - the operation to do
* @param terrain - the terrain
*/
update(transform, terrain) {
this.tileManager.update(transform, terrain);
this._renderableTilesKeys = [];
const keys = {};
for (const tileID of coveringTiles(transform, {
tileSize: this.tileSize,
minzoom: this.minzoom,
maxzoom: this.maxzoom,
reparseOverscaled: false,
terrain,
calculateTileZoom: this.tileManager._source.calculateTileZoom
})) {
keys[tileID.key] = true;
this._renderableTilesKeys.push(tileID.key);
if (!this._tiles[tileID.key]) {
tileID.terrainRttPosMatrix32f = /* @__PURE__ */ new Float32Array(16);
ortho(tileID.terrainRttPosMatrix32f, 0, EXTENT, EXTENT, 0, 0, 1);
this._tiles[tileID.key] = new Tile(tileID, this.tileSize);
this._lastTilesetChange = now();
}
}
for (const key in this._tiles) if (!keys[key]) {
this._tiles[key].releaseRTT(this.tileManager.map.painter);
delete this._tiles[key];
}
}
/**
* Release the RTT objects for `tileID` (and its ancestors/descendants),
*/
releaseRTT(tileID) {
for (const key in this._tiles) {
const tile = this._tiles[key];
if (tile.tileID.equals(tileID) || tile.tileID.isChildOf(tileID) || tileID.isChildOf(tile.tileID)) tile.releaseRTT(this.tileManager.map.painter);
}
}
/**
* Release the A RTT objects for all tiles.
*/
releaseAllRTT() {
for (const key in this._tiles) this._tiles[key].releaseRTT(this.tileManager.map.painter);
}
/**
* get a list of tiles, which are loaded and should be rendered in the current scene
* @returns the renderable tiles
*/
getRenderableTiles() {
return this._renderableTilesKeys.map((key) => this.getTileByID(key));
}
/**
* get terrain tile by the TileID key
* @param id - the tile id
* @returns the tile
*/
getTileByID(id) {
return this._tiles[id];
}
/**
* Searches for the corresponding current renderable terrain-tiles
* @param tileID - the tile to look for
* @returns the tiles that were found
*/
getTerrainCoords(tileID, terrainTileRanges) {
if (terrainTileRanges) return this._getTerrainCoordsForTileRanges(tileID, terrainTileRanges);
else return this._getTerrainCoordsForRegularTile(tileID);
}
/**
* Searches for the corresponding current renderable terrain-tiles.
* Includes terrain tiles that are either:
* - the same as the tileID
* - a parent of the tileID
* - a child of the tileID
* @param tileID - the tile to look for
* @returns the tiles that were found
*/
_getTerrainCoordsForRegularTile(tileID) {
const coords = {};
for (const key of this._renderableTilesKeys) {
const terrainTileID = this._tiles[key].tileID;
const coord = tileID.clone();
const mat = createMat4f64();
if (terrainTileID.canonical.equals(tileID.canonical)) ortho(mat, 0, EXTENT, EXTENT, 0, 0, 1);
else if (terrainTileID.canonical.isChildOf(tileID.canonical)) {
const dz = terrainTileID.canonical.z - tileID.canonical.z;
const dx = terrainTileID.canonical.x - (terrainTileID.canonical.x >> dz << dz);
const dy = terrainTileID.canonical.y - (terrainTileID.canonical.y >> dz << dz);
const size = EXTENT >> dz;
ortho(mat, 0, size, size, 0, 0, 1);
translate(mat, mat, [
-dx * size,
-dy * size,
0
]);
} else if (tileID.canonical.isChildOf(terrainTileID.canonical)) {
const dz = tileID.canonical.z - terrainTileID.canonical.z;
const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz);
const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz);
const size = EXTENT >> dz;
ortho(mat, 0, EXTENT, EXTENT, 0, 0, 1);
translate(mat, mat, [
dx * size,
dy * size,
0
]);
scale(mat, mat, [
1 / 2 ** dz,
1 / 2 ** dz,
0
]);
} else continue;
coord.terrainRttPosMatrix32f = new Float32Array(mat);
coords[key] = coord;
}
return coords;
}
/**
* Searches for the corresponding current renderable terrain-tiles.
* Includes terrain tiles that are within terrain tile ranges.
* @param tileID - the tile to look for
* @returns the tiles that were found
*/
_getTerrainCoordsForTileRanges(tileID, terrainTileRanges) {
const coords = {};
for (const key of this._renderableTilesKeys) {
const terrainTileID = this._tiles[key].tileID;
if (!this._isWithinTileRanges(terrainTileID, terrainTileRanges)) continue;
const coord = tileID.clone();
const mat = createMat4f64();
if (terrainTileID.canonical.z === tileID.canonical.z) {
const dx = tileID.canonical.x - terrainTileID.canonical.x + tileID.wrap * (1 << tileID.canonical.z);
const dy = tileID.canonical.y - terrainTileID.canonical.y;
ortho(mat, 0, EXTENT, EXTENT, 0, 0, 1);
translate(mat, mat, [
dx * EXTENT,
dy * EXTENT,
0
]);
} else if (terrainTileID.canonical.z > tileID.canonical.z) {
const dz = terrainTileID.canonical.z - tileID.canonical.z;
const dx = terrainTileID.canonical.x - (terrainTileID.canonical.x >> dz << dz) + tileID.wrap * (1 << terrainTileID.canonical.z);
const dy = terrainTileID.canonical.y - (terrainTileID.canonical.y >> dz << dz);
const dx2 = tileID.canonical.x - (terrainTileID.canonical.x >> dz);
const dy2 = tileID.canonical.y - (terrainTileID.canonical.y >> dz);
const size = EXTENT >> dz;
ortho(mat, 0, size, size, 0, 0, 1);
translate(mat, mat, [
-dx * size + dx2 * EXTENT,
-dy * size + dy2 * EXTENT,
0
]);
} else {
const dz = tileID.canonical.z - terrainTileID.canonical.z;
const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz) + tileID.wrap * (1 << tileID.canonical.z);
const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz);
const dx2 = (tileID.canonical.x >> dz) - terrainTileID.canonical.x;
const dy2 = (tileID.canonical.y >> dz) - terrainTileID.canonical.y;
const size = EXTENT << dz;
ortho(mat, 0, size, size, 0, 0, 1);
translate(mat, mat, [
dx * EXTENT + dx2 * size,
dy * EXTENT + dy2 * size,
0
]);
}
coord.terrainRttPosMatrix32f = new Float32Array(mat);
coords[key] = coord;
}
return coords;
}
/**
* find the covering raster-dem tile
* @param tileID - the tile to look for
* @param searchForDEM - Optional parameter to search for (parent) source tiles with loaded dem.
* @returns the tile
*/
getSourceTile(tileID, searchForDEM) {
const source = this.tileManager._source;
let z = tileID.overscaledZ - this.deltaZoom;
if (z > source.maxzoom) z = source.maxzoom;
if (z < source.minzoom) return void 0;
this._sourceTileCache[tileID.key] ||= tileID.scaledTo(z).key;
let tile = this.findTileInCaches(this._sourceTileCache[tileID.key]);
if (!tile?.dem && searchForDEM) while (z >= source.minzoom && !tile?.dem) tile = this.findTileInCaches(tileID.scaledTo(z--).key);
return tile;
}
findTileInCaches(key) {
let tile = this.tileManager.getTileByID(key);
if (tile) return tile;
tile = this.tileManager._outOfViewCache.getByKey(key);
return tile;
}
/**
* gets whether any tiles were loaded after a specific time. This is used to update depth & coords framebuffers.
* @param time - the time
* @returns true if any tiles came into view at or after the specified time
*/
anyTilesAfterTime(time = now()) {
return this._lastTilesetChange >= time;
}
/**
* Checks whether a tile is within the canonical tile ranges.
* @param tileID - Tile to check
* @param canonicalTileRanges - Canonical tile ranges
* @returns
*/
_isWithinTileRanges(tileID, canonicalTileRanges) {
const range = canonicalTileRanges[tileID.canonical.z];
return !!range && (tileID.wrap > range.minWrap || tileID.wrap < range.maxWrap || tileID.canonical.x >= range.minTileXWrapped && tileID.canonical.x <= range.maxTileXWrapped && tileID.canonical.y >= range.minTileY && tileID.canonical.y <= range.maxTileY);
}
};
//#endregion
//#region src/render/terrain.ts
/**
* @internal
* This is the main class which handles most of the 3D Terrain logic. It has the following topics:
*
* 1. loads raster-dem tiles via the internal tileManager this.tileManager
* 2. creates a depth-framebuffer, which is used to calculate the visibility of coordinates
* 3. creates a coords-framebuffer, which is used the get to tile-coordinate for a screen-pixel
* 4. stores all render-to-texture tiles in the this.tileManager._tiles
* 5. calculates the elevation for a specific tile-coordinate
* 6. creates a terrain-mesh
*
* A note about the GPU resource-usage:
*
* Framebuffers:
*
* - one for the depth & coords framebuffer with the size of the map-div.
* - one for rendering a tile to texture with the size of tileSize (= 512x512).
*
* Textures:
*
* - one texture for an empty raster-dem tile with size 1x1
* - one texture for an empty depth-buffer, when terrain is disabled with size 1x1
* - one texture for an each loaded raster-dem with size of the source.tileSize
* - one texture for the coords-framebuffer with the size of the map-div.
* - one texture for the depth-framebuffer with the size of the map-div.
* - one texture for the encoded tile-coords with the size 2*tileSize (=1024x1024)
* - finally for each render-to-texture tile (= this._tiles) a set of textures
* for each render stack (The stack-concept is documented in painter.ts).
*
* Normally there exists 1-3 Textures per tile, depending on the stylesheet.
* Each Textures has the size 2*tileSize (= 1024x1024). Also there exists a
* cache of the last 150 newest rendered tiles.
*
*/
var Terrain = class {
constructor(painter, tileManager, options, terrainSkirtLength = "auto") {
this._meshCache = {};
this.painter = painter;
this.tileManager = new TerrainTileManager(tileManager);
this.options = options;
this.exaggeration = typeof options.exaggeration === "number" ? options.exaggeration : 1;
this._terrainSkirtLength = terrainSkirtLength;
this.qualityFactor = 2;
this.meshSize = 128;
this._demMatrixCache = /* @__PURE__ */ new Map();
this._elevationSamplerCache = /* @__PURE__ */ new Map();
this.coordsIndex = [];
this._coordsTextureSize = 1024;
}
destroy() {
if (this._fbo) {
this._fbo.destroy();
this._fbo = null;
}
if (this._fboCoordsTexture) {
this._fboCoordsTexture.destroy();
this._fboCoordsTexture = null;
}
if (this._fboDepthTexture) {
this._fboDepthTexture.destroy();
this._fboDepthTexture = null;
}
if (this._emptyDemTexture) {
this._emptyDemTexture.destroy();
this._emptyDemTexture = null;
}
if (this._emptyDepthTexture) {
this._emptyDepthTexture.destroy();
this._emptyDepthTexture = null;
}
if (this._coordsTexture) {
this._coordsTexture.destroy();
this._coordsTexture = null;
}
for (const key in this._meshCache) this._meshCache[key].destroy();
this._meshCache = {};
this.tileManager.destruct();
}
/**
* Get the elevation-value from original dem-data for a given tile-coordinate.
* Coordinates that fall outside `[0, extent)` are normalized to the
* appropriate neighbor tile before lookup.
* @param tileID - the tile to get the elevation for
* @param x - x coordinate relative to the tile, may be outside `[0, extent)`
* @param y - y coordinate relative to the tile, may be outside `[0, extent)`
* @param extent - optional, default 8192
* @returns the elevation
*/
getDEMElevation(tileID, x, y, extent = EXTENT) {
const normalized = tileID.normalizeCoordinates(x, y, extent);
if (!normalized) return 0;
const sampler = this._getElevationSampler(normalized.tileID);
return sampler ? sampler(normalized.x, normalized.y, extent) : 0;
}
/**
* Get the elevation for given {@link LngLat} in respect of exaggeration.
* @param lnglat - the location
* @param zoom - the zoom, use {@link getElevationForLngLat} if you don't want a specific zoom level, but more accurate results.
* @returns the elevation
*/
getElevationForLngLatZoom(lnglat, zoom) {
if (!isInBoundsForZoomLngLat(zoom, lnglat.wrap())) return 0;
const { tileID, mercatorX, mercatorY } = this._getOverscaledTileIDFromLngLatZoom(lnglat, zoom);
return this.getElevation(tileID, mercatorX % EXTENT, mercatorY % EXTENT, EXTENT);
}
/**
* Get the elevation for given {@link LngLat} in respect of exaggeration.
* This will traverse up the zoom levels to find the first tile with data to return.
* @param lnglat - the location
* @returns the elevation
*/
getElevationForLngLat(lnglat, transform) {
const terrainCoveringTiles = coveringTiles(transform, {
maxzoom: this.tileManager.maxzoom,
minzoom: this.tileManager.minzoom,
tileSize: 512,
terrain: this
});
let zoom = 0;
for (const tile of terrainCoveringTiles) if (tile.canonical.z > zoom) zoom = Math.min(tile.canonical.z, this.tileManager.maxzoom);
return this.getElevationForLngLatZoom(lnglat, zoom);
}
/**
* Get the elevation for given coordinate in respect of exaggeration.
* @param tileID - the tile id
* @param x - x coordinate relative to the tile, may be outside `[0, extent)`
* @param y - y coordinate relative to the tile, may be outside `[0, extent)`
* @param extent - optional, default 8192
* @returns the elevation
*/
getElevation(tileID, x, y, extent = EXTENT) {
return this.getDEMElevation(tileID, x, y, extent) * this.exaggeration;
}
/**
* Clear CPU elevation samplers that may retain a previously selected DEM tile.
* @internal
*/
resetElevationCache() {
this._elevationSamplerCache.clear();
}
_getElevationSampler(tileID) {
const key = tileID.key;
const cachedSampler = this._elevationSamplerCache.get(key);
if (cachedSampler) return cachedSampler;
const sourceTile = this.tileManager.getSourceTile(tileID, true);
const dem = sourceTile?.dem;
if (!sourceTile || !dem) return null;
const matrix = this._getDEMTileMatrix(tileID, sourceTile);
const demPixelScaleX = matrix[0] * dem.dim;
const demPixelScaleY = matrix[5] * dem.dim;
const demPixelOffsetX = matrix[12] * dem.dim;
const demPixelOffsetY = matrix[13] * dem.dim;
const sampler = (x, y, extent) => {
const extentScale = extent === 8192 ? 1 : EXTENT / extent;
return dem.sampleBilinear(x * extentScale * demPixelScaleX + demPixelOffsetX, y * extentScale * demPixelScaleY + demPixelOffsetY);
};
this._elevationSamplerCache.set(key, sampler);
return sampler;
}
_getDEMTileMatrix(tileID, sourceTile) {
const matrixKey = `${sourceTile.tileID.key}/${tileID.key}`;
const cachedMatrix = this._demMatrixCache.get(matrixKey);
if (cachedMatrix) return cachedMatrix;
const maxzoom = this.tileManager.getSource().maxzoom;
let dz = tileID.canonical.z - sourceTile.tileID.canonical.z;
if (tileID.overscaledZ > tileID.canonical.z) {
if (tileID.canonical.z >= maxzoom) dz = tileID.canonical.z - maxzoom;
else warnOnce("cannot calculate elevation if elevation maxzoom > source.maxzoom");
}
const dx = tileID.canonical.x - (tileID.canonical.x >> dz << dz);
const dy = tileID.canonical.y - (tileID.canonical.y >> dz << dz);
const demMatrix = fromScaling(/* @__PURE__ */ new Float64Array(16), [
1 / (EXTENT << dz),
1 / (EXTENT << dz),
0
]);
translate(demMatrix, demMatrix, [
dx * EXTENT,
dy * EXTENT,
0
]);
this._demMatrixCache.set(matrixKey, demMatrix);
return demMatrix;
}
/**
* returns a Terrain Object for a tile. Unless the tile corresponds to data (e.g. tile is loading), return a flat dem object
* @param tileID - the tile to get the terrain for
* @returns the terrain data to use in the program
*/
getTerrainData(tileID) {
if (!this._emptyDemTexture) {
const context = this.painter.context;
const image = new RGBAImage({
width: 1,
height: 1
}, /* @__PURE__ */ new Uint8Array(4));
this._emptyDepthTexture = new Texture(context, image, context.gl.RGBA, { premultiply: false });
this._emptyDemUnpack = [
0,
0,
0,
0
];
this._emptyDemTexture = new Texture(context, new RGBAImage({
width: 1,
height: 1
}), context.gl.RGBA, { premultiply: false });
this._emptyDemTexture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE);
this._emptyDemMatrix = identity([]);
}
const sourceTile = this.tileManager.getSourceTile(tileID, true);
if (sourceTile?.dem && (!sourceTile.demTexture || sourceTile.needsTerrainPrepare)) {
const context = this.painter.context;
sourceTile.demTexture ||= this.painter.getTileTexture(sourceTile.dem.stride);
if (sourceTile.demTexture) sourceTile.demTexture.update(sourceTile.dem.getPixels(), { premultiply: false });
else sourceTile.demTexture = new Texture(context, sourceTile.dem.getPixels(), context.gl.RGBA, { premultiply: false });
sourceTile.demTexture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE);
sourceTile.needsTerrainPrepare = false;
}
const terrainMatrix = sourceTile ? this._getDEMTileMatrix(tileID, sourceTile) : this._emptyDemMatrix;
return {
"u_depth": 2,
"u_terrain": 3,
"u_terrain_dim": sourceTile?.dem?.dim || 1,
"u_terrain_matrix": terrainMatrix,
"u_terrain_unpack": sourceTile?.dem?.getUnpackVector() || this._emptyDemUnpack,
"u_terrain_exaggeration": this.exaggeration,
texture: (sourceTile?.demTexture || this._emptyDemTexture).texture,
depthTexture: (this._fboDepthTexture || this._emptyDepthTexture).texture,
tile: sourceTile
};
}
/**
* get a framebuffer as big as the map-div, which will be used to render depth & coords into a texture
* @param texture - the texture
* @returns the frame buffer
*/
getFramebuffer(texture) {
const painter = this.painter;
const width = painter.width / devicePixelRatio;
const height = painter.height / devicePixelRatio;
if (this._fbo && (this._fbo.width !== width || this._fbo.height !== height)) {
this._fbo.destroy();
this._fboCoordsTexture.destroy();
this._fboDepthTexture.destroy();
delete this._fbo;
delete this._fboDepthTexture;
delete this._fboCoordsTexture;
}
if (!this._fboCoordsTexture) {
this._fboCoordsTexture = new Texture(painter.context, {
width,
height,
data: null
}, painter.context.gl.RGBA, { premultiply: false });
this._fboCoordsTexture.bind(painter.context.gl.NEAREST, painter.context.gl.CLAMP_TO_EDGE);
}
if (!this._fboDepthTexture) {
this._fboDepthTexture = new Texture(painter.context, {
width,
height,
data: null
}, painter.context.gl.RGBA, { premultiply: false });
this._fboDepthTexture.bind(painter.context.gl.NEAREST, painter.context.gl.CLAMP_TO_EDGE);
}
if (!this._fbo) {
this._fbo = painter.context.createFramebuffer(width, height, true, false);
this._fbo.depthAttachment.set(painter.context.createRenderbuffer(painter.context.gl.DEPTH_COMPONENT16, width, height));
}
this._fbo.colorAttachment.set(texture === "coords" ? this._fboCoordsTexture.texture : this._fboDepthTexture.texture);
return this._fbo;
}
/**
* create coords texture, needed to grab coordinates from canvas
* encode coords coordinate into 4 bytes:
* - 8 lower bits for x
* - 8 lower bits for y
* - 4 higher bits for x
* - 4 higher bits for y
* - 8 bits for coordsIndex (1 .. 255) (= number of terraintile), is later set in draw_terrain uniform value
* @returns the texture
*/
getCoordsTexture() {
const context = this.painter.context;
if (this._coordsTexture) return this._coordsTexture;
const data = new Uint8Array(this._coordsTextureSize * this._coordsTextureSize * 4);
for (let y = 0, i = 0; y < this._coordsTextureSize; y++) for (let x = 0; x < this._coordsTextureSize; x++, i += 4) {
data[i + 0] = x & 255;
data[i + 1] = y & 255;
data[i + 2] = x >> 8 << 4 | y >> 8;
data[i + 3] = 0;
}
const image = new RGBAImage({
width: this._coordsTextureSize,
height: this._coordsTextureSize
}, new Uint8Array(data.buffer));
const texture = new Texture(context, image, context.gl.RGBA, { premultiply: false });
texture.bind(context.gl.NEAREST, context.gl.CLAMP_TO_EDGE);
this._coordsTexture = texture;
return texture;
}
/**
* Reads a pixel from the coords-framebuffer and translate this to mercator, or null, if the pixel doesn't lie on the terrain's surface (but the sky instead).
* @param p - Screen-Coordinate
* @returns Mercator coordinate for a screen pixel, or null, if the pixel is not covered by terrain (is in the sky).
*/
pointCoordinate(p) {
this.painter.maybeDrawDepth(true);
this.painter.maybeDrawCoords();
const rgba = /* @__PURE__ */ new Uint8Array(4);
const context = this.painter.context, gl = context.gl;
const px = Math.round(p.x * this.painter.pixelRatio / devicePixelRatio);
const py = Math.round(p.y * this.painter.pixelRatio / devicePixelRatio);
const fbHeight = Math.round(this.painter.height / devicePixelRatio);
context.bindFramebuffer.set(this.getFramebuffer("coords").framebuffer);
gl.readPixels(px, fbHeight - py - 1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, rgba);
context.bindFramebuffer.set(null);
const x = rgba[0] + (rgba[2] >> 4 << 8);
const y = rgba[1] + ((rgba[2] & 15) << 8);
const tileID = this.coordsIndex[255 - rgba[3]];
const tile = tileID && this.tileManager.getTileByID(tileID);
if (!tile) return null;
const coordsSize = this._coordsTextureSize;
const worldSize = (1 << tile.tileID.canonical.z) * coordsSize;
return new MercatorCoordinate((tile.tileID.canonical.x * coordsSize + x) / worldSize + tile.tileID.wrap, (tile.tileID.canonical.y * coordsSize + y) / worldSize, this.getElevation(tile.tileID, x, y, coordsSize));
}
/**
* Reads the depth value from the depth-framebuffer at a given screen pixel
* @param p - Screen coordinate
* @returns depth value in clip space (between 0 and 1)
*/
depthAtPoint(p) {
const rgba = /* @__PURE__ */ new Uint8Array(4);
const context = this.painter.context, gl = context.gl;
context.bindFramebuffer.set(this.getFramebuffer("depth").framebuffer);
gl.readPixels(p.x, this.painter.height / devicePixelRatio - p.y - 1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, rgba);
context.bindFramebuffer.set(null);
return (rgba[0] / 16777216 + rgba[1] / 65536 + rgba[2] / 256 + rgba[3]) / 256;
}
/**
* create a regular mesh which will be used by all terrain-tiles
* @returns the created regular mesh
*/
getTerrainMesh(tileId) {
const globeEnabled = this.painter.style.projection?.transitionState > 0;
const northPole = globeEnabled && tileId.canonical.y === 0;
const southPole = globeEnabled && tileId.canonical.y === (1 << tileId.canonical.z) - 1;
const key = `m_${northPole ? "n" : ""}_${southPole ? "s" : ""}`;
if (this._meshCache[key]) return this._meshCache[key];
const context = this.painter.context;
const vertexArray = new Pos3dArray();
const indexArray = new TriangleIndexArray();
const meshSize = this.meshSize;
const delta = EXTENT / meshSize;
const meshSize2 = meshSize * meshSize;
for (let y = 0; y <= meshSize; y++) for (let x = 0; x <= meshSize; x++) vertexArray.emplaceBack(x * delta, y * delta, 0);
for (let y = 0; y < meshSize2; y += meshSize + 1) for (let x = 0; x < meshSize; x++) {
indexArray.emplaceBack(x + y, meshSize + x + y + 1, meshSize + x + y + 2);
indexArray.emplaceBack(x + y, meshSize + x + y + 2, x + y + 1);
}
if (this._terrainSkirtLength !== "none") this._buildSkirts(vertexArray, indexArray, meshSize, delta, northPole, southPole);
const mesh = new Mesh(context.createVertexBuffer(vertexArray, pos3dAttributes.members), context.createIndexBuffer(indexArray), SegmentVector.simpleSegment(0, 0, vertexArray.length, indexArray.length));
this._meshCache[key] = mesh;
return mesh;
}
/**
* Calculates the height of the tile skirts for the "auto" strategy.
* @see {@link MapOptions.terrainSkirtLength}
* @param zoom - current zoomlevel
* @returns the elevation delta in meters
*/
getSkirtLength(zoom) {
return 2 * Math.PI * earthRadius / Math.pow(2, Math.max(zoom, 0)) / 5;
}
getMinTileElevationForLngLatZoom(lnglat, zoom) {
if (!isInBoundsForZoomLngLat(zoom, lnglat.wrap())) return 0;
const { tileID } = this._getOverscaledTileIDFromLngLatZoom(lnglat, zoom);
return this.getMinMaxElevation(tileID).minElevation ?? 0;
}
/**
* Get the minimum and maximum elevation contained in a tile. This includes any
* exaggeration included in the terrain.
*
* @param tileID - ID of the tile to be used as a source for the min/max elevation
* @returns the minimum and maximum elevation found in the tile, including the terrain's
* exaggeration
*/
getMinMaxElevation(tileID) {
const tile = this.tileManager.getSourceTile(tileID, true);
const minMax = {
minElevation: null,
maxElevation: null
};
if (tile?.dem) {
minMax.minElevation = tile.dem.min * this.exaggeration;
minMax.maxElevation = tile.dem.max * this.exaggeration;
}
return minMax;
}
_getOverscaledTileIDFromLngLatZoom(lnglat, zoom) {
const mercatorCoordinate = MercatorCoordinate.fromLngLat(lnglat.wrap());
const worldSize = (1 << zoom) * EXTENT;
const mercatorX = mercatorCoordinate.x * worldSize;
const mercatorY = mercatorCoordinate.y * worldSize;
const tileX = Math.floor(mercatorX / EXTENT), tileY = Math.floor(mercatorY / EXTENT);
return {
tileID: new OverscaledTileID(zoom, 0, zoom, tileX, tileY),
mercatorX,
mercatorY
};
}
/** Add an extra frame around the mesh to avoid hairline gaps (stitching) on tile boundaries with different zoomlevels.
* @see {@link MapOptions.terrainSkirtLength}
*/
_buildSkirts(vertexArray, indexArray, meshSize, delta, northPole, southPole) {
const offsetTop = vertexArray.length;
const offsetTopEdge = 0;
const offsetBottom = offsetTop + (meshSize + 1);
const offsetBottomEdge = (meshSize + 1) * meshSize;
const northY = northPole ? NORTH_POLE_Y : 0;
const northZ = northPole ? 0 : 1;
const southY = southPole ? SOUTH_POLE_Y : EXTENT;
const southZ = southPole ? 0 : 1;
for (let x = 0; x <= meshSize; x++) vertexArray.emplaceBack(x * delta, northY, northZ);
for (let x = 0; x <= meshSize; x++) vertexArray.emplaceBack(x * delta, southY, southZ);
for (let x = 0; x < meshSize; x++) {
indexArray.emplaceBack(offsetBottomEdge + x, offsetBottom + x, offsetBottom + x + 1);
indexArray.emplaceBack(offsetBottomEdge + x, offsetBottom + x + 1, offsetBottomEdge + x + 1);
indexArray.emplaceBack(offsetTopEdge + x, offsetTop + x + 1, offsetTop + x);
indexArray.emplaceBack(offsetTopEdge + x, offsetTopEdge + x + 1, offsetTop + x + 1);
}
const offsetLeft = vertexArray.length;
const offsetRight = offsetLeft + (meshSize + 1) * 2;
for (const x of [0, 1]) for (let y = 0; y <= meshSize; y++) for (const z of [0, 1]) vertexArray.emplaceBack(x * EXTENT, y * delta, z);
for (let y = 0; y < meshSize * 2; y += 2) {
indexArray.emplaceBack(offsetLeft + y, offsetLeft + y + 1, offsetLeft + y + 3);
indexArray.emplaceBack(offsetLeft + y, offsetLeft + y + 3, offsetLeft + y + 2);
indexArray.emplaceBack(offsetRight + y, offsetRight + y + 3, offsetRight + y + 1);
indexArray.emplaceBack(offsetRight + y, offsetRight + y + 2, offsetRight + y + 3);
}
}
};
//#endregion
//#region src/webgl/render_to_texture.ts
/**
* lookup table which layers should rendered to texture
*/
const LAYERS_TO_TEXTURES = {
background: true,
fill: true,
line: true,
raster: true,
hillshade: true,
"color-relief": true
};
/**
* @internal
* Renders RTT-eligible layers into per-tile cached textures, then drapes
* them onto the terrain mesh. Slots live on each Tile so their lifetime
* tracks the tile itself; the underlying FBO+texture handles are recycled
* via the painter's RTT pool.
*/
var RenderToTexture = class {
constructor(painter, terrain) {
this.painter = painter;
this.terrain = terrain;
this.rttSize = terrain.tileManager.tileSize * terrain.qualityFactor;
}
getTexture(tile) {
return tile.getRTT(this._stacks.length - 1).texture;
}
prepareForRender(style, zoom) {
this._stacks = [];
this._prevType = null;
this._rttTiles = [];
this._renderableTiles = this.terrain.tileManager.getRenderableTiles();
this._renderableLayerIds = style._order.filter((id) => !style._layers[id].isHidden(zoom));
const rttSourceIds = /* @__PURE__ */ new Set();
for (const layerId of this._renderableLayerIds) {
const layer = style._layers[layerId];
const source = layer.source;
if (source && LAYERS_TO_TEXTURES[layer.type]) rttSourceIds.add(source);
}
this._coordsAscending = {};
this._rttFingerprints = {};
for (const sourceId of rttSourceIds) {
const tileManager = style.tileManagers[sourceId];
if (!tileManager) continue;
this._coordsAscending[sourceId] = {};
const coordsAscending = this._coordsAscending[sourceId];
const source = tileManager.getSource();
const terrainTileRanges = source instanceof ImageSource ? source.terrainTileRanges : null;
for (const tileID of tileManager.getVisibleCoordinates()) {
const keys = this.terrain.tileManager.getTerrainCoords(tileID, terrainTileRanges);
for (const key in keys) {
coordsAscending[key] ||= [];
coordsAscending[key].push(keys[key]);
}
}
this._rttFingerprints[sourceId] = {};
const fingerprints = this._rttFingerprints[sourceId];
const revision = tileManager.getState().revision;
for (const key in coordsAscending) fingerprints[key] = `${coordsAscending[key].map((c) => c.key).sort().join()}#${revision}`;
}
for (const tile of this._renderableTiles) for (const source in this._rttFingerprints) {
const fingerprint = this._rttFingerprints[source][tile.tileID.key];
if (fingerprint && fingerprint !== tile.rttFingerprint[source]) tile.releaseRTT(this.painter);
}
}
/**
* due that switching textures is relatively slow, the render
* layer-by-layer context is not practicable. To bypass this problem
* this lines of code stack all layers and later render all at once.
* Because of the stylesheet possibility to mixing render-to-texture layers
* and 'live'-layers (f.e. symbols) it is necessary to create more stacks. For example
* a symbol-layer is in between of fill-layers.
* @param layer - the layer to render
* @param renderOptions - flags describing how to render the layer
* @returns if true layer is rendered to texture, otherwise false
*/
renderLayer(layer, renderOptions) {
if (layer.isHidden(this.painter.transform.zoom)) return false;
const options = {
...renderOptions,
isRenderingToTexture: true
};
const type = layer.type;
const painter = this.painter;
const isLastLayer = this._renderableLayerIds[this._renderableLayerIds.length - 1] === layer.id;
if (LAYERS_TO_TEXTURES[type]) {
if (!this._prevType || !LAYERS_TO_TEXTURES[this._prevType]) this._stacks.push([]);
this._prevType = type;
this._stacks[this._stacks.length - 1].push(layer.id);
if (!isLastLayer) return true;
}
if (LAYERS_TO_TEXTURES[this._prevType] || LAYERS_TO_TEXTURES[type] && isLastLayer) {
this._prevType = type;
const stack = this._stacks.length - 1, layers = this._stacks[stack] || [];
for (const tile of this._renderableTiles) {
this._rttTiles.push(tile);
if (tile.getRTT(stack)) continue;
const obj = tile.acquireRTT(painter, stack, this.rttSize);
painter.bindRTT(obj);
painter.context.clear({
color: Color.transparent,
stencil: 0
});
painter.currentStencilSource = void 0;
for (const layerId of layers) {
const layer = painter.style._layers[layerId];
const coords = layer.source ? this._coordsAscending[layer.source][tile.tileID.key] : [tile.tileID];
painter.context.viewport.set([
0,
0,
this.rttSize,
this.rttSize
]);
painter.renderTileClippingMasks(layer, coords, true);
painter.renderLayer(painter, painter.style.tileManagers[layer.source], layer, coords, options);
if (layer.source) tile.rttFingerprint[layer.source] = this._rttFingerprints[layer.source][tile.tileID.key];
}
}
drawTerrain(this.painter, this.terrain, this._rttTiles, options);
this._rttTiles = [];
return LAYERS_TO_TEXTURES[type];
}
return false;
}
};
//#endregion
//#region src/ui/default_locale.ts
const defaultLocale = {
"AttributionControl.ToggleAttribution": "Toggle attribution",
"AttributionControl.MapFeedback": "Map feedback",
"FullscreenControl.Enter": "Enter fullscreen",
"FullscreenControl.Exit": "Exit fullscreen",
"GeolocateControl.FindMyLocation": "Find my location",
"GeolocateControl.LocationNotAvailable": "Location not available",
"LogoControl.Title": "MapLibre logo",
"Map.Title": "Map",
"Marker.Title": "Map marker",
"NavigationControl.ResetBearing": "Drag to rotate map, click to reset north",
"NavigationControl.ZoomIn": "Zoom in",
"NavigationControl.ZoomOut": "Zoom out",
"Popup.Close": "Close popup",
"ScaleControl.Feet": "ft",
"ScaleControl.Meters": "m",
"ScaleControl.Kilometers": "km",
"ScaleControl.Miles": "mi",
"ScaleControl.NauticalMiles": "nm",
"GlobeControl.Enable": "Enable globe",
"GlobeControl.Disable": "Disable globe",
"TerrainControl.Enable": "Enable terrain",
"TerrainControl.Disable": "Disable terrain",
"CooperativeGesturesHandler.WindowsHelpText": "Use Ctrl + scroll to zoom the map",
"CooperativeGesturesHandler.MacHelpText": "Use ⌘ + scroll to zoom the map",
"CooperativeGesturesHandler.MobileHelpText": "Use two fingers to move the map"
};
//#endregion
//#region src/ui/map.ts
const version$1 = version$2;
const defaultMinZoom = -2;
const defaultMaxZoom = 22;
const defaultMinPitch = 0;
const defaultMaxPitch = 60;
const defaultAnisotropicFilterPitch = 20;
const maxPitchThreshold = 180;
const defaultOptions$4 = {
hash: false,
interactive: true,
bearingSnap: 7,
zoomSnap: 0,
attributionControl: defaultAttributionControlOptions,
maplibreLogo: false,
refreshExpiredTiles: true,
canvasContextAttributes: {
antialias: false,
preserveDrawingBuffer: false,
powerPreference: "high-performance",
failIfMajorPerformanceCaveat: false,
desynchronized: false,
contextType: void 0
},
scrollZoom: true,
minZoom: defaultMinZoom,
maxZoom: defaultMaxZoom,
minPitch: defaultMinPitch,
maxPitch: defaultMaxPitch,
boxZoom: true,
dragRotate: true,
dragPan: true,
keyboard: true,
doubleClickZoom: true,
touchZoomRotate: true,
touchPitch: true,
cooperativeGestures: false,
trackResize: true,
center: [0, 0],
elevation: 0,
zoom: 0,
bearing: 0,
pitch: 0,
roll: 0,
renderWorldCopies: true,
maxTileCacheSize: null,
maxTileCacheZoomLevels: config.MAX_TILE_CACHE_ZOOM_LEVELS,
transformRequest: null,
transformCameraUpdate: null,
transformConstrain: null,
fadeDuration: 300,
crossSourceCollisions: true,
clickTolerance: 3,
localIdeographFontFamily: "sans-serif",
pitchWithRotate: true,
rollEnabled: false,
rotateSpeed: .8,
pitchSpeed: -.5,
reduceMotion: void 0,
validateStyle: true,
/**Because GL MAX_TEXTURE_SIZE is usually at least 4096px. */
maxCanvasSize: [4096, 4096],
cancelPendingTileRequestsWhileZooming: true,
centerClampedToGround: true,
terrainSkirtLength: "auto",
zoomLevelsToOverscale: 4,
anisotropicFilterPitch: defaultAnisotropicFilterPitch
};
/**
* The `Map` object represents the map on your page. It exposes methods
* and properties that enable you to programmatically change the map,
* and fires events as users interact with it.
*
* You create a `Map` by specifying a `container` and other options, see {@link MapOptions} for the full list.
* Then MapLibre GL JS initializes the map on the page and returns your `Map` object.
*
* @group Main
*
* @example
* ```ts
* let map = new Map({
* container: 'map',
* center: [-122.420679, 37.772537],
* zoom: 13,
* style: style_object,
* hash: true,
* transformRequest: (url, resourceType)=> {
* if(resourceType === 'Source' && url.startsWith('http://myHost')) {
* return {
* url: url.replace('http', 'https'),
* headers: { 'my-custom-header': true},
* credentials: 'include' // Include cookies for cross-origin requests
* }
* }
* }
* });
* ```
* @see [Display a map](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-map/)
*/
var Map$1 = class extends Evented {
/**
* @internal
* The window that owns the map container element, for cross-window support.
* Returns `typeof window` to include global constructors like ResizeObserver.
*/
get _ownerWindow() {
return this._container?.ownerDocument?.defaultView || window;
}
constructor(options) {
super();
this._idleTriggered = false;
this._crossFadingFactor = 1;
this._renderTaskQueue = new TaskQueue();
this._controls = [];
this._mapId = uniqueId();
this._missingStyleImageResolver = null;
this._lostContextStyle = {
style: null,
images: null
};
this._contextLost = (event) => {
event.preventDefault();
if (this._frameRequest) {
this._frameRequest.abort();
this._frameRequest = null;
}
this.painter.destroy();
this._lostContextStyle = this._getStyleAndImages();
if (!this.style) {
this.fire(new MapContextEvent("webglcontextlost", { originalEvent: event }));
return;
}
for (const layer of Object.values(this.style._layers)) {
if (layer.type === "custom") console.warn(`Custom layer with id '${layer.id}' cannot be restored after WebGL context loss. You will need to re-add it manually after context restoration.`);
if (layer._listeners) for (const [event] of Object.entries(layer._listeners)) console.warn(`Custom layer with id '${layer.id}' had event listeners for event '${event}' which cannot be restored after WebGL context loss. You will need to re-add them manually after context restoration.`);
}
this.style.destroy();
this.style = null;
this.fire(new MapContextEvent("webglcontextlost", { originalEvent: event }));
};
this._contextRestored = (event) => {
if (this._lostContextStyle.style) this.setStyle(this._lostContextStyle.style, { diff: false });
if (this._lostContextStyle.images && this.style) {
this.style.imageManager.images = this._lostContextStyle.images;
for (const id in this._lostContextStyle.images) {
const image = this._lostContextStyle.images[id];
if (image.isWebGLImage) this.style.imageManager.updateImage(id, image, false);
}
}
this._lostContextStyle = {
style: null,
images: null
};
this._setupPainter();
if (!this.painter) return;
this.resize();
this._update();
this._resizeInternal();
this.fire(new MapContextEvent("webglcontextrestored", { originalEvent: event }));
};
this._onMapScroll = (event) => {
if (event.target !== this._container) return;
this._container.scrollTop = 0;
this._container.scrollLeft = 0;
return false;
};
this._onWindowOnline = () => {
this._update();
};
const resolvedOptions = {
...defaultOptions$4,
...options,
canvasContextAttributes: {
...defaultOptions$4.canvasContextAttributes,
...options.canvasContextAttributes
}
};
if (resolvedOptions.minZoom != null && resolvedOptions.maxZoom != null && resolvedOptions.minZoom > resolvedOptions.maxZoom) throw new Error("maxZoom must be greater than or equal to minZoom");
if (resolvedOptions.minPitch != null && resolvedOptions.maxPitch != null && resolvedOptions.minPitch > resolvedOptions.maxPitch) throw new Error("maxPitch must be greater than or equal to minPitch");
if (resolvedOptions.minPitch != null && resolvedOptions.minPitch < defaultMinPitch) throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`);
if (resolvedOptions.maxPitch != null && resolvedOptions.maxPitch > maxPitchThreshold) throw new Error(`maxPitch must be less than or equal to ${maxPitchThreshold}`);
this._camera = new Camera({
minZoom: resolvedOptions.minZoom,
maxZoom: resolvedOptions.maxZoom,
minPitch: resolvedOptions.minPitch,
maxPitch: resolvedOptions.maxPitch,
bearingSnap: resolvedOptions.bearingSnap,
zoomSnap: resolvedOptions.zoomSnap,
renderWorldCopies: resolvedOptions.renderWorldCopies,
centerClampedToGround: resolvedOptions.centerClampedToGround,
terrain: this.terrain,
transformConstrain: resolvedOptions.transformConstrain,
requestRenderFrame: (callback) => this._requestRenderFrame(callback),
cancelRenderFrame: (id) => this._cancelRenderFrame(id),
transformCameraUpdate: resolvedOptions.transformCameraUpdate,
stopHandlers: () => this._handlers?.stop(false)
});
this._camera.setEventedParent(this);
this._interactive = resolvedOptions.interactive;
this._maxTileCacheSize = resolvedOptions.maxTileCacheSize;
this._maxTileCacheZoomLevels = resolvedOptions.maxTileCacheZoomLevels;
this._canvasContextAttributes = { ...resolvedOptions.canvasContextAttributes };
this._trackResize = resolvedOptions.trackResize === true;
this._terrainSkirtLength = resolvedOptions.terrainSkirtLength;
this._refreshExpiredTiles = resolvedOptions.refreshExpiredTiles === true;
this._fadeDuration = resolvedOptions.fadeDuration;
this._crossSourceCollisions = resolvedOptions.crossSourceCollisions === true;
this._collectResourceTiming = resolvedOptions.collectResourceTiming === true;
this._locale = {
...defaultLocale,
...resolvedOptions.locale
};
this._clickTolerance = resolvedOptions.clickTolerance;
this._overridePixelRatio = resolvedOptions.pixelRatio;
this._maxCanvasSize = resolvedOptions.maxCanvasSize;
this._zoomLevelsToOverscale = resolvedOptions.zoomLevelsToOverscale;
this.cancelPendingTileRequestsWhileZooming = resolvedOptions.cancelPendingTileRequestsWhileZooming === true;
this.setAnisotropicFilterPitch(resolvedOptions.anisotropicFilterPitch);
if (resolvedOptions.reduceMotion !== void 0) browser.prefersReducedMotion = resolvedOptions.reduceMotion;
this._imageQueueHandle = ImageRequest.addThrottleControl(() => this.isMoving());
this._requestManager = new RequestManager(resolvedOptions.transformRequest);
this._container = this._resolveContainer(resolvedOptions.container);
if (resolvedOptions.maxBounds) this.setMaxBounds(resolvedOptions.maxBounds);
this._setupContainer();
this._setupPainter();
if (!this.painter) return;
this.on("move", () => this._update(false));
this.on("moveend", () => this._update(false));
this.on("zoom", () => this._update(true));
this.on("terrain", () => {
this.painter.terrainFacilitator.depthDirty = true;
this._update(true);
});
this.once("idle", () => this._idleTriggered = true);
this._handlers = new HandlerManager(this, this._camera, resolvedOptions);
if (typeof window !== "undefined") {
this._ownerWindow.addEventListener("online", this._onWindowOnline, false);
this._setupResizeObserver();
}
const hashName = typeof resolvedOptions.hash === "string" && resolvedOptions.hash || void 0;
this._hash = resolvedOptions.hash ? new Hash(hashName).addTo(this) : void 0;
if (!this._hash?._onHashChange()) {
this.jumpTo({
center: resolvedOptions.center,
elevation: resolvedOptions.elevation,
zoom: resolvedOptions.zoom,
bearing: resolvedOptions.bearing,
pitch: resolvedOptions.pitch,
roll: resolvedOptions.roll
});
if (resolvedOptions.bounds) {
this.resize();
this.fitBounds(resolvedOptions.bounds, extend({}, resolvedOptions.fitBoundsOptions, { duration: 0 }));
}
}
const shouldConstrainUsingMercatorTransform = typeof resolvedOptions.style === "string" || !(resolvedOptions.style?.projection?.type === "globe");
this.resize(null, shouldConstrainUsingMercatorTransform);
this._localIdeographFontFamily = resolvedOptions.localIdeographFontFamily;
this._validateStyle = resolvedOptions.validateStyle;
if (resolvedOptions.style) this.setStyle(resolvedOptions.style, { localIdeographFontFamily: resolvedOptions.localIdeographFontFamily });
if (resolvedOptions.attributionControl) this.addControl(new AttributionControl(typeof resolvedOptions.attributionControl === "boolean" ? void 0 : resolvedOptions.attributionControl));
if (resolvedOptions.maplibreLogo) this.addControl(new LogoControl(), resolvedOptions.logoPosition);
this.on("style.load", () => {
if (!shouldConstrainUsingMercatorTransform) this._resizeTransform();
if (this._camera.transform.unmodified) {
const coercedOptions = pick(this.style.stylesheet, [
"center",
"zoom",
"bearing",
"pitch",
"roll"
]);
this.jumpTo(coercedOptions);
}
});
this.on("data", (event) => {
this._update(event.dataType === "style");
this.fire(event.dataType === "style" ? new MapStyleDataEvent("styledata", event) : new MapSourceDataEvent("sourcedata", event));
});
this.on("dataloading", (event) => {
this.fire(event.dataType === "style" ? new MapStyleDataEvent("styledataloading", event) : new MapSourceDataEvent("sourcedataloading", event));
});
this.on("dataabort", (event) => {
this.fire(new MapSourceDataEvent("sourcedataabort", event));
});
}
/**
* @internal
* Returns a unique number for this map instance which is used for the MapLoadEvent
* to make sure we only fire one event per instantiated map object.
* @returns the uniq map ID
*/
_getMapId() {
return this._mapId;
}
/**
* Sets a global state property that can be retrieved with the [`global-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#global-state).
* If the value is null, it resets the property to its default value defined in the [`state` style property](https://maplibre.org/maplibre-style-spec/root/#state).
*
* @param propertyName - The name of the state property to set.
* @param value - The value of the state property to set.
*/
setGlobalStateProperty(propertyName, value) {
this.style.setGlobalStateProperty(propertyName, value);
return this._update(true);
}
/**
* Returns the global map state
*
* @returns The map state object.
*/
getGlobalState() {
return this.style.getGlobalState();
}
/**
* Adds an {@link IControl} to the map, calling `control.onAdd(this)`.
*
* An {@link ErrorEvent} will be fired if the control is invalid.
*
* @param control - The {@link IControl} to add.
* @param position - position on the map to which the control will be added.
* Valid values are `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`. Defaults to `'top-right'`.
* @example
* Add zoom and rotation controls to the map.
* ```ts
* map.addControl(new NavigationControl());
* ```
* @see [Display map navigation controls](https://maplibre.org/maplibre-gl-js/docs/examples/display-map-navigation-controls/)
*/
addControl(control, position) {
if (position === void 0) {
if (control.getDefaultPosition) position = control.getDefaultPosition();
else position = "top-right";
}
if (!control?.onAdd) return this.fire(new ErrorEvent(/* @__PURE__ */ new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));
const controlElement = control.onAdd(this);
this._controls.push(control);
const positionContainer = this._controlPositions[position];
if (position.includes("bottom")) positionContainer.insertBefore(controlElement, positionContainer.firstChild);
else positionContainer.appendChild(controlElement);
return this;
}
/**
* Removes the control from the map.
*
* An {@link ErrorEvent} will be fired if the control is invalid.
*
* @param control - The {@link IControl} to remove.
* @example
* ```ts
* // Define a new navigation control.
* let navigation = new NavigationControl();
* // Add zoom and rotation controls to the map.
* map.addControl(navigation);
* // Remove zoom and rotation controls from the map.
* map.removeControl(navigation);
* ```
*/
removeControl(control) {
if (!control?.onRemove) return this.fire(new ErrorEvent(/* @__PURE__ */ new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));
const ci = this._controls.indexOf(control);
if (ci > -1) this._controls.splice(ci, 1);
control.onRemove(this);
return this;
}
/**
* Checks if a control exists on the map.
*
* @param control - The {@link IControl} to check.
* @returns true if map contains control.
* @example
* ```ts
* // Define a new navigation control.
* let navigation = new NavigationControl();
* // Add zoom and rotation controls to the map.
* map.addControl(navigation);
* // Check that the navigation control exists on the map.
* map.hasControl(navigation);
* ```
*/
hasControl(control) {
return this._controls.includes(control);
}
/**
* Returns an array of `OverscaledTileID` objects that cover the current viewport for a given tile size.
* This method is useful for determining which tiles are visible in the current viewport.
*
* @param options - Options for calculating the covering tiles.
* @returns An array of `OverscaledTileID` objects.
* @example
* ```ts
* // Get the tiles to cover the view for a 512x512px tile source
* const tiles = map.coveringTiles({tileSize: 512});
* ```
*/
coveringTiles(options) {
return coveringTiles(this._camera.transform, options);
}
/**
* Sets the callback used to defer camera updates or apply arbitrary constraints.
* If specified, this Camera instance can be used as a stateless component in React etc.
*/
setTransformCameraUpdate(value) {
this._camera.transformCameraUpdate = value;
}
/**
* Returns the map's geographical centerpoint.
*
* @returns The map's geographical centerpoint.
* @example
* Return a LngLat object such as `{lng: 0, lat: 0}`
* ```ts
* let center = map.getCenter();
* // access longitude and latitude values directly
* let {lng, lat} = map.getCenter();
* ```
*/
getCenter() {
return new LngLat(this._camera.transform.center.lng, this._camera.transform.center.lat);
}
/**
* Sets the map's geographical centerpoint. Equivalent to `jumpTo({center: center})`.
*
* Triggers the following events: `movestart` and `moveend`.
*
* @param center - The centerpoint to set.
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* ```ts
* map.setCenter([-74, 38]);
* ```
*/
setCenter(center, eventData) {
this._camera.setCenter(center, eventData);
return this;
}
/**
* Returns the elevation of the map's center point.
*
* @returns The elevation of the map's center point, in meters above sea level.
*/
getCenterElevation() {
return this._camera.transform.elevation;
}
/**
* Sets the elevation of the map's center point, in meters above sea level. Equivalent to `jumpTo({elevation: elevation})`.
*
* Triggers the following events: `movestart` and `moveend`.
*
* @param elevation - The elevation to set, in meters above sea level.
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
*/
setCenterElevation(elevation, eventData) {
this._camera.setCenterElevation(elevation, eventData);
return this;
}
/**
* Sets the value of `centerClampedToGround`.
*
* If true, the elevation of the center point will automatically be set to the terrain elevation
* (or zero if terrain is not enabled). If false, the elevation of the center point will default
* to sea level and will not automatically update. Defaults to true. Needs to be set to false to
* keep the camera above ground when pitch \> 90 degrees.
*/
setCenterClampedToGround(centerClampedToGround) {
this._camera.setCenterClampedToGround(centerClampedToGround);
}
/**
* Pans the map by the specified offset.
*
* Triggers the following events: `movestart` and `moveend`.
*
* @param offset - `x` and `y` coordinates by which to pan the map.
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/navigate-the-map-with-game-like-controls/)
*/
panBy(offset, options, eventData) {
this._camera.panBy(offset, options, eventData);
return this;
}
/**
* Pans the map to the specified location with an animated transition.
*
* Triggers the following events: `movestart` and `moveend`.
*
* @param lnglat - The location to pan the map to.
* @param options - Options describing the destination and animation of the transition.
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* ```ts
* map.panTo([-74, 38]);
* // Specify that the panTo animation should last 5000 milliseconds.
* map.panTo([-74, 38], {duration: 5000});
* ```
* @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/update-a-feature-in-realtime/)
*/
panTo(lnglat, options, eventData) {
this._camera.panTo(lnglat, options, eventData);
return this;
}
/**
* Returns the map's current zoom level.
*
* @returns The map's current zoom level.
* @example
* ```ts
* map.getZoom();
* ```
*/
getZoom() {
return this._camera.transform.zoom;
}
/**
* Sets the map's zoom level. Equivalent to `jumpTo({zoom: zoom})`.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.
*
* @param zoom - The zoom level to set (0-20).
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* Zoom to the zoom level 5 without an animated transition
* ```ts
* map.setZoom(5);
* ```
*/
setZoom(zoom, eventData) {
this._camera.setZoom(zoom, eventData);
return this;
}
/**
* Zooms the map to the specified zoom level, with an animated transition.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.
*
* @param zoom - The zoom level to transition to.
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* ```ts
* // Zoom to the zoom level 5 without an animated transition
* map.zoomTo(5);
* // Zoom to the zoom level 8 with an animated transition
* map.zoomTo(8, {
* duration: 2000,
* offset: [100, 50]
* });
* ```
*/
zoomTo(zoom, options, eventData) {
this._camera.zoomTo(zoom, options, eventData);
return this;
}
/**
* Incrementally increases the map's zoom level by 1, first snapping to the nearest `zoomSnap` increment.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.
*
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* Zoom the map in one level with a custom animation duration
* ```ts
* map.zoomIn({duration: 1000});
* ```
*/
zoomIn(options, eventData) {
this._camera.zoomIn(options, eventData);
return this;
}
/**
* Decreases the map's zoom level by 1, first snapping to the nearest `zoomSnap` increment.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.
*
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* Zoom the map out one level with a custom animation offset
* ```ts
* map.zoomOut({offset: [80, 60]});
* ```
*/
zoomOut(options, eventData) {
this._camera.zoomOut(options, eventData);
return this;
}
/**
* Returns the map's current vertical field of view, in degrees.
*
* @returns The map's current vertical field of view.
* @defaultValue 36.87
* @example
* ```ts
* const verticalFieldOfView = map.getVerticalFieldOfView();
* ```
*/
getVerticalFieldOfView() {
return this._camera.transform.fov;
}
/**
* Sets the map's vertical field of view, in degrees.
*
* Triggers the following events: `movestart`, `move`, and `moveend`.
*
* @param fov - The vertical field of view to set, in degrees (0-180).
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @defaultValue 36.87
* @example
* Change vertical field of view to 30 degrees
* ```ts
* map.setVerticalFieldOfView(30);
* ```
*/
setVerticalFieldOfView(fov, eventData) {
this._camera.setVerticalFieldOfView(fov, eventData);
return this;
}
/**
* Returns the map's current bearing. The bearing is the compass direction that is "up"; for example, a bearing
* of 90° orients the map so that east is up.
*
* @returns The map's current bearing.
* @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/navigate-the-map-with-game-like-controls/)
*/
getBearing() {
return this._camera.transform.bearing;
}
/**
* Sets the map's bearing (rotation). The bearing is the compass direction that is "up"; for example, a bearing
* of 90° orients the map so that east is up.
*
* Equivalent to `jumpTo({bearing: bearing})`.
*
* Triggers the following events: `movestart`, `moveend`, and `rotate`.
*
* @param bearing - The desired bearing.
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* Rotate the map to 90 degrees
* ```ts
* map.setBearing(90);
* ```
*/
setBearing(bearing, eventData) {
this._camera.setBearing(bearing, eventData);
return this;
}
/**
* Returns the map's current zoom snap level.
*
* @returns The map's current zoom snap level.
*/
getZoomSnap() {
return this._camera.getZoomSnap();
}
/**
* Sets the map's zoom snap level.
*
* @param snap - The zoom snap level to set.
*/
setZoomSnap(snap) {
this._camera.setZoomSnap(snap);
return this;
}
/**
* Returns the current padding applied around the map viewport.
*
* @returns The current padding around the map viewport.
*/
getPadding() {
return this._camera.transform.padding;
}
/**
* Sets the padding in pixels around the viewport.
*
* Equivalent to `jumpTo({padding: padding})`.
*
* Triggers the following events: `movestart` and `moveend`.
*
* @param padding - The desired padding.
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* Sets a left padding of 300px, and a top padding of 50px
* ```ts
* map.setPadding({ left: 300, top: 50 });
* ```
*/
setPadding(padding, eventData) {
this._camera.setPadding(padding, eventData);
return this;
}
/**
* Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction
* that is "up"; for example, a bearing of 90° orients the map so that east is up.
*
* Triggers the following events: `movestart`, `moveend`, and `rotate`.
*
* @param bearing - The desired bearing.
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
*/
rotateTo(bearing, options, eventData) {
this._camera.rotateTo(bearing, options, eventData);
return this;
}
/**
* Rotates the map so that north is up (0° bearing), with an animated transition.
*
* Triggers the following events: `movestart`, `moveend`, and `rotate`.
*
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
*/
resetNorth(options, eventData) {
this._camera.resetNorth(options, eventData);
return this;
}
/**
* Rotates and pitches the map so that north is up (0° bearing) and pitch and roll are 0°, with an animated transition.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `pitchstart`, `pitch`, `pitchend`, `rollstart`, `roll`, `rollend`, and `rotate`.
*
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
*/
resetNorthPitch(options, eventData) {
this._camera.resetNorthPitch(options, eventData);
return this;
}
/**
* Snaps the map so that north is up (0° bearing), if the current bearing is close enough to it (i.e. within the
* `bearingSnap` threshold).
*
* Triggers the following events: `movestart`, `moveend`, and `rotate`.
*
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
*/
snapToNorth(options, eventData) {
this._camera.snapToNorth(options, eventData);
return this;
}
/**
* Returns the map's current pitch (tilt).
*
* @returns The map's current pitch, measured in degrees away from the plane of the screen.
*/
getPitch() {
return this._camera.transform.pitch;
}
/**
* Sets the map's pitch (tilt). Equivalent to `jumpTo({pitch: pitch})`.
*
* Triggers the following events: `movestart`, `moveend`, `pitchstart`, and `pitchend`.
*
* @param pitch - The pitch to set, measured in degrees away from the plane of the screen (0-60).
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
*/
setPitch(pitch, eventData) {
this._camera.setPitch(pitch, eventData);
return this;
}
/**
* Returns the map's current roll angle.
*
* @returns The map's current roll, measured in degrees about the camera boresight.
*/
getRoll() {
return this._camera.transform.roll;
}
/**
* Sets the map's roll angle. Equivalent to `jumpTo({roll: roll})`.
*
* Triggers the following events: `movestart`, `moveend`, `rollstart`, and `rollend`.
*
* @param roll - The roll to set, measured in degrees about the camera boresight
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
*/
setRoll(roll, eventData) {
this._camera.setRoll(roll, eventData);
return this;
}
/**
* @param bounds - Calculate the center for these bounds in the viewport and use
* the highest zoom level up to and including {@link Map.getMaxZoom} that fits
* in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0.
* Bounds will be taken in `[sw, ne]` order. Southwest point will always be to the left of the northeast point.
* @param options - Options object
* @returns If map is able to fit to provided bounds, returns `center`, `zoom`, and `bearing`.
* If map is unable to fit, method will warn and return undefined.
* @example
* ```ts
* let bbox = [[-79, 43], [-73, 45]];
* let newCameraTransform = map.cameraForBounds(bbox, {
* padding: {top: 10, bottom:25, left: 15, right: 5}
* });
* ```
*/
cameraForBounds(bounds, options) {
return this._camera.cameraForBounds(bounds, options);
}
/**
* Pans and zooms the map to contain its visible area within the specified geographical bounds.
* This function will also reset the map's bearing to 0 if bearing is nonzero.
*
* Triggers the following events: `movestart` and `moveend`.
*
* @param bounds - Center these bounds in the viewport and use the highest
* zoom level up to and including {@link Map.getMaxZoom} that fits them in the viewport.
* Bounds will be taken in `[sw, ne]` order. Southwest point will always be to the left of the northeast point.
* @param options - Options supports all properties from {@link AnimationOptions} and {@link CameraOptions} in addition to the fields below.
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* ```ts
* let bbox = [[-79, 43], [-73, 45]];
* map.fitBounds(bbox, {
* padding: {top: 10, bottom:25, left: 15, right: 5}
* });
* ```
* @see [Fit a map to a bounding box](https://maplibre.org/maplibre-gl-js/docs/examples/fit-a-map-to-a-bounding-box/)
*/
fitBounds(bounds, options, eventData) {
this._camera.fitBounds(bounds, options, eventData);
return this;
}
/**
* Pans, rotates and zooms the map to to fit the box made by points p0 and p1
* once the map is rotated to the specified bearing. To zoom without rotating,
* pass in the current map bearing.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend` and `rotate`.
*
* @param p0 - First point on screen, in pixel coordinates
* @param p1 - Second point on screen, in pixel coordinates
* @param bearing - Desired map bearing at end of animation, in degrees
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* ```ts
* let p0 = [220, 400];
* let p1 = [500, 900];
* map.fitScreenCoordinates(p0, p1, map.getBearing(), {
* padding: {top: 10, bottom:25, left: 15, right: 5}
* });
* ```
* @see Used by {@link BoxZoomHandler}
*/
fitScreenCoordinates(p0, p1, bearing, options, eventData) {
this._camera.fitScreenCoordinates(p0, p1, bearing, options, eventData);
return this;
}
/**
* Changes any combination of center, zoom, bearing, pitch, and roll, without
* an animated transition. The map will retain its current values for any
* details not specified in `options`.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`,
* `pitch`, `pitchend`, `rollstart`, `roll`, `rollend` and `rotate`.
*
* @param options - Options object
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* ```ts
* // jump to coordinates at current zoom
* map.jumpTo({center: [0, 0]});
* // jump with zoom, pitch, and bearing options
* map.jumpTo({
* center: [0, 0],
* zoom: 8,
* pitch: 45,
* bearing: 90
* });
* ```
* @see [Jump to a series of locations](https://maplibre.org/maplibre-gl-js/docs/examples/jump-to-a-series-of-locations/)
* @see [Update a feature in realtime](https://maplibre.org/maplibre-gl-js/docs/examples/update-a-feature-in-realtime/)
*/
jumpTo(options, eventData) {
this._camera.jumpTo(options, eventData);
return this;
}
/**
* Given a camera position and rotation, calculates zoom and center point and returns them as {@link CameraOptions}.
* @param cameraLngLat - The lng, lat of the camera to look from
* @param cameraAlt - The altitude of the camera to look from, in meters above sea level
* @param bearing - Bearing of the camera, in degrees
* @param pitch - Pitch of the camera, in degrees
* @param roll - Roll of the camera, in degrees
* @returns the calculated camera options
* @example
* ```ts
* // Calculate options to look from camera position(1°, 0°, 1000m) with bearing = 90°, pitch = 30°, and roll = 45°
* const cameraLngLat = new LngLat(1, 0);
* const cameraAltitude = 1000;
* const bearing = 90;
* const pitch = 30;
* const roll = 45;
* const cameraOptions = map.calculateCameraOptionsFromCameraLngLatAltRotation(cameraLngLat, cameraAltitude, bearing, pitch, roll);
* // Apply calculated options
* map.jumpTo(cameraOptions);
* ```
*/
calculateCameraOptionsFromCameraLngLatAltRotation(cameraLngLat, cameraAlt, bearing, pitch, roll) {
return this._camera.calculateCameraOptionsFromCameraLngLatAltRotation(cameraLngLat, cameraAlt, bearing, pitch, roll);
}
/**
* Changes any combination of `center`, `zoom`, `bearing`, `pitch`, `roll`, and `padding` with an animated transition
* between old and new values. The map will retain its current values for any
* details not specified in `options`.
*
* !!! note "Reduced Motion"
* The transition will happen instantly if the user has enabled
* the `reduced motion` accessibility feature enabled in their operating system,
* unless `options` includes `essential: true`.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`,
* `pitch`, `pitchend`, `rollstart`, `roll`, `rollend`, and `rotate`.
*
* @param options - Options describing the destination and animation of the transition.
* Accepts {@link CameraOptions} and {@link AnimationOptions}.
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @see [Navigate the map with game-like controls](https://maplibre.org/maplibre-gl-js/docs/examples/navigate-the-map-with-game-like-controls/)
*/
easeTo(options, eventData) {
this._camera.easeTo(options, eventData);
return this;
}
/**
* Changes any combination of center, zoom, bearing, pitch, and roll, animating the transition along a curve that
* evokes flight. The animation seamlessly incorporates zooming and panning to help
* the user maintain her bearings even after traversing a great distance.
*
* !!! note "Reduced Motion"
* The animation will be skipped, and this will behave equivalently to `jumpTo`
* if the user has the `reduced motion` accessibility feature enabled in their operating system,
* unless 'options' includes `essential: true`.
*
* Triggers the following events: `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, `zoomend`, `pitchstart`,
* `pitch`, `pitchend`, `rollstart`, `roll`, `rollend`, and `rotate`.
*
* @param options - Options describing the destination and animation of the transition.
* Accepts {@link CameraOptions}, {@link AnimationOptions},
* and the following additional options.
* @param eventData - Additional properties to be added to event objects of events triggered by this method.
* @example
* ```ts
* // fly with default options to null island
* map.flyTo({center: [0, 0], zoom: 9});
* // using flyTo options
* map.flyTo({
* center: [0, 0],
* zoom: 9,
* speed: 0.2,
* curve: 1,
* easing(t) {
* return t;
* }
* });
* ```
* @see [Fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/fly-to-a-location/)
* @see [Slowly fly to a location](https://maplibre.org/maplibre-gl-js/docs/examples/slowly-fly-to-a-location/)
* @see [Fly to a location based on scroll position](https://maplibre.org/maplibre-gl-js/docs/examples/fly-to-a-location-based-on-scroll-position/)
*/
flyTo(options, eventData) {
this._camera.flyTo(options, eventData);
return this;
}
/**
* Stops any animated transition underway.
*/
stop() {
this._camera.stop();
return this;
}
/**
* Gets the elevation at a given location, in meters above sea level.
* Returns null if terrain is not enabled.
* If terrain is enabled with some exaggeration value, the value returned here will be reflective of (multiplied by) that exaggeration value.
* This method should be used for proper positioning of custom 3d objects, as explained [here](https://maplibre.org/maplibre-gl-js/docs/examples/adding-3d-models-using-threejs-on-terrain/)
* @param lngLatLike - `[x, y]` or LngLat coordinates of the location
* @returns elevation in meters
*/
queryTerrainElevation(lngLatLike) {
if (!this.terrain) return null;
return this.terrain.getElevationForLngLat(LngLat.convert(lngLatLike), this._camera.transform);
}
/**
* Returns the value of `centerClampedToGround`.
*
* If true, the elevation of the center point will automatically be set to the terrain elevation
* (or zero if terrain is not enabled). If false, the elevation of the center point will default
* to sea level and will not automatically update. Defaults to true. Needs to be set to false to
* keep the camera above ground when pitch \> 90 degrees.
*/
getCenterClampedToGround() {
return this._camera.getCenterClampedToGround();
}
/**
* Given a camera 'from' position and a position to look at (`to`), calculates zoom and camera rotation and returns them as {@link CameraOptions}.
* @param from - The camera to look from
* @param altitudeFrom - The altitude of the camera to look from
* @param to - The center to look at
* @param altitudeTo - Optional altitude of the center to look at. If none given the ground height will be used.
* @returns the calculated camera options
* @example
* ```ts
* // Calculate options to look from (1°, 0°, 1000m) to (1°, 1°, 0m)
* const cameraLngLat = new LngLat(1, 0);
* const cameraAltitude = 1000;
* const targetLngLat = new LngLat(1, 1);
* const targetAltitude = 0;
* const cameraOptions = map.calculateCameraOptionsFromTo(cameraLngLat, cameraAltitude, targetLngLat, targetAltitude);
* // Apply calculated options
* map.jumpTo(cameraOptions);
* ```
*/
calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo) {
if (altitudeTo == null && this.terrain) altitudeTo = this.terrain.getElevationForLngLat(to, this._camera.transform);
return this._camera.calculateCameraOptionsFromTo(from, altitudeFrom, to, altitudeTo);
}
/**
* Resizes the map according to the dimensions of its
* `container` element.
*
* Checks if the map container size changed and updates the map if it has changed.
* This method must be called after the map's `container` is resized programmatically
* or when the map is shown after being initially hidden with CSS.
*
* Triggers the following events: `movestart`, `move`, `moveend`, and `resize`.
*
* @param eventData - Additional properties to be passed to `movestart`, `move`, `resize`, and `moveend`
* events that get triggered as a result of resize. This can be useful for differentiating the
* source of an event (for example, user-initiated or programmatically-triggered events).
* @example
* Resize the map when the map container is shown after being initially hidden with CSS.
* ```ts
* let mapDiv = document.getElementById('map');
* if (mapDiv.style.visibility === true) map.resize();
* ```
*/
resize(eventData, constrainTransform = true) {
if (this._lostContextStyle.style !== null) return this;
this._resizeInternal(constrainTransform);
const fireMoving = !this._camera._moving;
if (fireMoving) {
this.stop();
this.fire(new MapMovementEvent("movestart", eventData)).fire(new MapMovementEvent("move", eventData));
}
this.fire(new MapLibreEvent("resize", eventData));
if (fireMoving) this.fire(new MapMovementEvent("moveend", eventData));
return this;
}
/**
* Resizes the map according to the dimensions of its
* `container` element.
*
* It does not trigger any events, and does not check for context loss.
*
* It is used internally and by {@link Map.resize}.
*
* @internal
*
* @param constrainTransform - whether to constrain the transform after resizing.
*/
_resizeInternal(constrainTransform = true) {
const [width, height] = this._containerDimensions();
const clampedPixelRatio = this._getClampedPixelRatio(width, height);
this._resizeCanvas(width, height, clampedPixelRatio);
this.painter.resize(width, height, clampedPixelRatio);
if (this.painter.overLimit()) {
const gl = this.painter.context.gl;
this._maxCanvasSize = [gl.drawingBufferWidth, gl.drawingBufferHeight];
const clampedPixelRatio = this._getClampedPixelRatio(width, height);
this._resizeCanvas(width, height, clampedPixelRatio);
this.painter.resize(width, height, clampedPixelRatio);
}
this._resizeTransform(constrainTransform);
}
_resizeTransform(constrainTransform = true) {
const [width, height] = this._containerDimensions();
this._camera.transform.resize(width, height, constrainTransform);
this._camera._requestedCameraState?.resize(width, height, constrainTransform);
}
/**
* @internal
* Return the map's pixel ratio eventually scaled down to respect maxCanvasSize.
* Internally you should use this and not getPixelRatio().
*/
_getClampedPixelRatio(width, height) {
const { 0: maxCanvasWidth, 1: maxCanvasHeight } = this._maxCanvasSize;
const pixelRatio = this.getPixelRatio();
const canvasWidth = width * pixelRatio;
const canvasHeight = height * pixelRatio;
const widthScaleFactor = canvasWidth > maxCanvasWidth ? maxCanvasWidth / canvasWidth : 1;
const heightScaleFactor = canvasHeight > maxCanvasHeight ? maxCanvasHeight / canvasHeight : 1;
return Math.min(widthScaleFactor, heightScaleFactor) * pixelRatio;
}
/**
* Returns the map's pixel ratio.
* Note that the pixel ratio actually applied may be lower to respect maxCanvasSize.
* @returns The pixel ratio.
*/
getPixelRatio() {
return this._overridePixelRatio ?? devicePixelRatio;
}
/**
* Sets the map's pixel ratio. This allows to override `devicePixelRatio`.
* After this call, the canvas' `width` attribute will be `container.clientWidth * pixelRatio`
* and its height attribute will be `container.clientHeight * pixelRatio`.
* Set this to null to disable `devicePixelRatio` override.
* Note that the pixel ratio actually applied may be lower to respect maxCanvasSize.
* @param pixelRatio - The pixel ratio.
*/
setPixelRatio(pixelRatio) {
this._overridePixelRatio = pixelRatio;
this.resize();
}
/**
* Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not
* an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region.
* @returns The geographical bounds of the map as {@link LngLatBounds}.
* @example
* ```ts
* let bounds = map.getBounds();
* ```
*/
getBounds() {
return this._camera.transform.getBounds();
}
/**
* Returns the maximum geographical bounds the map is constrained to, or `null` if none set.
* @returns The map object.
* @example
* ```ts
* let maxBounds = map.getMaxBounds();
* ```
*/
getMaxBounds() {
return this._camera.transform.getMaxBounds();
}
/**
* Sets or clears the map's geographical bounds.
*
* Pan and zoom operations are constrained within these bounds.
* If a pan or zoom is performed that would
* display regions outside these bounds, the map will
* instead display a position and zoom level
* as close as possible to the operation's request while still
* remaining within the bounds.
*
* @param bounds - The maximum bounds to set. If `null` or `undefined` is provided, the function removes the map's maximum bounds.
* @example
* Define bounds that conform to the `LngLatBoundsLike` object as set the max bounds.
* ```ts
* let bounds = [
* [-74.04728, 40.68392], // [west, south]
* [-73.91058, 40.87764] // [east, north]
* ];
* map.setMaxBounds(bounds);
* ```
*/
setMaxBounds(bounds) {
this._camera.transform.setMaxBounds(LngLatBounds.convert(bounds));
return this._update();
}
/**
* Sets or clears the map's minimum zoom level.
* If the map's current zoom level is lower than the new minimum,
* the map will zoom to the new minimum and trigger the following events:
* `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.
*
* It is not always possible to zoom out and reach the set `minZoom`.
* Other factors such as map height may restrict zooming. For example,
* if the map is 512px tall it will not be possible to zoom below zoom 0
* no matter what the `minZoom` is set to.
*
* A {@link ErrorEvent} event will be fired if minZoom is out of bounds.
*
* @param minZoom - The minimum zoom level to set (-2 - 24).
* If `null` or `undefined` is provided, the function removes the current minimum zoom (i.e. sets it to -2).
* @example
* ```ts
* map.setMinZoom(12.25);
* ```
*/
setMinZoom(minZoom) {
minZoom = minZoom === null || minZoom === void 0 ? defaultMinZoom : minZoom;
if (minZoom >= defaultMinZoom && minZoom <= this._camera.transform.maxZoom) {
const zoomBefore = this._camera.transform.zoom;
const tr = this._camera.getTransformForUpdate();
tr.setMinZoom(minZoom);
this._camera.applyUpdatedTransform(tr);
this._update();
if (zoomBefore !== this._camera.transform.zoom) this.fire(new MapMovementEvent("zoomstart")).fire(new MapMovementEvent("zoom")).fire(new MapMovementEvent("zoomend")).fire(new MapMovementEvent("movestart")).fire(new MapMovementEvent("move")).fire(new MapMovementEvent("moveend"));
return this;
} else throw new Error(`minZoom must be between ${defaultMinZoom} and the current maxZoom, inclusive`);
}
/**
* Returns the map's minimum allowable zoom level.
*
* @returns minZoom
* @example
* ```ts
* let minZoom = map.getMinZoom();
* ```
*/
getMinZoom() {
return this._camera.transform.minZoom;
}
/**
* Sets or clears the map's maximum zoom level.
* If the map's current zoom level is higher than the new maximum,
* the map will zoom to the new maximum and trigger the following events:
* `movestart`, `move`, `moveend`, `zoomstart`, `zoom`, and `zoomend`.
*
* A {@link ErrorEvent} event will be fired if minZoom is out of bounds.
*
* @param maxZoom - The maximum zoom level to set.
* If `null` or `undefined` is provided, the function removes the current maximum zoom (sets it to 22).
* @example
* ```ts
* map.setMaxZoom(18.75);
* ```
*/
setMaxZoom(maxZoom) {
maxZoom = maxZoom === null || maxZoom === void 0 ? defaultMaxZoom : maxZoom;
if (maxZoom >= this._camera.transform.minZoom) {
const zoomBefore = this._camera.transform.zoom;
const tr = this._camera.getTransformForUpdate();
tr.setMaxZoom(maxZoom);
this._camera.applyUpdatedTransform(tr);
this._update();
if (zoomBefore !== this._camera.transform.zoom) this.fire(new MapMovementEvent("zoomstart")).fire(new MapMovementEvent("zoom")).fire(new MapMovementEvent("zoomend")).fire(new MapMovementEvent("movestart")).fire(new MapMovementEvent("move")).fire(new MapMovementEvent("moveend"));
return this;
} else throw new Error("maxZoom must be greater than the current minZoom");
}
/**
* Returns the map's maximum allowable zoom level.
*
* @returns The maxZoom
* @example
* ```ts
* let maxZoom = map.getMaxZoom();
* ```
*/
getMaxZoom() {
return this._camera.transform.maxZoom;
}
/**
* Sets or clears the map's minimum pitch.
* If the map's current pitch is lower than the new minimum,
* the map will pitch to the new minimum and trigger the following events:
* `movestart`, `move`, `moveend`, `pitchstart`, `pitch`, and `pitchend`.
*
* A {@link ErrorEvent} event will be fired if minPitch is out of bounds.
*
* @param minPitch - The minimum pitch to set (0-180). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project.
* If `null` or `undefined` is provided, the function removes the current minimum pitch (i.e. sets it to 0).
*/
setMinPitch(minPitch) {
minPitch = minPitch === null || minPitch === void 0 ? defaultMinPitch : minPitch;
if (minPitch < defaultMinPitch) throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`);
if (minPitch >= defaultMinPitch && minPitch <= this._camera.transform.maxPitch) {
const pitchBefore = this._camera.transform.pitch;
const tr = this._camera.getTransformForUpdate();
tr.setMinPitch(minPitch);
this._camera.applyUpdatedTransform(tr);
this._update();
if (pitchBefore !== this._camera.transform.pitch) this.fire(new MapMovementEvent("pitchstart")).fire(new MapMovementEvent("pitch")).fire(new MapMovementEvent("pitchend")).fire(new MapMovementEvent("movestart")).fire(new MapMovementEvent("move")).fire(new MapMovementEvent("moveend"));
return this;
} else throw new Error(`minPitch must be between ${defaultMinPitch} and the current maxPitch, inclusive`);
}
/**
* Returns the map's minimum allowable pitch.
*
* @returns The minPitch
*/
getMinPitch() {
return this._camera.transform.minPitch;
}
/**
* Sets or clears the map's maximum pitch.
* If the map's current pitch is higher than the new maximum,
* the map will pitch to the new maximum and trigger the following events:
* `movestart`, `move`, `moveend`, `pitchstart`, `pitch`, and `pitchend`.
*
* A {@link ErrorEvent} event will be fired if maxPitch is out of bounds.
*
* @param maxPitch - The maximum pitch to set (0-180). Values greater than 60 degrees are experimental and may result in rendering issues. If you encounter any, please raise an issue with details in the MapLibre project.
* If `null` or `undefined` is provided, the function removes the current maximum pitch (sets it to 60).
*/
setMaxPitch(maxPitch) {
maxPitch = maxPitch === null || maxPitch === void 0 ? defaultMaxPitch : maxPitch;
if (maxPitch > maxPitchThreshold) throw new Error(`maxPitch must be less than or equal to ${maxPitchThreshold}`);
if (maxPitch >= this._camera.transform.minPitch) {
const pitchBefore = this._camera.transform.pitch;
const tr = this._camera.getTransformForUpdate();
tr.setMaxPitch(maxPitch);
this._camera.applyUpdatedTransform(tr);
this._update();
if (pitchBefore !== this._camera.transform.pitch) this.fire(new MapMovementEvent("pitchstart")).fire(new MapMovementEvent("pitch")).fire(new MapMovementEvent("pitchend")).fire(new MapMovementEvent("movestart")).fire(new MapMovementEvent("move")).fire(new MapMovementEvent("moveend"));
return this;
} else throw new Error("maxPitch must be greater than the current minPitch");
}
/**
* Returns the map's maximum allowable pitch.
*
* @returns The maxPitch
*/
getMaxPitch() {
return this._camera.transform.maxPitch;
}
/**
* Returns the map's anisotropic filter pitch.
* If the map is pitched beyond this threshold, anisotropic filtering will be applied to all raster layers.
*
* @returns The anisotropicFilterPitch
* @example
* ```ts
* let anisotropicFilterPitch = map.getAnisotropicFilterPitch();
* ```
*/
getAnisotropicFilterPitch() {
return this._anisotropicFilterPitch;
}
/**
* Sets the map's anisotropic filter pitch or reverts it to its default.
*
* A {@link ErrorEvent} event will be fired if anisotropicFilterPitch is out of bounds.
*
* @param anisotropicFilterPitch - The pitch above which to apply anisotropic filtering to the map's raster layers (0-180).
* If `null` or `undefined` is provided, the function reverts to the default pitch threshold (20).
*
*
* @example
* ```ts
* map.setAnisotropicFilterPitch(85);
* ```
*/
setAnisotropicFilterPitch(anisotropicFilterPitch) {
anisotropicFilterPitch = anisotropicFilterPitch === null || anisotropicFilterPitch === void 0 ? defaultAnisotropicFilterPitch : anisotropicFilterPitch;
if (anisotropicFilterPitch > maxPitchThreshold) throw new Error(`anisotropicFilterPitch must be less than or equal to ${maxPitchThreshold}`);
if (anisotropicFilterPitch < defaultMinPitch) throw new Error(`anisotropicFilterPitch must be greater than or equal to ${defaultMinPitch}`);
this._anisotropicFilterPitch = anisotropicFilterPitch;
return this._update();
}
/**
* Returns the state of `renderWorldCopies`. If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`:
*
* - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire
* container, there will be blank space beyond 180 and -180 degrees longitude.
* - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the
* map and the other on the left edge of the map) at every zoom level.
* @returns The renderWorldCopies
* @example
* ```ts
* let worldCopiesRendered = map.getRenderWorldCopies();
* ```
* @see [Render world copies](https://maplibre.org/maplibre-gl-js/docs/examples/render-world-copies/)
*/
getRenderWorldCopies() {
return this._camera.transform.renderWorldCopies;
}
/**
* Sets the state of `renderWorldCopies`.
*
* @param renderWorldCopies - If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`:
*
* - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire
* container, there will be blank space beyond 180 and -180 degrees longitude.
* - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the
* map and the other on the left edge of the map) at every zoom level.
*
* `undefined` is treated as `true`, `null` is treated as `false`.
* @example
* ```ts
* map.setRenderWorldCopies(true);
* ```
* @see [Render world copies](https://maplibre.org/maplibre-gl-js/docs/examples/render-world-copies/)
*/
setRenderWorldCopies(renderWorldCopies) {
this._camera.transform.setRenderWorldCopies(renderWorldCopies);
return this._update();
}
/** Sets or clears the callback overriding how the map constrains the viewport's lnglat and zoom to respect the longitude and latitude bounds.
*
* @param constrain - A {@link TransformConstrainFunction} callback defining how the viewport should respect the bounds.
*
* `null` clears the callback and reverts the constrain to the map transform's default constrain function.
* @example
* ```ts
* function customTransformConstrain(lngLat, zoom) {
* return {center: lngLat, zoom: zoom ?? 0};
* };
* map.setTransformConstrain(customTransformConstrain);
* ```
* @see [Customize the map transform constrain](https://maplibre.org/maplibre-gl-js/docs/examples/customize-the-map-transform-constrain/)
*/
setTransformConstrain(constrain) {
this._camera.transform.setConstrainOverride(constrain);
return this._update();
}
/**
* Returns a [Point](https://github.com/mapbox/point-geometry) representing pixel coordinates, relative to the map's `container`,
* that correspond to the specified geographical location.
*
* @param lnglat - The geographical location to project.
* @returns The [Point](https://github.com/mapbox/point-geometry) corresponding to `lnglat`, relative to the map's `container`.
* @example
* ```ts
* let coordinate = [-122.420679, 37.772537];
* let point = map.project(coordinate);
* ```
*/
project(lnglat) {
return this._camera.transform.locationToScreenPoint(LngLat.convert(lnglat), this.style && this.terrain);
}
/**
* Returns a {@link LngLat} representing geographical coordinates that correspond
* to the specified pixel coordinates.
*
* @param point - The pixel coordinates to unproject.
* @returns The {@link LngLat} corresponding to `point`.
* @example
* ```ts
* map.on('click', (e) => {
* // When the map is clicked, get the geographic coordinate.
* let coordinate = map.unproject(e.point);
* });
* ```
*/
unproject(point) {
return this._camera.transform.screenPointToLocation(Point.convert(point), this.terrain);
}
/**
* Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture.
* @returns true if the map is moving.
* @example
* ```ts
* let isMoving = map.isMoving();
* ```
*/
isMoving() {
return this._camera.isMoving() || this._handlers?.isMoving() || false;
}
/**
* Returns true if the map is zooming due to a camera animation or user gesture.
* @returns true if the map is zooming.
* @example
* ```ts
* let isZooming = map.isZooming();
* ```
*/
isZooming() {
return this._camera.isZooming() || this._handlers?.isZooming() || false;
}
/**
* Returns true if the map is rotating due to a camera animation or user gesture.
* @returns true if the map is rotating.
* @example
* ```ts
* map.isRotating();
* ```
*/
isRotating() {
return this._camera.isRotating() || this._handlers?.isRotating() || false;
}
_createDelegatedListener(type, layerIds, listener) {
if (type === "mouseenter" || type === "mouseover") {
let mousein = false;
const mousemove = (e) => {
const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId));
const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, { layers: existingLayers }) : [];
if (!features.length) mousein = false;
else if (!mousein) {
mousein = true;
listener.call(this, new MapMouseEvent(type, this, e.originalEvent, { features }));
}
};
const mouseout = () => {
mousein = false;
};
return {
layers: layerIds,
listener,
delegates: {
mousemove,
mouseout
}
};
} else if (type === "mouseleave" || type === "mouseout") {
let mousein = false;
const mousemove = (e) => {
const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId));
if ((existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, { layers: existingLayers }) : []).length) mousein = true;
else if (mousein) {
mousein = false;
listener.call(this, new MapMouseEvent(type, this, e.originalEvent));
}
};
const mouseout = (e) => {
if (mousein) {
mousein = false;
listener.call(this, new MapMouseEvent(type, this, e.originalEvent));
}
};
return {
layers: layerIds,
listener,
delegates: {
mousemove,
mouseout
}
};
} else {
const delegate = (e) => {
const existingLayers = layerIds.filter((layerId) => this.getLayer(layerId));
const features = existingLayers.length !== 0 ? this.queryRenderedFeatures(e.point, { layers: existingLayers }) : [];
if (features.length) {
e.features = features;
listener.call(this, e);
delete e.features;
}
};
return {
layers: layerIds,
listener,
delegates: { [type]: delegate }
};
}
}
_saveDelegatedListener(type, delegatedListener) {
this._delegatedListeners ||= {};
this._delegatedListeners[type] ||= [];
this._delegatedListeners[type].push(delegatedListener);
}
_removeDelegatedListener(type, layerIds, listener) {
if (!this._delegatedListeners?.[type]) return;
const listeners = this._delegatedListeners[type];
for (let i = 0; i < listeners.length; i++) {
const delegatedListener = listeners[i];
if (delegatedListener.listener === listener && delegatedListener.layers.length === layerIds.length && delegatedListener.layers.every((layerId) => layerIds.includes(layerId))) {
for (const event in delegatedListener.delegates) this.off(event, delegatedListener.delegates[event]);
listeners.splice(i, 1);
return;
}
}
}
on(type, layerIdsOrListener, listener) {
if (listener === void 0) return super.on(type, layerIdsOrListener);
const layerIds = typeof layerIdsOrListener === "string" ? [layerIdsOrListener] : layerIdsOrListener;
const delegatedListener = this._createDelegatedListener(type, layerIds, listener);
this._saveDelegatedListener(type, delegatedListener);
for (const event in delegatedListener.delegates) this.on(event, delegatedListener.delegates[event]);
return { unsubscribe: () => {
this._removeDelegatedListener(type, layerIds, listener);
} };
}
once(type, layerIdsOrListener, listener) {
if (listener === void 0) return super.once(type, layerIdsOrListener);
const layerIds = typeof layerIdsOrListener === "string" ? [layerIdsOrListener] : layerIdsOrListener;
const delegatedListener = this._createDelegatedListener(type, layerIds, listener);
for (const key in delegatedListener.delegates) {
const delegate = delegatedListener.delegates[key];
delegatedListener.delegates[key] = (...args) => {
this._removeDelegatedListener(type, layerIds, listener);
delegate(...args);
};
}
this._saveDelegatedListener(type, delegatedListener);
for (const event in delegatedListener.delegates) this.once(event, delegatedListener.delegates[event]);
return this;
}
off(type, layerIdsOrListener, listener) {
if (listener === void 0) return super.off(type, layerIdsOrListener);
const layerIds = typeof layerIdsOrListener === "string" ? [layerIdsOrListener] : layerIdsOrListener;
this._removeDelegatedListener(type, layerIds, listener);
return this;
}
/**
* Returns an array of MapGeoJSONFeature objects
* representing visible features that satisfy the query parameters.
*
* @param geometryOrOptions - (optional) The geometry of the query region in pixel points within the map viewport:
* either a single pixel point or a pair of top-left and bottom-right pixel points describing a bounding box.
* The origin of the pixel points is at the top-left of the map viewport.
* Omitting this parameter (i.e. calling {@link Map.queryRenderedFeatures} with zero arguments,
* or with only a `options` argument) is equivalent to passing a bounding box encompassing the entire
* map viewport.
* The geometryOrOptions can receive a {@link QueryRenderedFeaturesOptions} only to support a situation where the function receives only one parameter which is the options parameter.
* @param options - (optional) Options object.
*
* @returns An array of MapGeoJSONFeature objects.
*
* The `properties` value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only
* string and numeric property values are supported (i.e. `null`, `Array`, and `Object` values are not supported).
*
* Each feature includes top-level `layer`, `source`, and `sourceLayer` properties. The `layer` property is an object
* representing the style layer to which the feature belongs. Layout and paint properties in this object contain values
* which are fully evaluated for the given zoom level and feature.
*
* Only features that are currently rendered are included. Some features will **not** be included, like:
*
* - Features from layers whose `visibility` property is `"none"`.
* - Features from layers whose zoom range excludes the current zoom level.
* - Symbol features that have been hidden due to text or icon collision.
*
* Features from all other layers are included, including features that may have no visible
* contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to
* 0.
*
* The topmost rendered feature appears first in the returned array, and subsequent features are sorted by
* descending z-order. Features that are rendered multiple times (due to wrapping across the antemeridian at low
* zoom levels) are returned only once (though subject to the following caveat).
*
* Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature
* geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple
* times in query results. For example, suppose there is a highway running through the bounding rectangle of a query.
* The results of the query will be those parts of the highway that lie within the map tiles covering the bounding
* rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile
* will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple
* tiles due to tile buffering.
*
* @example
* Find all features at a point
* ```ts
* let features = map.queryRenderedFeatures(
* [20, 35],
* { layers: ['my-layer-name'] }
* );
* ```
*
* @example
* Find all features within a static bounding box
* ```ts
* let features = map.queryRenderedFeatures(
* [[10, 20], [30, 50]],
* { layers: ['my-layer-name'] }
* );
* ```
*
* @example
* Find all features within a bounding box around a point
* ```ts
* let width = 10;
* let height = 20;
* let features = map.queryRenderedFeatures([
* [point.x - width / 2, point.y - height / 2],
* [point.x + width / 2, point.y + height / 2]
* ], { layers: ['my-layer-name'] });
* ```
*
* @example
* Query all rendered features from a single layer
* ```ts
* let features = map.queryRenderedFeatures({ layers: ['my-layer-name'] });
* ```
* @see [Get features under the mouse pointer](https://maplibre.org/maplibre-gl-js/docs/examples/get-features-under-the-mouse-pointer/)
*/
queryRenderedFeatures(geometryOrOptions, options) {
if (!this.style) return [];
let queryGeometry;
const isGeometry = geometryOrOptions instanceof Point || Array.isArray(geometryOrOptions);
const geometry = isGeometry ? geometryOrOptions : [[0, 0], [this._camera.transform.width, this._camera.transform.height]];
options ||= (isGeometry ? {} : geometryOrOptions) || {};
if (geometry instanceof Point || typeof geometry[0] === "number") queryGeometry = [Point.convert(geometry)];
else {
const tl = Point.convert(geometry[0]);
const br = Point.convert(geometry[1]);
queryGeometry = [
tl,
new Point(br.x, tl.y),
br,
new Point(tl.x, br.y),
tl
];
}
return this.style.queryRenderedFeatures(queryGeometry, options, this._camera.transform);
}
/**
* Returns an array of MapGeoJSONFeature objects
* representing features within the specified vector tile or GeoJSON source that satisfy the query parameters.
*
* @param sourceId - The ID of the vector tile or GeoJSON source to query.
* @param parameters - The options object.
* @returns An array of MapGeoJSONFeature objects.
*
* In contrast to {@link Map.queryRenderedFeatures}, this function returns all features matching the query parameters,
* whether or not they are rendered by the current style (i.e. visible). The domain of the query includes all currently-loaded
* vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently
* visible viewport.
*
* Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature
* geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple
* times in query results. For example, suppose there is a highway running through the bounding rectangle of a query.
* The results of the query will be those parts of the highway that lie within the map tiles covering the bounding
* rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile
* will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple
* tiles due to tile buffering.
*
* @example
* Find all features in one source layer in a vector source
* ```ts
* let features = map.querySourceFeatures('your-source-id', {
* sourceLayer: 'your-source-layer'
* });
* ```
*
*/
querySourceFeatures(sourceId, parameters) {
return this.style.querySourceFeatures(sourceId, parameters);
}
/**
* Updates the map's MapLibre style object with a new value.
*
* If a style is already set when this is used and options.diff is set to true, the map renderer will attempt to compare the given style
* against the map's current state and perform only the changes necessary to make the map style match the desired state. Changes in sprites
* (images used for icons and patterns) and glyphs (fonts for label text) **cannot** be diffed. If the sprites or fonts used in the current
* style and the given style are different in any way, the map renderer will force a full update, removing the current style and building
* the given one from scratch.
*
*
* @param style - A JSON object conforming to the schema described in the
* [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/), or a URL to such JSON.
* @param options - The options object.
*
* @example
* ```ts
* map.setStyle("https://demotiles.maplibre.org/style.json");
*
* map.setStyle('https://demotiles.maplibre.org/style.json', {
* transformStyle: (previousStyle, nextStyle) => ({
* ...nextStyle,
* sources: {
* ...nextStyle.sources,
* // copy a source from previous style
* 'osm': previousStyle.sources.osm
* },
* layers: [
* // background layer
* nextStyle.layers[0],
* // copy a layer from previous style
* previousStyle.layers[0],
* // other layers from the next style
* ...nextStyle.layers.slice(1).map(layer => {
* // hide the layers we don't need from demotiles style
* if (layer.id.startsWith('geolines')) {
* layer.layout = {...layer.layout || {}, visibility: 'none'};
* // filter out US polygons
* } else if (layer.id.startsWith('coastline') || layer.id.startsWith('countries')) {
* layer.filter = ['!=', ['get', 'ADM0_A3'], 'USA'];
* }
* return layer;
* })
* ]
* })
* });
* ```
*/
setStyle(style, options) {
options = extend({}, {
localIdeographFontFamily: this._localIdeographFontFamily,
validate: this._validateStyle
}, options);
if (options.diff !== false && options.localIdeographFontFamily === this._localIdeographFontFamily && this.style && style) {
this._diffStyle(style, options);
return this;
} else {
this._localIdeographFontFamily = options.localIdeographFontFamily;
return this._updateStyle(style, options);
}
}
/**
* Updates the requestManager's transform request with a new function
*
* @param transformRequest - A callback run before the Map makes a request for an external URL. The callback can be used to modify the url, set headers, or set the credentials property for cross-origin requests.
* Expected to return an object with a `url` property and optionally `headers` and `credentials` properties
*
* @example
* ```ts
* map.setTransformRequest((url: string, resourceType: string) => {});
* ```
*/
setTransformRequest(transformRequest) {
this._requestManager.setTransformRequest(transformRequest);
return this;
}
_getUIString(key) {
const str = this._locale[key];
if (str == null) throw new Error(`Missing UI string '${key}'`);
return str;
}
_updateStyle(style, options) {
this._diffStyleRequest?.abort();
this._diffStyleRequest = null;
if (options.transformStyle && this.style && !this.style._loaded) {
this.style.once("style.load", () => this._updateStyle(style, options));
return;
}
const previousStyle = this.style && options.transformStyle ? this.style.serialize() : void 0;
if (this.style) {
this.style.setEventedParent(null);
this.style._remove(!style);
}
if (!style) {
if (this._frameRequest) {
this._frameRequest.abort();
this._frameRequest = null;
}
this.style?.projection?.destroy();
delete this.style;
return this;
} else this.style = new Style(this, options || {});
this.style.setEventedParent(this, { style: this.style });
if (typeof style === "string") this.style.loadURL(style, options, previousStyle);
else this.style.loadJSON(style, options, previousStyle);
return this;
}
_lazyInitEmptyStyle() {
if (!this.style) {
this.style = new Style(this, {});
this.style.setEventedParent(this, { style: this.style });
this.style.loadEmpty();
}
}
async _diffStyle(style, options) {
this._diffStyleRequest?.abort();
if (typeof style === "string") {
const url = style;
this._diffStyleRequest = new AbortController();
const abortController = this._diffStyleRequest;
try {
const request = await this._requestManager.transformRequest(url, "Style");
if (abortController.signal.aborted) {
this._diffStyleRequest = null;
return;
}
const response = await getJSON(request, abortController);
this._diffStyleRequest = null;
this._updateDiff(response.data, options);
} catch (error) {
this._diffStyleRequest = null;
if (!isAbortError(error)) this.fire(new ErrorEvent(ensureError(error)));
}
} else if (typeof style === "object") {
this._diffStyleRequest = null;
this._updateDiff(style, options);
}
}
_updateDiff(style, options) {
try {
if (this.style.setState(style, options)) this._update(true);
} catch (e) {
warnOnce(`Unable to perform style diff: ${ensureError(e).message}. Rebuilding the style from scratch.`);
this._updateStyle(style, options);
}
}
/**
* Returns the map's MapLibre style object, a JSON object which can be used to recreate the map's style.
*
* @returns The map's style JSON object.
*
* @example
* ```ts
* let styleJson = map.getStyle();
* ```
*
*/
getStyle() {
if (this.style) return this.style.serialize();
}
/**
* @internal
* Returns the map's style and cloned images to restore context.
* @returns An object containing the style and images.
*/
_getStyleAndImages() {
if (this.style) return {
style: this.style.serialize(),
images: this.style.imageManager.cloneImages()
};
return {
style: null,
images: {}
};
}
/**
* Returns a Boolean indicating whether the map's style is fully loaded.
*
* @returns A Boolean indicating whether the style is fully loaded.
*
* @example
* ```ts
* let styleLoadStatus = map.isStyleLoaded();
* ```
*/
isStyleLoaded() {
if (!this.style) {
warnOnce("There is no style added to the map.");
return;
}
return this.style.loaded();
}
/**
* Adds a source to the map's style.
*
* Events triggered:
*
* Triggers the `source.add` event.
*
* @param id - The ID of the source to add. Must not conflict with existing sources.
* @param source - The source object, conforming to the
* MapLibre Style Specification's [source definition](https://maplibre.org/maplibre-style-spec/sources) or
* {@link CanvasSourceSpecification}.
* @example
* ```ts
* map.addSource('my-data', {
* type: 'vector',
* url: 'https://demotiles.maplibre.org/tiles/tiles.json'
* });
* ```
* @example
* ```ts
* map.addSource('my-data', {
* "type": "geojson",
* "data": {
* "type": "Feature",
* "geometry": {
* "type": "Point",
* "coordinates": [-77.0396, 38.8891]
* },
* "properties": {
* "title": "Washington DC",
* "marker-symbol": "monument"
* }
* }
* });
* ```
* @see GeoJSON source: [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/add-live-realtime-data/)
*/
addSource(id, source) {
this._lazyInitEmptyStyle();
this.style.addSource(id, source);
return this._update(true);
}
/**
* Returns a Boolean indicating whether the source is loaded. Returns `true` if the source with
* the given ID in the map's style has no outstanding network requests, otherwise `false`.
*
* A {@link ErrorEvent} event will be fired if there is no source with the specified ID.
*
* @param id - The ID of the source to be checked.
* @returns A Boolean indicating whether the source is loaded.
* @example
* ```ts
* let sourceLoaded = map.isSourceLoaded('bathymetry-data');
* ```
*/
isSourceLoaded(id) {
const tileManager = this.style?.tileManagers[id];
if (tileManager === void 0) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error(`There is no tile manager with ID '${id}'`)));
return;
}
return tileManager.loaded();
}
/**
* Loads a 3D terrain mesh, based on a "raster-dem" source.
*
* Triggers the `terrain` event.
*
* @param options - Options object.
* @example
* ```ts
* map.setTerrain({ source: 'terrain' });
* ```
*/
setTerrain(options, styleOptions = {}) {
this.style._checkLoaded();
if (options && validateAndEmit(this, validateStyle.terrain, { value: options }, styleOptions)) return this;
if (this._terrainDataCallback) this.style.off("data", this._terrainDataCallback);
if (!options) {
if (this.terrain) this.terrain.destroy();
this.terrain = null;
this.painter.renderToTexture = null;
this._camera.terrain = null;
this._camera.transform.setMinElevationForCurrentTile(0);
if (this.getCenterClampedToGround()) this._camera.transform.setElevation(0);
} else {
const tileManager = this.style.tileManagers[options.source];
if (!tileManager) throw new Error(`cannot load terrain, because there exists no source with ID: ${options.source}`);
if (this.terrain === null) tileManager.reload();
for (const index in this.style._layers) {
const thisLayer = this.style._layers[index];
if (thisLayer.type === "hillshade" && thisLayer.source === options.source) warnOnce("You are using the same source for a hillshade layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.");
if (thisLayer.type === "color-relief" && thisLayer.source === options.source) warnOnce("You are using the same source for a color-relief layer and for 3D terrain. Please consider using two separate sources to improve rendering quality.");
}
if (this.terrain) this.terrain.destroy();
this.terrain = new Terrain(this.painter, tileManager, options, this._terrainSkirtLength);
this.painter.renderToTexture = new RenderToTexture(this.painter, this.terrain);
this._camera.terrain = this.terrain;
this._camera.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._camera.transform.center, this._camera.transform.tileZoom));
this._camera.transform.setElevation(this.terrain.getElevationForLngLatZoom(this._camera.transform.center, this._camera.transform.tileZoom));
this._terrainDataCallback = (e) => this._handleTerrainDataEvent(e, options.source);
this.style.on("data", this._terrainDataCallback);
}
this.fire(new MapTerrainEvent({ terrain: options }));
return this;
}
_handleTerrainDataEvent(event, terrainSourceId) {
if (event.dataType === "style") {
this.terrain.tileManager.releaseAllRTT();
return;
}
const isTerrainSourceEvent = event.sourceId === terrainSourceId;
if (isTerrainSourceEvent) this.terrain.resetElevationCache();
if (isTerrainSourceEvent && event.tile && !this._camera.elevationFreeze) {
this._camera.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._camera.transform.center, this._camera.transform.tileZoom));
if (this.getCenterClampedToGround()) this._camera.transform.setElevation(this.terrain.getElevationForLngLatZoom(this._camera.transform.center, this._camera.transform.tileZoom));
}
if (!event.tile) return;
if (event.source?.type === "image") {
this.terrain.tileManager.releaseAllRTT();
return;
}
this.terrain.tileManager.releaseRTT(event.tile.tileID);
}
/**
* Get the terrain-options if terrain is loaded
* @returns the TerrainSpecification passed to setTerrain
* @example
* ```ts
* map.getTerrain(); // { source: 'terrain' };
* ```
*/
getTerrain() {
return this.terrain?.options ?? null;
}
/**
* Returns a Boolean indicating whether all tiles in the viewport from all sources on
* the style are loaded.
*
* @returns A Boolean indicating whether all tiles are loaded.
* @example
* ```ts
* let tilesLoaded = map.areTilesLoaded();
* ```
*/
areTilesLoaded() {
const tileManagers = this.style?.tileManagers;
for (const tileManager of Object.values(tileManagers)) if (!tileManager.areTilesLoaded()) return false;
return true;
}
/**
* Removes a source from the map's style.
*
* @param id - The ID of the source to remove.
* @example
* ```ts
* map.removeSource('bathymetry-data');
* ```
*/
removeSource(id) {
this.style.removeSource(id);
return this._update(true);
}
/**
* Returns the source with the specified ID in the map's style.
*
* This method is often used to update a source using the instance members for the relevant
* source type as defined in classes that derive from {@link Source}.
* For example, setting the `data` for a GeoJSON source or updating the `url` and `coordinates`
* of an image source.
*
* @param id - The ID of the source to get.
* @returns The style source with the specified ID or `undefined` if the ID
* corresponds to no existing sources.
* The shape of the object varies by source type.
* A list of options for each source type is available on the MapLibre Style Specification's
* [Sources](https://maplibre.org/maplibre-style-spec/sources/) page.
* @example
* ```ts
* let sourceObject = map.getSource('points');
* ```
* @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)
* @see [Animate a point](https://maplibre.org/maplibre-gl-js/docs/examples/animate-a-point/)
* @see [Add live realtime data](https://maplibre.org/maplibre-gl-js/docs/examples/add-live-realtime-data/)
*/
getSource(id) {
return this.style?.getSource(id);
}
/**
* Change the tile Level of Detail behavior of the specified source. These parameters have no effect when
* pitch == 0, and the largest effect when the horizon is visible on screen.
*
* @param maxZoomLevelsOnScreen - The maximum number of distinct zoom levels allowed on screen at a time.
* There will generally be fewer zoom levels on the screen, the maximum can only be reached when the horizon
* is at the top of the screen. Increasing the maximum number of zoom levels causes the zoom level to decay
* faster toward the horizon.
* @param tileCountMaxMinRatio - The ratio of the maximum number of tiles loaded (at high pitch) to the minimum
* number of tiles loaded. Increasing this ratio allows more tiles to be loaded at high pitch angles. If the ratio
* would otherwise be exceeded, the zoom level is reduced uniformly to keep the number of tiles within the limit.
* @param sourceId - The ID of the source to set tile LOD parameters for. All sources will be updated if unspecified.
* If `sourceId` is specified but a corresponding source does not exist, an error is thrown.
* @example
* ```ts
* map.setSourceTileLodParams(4.0, 3.0, 'terrain');
* ```
* @see [Modify Level of Detail behavior](https://maplibre.org/maplibre-gl-js/docs/examples/level-of-detail-control/)
*/
setSourceTileLodParams(maxZoomLevelsOnScreen, tileCountMaxMinRatio, sourceId) {
if (sourceId) {
const source = this.getSource(sourceId);
if (!source) throw new Error(`There is no source with ID "${sourceId}", cannot set LOD parameters`);
source.calculateTileZoom = createCalculateTileZoomFunction(Math.max(1, maxZoomLevelsOnScreen), Math.max(1, tileCountMaxMinRatio));
} else for (const id in this.style.tileManagers) this.style.tileManagers[id].getSource().calculateTileZoom = createCalculateTileZoomFunction(Math.max(1, maxZoomLevelsOnScreen), Math.max(1, tileCountMaxMinRatio));
this._update(true);
return this;
}
/**
* Triggers a reload of the selected tiles
*
* @param sourceId - The ID of the source
* @param tileIds - An array of tile IDs to be reloaded. If not defined, all tiles will be reloaded.
* @example
* ```ts
* map.refreshTiles('satellite', [{x:1024, y: 1023, z: 11}, {x:1023, y: 1023, z: 11}]);
* ```
*/
refreshTiles(sourceId, tileIds) {
const tileManager = this.style.tileManagers[sourceId];
if (!tileManager) throw new Error(`There is no tile manager with ID "${sourceId}", cannot refresh tile`);
if (tileIds === void 0) tileManager.reload(true);
else tileManager.refreshTiles(tileIds.map((tileId) => {
return new CanonicalTileID(tileId.z, tileId.x, tileId.y);
}));
}
/**
* Add an image to the style. This image can be displayed on the map like any other icon in the style's
* sprite using the image's ID with
* [`icon-image`](https://maplibre.org/maplibre-style-spec/layers/#layout-symbol-icon-image),
* [`background-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-background-background-pattern),
* [`fill-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-fill-fill-pattern),
* or [`line-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-line-line-pattern).
*
* A {@link ErrorEvent} event will be fired if the image parameter is invalid or there is not enough space in the sprite to add this image.
*
* @param id - The ID of the image.
* @param image - The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data`
* properties with the same format as `ImageData`.
* @param options - Options object.
* @example
* ```ts
* // If the style's sprite does not already contain an image with ID 'cat',
* // add the image 'cat-icon.png' to the style's sprite with the ID 'cat'.
* const image = await map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png');
* if (!map.hasImage('cat')) map.addImage('cat', image.data);
*
* // Add a stretchable image that can be used with `icon-text-fit`
* // In this example, the image is 600px wide by 400px high.
* const image = await map.loadImage('https://upload.wikimedia.org/wikipedia/commons/8/89/Black_and_White_Boxed_%28bordered%29.png');
* if (map.hasImage('border-image')) return;
* map.addImage('border-image', image.data, {
* content: [16, 16, 300, 384], // place text over left half of image, avoiding the 16px border
* stretchX: [[16, 584]], // stretch everything horizontally except the 16px border
* stretchY: [[16, 384]], // stretch everything vertically except the 16px border
* });
* ```
* @see Use `HTMLImageElement`: [Add an icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-an-icon-to-the-map/)
* @see Use `ImageData`: [Add a generated icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-generated-icon-to-the-map/)
*/
addImage(id, image, options = {}) {
this._lazyInitEmptyStyle();
const styleImage = this._createStyleImage(image, options);
if (!styleImage) return this;
this.style.addImage(id, styleImage);
if (styleImage.userImage?.onAdd) styleImage.userImage.onAdd(this, id);
return this;
}
/**
* Sets a callback that is invoked when an icon or pattern needed by the style is missing.
*
* The resolver typically loads or generates the image and registers it with {@link Map.addImage}.
* MapLibre awaits the returned promise before treating the image as missing, so async work is
* supported. If the image is still missing afterwards, the `styleimagemissing` event is fired.
*
* @param resolver - Callback used to resolve missing images, or `null` to remove the resolver.
* @example
* ```ts
* map.setMissingStyleImageResolver(async (id) => {
* const response = await fetch(`/icons/${id}.png`);
* const image = await createImageBitmap(await response.blob());
* map.addImage(id, image, {pixelRatio: 2});
* });
* ```
*/
setMissingStyleImageResolver(resolver) {
this._missingStyleImageResolver = resolver;
this.style?.setMissingImageResolver(resolver);
return this;
}
_createStyleImage(image, options = {}) {
const { pixelRatio = 1, sdf = false, stretchX, stretchY, content, textFitWidth, textFitHeight } = options;
const version = 0;
if (image instanceof HTMLImageElement || isImageBitmap(image)) {
const { width, height, data } = browser.getImageData(image);
return {
data: new RGBAImage({
width,
height
}, data),
pixelRatio,
stretchX,
stretchY,
content,
textFitWidth,
textFitHeight,
sdf,
version
};
} else if (image.width === void 0 || image.height === void 0) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));
return null;
} else {
const { width, height, data } = image;
const userImage = image;
const isWebGLImage = isStyleImageWebGLData(userImage.data);
return {
data: isWebGLImage ? new RGBAImage({
width,
height
}) : new RGBAImage({
width,
height
}, new Uint8Array(data)),
pixelRatio,
stretchX,
stretchY,
content,
textFitWidth,
textFitHeight,
sdf,
version,
isWebGLImage,
userImage
};
}
}
/**
* Update an existing image in a style. This image can be displayed on the map like any other icon in the style's
* sprite using the image's ID with
* [`icon-image`](https://maplibre.org/maplibre-style-spec/layers/#layout-symbol-icon-image),
* [`background-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-background-background-pattern),
* [`fill-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-fill-fill-pattern),
* or [`line-pattern`](https://maplibre.org/maplibre-style-spec/layers/#paint-line-line-pattern).
*
* An {@link ErrorEvent} will be fired if the image parameter is invalid.
*
* @param id - The ID of the image.
* @param image - The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data`
* properties with the same format as `ImageData`.
* @example
* ```ts
* // If an image with the ID 'cat' already exists in the style's sprite,
* // replace that image with a new image, 'other-cat-icon.png'.
* if (map.hasImage('cat')) map.updateImage('cat', './other-cat-icon.png');
* ```
*/
updateImage(id, image) {
const existingImage = this.style.getImage(id);
if (!existingImage) return this.fire(new ErrorEvent(/* @__PURE__ */ new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));
const { width, height, data } = image instanceof HTMLImageElement || isImageBitmap(image) ? browser.getImageData(image) : image;
if (width === void 0 || height === void 0) return this.fire(new ErrorEvent(/* @__PURE__ */ new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));
if (width !== existingImage.data.width || height !== existingImage.data.height) return this.fire(new ErrorEvent(/* @__PURE__ */ new Error("The width and height of the updated image must be that same as the previous version of the image")));
existingImage.isWebGLImage = isStyleImageWebGLData(data);
if (existingImage.isWebGLImage) existingImage.userImage = image;
else {
const copy = !(image instanceof HTMLImageElement || isImageBitmap(image));
existingImage.data.replace(data, copy);
}
this.style.updateImage(id, existingImage);
return this;
}
/**
* Returns an image, specified by ID, currently available in the map.
* This includes both images from the style's original sprite
* and any images that have been added at runtime using {@link Map.addImage}.
*
* @param id - The ID of the image.
* @returns An image in the map with the specified ID.
*
* @example
* ```ts
* let coffeeShopIcon = map.getImage("coffee_cup");
* ```
*/
getImage(id) {
return this.style.getImage(id);
}
/**
* Check whether or not an image with a specific ID exists in the style. This checks both images
* in the style's original sprite and any images
* that have been added at runtime using {@link Map.addImage}.
*
* An {@link ErrorEvent} will be fired if the image ID is missing.
*
* @param id - The ID of the image.
*
* @returns A Boolean indicating whether the image exists.
* @example
* Check if an image with the ID 'cat' exists in the style's sprite.
* ```ts
* let catIconExists = map.hasImage('cat');
* ```
*/
hasImage(id) {
if (!id) {
this.fire(new ErrorEvent(/* @__PURE__ */ new Error("Missing required image id")));
return false;
}
return !!this.style.getImage(id);
}
/**
* Remove an image from a style. This can be an image from the style's original
* sprite or any images
* that have been added at runtime using {@link Map.addImage}.
*
* @param id - The ID of the image.
*
* @example
* ```ts
* // If an image with the ID 'cat' exists in
* // the style's sprite, remove it.
* if (map.hasImage('cat')) map.removeImage('cat');
* ```
*/
removeImage(id) {
this.style.removeImage(id);
}
/**
* Load an image from an external URL to be used with {@link Map.addImage}. External
* domains must support [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS).
*
* @param url - The URL of the image file. Image file must be in png, webp, or jpg format.
* @returns a promise that is resolved when the image is loaded
*
* @example
* Load an image from an external URL.
* ```ts
* const response = await map.loadImage('https://picsum.photos/50/50');
* // Add the loaded image to the style's sprite with the ID 'photo'.
* map.addImage('photo', response.data);
* ```
* @see [Add an icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-an-icon-to-the-map/)
*/
async loadImage(url) {
return ImageRequest.getImage(await this._requestManager.transformRequest(url, "Image"), new AbortController());
}
/**
* Returns an Array of strings containing the IDs of all images currently available in the map.
* This includes both images from the style's original sprite
* and any images that have been added at runtime using {@link Map.addImage}.
*
* @returns An Array of strings containing the names of all sprites/images currently available in the map.
*
* @example
* ```ts
* let allImages = map.listImages();
* ```
*/
listImages() {
return this.style?.listImages() ?? [];
}
/**
* Adds a [MapLibre style layer](https://maplibre.org/maplibre-style-spec/layers)
* to the map's style.
*
* A layer defines how data from a specified source will be styled. Read more about layer types
* and available paint and layout properties in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/layers).
*
* @param layer - The layer to add,
* conforming to either the MapLibre Style Specification's [layer definition](https://maplibre.org/maplibre-style-spec/layers) or,
* less commonly, the {@link CustomLayerInterface} specification. Can also be a layer definition with an embedded source definition.
* The MapLibre Style Specification's layer definition is appropriate for most layers.
*
* @param beforeId - The ID of an existing layer to insert the new layer before,
* resulting in the new layer appearing visually beneath the existing layer.
* If this argument is not specified, the layer will be appended to the end of the layers array
* and appear visually above all other layers.
*
* @example
* Add a circle layer with a vector source
* ```ts
* map.addLayer({
* id: 'points-of-interest',
* source: {
* type: 'vector',
* url: 'https://demotiles.maplibre.org/tiles/tiles.json'
* },
* 'source-layer': 'poi_label',
* type: 'circle',
* paint: {
* // MapLibre Style Specification paint properties
* },
* layout: {
* // MapLibre Style Specification layout properties
* }
* });
* ```
*
* @example
* Define a source before using it to create a new layer
* ```ts
* map.addSource('state-data', {
* type: 'geojson',
* data: 'path/to/data.geojson'
* });
*
* map.addLayer({
* id: 'states',
* // References the GeoJSON source defined above
* // and does not require a `source-layer`
* source: 'state-data',
* type: 'symbol',
* layout: {
* // Set the label content to the
* // feature's `name` property
* text-field: ['get', 'name']
* }
* });
* ```
*
* @example
* Add a new symbol layer before an existing layer
* ```ts
* map.addLayer({
* id: 'states',
* // References a source that's already been defined
* source: 'state-data',
* type: 'symbol',
* layout: {
* // Set the label content to the
* // feature's `name` property
* text-field: ['get', 'name']
* }
* // Add the layer before the existing `cities` layer
* }, 'cities');
* ```
* @see [Create and style clusters](https://maplibre.org/maplibre-gl-js/docs/examples/create-and-style-clusters/)
* @see [Add a vector tile source](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-vector-tile-source/)
* @see [Add a WMS source](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-wms-source/)
*/
addLayer(layer, beforeId) {
this._lazyInitEmptyStyle();
this.style.addLayer(layer, beforeId);
return this._update(true);
}
/**
* Moves a layer to a different z-position.
*
* @param id - The ID of the layer to move.
* @param beforeId - The ID of an existing layer to insert the new layer before. When viewing the map, the `id` layer will appear beneath the `beforeId` layer. If `beforeId` is omitted, the layer will be appended to the end of the layers array and appear above all other layers on the map.
*
* @example
* Move a layer with ID 'polygon' before the layer with ID 'country-label'. The `polygon` layer will appear beneath the `country-label` layer on the map.
* ```ts
* map.moveLayer('polygon', 'country-label');
* ```
*/
moveLayer(id, beforeId) {
this.style.moveLayer(id, beforeId);
return this._update(true);
}
/**
* Removes the layer with the given ID from the map's style.
*
* An {@link ErrorEvent} will be fired if no such layer exists.
*
* @param id - The ID of the layer to remove
*
* @example
* If a layer with ID 'state-data' exists, remove it.
* ```ts
* if (map.getLayer('state-data')) map.removeLayer('state-data');
* ```
*/
removeLayer(id) {
this.style.removeLayer(id);
return this._update(true);
}
/**
* Returns the layer with the specified ID in the map's style.
*
* @param id - The ID of the layer to get.
* @returns The layer with the specified ID, or `undefined`
* if the ID corresponds to no existing layers.
*
* @example
* ```ts
* let stateDataLayer = map.getLayer('state-data');
* ```
* @see [Filter symbols by toggling a list](https://maplibre.org/maplibre-gl-js/docs/examples/filter-symbols-by-toggling-a-list/)
* @see [Filter symbols by text input](https://maplibre.org/maplibre-gl-js/docs/examples/filter-symbols-by-text-input/)
*/
getLayer(id) {
return this.style?.getLayer(id);
}
/**
* Return the ids of all layers currently in the style, including custom layers, in order.
*
* @returns ids of layers, in order
*
* @example
* ```ts
* const orderedLayerIds = map.getLayersOrder();
* ```
*/
getLayersOrder() {
return this.style?.getLayersOrder() ?? [];
}
/**
* Sets the zoom extent for the specified style layer. The zoom extent includes the
* [minimum zoom level](https://maplibre.org/maplibre-style-spec/layers/#minzoom)
* and [maximum zoom level](https://maplibre.org/maplibre-style-spec/layers/#maxzoom))
* at which the layer will be rendered.
*
* !!! note
* For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the
* minimum zoom level of the _source layer_ because the data does not exist at those zoom levels. If the minimum
* zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style
* layer will not be rendered at all zoom levels in the zoom range.
*
* @param layerId - The ID of the layer to which the zoom extent will be applied.
* @param minzoom - The minimum zoom to set (0-24).
* @param maxzoom - The maximum zoom to set (0-24).
*
* @example
* ```ts
* map.setLayerZoomRange('my-layer', 2, 5);
* ```
*/
setLayerZoomRange(layerId, minzoom, maxzoom) {
this.style.setLayerZoomRange(layerId, minzoom, maxzoom);
return this._update(true);
}
/**
* Sets the filter for the specified style layer.
*
* Filters control which features a style layer renders from its source.
* Any feature for which the filter expression evaluates to `true` will be
* rendered on the map. Those that are false will be hidden.
*
* Use `setFilter` to show a subset of your source data.
*
* To clear the filter, pass `null` or `undefined` as the second parameter.
*
* @param layerId - The ID of the layer to which the filter will be applied.
* @param filter - The filter, conforming to the MapLibre Style Specification's
* [filter definition](https://maplibre.org/maplibre-style-spec/layers/#filter). If `null` or `undefined` is provided, the function removes any existing filter from the layer.
* @param options - Options object.
*
* @example
* Display only features with the 'name' property 'USA'
* ```ts
* map.setFilter('my-layer', ['==', ['get', 'name'], 'USA']);
* ```
* @example
* Display only features with five or more 'available-spots'
* ```ts
* map.setFilter('bike-docks', ['>=', ['get', 'available-spots'], 5]);
* ```
* @example
* Remove the filter for the 'bike-docks' style layer
* ```ts
* map.setFilter('bike-docks', null);
* ```
* @see [Create a timeline animation](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-time-slider/)
*/
setFilter(layerId, filter, options = {}) {
this.style?.setFilter(layerId, filter, options);
return this._update(true);
}
/**
* Returns the filter applied to the specified style layer.
*
* @param layerId - The ID of the style layer whose filter to get.
* @returns The layer's filter.
*/
getFilter(layerId) {
return this.style.getFilter(layerId);
}
/**
* Sets the value of a paint property in the specified style layer.
*
* @param layerId - The ID of the layer to set the paint property in.
* @param name - The name of the paint property to set.
* @param value - The value of the paint property to set.
* Must be of a type appropriate for the property, as defined in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/).
* Pass `null` to unset the existing value.
* @param options - Options object.
* @example
* ```ts
* map.setPaintProperty('my-layer', 'fill-color', '#faafee');
* ```
* @see [Change a layer's color with buttons](https://maplibre.org/maplibre-gl-js/docs/examples/change-a-layers-color-with-buttons/)
* @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)
*/
setPaintProperty(layerId, name, value, options = {}) {
this.style?.setPaintProperty(layerId, name, value, options);
return this._update(true);
}
/**
* Returns the value of a paint property in the specified style layer.
*
* @param layerId - The ID of the layer to get the paint property from.
* @param name - The name of a paint property to get.
* @returns The value of the specified paint property.
*/
getPaintProperty(layerId, name) {
return this.style.getPaintProperty(layerId, name);
}
/**
* Sets the value of a layout property in the specified style layer.
*
* @param layerId - The ID of the layer to set the layout property in.
* @param name - The name of the layout property to set.
* @param value - The value of the layout property. Must be of a type appropriate for the property, as defined in the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/).
* @param options - The options object.
* @example
* ```ts
* map.setLayoutProperty('my-layer', 'visibility', 'none');
* ```
*/
setLayoutProperty(layerId, name, value, options = {}) {
this.style.setLayoutProperty(layerId, name, value, options);
return this._update(true);
}
/**
* Returns the value of a layout property in the specified style layer.
*
* @param layerId - The ID of the layer to get the layout property from.
* @param name - The name of the layout property to get.
* @returns The value of the specified layout property.
*/
getLayoutProperty(layerId, name) {
return this.style.getLayoutProperty(layerId, name);
}
/**
* Sets the value of the style's glyphs property. Pass a falsy value (null or undefined)
* to unset glyphs.
*
* @param glyphsUrl - Glyph URL to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/glyphs/).
* @param options - Options object.
* @example
* ```ts
* map.setGlyphs('https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf');
* ```
*/
setGlyphs(glyphsUrl, options = {}) {
this._lazyInitEmptyStyle();
this.style.setGlyphs(glyphsUrl, options);
return this._update(true);
}
/**
* Returns the value of the style's glyphs URL
*
* @returns glyphs Style's glyphs url, or `null` if glyphs are unset.
*/
getGlyphs() {
return this.style.getGlyphsUrl();
}
/**
* Adds a sprite to the map's style. Fires the `style` event.
*
* @param id - The ID of the sprite to add. Must not conflict with existing sprites.
* @param url - The URL to load the sprite from
* @param options - Options object.
* @example
* ```ts
* map.addSprite('sprite-two', 'http://example.com/sprite-two');
* ```
*/
addSprite(id, url, options = {}) {
this._lazyInitEmptyStyle();
this.style.addSprite(id, url, options, (err) => {
if (!err) this._update(true);
});
return this;
}
/**
* Removes the sprite from the map's style. Fires the `style` event.
*
* @param id - The ID of the sprite to remove. If the sprite is declared as a single URL, the ID must be "default".
* @example
* ```ts
* map.removeSprite('sprite-two');
* map.removeSprite('default');
* ```
*/
removeSprite(id) {
this._lazyInitEmptyStyle();
this.style.removeSprite(id);
return this._update(true);
}
/**
* Returns the as-is value of the style's sprite.
*
* @returns style's sprite list of id-url pairs
*/
getSprite() {
return this.style.getSprite();
}
/**
* Sets the value of the style's sprite property.
*
* @param spriteUrl - Sprite URL to set.
* @param options - Options object.
* @example
* ```ts
* map.setSprite('YOUR_SPRITE_URL');
* ```
*/
setSprite(spriteUrl, options = {}) {
this._lazyInitEmptyStyle();
this.style.setSprite(spriteUrl, options, (err) => {
if (!err) this._update(true);
});
return this;
}
/**
* Sets the any combination of light values.
*
* @param light - Light properties to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/light).
* @param options - Options object.
*
* @example
* ```ts
* let layerVisibility = map.getLayoutProperty('my-layer', 'visibility');
* ```
*/
setLight(light, options = {}) {
this._lazyInitEmptyStyle();
this.style.setLight(light, options);
return this._update(true);
}
/**
* Returns the value of the light object.
*
* @returns light Light properties of the style.
*/
getLight() {
return this.style.getLight();
}
/**
* Sets the value of style's sky properties.
*
* @param sky - Sky properties to set. Must conform to the [MapLibre Style Specification](https://maplibre.org/maplibre-style-spec/sky/).
* @param options - Options object.
*
* @example
* ```ts
* map.setSky({'atmosphere-blend': 1.0});
* ```
*/
setSky(sky, options = {}) {
this._lazyInitEmptyStyle();
this.style.setSky(sky, options);
return this._update(true);
}
/**
* Returns the value of the style's sky.
*
* @returns the sky properties of the style.
* @example
* ```ts
* map.getSky();
* ```
*/
getSky() {
return this.style.getSky();
}
/**
* Sets the `state` of a feature.
* A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime.
* When using this method, the `state` object is merged with any existing key-value pairs in the feature's state.
* Features are identified by their `feature.id` attribute, which can be any number or string.
*
* This method can only be used with sources that have a `feature.id` attribute. The `feature.id` attribute can be defined in three ways:
*
* - For vector or GeoJSON sources, including an `id` attribute in the original data file.
* - For vector or GeoJSON sources, using the [`promoteId`](https://maplibre.org/maplibre-style-spec/sources/#promoteid) option at the time the source is defined.
* - For GeoJSON sources, using the [`generateId`](https://maplibre.org/maplibre-style-spec/sources/#generateid) option to auto-assign an `id` based on the feature's index in the source data. If you change feature data using `map.getSource('some id').setData(..)`, you may need to re-apply state taking into account updated `id` values.
*
* !!! note
* You can use the [`feature-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#feature-state) to access the values in a feature's state object for the purposes of styling.
*
* @param feature - Feature identifier. Feature objects returned from
* {@link Map.queryRenderedFeatures} or event handlers can be used as feature identifiers.
* @param state - A set of key-value pairs. The values should be valid JSON types.
*
* @example
* ```ts
* // When the mouse moves over the `my-layer` layer, update
* // the feature state for the feature under the mouse
* map.on('mousemove', 'my-layer', (e) => {
* if (e.features.length > 0) {
* map.setFeatureState({
* source: 'my-source',
* sourceLayer: 'my-source-layer',
* id: e.features[0].id,
* }, {
* hover: true
* });
* }
* });
* ```
* @see [Create a hover effect](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-hover-effect/)
*/
setFeatureState(feature, state) {
this.style.setFeatureState(feature, state);
return this._update();
}
/**
* Removes the `state` of a feature, setting it back to the default behavior.
* If only a `target.source` is specified, it will remove the state for all features from that source.
* If `target.id` is also specified, it will remove all keys for that feature's state.
* If `key` is also specified, it removes only that key from that feature's state.
* Features are identified by their `feature.id` attribute, which can be any number or string.
*
* @param target - Identifier of where to remove state. It can be a source, a feature, or a specific key of feature.
* Feature objects returned from {@link Map.queryRenderedFeatures} or event handlers can be used as feature identifiers.
* @param key - (optional) The key in the feature state to reset.
* @example
* Reset the entire state object for all features in the `my-source` source
* ```ts
* map.removeFeatureState({
* source: 'my-source'
* });
* ```
*
* @example
* When the mouse leaves the `my-layer` layer,
* reset the entire state object for the
* feature under the mouse
* ```ts
* map.on('mouseleave', 'my-layer', (e) => {
* map.removeFeatureState({
* source: 'my-source',
* sourceLayer: 'my-source-layer',
* id: e.features[0].id
* });
* });
* ```
*
* @example
* When the mouse leaves the `my-layer` layer,
* reset only the `hover` key-value pair in the
* state for the feature under the mouse
* ```ts
* map.on('mouseleave', 'my-layer', (e) => {
* map.removeFeatureState({
* source: 'my-source',
* sourceLayer: 'my-source-layer',
* id: e.features[0].id
* }, 'hover');
* });
* ```
*/
removeFeatureState(target, key) {
this.style.removeFeatureState(target, key);
return this._update();
}
/**
* Gets the `state` of a feature.
* A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime.
* Features are identified by their `feature.id` attribute, which can be any number or string.
*
* !!! note
* To access the values in a feature's state object for the purposes of styling the feature, use the [`feature-state` expression](https://maplibre.org/maplibre-style-spec/expressions/#feature-state).
*
* @param feature - Feature identifier. Feature objects returned from
* {@link Map.queryRenderedFeatures} or event handlers can be used as feature identifiers.
* @returns The state of the feature: a set of key-value pairs that was assigned to the feature at runtime.
*
* @example
* When the mouse moves over the `my-layer` layer,
* get the feature state for the feature under the mouse
* ```ts
* map.on('mousemove', 'my-layer', (e) => {
* if (e.features.length > 0) {
* map.getFeatureState({
* source: 'my-source',
* sourceLayer: 'my-source-layer',
* id: e.features[0].id
* });
* }
* });
* ```
*/
getFeatureState(feature) {
return this.style.getFeatureState(feature);
}
/**
* Returns the map's containing HTML element.
*
* @returns The map's container.
*/
getContainer() {
return this._container;
}
/**
* Returns the HTML element containing the map's `<canvas>` element.
*
* If you want to add non-GL overlays to the map, you should append them to this element.
*
* This is the element to which event bindings for map interactivity (such as panning and zooming) are
* attached. It will receive bubbled events from child elements such as the `<canvas>`, but not from
* map controls.
*
* @returns The container of the map's `<canvas>`.
* @see [Create a draggable point](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-point/)
*/
getCanvasContainer() {
return this._canvasContainer;
}
/**
* Returns the map's `<canvas>` element.
*
* @returns The map's `<canvas>` element.
* @see [Measure distances](https://maplibre.org/maplibre-gl-js/docs/examples/measure-distances/)
* @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-hover/)
* @see [Center the map on a clicked symbol](https://maplibre.org/maplibre-gl-js/docs/examples/center-the-map-on-a-clicked-symbol/)
*/
getCanvas() {
return this._canvas;
}
_containerDimensions() {
let width = 0;
let height = 0;
if (this._container) {
width = this._container.clientWidth || 400;
height = this._container.clientHeight || 300;
}
return [width, height];
}
/**
* @internal
* Sets up the ResizeObserver to track container size changes.
* Uses the owning window's ResizeObserver for cross-window support.
*/
_setupResizeObserver() {
let initialResizeEventCaptured = false;
const throttledResizeCallback = throttle((entries) => {
if (this._trackResize && !this._removed) {
this.resize(entries);
this.redraw();
}
}, 50);
const ResizeObserverClass = this._ownerWindow.ResizeObserver ?? ResizeObserver;
this._resizeObserver = new ResizeObserverClass((entries) => {
if (!initialResizeEventCaptured) {
initialResizeEventCaptured = true;
return;
}
throttledResizeCallback(entries);
});
this._resizeObserver.observe(this._container);
}
/**
* @internal
* Resolves the container option to an HTMLElement.
* Supports string ID, HTMLElement, or cross-window elements (using nodeType check).
*/
_resolveContainer(container) {
if (typeof container === "string") {
const element = document.getElementById(container);
if (!element) throw new Error(`Container '${container}' not found.`);
return element;
}
if (container instanceof HTMLElement) return container;
if (container && typeof container === "object" && container.nodeType === 1) return container;
throw new Error("Invalid type: 'container' must be a String or HTMLElement.");
}
_setupContainer() {
const container = this._container;
container.classList.add("maplibregl-map");
const canvasContainer = this._canvasContainer = DOM.create("div", "maplibregl-canvas-container", container);
if (this._interactive) canvasContainer.classList.add("maplibregl-interactive");
this._canvas = DOM.create("canvas", "maplibregl-canvas", canvasContainer);
this._canvas.addEventListener("webglcontextlost", this._contextLost, false);
this._canvas.addEventListener("webglcontextrestored", this._contextRestored, false);
this._canvas.setAttribute("tabindex", this._interactive ? "0" : "-1");
this._canvas.setAttribute("aria-label", this._getUIString("Map.Title"));
this._canvas.setAttribute("role", "region");
const dimensions = this._containerDimensions();
const clampedPixelRatio = this._getClampedPixelRatio(dimensions[0], dimensions[1]);
this._resizeCanvas(dimensions[0], dimensions[1], clampedPixelRatio);
const controlContainer = this._controlContainer = DOM.create("div", "maplibregl-control-container", container);
const positions = this._controlPositions = {};
for (const positionName of [
"top-left",
"top-right",
"bottom-left",
"bottom-right"
]) positions[positionName] = DOM.create("div", `maplibregl-ctrl-${positionName} `, controlContainer);
this._container.addEventListener("scroll", this._onMapScroll, false);
}
_resizeCanvas(width, height, pixelRatio) {
this._canvas.width = Math.floor(pixelRatio * width);
this._canvas.height = Math.floor(pixelRatio * height);
this._canvas.style.width = `${width}px`;
this._canvas.style.height = `${height}px`;
}
_setupPainter() {
const attributes = {
...this._canvasContextAttributes,
alpha: true,
depth: true,
stencil: true,
premultipliedAlpha: true
};
let creationEvent = null;
this._canvas.addEventListener("webglcontextcreationerror", (event) => {
creationEvent = event;
}, { once: true });
const gl = this._canvas.getContext("webgl2", attributes);
if (!gl) {
this.fire(new ErrorEvent(new GPUInitializationError(attributes, creationEvent)));
return;
}
this.painter = new Painter(gl, this._camera.transform);
}
/**
* @internal
* Creates a new specialized transform instance from a projection instance and migrates
* to this new transform, carrying over all the properties of the old transform (center, pitch, etc.).
* When the style's projection is changed (or first set), this function should be called.
*/
migrateProjection(newTransform, newCameraHelper) {
this._camera.migrateProjection(newTransform, newCameraHelper);
this.painter.transform = newTransform;
this.fire(new MapProjectionEvent({ newProjection: this.style.projection.name }));
}
/**
* Returns a Boolean indicating whether the map is fully loaded.
*
* Returns `false` if the style is not yet fully loaded,
* or if there has been a change to the sources or style that
* has not yet fully loaded.
*
* @returns A Boolean indicating whether the map is fully loaded.
*/
loaded() {
return !this._styleDirty && !this._sourcesDirty && !!this.style && this.style.loaded();
}
/**
* @internal
* Update this map's style and sources, and re-render the map.
*
* @param updateStyle - mark the map's style for reprocessing as
* well as its sources
*/
_update(updateStyle) {
if (!this.style?._loaded) return this;
this._styleDirty ||= updateStyle;
this._sourcesDirty = true;
this.triggerRepaint();
return this;
}
/**
* @internal
* Request that the given callback be executed during the next render
* frame. Schedule a render frame if one is not already scheduled.
*
* @returns An id that can be used to cancel the callback
*/
_requestRenderFrame(callback) {
this._update();
return this._renderTaskQueue.add(callback);
}
_cancelRenderFrame(id) {
this._renderTaskQueue.remove(id);
}
/**
* @internal
* Call when a (re-)render of the map is required:
*
* - The style has changed (`setPaintProperty()`, etc.)
* - Source data has changed (e.g. tiles have finished loading)
* - The map has is moving (or just finished moving)
* - A transition is in progress
*
* @param paintStartTimeStamp - The time when the animation frame began executing.
*/
_render(paintStartTimeStamp) {
const fadeDuration = this._idleTriggered ? this._fadeDuration : 0;
const isGlobeRendering = this.style.projection?.transitionState > 0;
this.painter.context.setDirty();
this.painter.setBaseState();
this._renderTaskQueue.run(paintStartTimeStamp);
if (this._removed) return;
let crossFading = false;
if (this.style && this._styleDirty) {
this._styleDirty = false;
const zoom = this._camera.transform.zoom;
const currentTime = now();
this.style.zoomHistory.update(zoom, currentTime);
const parameters = new EvaluationParameters(zoom, {
now: currentTime,
fadeDuration,
zoomHistory: this.style.zoomHistory,
transition: this.style.getTransition()
});
const factor = parameters.crossFadingFactor();
if (factor !== 1 || factor !== this._crossFadingFactor) {
crossFading = true;
this._crossFadingFactor = factor;
}
this.style.update(parameters);
}
const globeRenderingChanged = this.style.projection?.transitionState > 0 !== isGlobeRendering;
this._camera.transform.setTransitionState(this.style.projection?.transitionState);
if (this.style && (this._sourcesDirty || globeRenderingChanged)) {
this._sourcesDirty = false;
this.style._updateSources(this._camera.transform);
}
if (this.terrain) {
this.terrain.tileManager.update(this._camera.transform, this.terrain);
this.terrain.resetElevationCache();
this._camera.transform.setMinElevationForCurrentTile(this.terrain.getMinTileElevationForLngLatZoom(this._camera.transform.center, this._camera.transform.tileZoom));
if (!this._camera.elevationFreeze && this.getCenterClampedToGround()) this._camera.transform.setElevation(this.terrain.getElevationForLngLatZoom(this._camera.transform.center, this._camera.transform.tileZoom));
} else {
this._camera.transform.setMinElevationForCurrentTile(0);
if (this.getCenterClampedToGround()) this._camera.transform.setElevation(0);
}
this._placementDirty = this.style?._updatePlacement(this._camera.transform, this.showCollisionBoxes, fadeDuration, this._crossSourceCollisions, globeRenderingChanged);
this.painter.render(this.style, {
showTileBoundaries: this.showTileBoundaries,
showOverdrawInspector: this._showOverdrawInspector,
rotating: this.isRotating(),
zooming: this.isZooming(),
moving: this.isMoving(),
fadeDuration,
showPadding: this.showPadding,
anisotropicFilterPitch: this.getAnisotropicFilterPitch()
});
this.fire(new MapLibreEvent("render"));
if (this.loaded() && !this._loaded) {
this._loaded = true;
this.fire(new MapLibreEvent("load"));
}
if (this.style && (this.style.hasTransitions() || crossFading)) this._styleDirty = true;
if (this.style && !this._placementDirty) this.style._releaseSymbolFadeTiles();
const somethingDirty = this._sourcesDirty || this._styleDirty || this._placementDirty;
if (somethingDirty || this._repaint) this.triggerRepaint();
else if (!this.isMoving() && this.loaded()) this.fire(new MapLibreEvent("idle"));
if (this._loaded && !this._fullyLoaded && !somethingDirty) this._fullyLoaded = true;
return this;
}
/**
* Force a synchronous redraw of the map.
* @example
* ```ts
* map.redraw();
* ```
*/
redraw() {
if (this.style) {
if (this._frameRequest) {
this._frameRequest.abort();
this._frameRequest = null;
}
this._render(0);
}
return this;
}
/**
* Clean up and release all internal resources associated with this map.
*
* This includes DOM elements, event bindings, web workers, and WebGL resources.
*
* Use this method when you are done using the map and wish to ensure that it no
* longer consumes browser resources. Afterwards, you must not call any other
* methods on the map.
*/
remove() {
if (this._hash) this._hash.remove();
for (const control of this._controls) control.onRemove(this);
this._controls = [];
if (this._frameRequest) {
this._frameRequest.abort();
this._frameRequest = null;
}
this._renderTaskQueue.clear();
this._diffStyleRequest?.abort();
this.painter.destroy();
this._handlers.destroy();
this.setStyle(null);
if (typeof window !== "undefined") this._ownerWindow.removeEventListener("online", this._onWindowOnline, false);
ImageRequest.removeThrottleControl(this._imageQueueHandle);
this._resizeObserver?.disconnect();
const extension = this.painter.context.gl.getExtension("WEBGL_lose_context");
if (extension?.loseContext) extension.loseContext();
this._canvas.removeEventListener("webglcontextrestored", this._contextRestored, false);
this._canvas.removeEventListener("webglcontextlost", this._contextLost, false);
this._canvasContainer.remove();
this._controlContainer.remove();
this._container.removeEventListener("scroll", this._onMapScroll, false);
this._container.classList.remove("maplibregl-map");
this._removed = true;
this.fire(new MapLibreEvent("remove"));
}
/**
* Trigger the rendering of a single frame. Use this method with custom layers to
* repaint the map when the layer changes. Calling this multiple times before the
* next frame is rendered will still result in only a single frame being rendered.
* @example
* ```ts
* map.triggerRepaint();
* ```
* @see [Add a 3D model](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-3d-model-using-threejs/)
* @see [Add an animated icon to the map](https://maplibre.org/maplibre-gl-js/docs/examples/add-an-animated-icon-to-the-map/)
*/
triggerRepaint() {
if (this.style && !this._frameRequest) {
this._frameRequest = new AbortController();
browser.frame(this._frameRequest, (paintStartTimeStamp) => {
this._frameRequest = null;
try {
this._render(paintStartTimeStamp);
} catch (error) {
if (!isAbortError(error)) throw error;
}
}, () => {}, this._ownerWindow);
}
}
/**
* Gets and sets a Boolean indicating whether the map will render an outline
* around each tile and the tile ID. These tile boundaries are useful for
* debugging.
*
* The uncompressed file size of the first vector source is drawn in the top left
* corner of each tile, next to the tile ID.
*
* @example
* ```ts
* map.showTileBoundaries = true;
* ```
*/
get showTileBoundaries() {
return !!this._showTileBoundaries;
}
set showTileBoundaries(value) {
if (this._showTileBoundaries === value) return;
this._showTileBoundaries = value;
this._update();
}
/**
* Gets and sets a Boolean indicating whether the map will visualize
* the padding offsets.
*/
get showPadding() {
return !!this._showPadding;
}
set showPadding(value) {
if (this._showPadding === value) return;
this._showPadding = value;
this._update();
}
/**
* Gets and sets a Boolean indicating whether the map will render boxes
* around all symbols in the data source, revealing which symbols
* were rendered or which were hidden due to collisions.
* This information is useful for debugging.
*/
get showCollisionBoxes() {
return !!this._showCollisionBoxes;
}
set showCollisionBoxes(value) {
if (this._showCollisionBoxes === value) return;
this._showCollisionBoxes = value;
if (value) this.style._generateCollisionBoxes();
else this._update();
}
/**
* Gets and sets a Boolean indicating whether the map should color-code
* each fragment to show how many times it has been shaded.
* White fragments have been shaded 8 or more times.
* Black fragments have been shaded 0 times.
* This information is useful for debugging.
*/
get showOverdrawInspector() {
return !!this._showOverdrawInspector;
}
set showOverdrawInspector(value) {
if (this._showOverdrawInspector === value) return;
this._showOverdrawInspector = value;
this._update();
}
/**
* Gets and sets a Boolean indicating whether the map will
* continuously repaint. This information is useful for analyzing performance.
*/
get repaint() {
return !!this._repaint;
}
set repaint(value) {
if (this._repaint !== value) {
this._repaint = value;
this.triggerRepaint();
}
}
get vertices() {
return !!this._vertices;
}
set vertices(value) {
this._vertices = value;
this._update();
}
/**
* Returns the package version of the library
* @returns Package version of the library
*/
get version() {
return version$1;
}
/**
* Returns the elevation for the point where the camera is looking.
* This value corresponds to:
* "meters above sea level" * "exaggeration"
* @returns The elevation.
*/
getCameraTargetElevation() {
return this._camera.transform.elevation;
}
/**
* Gets the {@link ProjectionSpecification}.
* @returns the projection specification.
* @example
* ```ts
* let projection = map.getProjection();
* ```
*/
getProjection() {
return this.style.getProjection();
}
/**
* Sets the {@link ProjectionSpecification}.
* @param projection - the projection specification to set
* @returns
*/
setProjection(projection) {
this._lazyInitEmptyStyle();
this.style.setProjection(projection);
return this._update(true);
}
};
//#endregion
//#region src/ui/control/navigation_control.ts
const defaultOptions$3 = {
showCompass: true,
showZoom: true,
visualizePitch: false,
visualizeRoll: true
};
/**
* A `NavigationControl` control contains zoom buttons and a compass.
*
* @group Markers and Controls
*
* @example
* ```ts
* let nav = new NavigationControl();
* map.addControl(nav, 'top-left');
* ```
* @see [Display map navigation controls](https://maplibre.org/maplibre-gl-js/docs/examples/display-map-navigation-controls/)
*/
var NavigationControl = class {
/**
* @param options - the control's options
*/
constructor(options) {
this._updateZoomButtons = () => {
const zoom = this._map.getZoom();
const isMax = zoom === this._map.getMaxZoom();
const isMin = zoom === this._map.getMinZoom();
this._zoomInButton.disabled = isMax;
this._zoomOutButton.disabled = isMin;
this._zoomInButton.setAttribute("aria-disabled", isMax.toString());
this._zoomOutButton.setAttribute("aria-disabled", isMin.toString());
};
this._rotateCompassArrow = () => {
const pitch = this._map.getPitch();
const roll = this._map.getRoll();
const bearing = this._map.getBearing();
const pitchScale = 1 / Math.pow(Math.cos(degreesToRadians(pitch)), .5);
if (this.options.visualizePitch && this.options.visualizeRoll) {
this._compassIcon.style.transform = `scale(${pitchScale}) rotateZ(${-roll}deg) rotateX(${pitch}deg) rotateZ(${-bearing}deg)`;
return;
}
if (this.options.visualizePitch) {
this._compassIcon.style.transform = `scale(${pitchScale}) rotateX(${pitch}deg) rotateZ(${-bearing}deg)`;
return;
}
if (this.options.visualizeRoll) {
this._compassIcon.style.transform = `rotate(${-bearing - roll}deg)`;
return;
}
this._compassIcon.style.transform = `rotate(${-bearing}deg)`;
};
this._setButtonTitle = (button, title) => {
const str = this._map._getUIString(`NavigationControl.${title}`);
button.title = str;
button.setAttribute("aria-label", str);
};
this.options = extend({}, defaultOptions$3, options);
this._container = DOM.create("div", "maplibregl-ctrl maplibregl-ctrl-group");
this._container.addEventListener("contextmenu", (e) => e.preventDefault());
if (this.options.showZoom) {
this._zoomInButton = this._createButton("maplibregl-ctrl-zoom-in", (e) => this._map.zoomIn({}, { originalEvent: e }));
DOM.create("span", "maplibregl-ctrl-icon", this._zoomInButton).setAttribute("aria-hidden", "true");
this._zoomOutButton = this._createButton("maplibregl-ctrl-zoom-out", (e) => this._map.zoomOut({}, { originalEvent: e }));
DOM.create("span", "maplibregl-ctrl-icon", this._zoomOutButton).setAttribute("aria-hidden", "true");
}
if (this.options.showCompass) {
this._compass = this._createButton("maplibregl-ctrl-compass", (e) => {
if (this.options.visualizePitch) this._map.resetNorthPitch({}, { originalEvent: e });
else this._map.resetNorth({}, { originalEvent: e });
});
this._compassIcon = DOM.create("span", "maplibregl-ctrl-icon", this._compass);
this._compassIcon.setAttribute("aria-hidden", "true");
}
}
/** {@inheritDoc IControl.onAdd} */
onAdd(map) {
this._map = map;
if (this.options.showZoom) {
this._setButtonTitle(this._zoomInButton, "ZoomIn");
this._setButtonTitle(this._zoomOutButton, "ZoomOut");
this._map.on("zoom", this._updateZoomButtons);
this._updateZoomButtons();
}
if (this.options.showCompass) {
this._setButtonTitle(this._compass, "ResetBearing");
if (this.options.visualizePitch) this._map.on("pitch", this._rotateCompassArrow);
if (this.options.visualizeRoll) this._map.on("roll", this._rotateCompassArrow);
this._map.on("rotate", this._rotateCompassArrow);
this._rotateCompassArrow();
this._handler = new MouseRotateWrapper(this._map, this._compass, this.options.visualizePitch);
}
return this._container;
}
/** {@inheritDoc IControl.onRemove} */
onRemove() {
this._container.remove();
if (this.options.showZoom) this._map.off("zoom", this._updateZoomButtons);
if (this.options.showCompass) {
if (this.options.visualizePitch) this._map.off("pitch", this._rotateCompassArrow);
if (this.options.visualizeRoll) this._map.off("roll", this._rotateCompassArrow);
this._map.off("rotate", this._rotateCompassArrow);
this._handler.off();
delete this._handler;
}
delete this._map;
}
_createButton(className, fn) {
const a = DOM.create("button", className, this._container);
a.type = "button";
a.addEventListener("click", fn);
return a;
}
};
var MouseRotateWrapper = class {
constructor(map, element, pitch = false) {
this.mousedown = (e) => {
this.startMove(e, DOM.mousePos(this.element, e));
window.addEventListener("mousemove", this.mousemove);
window.addEventListener("mouseup", this.mouseup);
};
this.mousemove = (e) => {
this.move(e, DOM.mousePos(this.element, e));
};
this.mouseup = (e) => {
this._rotatePitchHandler.dragEnd(e);
this.offTemp();
};
this.touchstart = (e) => {
if (e.targetTouches.length !== 1) this.reset();
else {
this._startPos = this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0];
this.startMove(e, this._startPos);
window.addEventListener("touchmove", this.touchmove, { passive: false });
window.addEventListener("touchend", this.touchend);
}
};
this.touchmove = (e) => {
if (e.targetTouches.length !== 1) this.reset();
else {
this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0];
this.move(e, this._lastPos);
}
};
this.touchend = (e) => {
if (e.targetTouches.length === 0 && this._startPos && this._lastPos && this._startPos.dist(this._lastPos) < this._clickTolerance) this.element.click();
delete this._startPos;
delete this._lastPos;
this.offTemp();
};
this.reset = () => {
this._rotatePitchHandler.reset();
delete this._startPos;
delete this._lastPos;
this.offTemp();
};
this._clickTolerance = 10;
this.element = element;
const moveStateManager = new MouseOrTouchMoveStateManager();
this._rotatePitchHandler = new DragHandler({
clickTolerance: 3,
move: (lastPoint, currentPoint) => {
const rect = element.getBoundingClientRect();
const center = new Point((rect.bottom - rect.top) / 2, (rect.right - rect.left) / 2);
return {
bearingDelta: getAngleDelta(new Point(lastPoint.x, currentPoint.y), currentPoint, center),
pitchDelta: pitch ? (currentPoint.y - lastPoint.y) * -.5 : void 0
};
},
moveStateManager,
enable: true,
assignEvents: () => {}
});
this.map = map;
element.addEventListener("mousedown", this.mousedown);
element.addEventListener("touchstart", this.touchstart, { passive: false });
element.addEventListener("touchcancel", this.reset);
}
startMove(e, point) {
this._rotatePitchHandler.dragStart(e, point);
DOM.disableDrag();
}
move(e, point) {
const map = this.map;
const { bearingDelta, pitchDelta } = this._rotatePitchHandler.dragMove(e, point) || {};
if (bearingDelta) map.setBearing(map.getBearing() + bearingDelta);
if (pitchDelta) map.setPitch(map.getPitch() + pitchDelta);
}
off() {
const element = this.element;
element.removeEventListener("mousedown", this.mousedown);
element.removeEventListener("touchstart", this.touchstart);
window.removeEventListener("touchmove", this.touchmove);
window.removeEventListener("touchend", this.touchend);
element.removeEventListener("touchcancel", this.reset);
this.offTemp();
}
offTemp() {
DOM.enableDrag();
window.removeEventListener("mousemove", this.mousemove);
window.removeEventListener("mouseup", this.mouseup);
window.removeEventListener("touchmove", this.touchmove);
window.removeEventListener("touchend", this.touchend);
}
};
//#endregion
//#region src/util/geolocation_support.ts
let supportsGeolocation;
async function checkGeolocationSupport(forceRecalculation = false) {
if (supportsGeolocation !== void 0 && !forceRecalculation) return supportsGeolocation;
if (window.navigator.permissions === void 0) {
supportsGeolocation = !!window.navigator.geolocation;
return supportsGeolocation;
}
try {
supportsGeolocation = (await window.navigator.permissions.query({ name: "geolocation" })).state !== "denied";
} catch {
supportsGeolocation = !!window.navigator.geolocation;
}
return supportsGeolocation;
}
//#endregion
//#region src/util/smart_wrap.ts
/**
* Given a LngLat, prior projected position, and a transform, return a new LngLat shifted
* n × 360° east or west for some n ≥ 0 such that:
*
* * the projected location of the result is on screen, if possible, and secondarily:
* * the difference between the projected location of the result and the prior position
* is minimized.
*
* The object is to preserve perceived object constancy for Popups and Markers as much as
* possible; they should avoid shifting large distances across the screen, even when the
* map center changes by ±360° due to automatic wrapping, and when about to go off screen,
* should wrap just enough to avoid doing so.
*/
function smartWrap(lngLat, priorPos, transform, useNormalWrap = false) {
if (useNormalWrap || !transform.getCoveringTilesDetailsProvider().allowWorldCopies()) return lngLat?.wrap();
const originalLngLat = new LngLat(lngLat.lng, lngLat.lat);
lngLat = new LngLat(lngLat.lng, lngLat.lat);
if (priorPos) {
const left = new LngLat(lngLat.lng - 360, lngLat.lat);
const right = new LngLat(lngLat.lng + 360, lngLat.lat);
const delta = transform.locationToScreenPoint(lngLat).distSqr(priorPos);
if (transform.locationToScreenPoint(left).distSqr(priorPos) < delta) lngLat = left;
else if (transform.locationToScreenPoint(right).distSqr(priorPos) < delta) lngLat = right;
}
while (Math.abs(lngLat.lng - transform.center.lng) > 180) {
const pos = transform.locationToScreenPoint(lngLat);
if (pos.x >= 0 && pos.y >= 0 && pos.x <= transform.width && pos.y <= transform.height) break;
if (lngLat.lng > transform.center.lng) lngLat.lng -= 360;
else lngLat.lng += 360;
}
if (lngLat.lng !== originalLngLat.lng && transform.isPointOnMapSurface(transform.locationToScreenPoint(lngLat))) return lngLat;
return originalLngLat;
}
//#endregion
//#region src/ui/anchor.ts
const anchorTranslate = {
"center": "translate(-50%,-50%)",
"top": "translate(-50%,0)",
"top-left": "translate(0,0)",
"top-right": "translate(-100%,0)",
"bottom": "translate(-50%,-100%)",
"bottom-left": "translate(0,-100%)",
"bottom-right": "translate(-100%,-100%)",
"left": "translate(0,-50%)",
"right": "translate(-100%,-50%)"
};
function applyAnchorClass(element, anchor, prefix) {
const classList = element.classList;
for (const key in anchorTranslate) classList.remove(`maplibregl-${prefix}-anchor-${key}`);
classList.add(`maplibregl-${prefix}-anchor-${anchor}`);
}
//#endregion
//#region src/ui/marker.ts
/**
* Screen-pixel deltas applied when a focused draggable marker is moved with the arrow keys.
*/
const ARROW_KEY_DELTAS = {
ArrowLeft: [-1, 0],
ArrowRight: [1, 0],
ArrowUp: [0, -1],
ArrowDown: [0, 1]
};
const KEYBOARD_DRAG_SMALL_STEP = 1;
const KEYBOARD_DRAG_LARGE_STEP = 10;
/**
* The event class for marker drag events (`dragstart`, `drag` and `dragend`).
*
* @group Event Related
*/
var MarkerDragEvent = class extends Event {};
/**
* The event class for the marker `click` event.
*
* @group Event Related
*/
var MarkerClickEvent = class extends Event {};
/**
* Creates a marker component
*
* @group Markers and Controls
*
* @example
* ```ts
* let marker = new Marker()
* .setLngLat([30.5, 50.5])
* .addTo(map);
* ```
*
* @example
* Set options
* ```ts
* let marker = new Marker({
* color: "#FFFFFF",
* draggable: true
* }).setLngLat([30.5, 50.5])
* .addTo(map);
* ```
* @see [Add a default marker](https://maplibre.org/maplibre-gl-js/docs/examples/add-a-default-marker/)
* @see [Add custom icons with Markers](https://maplibre.org/maplibre-gl-js/docs/examples/add-custom-icons-with-markers/)
* @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-marker/)
* @see [Animate a marker](https://maplibre.org/maplibre-gl-js/docs/examples/animate-a-marker/)
* @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/attach-a-popup-to-a-marker-instance/)
*
* ## Events
*
* **Event** `dragstart` of type {@link MarkerDragEvent} will be fired when dragging starts.
*
* **Event** `drag` of type {@link MarkerDragEvent} will be fired while dragging.
*
* **Event** `dragend` of type {@link MarkerDragEvent} will be fired when the marker is finished being dragged.
*
* **Event** `click` of type {@link MarkerClickEvent} will be fired when the marker is clicked.
*
* ## CSS Classes
*
* **CSS class** `maplibregl-marker-covered` is toggled on the marker element when the marker
* is hidden behind 3D terrain or on the back of a globe.
* Use this class to apply custom styles to covered markers.
*
* @example
* ```css
* .maplibregl-marker-covered {
* pointer-events: none;
* cursor: default;
* }
* ```
*/
var Marker = class extends Evented {
/**
* @param options - the options
*/
constructor(options) {
super();
this._onClick = (e) => {
this.fire(new MarkerClickEvent("click", { originalEvent: e }));
};
this._onKeyPress = (e) => {
if (e.code === "Space" || e.code === "Enter") this.togglePopup();
};
this._onKeyDown = (e) => {
if (!this._defaultMarker || !this._draggable || !this._map || !this._lngLat) return;
if (e.composedPath()[0] !== this._element) return;
if (e.altKey || e.ctrlKey || e.metaKey) return;
const delta = ARROW_KEY_DELTAS[e.key];
if (!delta) return;
e.preventDefault();
e.stopPropagation();
const step = e.shiftKey ? KEYBOARD_DRAG_LARGE_STEP : KEYBOARD_DRAG_SMALL_STEP;
const pos = this._map.project(this._lngLat);
this.setLngLat(this._map.unproject(new Point(pos.x + delta[0] * step, pos.y + delta[1] * step)));
if (!this._keyboardDragActive) {
this._keyboardDragActive = true;
this.fire(new MarkerDragEvent("dragstart"));
}
this.fire(new MarkerDragEvent("drag"));
};
this._onKeyUp = (e) => {
if (!ARROW_KEY_DELTAS[e.key]) return;
this._endKeyboardDrag();
};
this._onBlur = () => {
this._endKeyboardDrag();
};
this._onMapClick = (e) => {
const targetElement = e.originalEvent.target;
const element = this._element;
if (this._popup && (targetElement === element || element.contains(targetElement))) this.togglePopup();
};
this._update = (e) => {
if (!this._map) return;
const isFullyLoaded = this._map.loaded() && !this._map.isMoving();
if (e?.type === "terrain" || e?.type === "render" && !isFullyLoaded) this._map.once("render", this._update);
this._lngLat = smartWrap(this._lngLat, this._flatPos, this._map._camera.transform);
this._flatPos = this._pos = this._map.project(this._lngLat)._add(this._offset);
if (this._map.terrain) this._flatPos = this._map._camera.transform.locationToScreenPoint(this._lngLat)._add(this._offset);
let rotation = "";
if (this._rotationAlignment === "viewport" || this._rotationAlignment === "auto") rotation = `rotateZ(${this._rotation}deg)`;
else if (this._rotationAlignment === "map") rotation = `rotateZ(${this._rotation - this._map.getBearing()}deg)`;
let pitch = "";
if (this._pitchAlignment === "viewport" || this._pitchAlignment === "auto") pitch = "rotateX(0deg)";
else if (this._pitchAlignment === "map") pitch = `rotateX(${this._map.getPitch()}deg)`;
if (!this._subpixelPositioning && (!e || e.type === "moveend")) this._pos = this._pos.round();
this._element.style.transform = `${anchorTranslate[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${pitch} ${rotation}`;
browser.frameAsync(new AbortController(), this._map._ownerWindow).then(() => {
this._updateOpacity(e?.type === "moveend");
}).catch(() => {});
};
this._onMove = (e) => {
if (!this._isDragging) {
const clickTolerance = this._clickTolerance || this._map._clickTolerance;
this._isDragging = e.point.dist(this._pointerdownPos) >= clickTolerance;
}
if (!this._isDragging) return;
this._pos = e.point.sub(this._positionDelta);
this._lngLat = this._map.unproject(this._pos);
this.setLngLat(this._lngLat);
this._element.style.pointerEvents = "none";
if (this._state === "pending") {
this._state = "active";
this.fire(new MarkerDragEvent("dragstart"));
}
this.fire(new MarkerDragEvent("drag"));
};
this._onUp = () => {
this._element.style.pointerEvents = "auto";
this._positionDelta = null;
this._pointerdownPos = null;
this._isDragging = false;
this._map.off("mousemove", this._onMove);
this._map.off("touchmove", this._onMove);
if (this._state === "active") this.fire(new MarkerDragEvent("dragend"));
this._state = "inactive";
};
this._addDragHandler = (e) => {
if (this._element.contains(e.originalEvent.target)) {
e.preventDefault();
this._positionDelta = e.point.sub(this._pos).add(this._offset);
this._pointerdownPos = e.point;
this._state = "pending";
this._map.on("mousemove", this._onMove);
this._map.on("touchmove", this._onMove);
this._map.once("mouseup", this._onUp);
this._map.once("touchend", this._onUp);
}
};
this._anchor = options?.anchor || "center";
this._color = options?.color || "#3FB1CE";
this._scale = options?.scale || 1;
this._draggable = options?.draggable || false;
this._clickTolerance = options?.clickTolerance || 0;
this._subpixelPositioning = options?.subpixelPositioning || false;
this._isDragging = false;
this._roleManaged = false;
this._tabIndexManaged = false;
this._keyboardDragActive = false;
this._state = "inactive";
this._rotation = options?.rotation || 0;
this._rotationAlignment = options?.rotationAlignment || "auto";
this._pitchAlignment = options?.pitchAlignment && options.pitchAlignment !== "auto" ? options.pitchAlignment : this._rotationAlignment;
this.setOpacity(options?.opacity, options?.opacityWhenCovered);
if (!options?.element) {
this._defaultMarker = true;
this._element = DOM.create("div");
const svg = DOM.createNS("http://www.w3.org/2000/svg", "svg");
const defaultHeight = 41;
const defaultWidth = 27;
svg.setAttributeNS(null, "display", "block");
svg.setAttributeNS(null, "height", `${defaultHeight}px`);
svg.setAttributeNS(null, "width", `${defaultWidth}px`);
svg.setAttributeNS(null, "viewBox", `0 0 ${defaultWidth} ${defaultHeight}`);
const markerLarge = DOM.createNS("http://www.w3.org/2000/svg", "g");
markerLarge.setAttributeNS(null, "stroke", "none");
markerLarge.setAttributeNS(null, "stroke-width", "1");
markerLarge.setAttributeNS(null, "fill", "none");
markerLarge.setAttributeNS(null, "fill-rule", "evenodd");
const page1 = DOM.createNS("http://www.w3.org/2000/svg", "g");
page1.setAttributeNS(null, "fill-rule", "nonzero");
const shadow = DOM.createNS("http://www.w3.org/2000/svg", "g");
shadow.setAttributeNS(null, "transform", "translate(3.0, 29.0)");
shadow.setAttributeNS(null, "fill", "#000000");
for (const data of [
{
"rx": "10.5",
"ry": "5.25002273"
},
{
"rx": "10.5",
"ry": "5.25002273"
},
{
"rx": "9.5",
"ry": "4.77275007"
},
{
"rx": "8.5",
"ry": "4.29549936"
},
{
"rx": "7.5",
"ry": "3.81822308"
},
{
"rx": "6.5",
"ry": "3.34094679"
},
{
"rx": "5.5",
"ry": "2.86367051"
},
{
"rx": "4.5",
"ry": "2.38636864"
}
]) {
const ellipse = DOM.createNS("http://www.w3.org/2000/svg", "ellipse");
ellipse.setAttributeNS(null, "opacity", "0.04");
ellipse.setAttributeNS(null, "cx", "10.5");
ellipse.setAttributeNS(null, "cy", "5.80029008");
ellipse.setAttributeNS(null, "rx", data["rx"]);
ellipse.setAttributeNS(null, "ry", data["ry"]);
shadow.appendChild(ellipse);
}
const background = DOM.createNS("http://www.w3.org/2000/svg", "g");
background.setAttributeNS(null, "fill", this._color);
const bgPath = DOM.createNS("http://www.w3.org/2000/svg", "path");
bgPath.setAttributeNS(null, "d", "M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z");
background.appendChild(bgPath);
const border = DOM.createNS("http://www.w3.org/2000/svg", "g");
border.setAttributeNS(null, "opacity", "0.25");
border.setAttributeNS(null, "fill", "#000000");
const borderPath = DOM.createNS("http://www.w3.org/2000/svg", "path");
borderPath.setAttributeNS(null, "d", "M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z");
border.appendChild(borderPath);
const maki = DOM.createNS("http://www.w3.org/2000/svg", "g");
maki.setAttributeNS(null, "transform", "translate(6.0, 7.0)");
maki.setAttributeNS(null, "fill", "#FFFFFF");
const circleContainer = DOM.createNS("http://www.w3.org/2000/svg", "g");
circleContainer.setAttributeNS(null, "transform", "translate(8.0, 8.0)");
const circle1 = DOM.createNS("http://www.w3.org/2000/svg", "circle");
circle1.setAttributeNS(null, "fill", "#000000");
circle1.setAttributeNS(null, "opacity", "0.25");
circle1.setAttributeNS(null, "cx", "5.5");
circle1.setAttributeNS(null, "cy", "5.5");
circle1.setAttributeNS(null, "r", "5.4999962");
const circle2 = DOM.createNS("http://www.w3.org/2000/svg", "circle");
circle2.setAttributeNS(null, "fill", "#FFFFFF");
circle2.setAttributeNS(null, "cx", "5.5");
circle2.setAttributeNS(null, "cy", "5.5");
circle2.setAttributeNS(null, "r", "5.4999962");
circleContainer.appendChild(circle1);
circleContainer.appendChild(circle2);
page1.appendChild(shadow);
page1.appendChild(background);
page1.appendChild(border);
page1.appendChild(maki);
page1.appendChild(circleContainer);
svg.appendChild(page1);
svg.setAttributeNS(null, "height", `${defaultHeight * this._scale}px`);
svg.setAttributeNS(null, "width", `${defaultWidth * this._scale}px`);
this._element.appendChild(svg);
this._offset = Point.convert(options?.offset || [0, -14]);
} else {
this._element = options.element;
this._offset = Point.convert(options?.offset || [0, 0]);
}
this._element.classList.add("maplibregl-marker");
this._element.addEventListener("dragstart", (e) => {
e.preventDefault();
});
this._element.addEventListener("mousedown", (e) => {
e.preventDefault();
});
applyAnchorClass(this._element, this._anchor, "marker");
if (options?.className) for (const name of options.className.split(" ")) this._element.classList.add(name);
this._popup = null;
}
/**
* Attaches the `Marker` to a `Map` object.
* @param map - The MapLibre GL JS map to add the marker to.
* @example
* ```ts
* let marker = new Marker()
* .setLngLat([30.5, 50.5])
* .addTo(map); // add the marker to the map
* ```
*/
addTo(map) {
this.remove();
this._map = map;
if (this._defaultMarker && !this._element.hasAttribute("aria-label")) this._element.setAttribute("aria-label", map._getUIString("Marker.Title"));
this._updateAccessibilityRole();
map.getCanvasContainer().appendChild(this._element);
map.on("move", this._update);
map.on("moveend", this._update);
map.on("terrain", this._update);
map.on("projectiontransition", this._update);
this._element.addEventListener("click", this._onClick);
this.setDraggable(this._draggable);
this._update();
this._map.on("click", this._onMapClick);
return this;
}
/**
* Removes the marker from a map
* @example
* ```ts
* let marker = new Marker().addTo(map);
* marker.remove();
* ```
*/
remove() {
if (this._opacityTimeout) {
clearTimeout(this._opacityTimeout);
delete this._opacityTimeout;
}
if (this._map) {
this._map.off("click", this._onMapClick);
this._map.off("move", this._update);
this._map.off("moveend", this._update);
this._map.off("terrain", this._update);
this._map.off("projectiontransition", this._update);
this._map.off("mousedown", this._addDragHandler);
this._map.off("touchstart", this._addDragHandler);
this._map.off("mouseup", this._onUp);
this._map.off("touchend", this._onUp);
this._map.off("mousemove", this._onMove);
this._map.off("touchmove", this._onMove);
delete this._map;
}
this._element.removeEventListener("click", this._onClick);
this._element.removeEventListener("keydown", this._onKeyDown);
this._element.removeEventListener("keyup", this._onKeyUp);
this._element.removeEventListener("blur", this._onBlur);
this._element.removeEventListener("keypress", this._onKeyPress);
this._keyboardDragActive = false;
this._element.remove();
if (this._popup) this._popup.remove();
return this;
}
/**
* Get the marker's geographical location.
*
* The longitude of the result may differ by a multiple of 360 degrees from the longitude previously
* set by `setLngLat` because `Marker` wraps the anchor longitude across copies of the world to keep
* the marker on screen.
*
* @returns A {@link LngLat} describing the marker's location.
* @example
* ```ts
* // Store the marker's longitude and latitude coordinates in a variable
* let lngLat = marker.getLngLat();
* // Print the marker's longitude and latitude values in the console
* console.log('Longitude: ' + lngLat.lng + ', Latitude: ' + lngLat.lat )
* ```
* @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-marker/)
*/
getLngLat() {
return this._lngLat;
}
/**
* Set the marker's geographical position and move it.
* @param lnglat - A {@link LngLat} describing where the marker should be located.
* @example
* Create a new marker, set the longitude and latitude, and add it to the map
* ```ts
* new Marker()
* .setLngLat([-65.017, -16.457])
* .addTo(map);
* ```
* @see [Add custom icons with Markers](https://maplibre.org/maplibre-gl-js/docs/examples/add-custom-icons-with-markers/)
* @see [Create a draggable Marker](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-draggable-marker/)
*/
setLngLat(lnglat) {
this._lngLat = LngLat.convert(lnglat);
this._pos = null;
if (this._popup) this._popup.setLngLat(this._lngLat);
this._update();
return this;
}
/**
* Returns the `Marker`'s HTML element.
* @returns element
*/
getElement() {
return this._element;
}
/**
* Binds a {@link Popup} to the {@link Marker}.
* @param popup - An instance of the {@link Popup} class. If undefined or null, any popup
* set on this {@link Marker} instance is unset.
* @example
* ```ts
* let marker = new Marker()
* .setLngLat([0, 0])
* .setPopup(new Popup().setHTML("<h1>Hello World!</h1>")) // add popup
* .addTo(map);
* ```
* @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/attach-a-popup-to-a-marker-instance/)
*/
setPopup(popup) {
if (this._popup) {
this._popup.remove();
this._popup = null;
this._element.removeEventListener("keypress", this._onKeyPress);
}
if (popup) {
if (!("offset" in popup.options)) {
const markerRadius = 13.5;
const linearOffset = Math.abs(markerRadius) / Math.SQRT2;
popup.options.offset = this._defaultMarker ? {
"top": [0, 0],
"top-left": [0, 0],
"top-right": [0, 0],
"bottom": [0, -38.1],
"bottom-left": [linearOffset, (24.6 + linearOffset) * -1],
"bottom-right": [-linearOffset, (24.6 + linearOffset) * -1],
"left": [markerRadius, -24.6],
"right": [-13.5, -24.6]
} : this._offset;
}
this._popup = popup;
this._element.addEventListener("keypress", this._onKeyPress);
}
this._updateTabIndex();
this._updateAccessibilityRole();
return this;
}
/**
* Set the option to allow subpixel positioning of the marker by passing a boolean
*
* @param value - when set to `true`, subpixel positioning is enabled for the marker.
*
* @example
* ```ts
* let marker = new Marker()
* marker.setSubpixelPositioning(true);
* ```
*/
setSubpixelPositioning(value) {
this._subpixelPositioning = value;
return this;
}
_endKeyboardDrag() {
if (this._keyboardDragActive) {
this._keyboardDragActive = false;
this.fire(new MarkerDragEvent("dragend"));
}
}
/**
* Returns the {@link Popup} instance that is bound to the {@link Marker}.
* @returns popup
* @example
* ```ts
* let marker = new Marker()
* .setLngLat([0, 0])
* .setPopup(new Popup().setHTML("<h1>Hello World!</h1>"))
* .addTo(map);
*
* console.log(marker.getPopup()); // return the popup instance
* ```
*/
getPopup() {
return this._popup;
}
/**
* Opens or closes the {@link Popup} instance that is bound to the {@link Marker}, depending on the current state of the {@link Popup}.
* @example
* ```ts
* let marker = new Marker()
* .setLngLat([0, 0])
* .setPopup(new Popup().setHTML("<h1>Hello World!</h1>"))
* .addTo(map);
*
* marker.togglePopup(); // toggle popup open or closed
* ```
*/
togglePopup() {
const popup = this._popup;
if (this._element.style.opacity === this._opacityWhenCovered) return this;
if (!popup) return this;
else if (popup.isOpen()) popup.remove();
else {
popup.setLngLat(this._lngLat);
popup.addTo(this._map);
}
return this;
}
_updateOpacity(force = false) {
const terrain = this._map?.terrain;
const occluded = this._map._camera.transform.isLocationOccluded(this._lngLat);
if (!terrain || occluded) {
const targetOpacity = occluded ? this._opacityWhenCovered : this._opacity;
if (this._element.style.opacity !== targetOpacity) {
this._element.style.opacity = targetOpacity;
this._element.classList.toggle("maplibregl-marker-covered", occluded);
}
return;
}
if (force) this._opacityTimeout = null;
else {
if (this._opacityTimeout) return;
this._opacityTimeout = setTimeout(() => {
this._opacityTimeout = null;
}, 100);
}
const map = this._map;
const terrainDistance = map.terrain.depthAtPoint(this._pos);
const elevation = map.terrain.getElevationForLngLat(this._lngLat, map._camera.transform);
const markerDistance = map._camera.transform.lngLatToCameraDepth(this._lngLat, elevation);
const forgiveness = .006;
if (markerDistance - terrainDistance < forgiveness) {
this._element.style.opacity = this._opacity;
this._element.classList.remove("maplibregl-marker-covered");
return;
}
const metersToCenter = -this._offset.y / map._camera.transform.pixelsPerMeter;
const elevationToCenter = Math.sin(map.getPitch() * Math.PI / 180) * metersToCenter;
const terrainDistanceCenter = map.terrain.depthAtPoint(new Point(this._pos.x, this._pos.y - this._offset.y));
const centerIsInvisible = map._camera.transform.lngLatToCameraDepth(this._lngLat, elevation + elevationToCenter) - terrainDistanceCenter > forgiveness;
if (this._popup?.isOpen() && centerIsInvisible) this._popup.remove();
this._element.style.opacity = centerIsInvisible ? this._opacityWhenCovered : this._opacity;
this._element.classList.toggle("maplibregl-marker-covered", centerIsInvisible);
}
/**
* Get the marker's offset.
* @returns The marker's screen coordinates in pixels.
*/
getOffset() {
return this._offset;
}
/**
* Sets the offset of the marker
* @param offset - The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up.
*/
setOffset(offset) {
this._offset = Point.convert(offset);
this._update();
return this;
}
/**
* Adds a CSS class to the marker element.
*
* @param className - on-empty string with CSS class name to add to marker element
*
* @example
* ```
* let marker = new Marker()
* marker.addClassName('some-class')
* ```
*/
addClassName(className) {
this._element.classList.add(className);
}
/**
* Removes a CSS class from the marker element.
*
* @param className - Non-empty string with CSS class name to remove from marker element
*
* @example
* ```ts
* let marker = new Marker()
* marker.removeClassName('some-class')
* ```
*/
removeClassName(className) {
this._element.classList.remove(className);
}
/**
* Add or remove the given CSS class on the marker element, depending on whether the element currently has that class.
*
* @param className - Non-empty string with CSS class name to add/remove
*
* @returns if the class was removed return false, if class was added, then return true
*
* @example
* ```ts
* let marker = new Marker()
* marker.toggleClassName('toggleClass')
* ```
*/
toggleClassName(className) {
return this._element.classList.toggle(className);
}
/**
* Sets the `draggable` property and functionality of the marker.
* A draggable default marker is also keyboard focusable and movable with the
* arrow keys (see {@link MarkerOptions.draggable}); custom marker elements keep
* their focusability and keyboard behavior application-owned.
* @param shouldBeDraggable - Turns drag functionality on/off
*/
setDraggable(shouldBeDraggable) {
this._draggable = !!shouldBeDraggable;
this._element.classList.toggle("maplibregl-marker-draggable", this._draggable);
if (this._map) {
if (shouldBeDraggable) {
this._map.on("mousedown", this._addDragHandler);
this._map.on("touchstart", this._addDragHandler);
} else {
this._map.off("mousedown", this._addDragHandler);
this._map.off("touchstart", this._addDragHandler);
}
}
if (this._defaultMarker) {
if (this._draggable) {
this._element.addEventListener("keydown", this._onKeyDown);
this._element.addEventListener("keyup", this._onKeyUp);
this._element.addEventListener("blur", this._onBlur);
} else {
this._element.removeEventListener("keydown", this._onKeyDown);
this._element.removeEventListener("keyup", this._onKeyUp);
this._element.removeEventListener("blur", this._onBlur);
this._endKeyboardDrag();
}
}
this._updateTabIndex();
this._updateAccessibilityRole();
return this;
}
/**
* Returns true if the marker can be dragged
* @returns True if the marker is draggable.
*/
isDraggable() {
return this._draggable;
}
/**
* Keep the marker element focusable while it has built-in keyboard behavior.
* A popup makes any marker element interactive; dragging only manages
* focusability for the default marker so custom elements stay
* application-owned (#7790). A tabindex supplied by the application is
* never added, changed, or removed here.
*/
_updateTabIndex() {
if (!!this._popup || this._defaultMarker && this._draggable) {
if (!this._element.hasAttribute("tabindex")) {
this._element.setAttribute("tabindex", "0");
this._tabIndexManaged = true;
}
} else if (this._tabIndexManaged) {
if (this._element.getAttribute("tabindex") === "0") this._element.removeAttribute("tabindex");
this._tabIndexManaged = false;
}
}
/**
* Keep the default marker role aligned with interactivity.
* Default markers need a role because `aria-label` is set in {@link Marker.addTo}.
* Non-interactive markers use `role=img`; interactive ones (draggable or with a popup) use `role=button`.
* Click listeners are application-owned and do not automatically change the role.
* Custom marker elements are left alone so applications own their a11y tree.
* Explicit roles set by the application are preserved.
*/
_updateAccessibilityRole() {
if (!this._defaultMarker) return;
if (this._element.hasAttribute("role") && !this._roleManaged) return;
const role = this._draggable || !!this._popup ? "button" : "img";
this._element.setAttribute("role", role);
this._roleManaged = true;
}
/**
* Sets the `rotation` property of the marker.
* @param rotation - The rotation angle of the marker (clockwise, in degrees), relative to its respective {@link Marker.setRotationAlignment} setting.
*/
setRotation(rotation) {
this._rotation = rotation || 0;
this._update();
return this;
}
/**
* Returns the current rotation angle of the marker (in degrees).
* @returns The current rotation angle of the marker.
*/
getRotation() {
return this._rotation;
}
/**
* Sets the `rotationAlignment` property of the marker.
* @param alignment - Sets the `rotationAlignment` property of the marker. defaults to 'auto'
*/
setRotationAlignment(alignment) {
this._rotationAlignment = alignment || "auto";
this._update();
return this;
}
/**
* Returns the current `rotationAlignment` property of the marker.
* @returns The current rotational alignment of the marker.
*/
getRotationAlignment() {
return this._rotationAlignment;
}
/**
* Sets the `pitchAlignment` property of the marker.
* @param alignment - Sets the `pitchAlignment` property of the marker. If alignment is 'auto', it will automatically match `rotationAlignment`.
*/
setPitchAlignment(alignment) {
this._pitchAlignment = alignment && alignment !== "auto" ? alignment : this._rotationAlignment;
this._update();
return this;
}
/**
* Returns the current `pitchAlignment` property of the marker.
* @returns The current pitch alignment of the marker in degrees.
*/
getPitchAlignment() {
return this._pitchAlignment;
}
/**
* Sets the `opacity` and `opacityWhenCovered` properties of the marker.
* When called without arguments, resets opacity and opacityWhenCovered to defaults
* @param opacity - Sets the `opacity` property of the marker.
* @param opacityWhenCovered - Sets the `opacityWhenCovered` property of the marker.
*/
setOpacity(opacity, opacityWhenCovered) {
if (this._opacity === void 0 || opacity === void 0 && opacityWhenCovered === void 0) {
this._opacity = "1";
this._opacityWhenCovered = "0.2";
}
if (opacity !== void 0) this._opacity = String(opacity);
if (opacityWhenCovered !== void 0) this._opacityWhenCovered = String(opacityWhenCovered);
if (this._map) this._updateOpacity(true);
return this;
}
};
//#endregion
//#region src/ui/control/geolocate_control.ts
const defaultOptions$2 = {
positionOptions: {
enableHighAccuracy: false,
maximumAge: 0,
timeout: 6e3
},
fitBoundsOptions: { maxZoom: 15 },
trackUserLocation: false,
showAccuracyCircle: true,
showUserLocation: true
};
let numberOfWatches = 0;
let noTimeout = false;
/**
* The event class for geolocate control state events
* (`trackuserlocationstart`, `trackuserlocationend`, `userlocationfocus` and `userlocationlostfocus`).
*
* @group Event Related
*/
var GeolocateEvent = class extends Event {};
/**
* The event class for the geolocate control `geolocate` and `outofmaxbounds` events.
* Carries the [Position](https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPosition) returned by the Geolocation API.
*
* @group Event Related
*/
var GeolocatePositionEvent = class extends Event {};
/**
* The event class for the geolocate control `error` event.
* Carries the [PositionError](https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPositionError) returned by the Geolocation API.
*
* @group Event Related
*/
var GeolocateErrorEvent = class extends Event {};
/**
* A `GeolocateControl` control provides a button that uses the browser's geolocation
* API to locate the user on the map.
*
* Not all browsers support geolocation,
* and some users may disable the feature. Geolocation support for modern
* browsers including Chrome requires sites to be served over HTTPS. If
* geolocation support is not available, the `GeolocateControl` will show
* as disabled.
*
* The zoom level applied will depend on the accuracy of the geolocation provided by the device.
*
* The `GeolocateControl` has two modes. If `trackUserLocation` is `false` (default) the control acts as a button, which when pressed will set the map's camera to target the user location. If the user moves, the map won't update. This is most suited for the desktop. If `trackUserLocation` is `true` the control acts as a toggle button that when active the user's location is actively monitored for changes. In this mode the `GeolocateControl` has three interaction states:
* * active - the map's camera automatically updates as the user's location changes, keeping the location dot in the center. Initial state and upon clicking the `GeolocateControl` button.
* * passive - the user's location dot automatically updates, but the map's camera does not. Occurs upon the user initiating a map movement.
* * disabled - occurs if Geolocation is not available, disabled or denied.
*
* These interaction states can't be controlled programmatically, rather they are set based on user interactions.
*
* ## State Diagram
* 
*
* @group Markers and Controls
*
* @example
* ```ts
* map.addControl(new GeolocateControl({
* positionOptions: {
* enableHighAccuracy: true
* },
* trackUserLocation: true
* }));
* ```
* @see [Locate the user](https://maplibre.org/maplibre-gl-js/docs/examples/locate-the-user/)
*
* ## Events
*
* **Event** `trackuserlocationend` of type {@link Event} will be fired when the `GeolocateControl` changes to the background state, which happens when a user changes the camera during an active position lock. This only applies when `trackUserLocation` is `true`. In the background state, the dot on the map will update with location updates but the camera will not.
*
* **Event** `trackuserlocationstart` of type {@link Event} will be fired when the `GeolocateControl` changes to the active lock state, which happens either upon first obtaining a successful Geolocation API position for the user (a `geolocate` event will follow), or the user clicks the geolocate button when in the background state which uses the last known position to recenter the map and enter active lock state (no `geolocate` event will follow unless the users's location changes).
*
* **Event** `userlocationlostfocus` of type {@link Event} will be fired when the `GeolocateControl` changes to the background state, which happens when a user changes the camera during an active position lock. This only applies when `trackUserLocation` is `true`. In the background state, the dot on the map will update with location updates but the camera will not.
*
* **Event** `userlocationfocus` of type {@link Event} will be fired when the `GeolocateControl` changes to the active lock state, which happens upon the user clicks the geolocate button when in the background state which uses the last known position to recenter the map and enter active lock state.
*
* **Event** `geolocate` of type {@link Event} will be fired on each Geolocation API position update which returned as success.
* `data` - The returned [Position](https://developer.mozilla.org/en-US/docs/Web/API/Position) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition).
*
* **Event** `error` of type {@link Event} will be fired on each Geolocation API position update which returned as an error.
* `data` - The returned [PositionError](https://developer.mozilla.org/en-US/docs/Web/API/PositionError) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition).
*
* **Event** `outofmaxbounds` of type {@link Event} will be fired on each Geolocation API position update which returned as success but user position is out of map `maxBounds`.
* `data` - The returned [Position](https://developer.mozilla.org/en-US/docs/Web/API/Position) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition).
*
* @example
* ```ts
* // Initialize the geolocate control.
* let geolocate = new GeolocateControl({
* positionOptions: {
* enableHighAccuracy: true
* },
* trackUserLocation: true
* });
* // Add the control to the map.
* map.addControl(geolocate);
* // Set an event listener that fires
* // when a trackuserlocationend event occurs.
* geolocate.on('trackuserlocationend', () => {
* console.log('A trackuserlocationend event has occurred.')
* });
* ```
*
* @example
* ```ts
* // Initialize the geolocate control.
* let geolocate = new GeolocateControl({
* positionOptions: {
* enableHighAccuracy: true
* },
* trackUserLocation: true
* });
* // Add the control to the map.
* map.addControl(geolocate);
* // Set an event listener that fires
* // when a trackuserlocationstart event occurs.
* geolocate.on('trackuserlocationstart', () => {
* console.log('A trackuserlocationstart event has occurred.')
* });
* ```
*
* @example
* ```ts
* // Initialize the geolocate control.
* let geolocate = new GeolocateControl({
* positionOptions: {
* enableHighAccuracy: true
* },
* trackUserLocation: true
* });
* // Add the control to the map.
* map.addControl(geolocate);
* // Set an event listener that fires
* // when an userlocationlostfocus event occurs.
* geolocate.on('userlocationlostfocus', function() {
* console.log('An userlocationlostfocus event has occurred.')
* });
* ```
*
* @example
* ```ts
* // Initialize the geolocate control.
* let geolocate = new GeolocateControl({
* positionOptions: {
* enableHighAccuracy: true
* },
* trackUserLocation: true
* });
* // Add the control to the map.
* map.addControl(geolocate);
* // Set an event listener that fires
* // when an userlocationfocus event occurs.
* geolocate.on('userlocationfocus', function() {
* console.log('An userlocationfocus event has occurred.')
* });
* ```
*
* @example
* ```ts
* // Initialize the geolocate control.
* let geolocate = new GeolocateControl({
* positionOptions: {
* enableHighAccuracy: true
* },
* trackUserLocation: true
* });
* // Add the control to the map.
* map.addControl(geolocate);
* // Set an event listener that fires
* // when a geolocate event occurs.
* geolocate.on('geolocate', () => {
* console.log('A geolocate event has occurred.')
* });
* ```
*
* @example
* ```ts
* // Initialize the geolocate control.
* let geolocate = new GeolocateControl({
* positionOptions: {
* enableHighAccuracy: true
* },
* trackUserLocation: true
* });
* // Add the control to the map.
* map.addControl(geolocate);
* // Set an event listener that fires
* // when an error event occurs.
* geolocate.on('error', () => {
* console.log('An error event has occurred.')
* });
* ```
*
* @example
* ```ts
* // Initialize the geolocate control.
* let geolocate = new GeolocateControl({
* positionOptions: {
* enableHighAccuracy: true
* },
* trackUserLocation: true
* });
* // Add the control to the map.
* map.addControl(geolocate);
* // Set an event listener that fires
* // when an outofmaxbounds event occurs.
* geolocate.on('outofmaxbounds', () => {
* console.log('An outofmaxbounds event has occurred.')
* });
* ```
*/
var GeolocateControl = class extends Evented {
/**
* @param options - the control's options
*/
constructor(options) {
super();
this._onSuccess = (position) => {
if (!this._map) return;
if (this._isOutOfMapMaxBounds(position)) {
this._setErrorState();
this.fire(new GeolocatePositionEvent("outofmaxbounds", position));
this._updateMarker();
this._finish();
return;
}
if (this.options.trackUserLocation) {
this._lastKnownPosition = position;
switch (this._watchState) {
case "WAITING_ACTIVE":
case "ACTIVE_LOCK":
case "ACTIVE_ERROR":
this._watchState = "ACTIVE_LOCK";
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting");
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error");
this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");
break;
case "BACKGROUND":
case "BACKGROUND_ERROR":
this._watchState = "BACKGROUND";
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting");
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error");
this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");
break;
default: throw new Error(`Unexpected watchState ${this._watchState}`);
}
}
if (this.options.showUserLocation && this._watchState !== "OFF") this._updateMarker(position);
if (!this.options.trackUserLocation || this._watchState === "ACTIVE_LOCK") this._updateCamera(position);
if (this.options.showUserLocation) this._dotElement.classList.remove("maplibregl-user-location-dot-stale");
this.fire(new GeolocatePositionEvent("geolocate", position));
this._finish();
};
this._updateCamera = (position) => {
const center = new LngLat(position.coords.longitude, position.coords.latitude);
const radius = position.coords.accuracy;
const bearing = this._map.getBearing();
const options = extend({ bearing }, this.options.fitBoundsOptions);
const newBounds = LngLatBounds.fromLngLat(center, radius);
this._map.fitBounds(newBounds, options, { geolocateSource: true });
};
this._updateMarker = (position) => {
if (position) {
const center = new LngLat(position.coords.longitude, position.coords.latitude);
this._accuracyCircleMarker.setLngLat(center).addTo(this._map);
this._userLocationDotMarker.setLngLat(center).addTo(this._map);
this._accuracy = position.coords.accuracy;
this._updateCircleRadiusIfNeeded();
} else {
this._userLocationDotMarker.remove();
this._accuracyCircleMarker.remove();
}
};
this._onUpdate = () => {
this._updateCircleRadiusIfNeeded();
};
this._onError = (error) => {
if (!this._map) return;
if (error.code === 1) {
this._watchState = "OFF";
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting");
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active");
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error");
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background");
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error");
this._geolocateButton.disabled = true;
const title = this._map._getUIString("GeolocateControl.LocationNotAvailable");
this._geolocateButton.title = title;
this._geolocateButton.setAttribute("aria-label", title);
if (this._geolocationWatchID !== void 0) this._clearWatch();
} else if (error.code === 3 && noTimeout) return;
else this._setErrorState();
if (this._watchState !== "OFF" && this.options.showUserLocation) this._dotElement.classList.add("maplibregl-user-location-dot-stale");
this.fire(new GeolocateErrorEvent("error", error));
this._finish();
};
this._finish = () => {
if (this._timeoutId) clearTimeout(this._timeoutId);
this._timeoutId = void 0;
};
this._onMoveStart = (event) => {
if (!this._map) return;
const fromResize = event?.[0] instanceof ResizeObserverEntry;
if (!event.geolocateSource && this._watchState === "ACTIVE_LOCK" && !fromResize && !this._map.isZooming()) {
this._watchState = "BACKGROUND";
this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background");
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active");
this.fire(new GeolocateEvent("trackuserlocationend"));
this.fire(new GeolocateEvent("userlocationlostfocus"));
}
};
this._setupUI = () => {
if (!this._map) return;
this._container.addEventListener("contextmenu", (e) => {
e.preventDefault();
});
this._geolocateButton = DOM.create("button", "maplibregl-ctrl-geolocate", this._container);
DOM.create("span", "maplibregl-ctrl-icon", this._geolocateButton).setAttribute("aria-hidden", "true");
this._geolocateButton.type = "button";
this._geolocateButton.disabled = true;
};
this._finishSetupUI = (supported) => {
if (!this._map) return;
if (supported === false) {
warnOnce("Geolocation support is not available so the GeolocateControl will be disabled.");
const title = this._map._getUIString("GeolocateControl.LocationNotAvailable");
this._geolocateButton.disabled = true;
this._geolocateButton.title = title;
this._geolocateButton.setAttribute("aria-label", title);
} else {
const title = this._map._getUIString("GeolocateControl.FindMyLocation");
this._geolocateButton.disabled = false;
this._geolocateButton.title = title;
this._geolocateButton.setAttribute("aria-label", title);
}
if (this.options.trackUserLocation) {
this._geolocateButton.setAttribute("aria-pressed", "false");
this._watchState = "OFF";
}
if (this.options.showUserLocation) {
this._dotElement = DOM.create("div", "maplibregl-user-location-dot");
this._userLocationDotMarker = new Marker({ element: this._dotElement });
this._circleElement = DOM.create("div", "maplibregl-user-location-accuracy-circle");
this._accuracyCircleMarker = new Marker({
element: this._circleElement,
pitchAlignment: "map"
});
if (this.options.trackUserLocation) this._watchState = "OFF";
this._map.on("zoom", this._onUpdate);
this._map.on("move", this._onUpdate);
this._map.on("rotate", this._onUpdate);
this._map.on("pitch", this._onUpdate);
}
this._geolocateButton.addEventListener("click", () => this.trigger());
this._setup = true;
if (this.options.trackUserLocation) this._map.on("movestart", this._onMoveStart);
};
this.options = extend({}, defaultOptions$2, options);
}
/** {@inheritDoc IControl.onAdd} */
onAdd(map) {
this._map = map;
this._container = DOM.create("div", "maplibregl-ctrl maplibregl-ctrl-group");
this._setupUI();
checkGeolocationSupport().then((supported) => this._finishSetupUI(supported));
return this._container;
}
/** {@inheritDoc IControl.onRemove} */
onRemove() {
if (this._geolocationWatchID !== void 0) {
window.navigator.geolocation.clearWatch(this._geolocationWatchID);
this._geolocationWatchID = void 0;
}
if (this.options.showUserLocation && this._userLocationDotMarker) this._userLocationDotMarker.remove();
if (this.options.showAccuracyCircle && this._accuracyCircleMarker) this._accuracyCircleMarker.remove();
this._container.remove();
this._map.off("movestart", this._onMoveStart);
this._map.off("zoom", this._onUpdate);
this._map.off("move", this._onUpdate);
this._map.off("rotate", this._onUpdate);
this._map.off("pitch", this._onUpdate);
this._map = void 0;
numberOfWatches = 0;
noTimeout = false;
}
/**
* Check if the Geolocation API Position is outside the map's `maxBounds`.
*
* @param position - the Geolocation API Position
* @returns `true` if position is outside the map's `maxBounds`, otherwise returns `false`.
*/
_isOutOfMapMaxBounds(position) {
const bounds = this._map.getMaxBounds();
const coordinates = position.coords;
return bounds && (coordinates.longitude < bounds.getWest() || coordinates.longitude > bounds.getEast() || coordinates.latitude < bounds.getSouth() || coordinates.latitude > bounds.getNorth());
}
_setErrorState() {
switch (this._watchState) {
case "WAITING_ACTIVE":
this._watchState = "ACTIVE_ERROR";
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active");
this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");
break;
case "ACTIVE_LOCK":
this._watchState = "ACTIVE_ERROR";
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active");
this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active-error");
this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");
break;
case "BACKGROUND":
this._watchState = "BACKGROUND_ERROR";
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background");
this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-background-error");
this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");
break;
case "ACTIVE_ERROR":
case "BACKGROUND_ERROR": break;
case "OFF":
case void 0: break;
default: throw new Error(`Unexpected watchState ${this._watchState}`);
}
}
_updateCircleRadiusIfNeeded() {
const userLocation = this._userLocationDotMarker.getLngLat();
if (!this.options.showUserLocation || !this.options.showAccuracyCircle || !this._accuracy || !userLocation) return;
const screenPosition = this._map.project(userLocation);
const userLocationWith100Px = this._map.unproject([screenPosition.x + 100, screenPosition.y]);
const pixelsToMeters = userLocation.distanceTo(userLocationWith100Px) / 100;
const circleDiameter = 2 * this._accuracy / pixelsToMeters;
this._circleElement.style.width = `${circleDiameter.toFixed(2)}px`;
this._circleElement.style.height = `${circleDiameter.toFixed(2)}px`;
}
/**
* Programmatically request and move the map to the user's location.
*
* @returns `false` if called before control was added to a map, otherwise returns `true`.
* @example
* ```ts
* // Initialize the geolocate control.
* let geolocate = new GeolocateControl({
* positionOptions: {
* enableHighAccuracy: true
* },
* trackUserLocation: true
* });
* // Add the control to the map.
* map.addControl(geolocate);
* map.on('load', () => {
* geolocate.trigger();
* });
* ```
*/
trigger() {
if (!this._setup) {
warnOnce("Geolocate control triggered before added to a map");
return false;
}
if (this.options.trackUserLocation) {
switch (this._watchState) {
case "OFF":
this._watchState = "WAITING_ACTIVE";
this.fire(new GeolocateEvent("trackuserlocationstart"));
break;
case "WAITING_ACTIVE":
case "ACTIVE_LOCK":
case "ACTIVE_ERROR":
case "BACKGROUND_ERROR":
numberOfWatches--;
noTimeout = false;
this._watchState = "OFF";
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting");
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active");
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-active-error");
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background");
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background-error");
this.fire(new GeolocateEvent("trackuserlocationend"));
break;
case "BACKGROUND":
this._watchState = "ACTIVE_LOCK";
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-background");
if (this._lastKnownPosition) this._updateCamera(this._lastKnownPosition);
this.fire(new GeolocateEvent("trackuserlocationstart"));
this.fire(new GeolocateEvent("userlocationfocus"));
break;
default: throw new Error(`Unexpected watchState ${this._watchState}`);
}
switch (this._watchState) {
case "WAITING_ACTIVE":
this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");
this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");
break;
case "ACTIVE_LOCK":
this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-active");
break;
case "OFF": break;
default: throw new Error(`Unexpected watchState ${this._watchState}`);
}
if (this._watchState === "OFF" && this._geolocationWatchID !== void 0) this._clearWatch();
else if (this._geolocationWatchID === void 0) {
this._geolocateButton.classList.add("maplibregl-ctrl-geolocate-waiting");
this._geolocateButton.setAttribute("aria-pressed", "true");
numberOfWatches++;
let positionOptions;
if (numberOfWatches > 1) {
positionOptions = {
maximumAge: 6e5,
timeout: 0
};
noTimeout = true;
} else {
positionOptions = this.options.positionOptions;
noTimeout = false;
}
this._geolocationWatchID = window.navigator.geolocation.watchPosition(this._onSuccess, this._onError, positionOptions);
}
} else {
window.navigator.geolocation.getCurrentPosition(this._onSuccess, this._onError, this.options.positionOptions);
this._timeoutId = setTimeout(this._finish, 1e4);
}
return true;
}
_clearWatch() {
window.navigator.geolocation.clearWatch(this._geolocationWatchID);
this._geolocationWatchID = void 0;
this._geolocateButton.classList.remove("maplibregl-ctrl-geolocate-waiting");
this._geolocateButton.setAttribute("aria-pressed", "false");
if (this.options.showUserLocation) this._updateMarker(null);
}
};
//#endregion
//#region src/ui/control/scale_control.ts
const defaultOptions$1 = {
maxWidth: 100,
unit: "metric"
};
/**
* A `ScaleControl` control displays the ratio of a distance on the map to the corresponding distance on the ground.
*
* @group Markers and Controls
*
* @example
* ```ts
* let scale = new ScaleControl({
* maxWidth: 80,
* unit: 'imperial'
* });
* map.addControl(scale);
*
* scale.setUnit('metric');
* ```
*/
var ScaleControl = class {
/**
* @param options - the control's options
*/
constructor(options) {
this._onMove = () => {
updateScale(this._map, this._container, this.options);
};
this.setUnit = (unit) => {
this.options.unit = unit;
updateScale(this._map, this._container, this.options);
};
this.options = {
...defaultOptions$1,
...options
};
}
getDefaultPosition() {
return "bottom-left";
}
/** {@inheritDoc IControl.onAdd} */
onAdd(map) {
this._map = map;
this._container = DOM.create("div", "maplibregl-ctrl maplibregl-ctrl-scale", map.getContainer());
this._map.on("move", this._onMove);
this._onMove();
return this._container;
}
/** {@inheritDoc IControl.onRemove} */
onRemove() {
this._container.remove();
this._map.off("move", this._onMove);
this._map = void 0;
}
};
function updateScale(map, container, options) {
const optWidth = options?.maxWidth || 100;
const y = map._container.clientHeight / 2;
const x = map._container.clientWidth / 2;
const left = map.unproject([x - optWidth / 2, y]);
const right = map.unproject([x + optWidth / 2, y]);
const globeWidth = Math.round(map.project(right).x - map.project(left).x);
const maxWidth = Math.min(optWidth, globeWidth, map._container.clientWidth);
const maxMeters = left.distanceTo(right);
if (options?.unit === "imperial") {
const maxFeet = 3.2808 * maxMeters;
if (maxFeet > 5280) setScale(container, maxWidth, maxFeet / 5280, map._getUIString("ScaleControl.Miles"));
else setScale(container, maxWidth, maxFeet, map._getUIString("ScaleControl.Feet"));
} else if (options?.unit === "nautical") setScale(container, maxWidth, maxMeters / 1852, map._getUIString("ScaleControl.NauticalMiles"));
else if (maxMeters >= 1e3) setScale(container, maxWidth, maxMeters / 1e3, map._getUIString("ScaleControl.Kilometers"));
else setScale(container, maxWidth, maxMeters, map._getUIString("ScaleControl.Meters"));
}
function setScale(container, maxWidth, maxDistance, unit) {
const distance = getRoundNum(maxDistance);
const ratio = distance / maxDistance;
container.style.width = `${maxWidth * ratio}px`;
container.innerHTML = `${distance} ${unit}`;
}
function getDecimalRoundNum(d) {
const multiplier = Math.pow(10, Math.ceil(-Math.log(d) / Math.LN10));
return Math.round(d * multiplier) / multiplier;
}
function getRoundNum(num) {
const pow10 = Math.pow(10, `${Math.floor(num)}`.length - 1);
let d = num / pow10;
d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : d >= 1 ? 1 : getDecimalRoundNum(d);
return pow10 * d;
}
//#endregion
//#region src/ui/control/fullscreen_control.ts
/**
* The event class for fullscreen control events (`fullscreenstart` and `fullscreenend`).
*
* @group Event Related
*/
var FullscreenEvent = class extends Event {};
/**
* A `FullscreenControl` control contains a button for toggling the map in and out of fullscreen mode.
* When [requestFullscreen](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullscreen) is not supported, fullscreen is handled via CSS properties.
* The map's `cooperativeGestures` option is temporarily disabled while the map
* is in fullscreen mode, and is restored when the map exist fullscreen mode.
*
* @group Markers and Controls
* @param options - the full screen control options
*
* @example
* ```ts
* map.addControl(new FullscreenControl({container: document.querySelector('body')}));
* ```
* @see [View a fullscreen map](https://maplibre.org/maplibre-gl-js/docs/examples/view-a-fullscreen-map/)
*
* ## Events
*
* **Event** `fullscreenstart` of type {@link FullscreenEvent} will be fired when fullscreen mode has started.
*
* **Event** `fullscreenend` of type {@link FullscreenEvent} will be fired when fullscreen mode has ended.
*/
var FullscreenControl = class extends Evented {
/**
* @param options - the control's options
*/
constructor(options = {}) {
super();
this._onFullscreenChange = () => {
let fullscreenElement = window.document.fullscreenElement || window.document.webkitFullscreenElement;
while (fullscreenElement?.shadowRoot?.fullscreenElement) fullscreenElement = fullscreenElement.shadowRoot.fullscreenElement;
if (fullscreenElement === this._container !== this._fullscreen) this._handleFullscreenChange();
};
this._onClickFullscreen = () => {
if (this._isFullscreen()) this._exitFullscreen();
else this._requestFullscreen();
};
this._fullscreen = false;
this._pseudo = options.pseudo ?? false;
if (options?.container) {
if (options.container instanceof HTMLElement) this._container = options.container;
else warnOnce("Full screen control 'container' must be a DOM element.");
}
if ("onfullscreenchange" in document) this._fullscreenchange = "fullscreenchange";
else if ("onmozfullscreenchange" in document) this._fullscreenchange = "mozfullscreenchange";
else if ("onwebkitfullscreenchange" in document) this._fullscreenchange = "webkitfullscreenchange";
else if ("onmsfullscreenchange" in document) this._fullscreenchange = "MSFullscreenChange";
}
/** {@inheritDoc IControl.onAdd} */
onAdd(map) {
this._map = map;
this._container ||= this._map.getContainer();
this._controlContainer = DOM.create("div", "maplibregl-ctrl maplibregl-ctrl-group");
this._setupUI();
return this._controlContainer;
}
/** {@inheritDoc IControl.onRemove} */
onRemove() {
this._controlContainer.remove();
this._map = null;
window.document.removeEventListener(this._fullscreenchange, this._onFullscreenChange);
}
_setupUI() {
const button = this._fullscreenButton = DOM.create("button", "maplibregl-ctrl-fullscreen", this._controlContainer);
DOM.create("span", "maplibregl-ctrl-icon", button).setAttribute("aria-hidden", "true");
button.type = "button";
this._updateTitle();
this._fullscreenButton.addEventListener("click", this._onClickFullscreen);
window.document.addEventListener(this._fullscreenchange, this._onFullscreenChange);
}
_updateTitle() {
const title = this._getTitle();
this._fullscreenButton.setAttribute("aria-label", title);
this._fullscreenButton.title = title;
}
_getTitle() {
return this._map._getUIString(this._isFullscreen() ? "FullscreenControl.Exit" : "FullscreenControl.Enter");
}
_isFullscreen() {
return this._fullscreen;
}
_handleFullscreenChange() {
this._fullscreen = !this._fullscreen;
this._fullscreenButton.classList.toggle("maplibregl-ctrl-shrink");
this._fullscreenButton.classList.toggle("maplibregl-ctrl-fullscreen");
this._updateTitle();
if (this._fullscreen) {
this.fire(new FullscreenEvent("fullscreenstart"));
this._prevCooperativeGesturesEnabled = this._map.cooperativeGestures.isEnabled();
this._map.cooperativeGestures.disable();
} else {
this.fire(new FullscreenEvent("fullscreenend"));
if (this._prevCooperativeGesturesEnabled) this._map.cooperativeGestures.enable();
}
}
_exitFullscreen() {
if (this._pseudo) this._togglePseudoFullScreen();
else if (window.document.exitFullscreen) window.document.exitFullscreen();
else if (window.document.webkitCancelFullScreen) window.document.webkitCancelFullScreen();
else this._togglePseudoFullScreen();
}
_requestFullscreen() {
if (this._pseudo) this._togglePseudoFullScreen();
else if (this._container.requestFullscreen) this._container.requestFullscreen();
else if (this._container.webkitRequestFullscreen) this._container.webkitRequestFullscreen();
else this._togglePseudoFullScreen();
}
_togglePseudoFullScreen() {
this._container.classList.toggle("maplibregl-pseudo-fullscreen");
this._handleFullscreenChange();
this._map.resize();
}
};
//#endregion
//#region src/ui/control/terrain_control.ts
/**
* A `TerrainControl` control contains a button for turning the terrain on and off.
*
* @group Markers and Controls
*
* @example
* ```ts
* let map = new Map({TerrainControl: false})
* .addControl(new TerrainControl({
* source: "terrain"
* }));
* ```
* @see [3D Terrain](https://maplibre.org/maplibre-gl-js/docs/examples/3d-terrain/)
* @see [Create a Heatmap layer on a globe with terrain elevation](https://maplibre.org/maplibre-gl-js/docs/examples/create-a-heatmap-layer-on-a-globe-with-terrain-elevation/)
* @see [Display a hybrid satellite map with terrain elevation](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-hybrid-satellite-map-with-terrain-elevation/)
* @see [Sky, Fog, Terrain](https://maplibre.org/maplibre-gl-js/docs/examples/sky-fog-terrain/)
*/
var TerrainControl = class {
/**
* @param options - the control's options
*/
constructor(options) {
this._toggleTerrain = () => {
if (this._map.getTerrain()) this._map.setTerrain(null);
else this._map.setTerrain(this.options);
this._updateTerrainIcon();
};
this._updateTerrainIcon = () => {
this._terrainButton.classList.remove("maplibregl-ctrl-terrain");
this._terrainButton.classList.remove("maplibregl-ctrl-terrain-enabled");
if (this._map.terrain) {
this._terrainButton.classList.add("maplibregl-ctrl-terrain-enabled");
this._terrainButton.title = this._map._getUIString("TerrainControl.Disable");
} else {
this._terrainButton.classList.add("maplibregl-ctrl-terrain");
this._terrainButton.title = this._map._getUIString("TerrainControl.Enable");
}
};
this.options = options;
}
/** {@inheritDoc IControl.onAdd} */
onAdd(map) {
this._map = map;
this._container = DOM.create("div", "maplibregl-ctrl maplibregl-ctrl-group");
this._terrainButton = DOM.create("button", "maplibregl-ctrl-terrain", this._container);
DOM.create("span", "maplibregl-ctrl-icon", this._terrainButton).setAttribute("aria-hidden", "true");
this._terrainButton.type = "button";
this._terrainButton.addEventListener("click", this._toggleTerrain);
this._updateTerrainIcon();
this._map.on("terrain", this._updateTerrainIcon);
return this._container;
}
/** {@inheritDoc IControl.onRemove} */
onRemove() {
this._container.remove();
this._map.off("terrain", this._updateTerrainIcon);
this._map = void 0;
}
};
//#endregion
//#region src/ui/control/globe_control.ts
/**
* A `GlobeControl` control contains a button for toggling the map projection between "mercator" and "globe".
*
* @group Markers and Controls
*
* @example
* ```ts
* let map = new Map()
* .addControl(new GlobeControl());
* ```
*
* @see [Display a globe with a fill extrusion layer](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-globe-with-a-fill-extrusion-layer/)
* @see [Sky, Fog, Terrain](https://maplibre.org/maplibre-gl-js/docs/examples/sky-fog-terrain/)
*/
var GlobeControl = class {
constructor() {
this._toggleProjection = () => {
const currentProjection = this._map.getProjection()?.type;
if (currentProjection === "mercator" || !currentProjection) this._map.setProjection({ type: "globe" });
else this._map.setProjection({ type: "mercator" });
this._updateGlobeIcon();
};
this._updateGlobeIcon = () => {
this._globeButton.classList.remove("maplibregl-ctrl-globe");
this._globeButton.classList.remove("maplibregl-ctrl-globe-enabled");
if (this._map.getProjection()?.type === "globe") {
this._globeButton.classList.add("maplibregl-ctrl-globe-enabled");
this._globeButton.title = this._map._getUIString("GlobeControl.Disable");
} else {
this._globeButton.classList.add("maplibregl-ctrl-globe");
this._globeButton.title = this._map._getUIString("GlobeControl.Enable");
}
};
}
/** {@inheritDoc IControl.onAdd} */
onAdd(map) {
this._map = map;
this._container = DOM.create("div", "maplibregl-ctrl maplibregl-ctrl-group");
this._globeButton = DOM.create("button", "maplibregl-ctrl-globe", this._container);
DOM.create("span", "maplibregl-ctrl-icon", this._globeButton).setAttribute("aria-hidden", "true");
this._globeButton.type = "button";
this._globeButton.addEventListener("click", this._toggleProjection);
this._updateGlobeIcon();
this._map.on("styledata", this._updateGlobeIcon);
this._map.on("projectiontransition", this._updateGlobeIcon);
return this._container;
}
/** {@inheritDoc IControl.onRemove} */
onRemove() {
this._container.remove();
this._map.off("styledata", this._updateGlobeIcon);
this._map.off("projectiontransition", this._updateGlobeIcon);
this._globeButton.removeEventListener("click", this._toggleProjection);
this._map = void 0;
}
};
//#endregion
//#region src/ui/popup.ts
const defaultOptions = {
closeButton: true,
closeOnClick: true,
focusAfterOpen: true,
className: "",
maxWidth: "240px",
subpixelPositioning: false,
locationOccludedOpacity: void 0,
padding: void 0
};
const focusQuerySelector = [
"a[href]",
"[tabindex]:not([tabindex='-1'])",
"[contenteditable]:not([contenteditable='false'])",
"button:not([disabled])",
"input:not([disabled])",
"select:not([disabled])",
"textarea:not([disabled])"
].join(", ");
/**
* The event class for popup events (`open` and `close`).
*
* @group Event Related
*/
var PopupEvent = class extends Event {};
/**
* A popup component.
*
* @group Markers and Controls
*
*
* @example
* Create a popup
* ```ts
* let popup = new Popup();
* // Set an event listener that will fire
* // any time the popup is opened
* popup.on('open', () => {
* console.log('popup was opened');
* });
* ```
*
* @example
* Create a popup
* ```ts
* let popup = new Popup();
* // Set an event listener that will fire
* // any time the popup is closed
* popup.on('close', () => {
* console.log('popup was closed');
* });
* ```
*
* @example
* ```ts
* let markerHeight = 50, markerRadius = 10, linearOffset = 25;
* let popupOffsets = {
* 'top': [0, 0],
* 'top-left': [0,0],
* 'top-right': [0,0],
* 'bottom': [0, -markerHeight],
* 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1],
* 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1],
* 'left': [markerRadius, (markerHeight - markerRadius) * -1],
* 'right': [-markerRadius, (markerHeight - markerRadius) * -1]
* };
* let popup = new Popup({offset: popupOffsets, className: 'my-class'})
* .setLngLat(e.lngLat)
* .setHTML("<h1>Hello World!</h1>")
* .setMaxWidth("300px")
* .addTo(map);
* ```
* @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup/)
* @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-hover/)
* @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-click/)
* @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/attach-a-popup-to-a-marker-instance/)
* @see [Show polygon information on click](https://maplibre.org/maplibre-gl-js/docs/examples/show-polygon-information-on-click/)
*
* ## Events
*
* **Event** `open` of type {@link PopupEvent} will be fired when the popup is opened manually or programmatically.
*
* **Event** `close` of type {@link PopupEvent} will be fired when the popup is closed manually or programmatically.
*/
var Popup = class extends Evented {
/**
* @param options - the options
*/
constructor(options) {
super();
this._updateOpacity = () => {
if (this.options.locationOccludedOpacity === void 0) return;
if (this._map._camera.transform.isLocationOccluded(this.getLngLat())) this._container.style.opacity = `${this.options.locationOccludedOpacity}`;
else this._container.style.opacity = "";
};
this.remove = () => {
if (this._content) this._content.remove();
if (this._container) {
this._container.remove();
delete this._container;
}
if (this._map) {
this._map.off("move", this._update);
this._map.off("move", this._onClose);
this._map.off("click", this._onClose);
this._map.off("remove", this.remove);
this._map.off("terrain", this._update);
this._map.off("projectiontransition", this._update);
this._map.off("mousemove", this._update);
this._map.off("mouseup", this._update);
this._map.off("drag", this._update);
this._map._canvasContainer.classList.remove("maplibregl-track-pointer");
delete this._map;
this.fire(new PopupEvent("close"));
}
return this;
};
this._update = (event) => {
const hasPosition = this._lngLat || this._trackPointer;
if (!this._map || !hasPosition || !this._content) return;
if (!this._container) {
this._container = DOM.create("div", "maplibregl-popup", this._map.getContainer());
this._tip = DOM.create("div", "maplibregl-popup-tip", this._container);
this._container.appendChild(this._content);
if (this.options.className) for (const name of this.options.className.split(" ")) this._container.classList.add(name);
if (this._closeButton) this._closeButton.setAttribute("aria-label", this._map._getUIString("Popup.Close"));
if (this._trackPointer) this._container.classList.add("maplibregl-popup-track-pointer");
}
if (this.options.maxWidth && this._container.style.maxWidth !== this.options.maxWidth) this._container.style.maxWidth = this.options.maxWidth;
this._lngLat = smartWrap(this._lngLat, this._flatPos, this._map._camera.transform, this._trackPointer);
let cursor;
if (event && "point" in event && event.point) cursor = event.point;
if (this._trackPointer && !cursor) return;
const pos = this._flatPos = this._pos = this._trackPointer && cursor ? cursor : this._map.project(this._lngLat);
if (this._map.terrain) this._flatPos = this._trackPointer && cursor ? cursor : this._map._camera.transform.locationToScreenPoint(this._lngLat);
let anchor = this.options.anchor;
const offset = normalizeOffset(this.options.offset);
if (!anchor) {
const width = this._container.offsetWidth;
const height = this._container.offsetHeight;
const padding = normalizePadding(this.options.padding);
let anchorComponents;
if (pos.y + offset.bottom.y < height + padding.top) anchorComponents = ["top"];
else if (pos.y > this._map._camera.transform.height - height - padding.bottom) anchorComponents = ["bottom"];
else anchorComponents = [];
if (pos.x < width / 2 + padding.left) anchorComponents.push("left");
else if (pos.x > this._map._camera.transform.width - width / 2 - padding.right) anchorComponents.push("right");
if (anchorComponents.length === 0) anchor = "bottom";
else anchor = anchorComponents.join("-");
}
let offsetedPos = pos.add(offset[anchor]);
if (!this.options.subpixelPositioning) offsetedPos = offsetedPos.round();
this._container.style.transform = `${anchorTranslate[anchor]} translate(${offsetedPos.x}px,${offsetedPos.y}px)`;
applyAnchorClass(this._container, anchor, "popup");
this._updateOpacity();
};
this._onClose = () => {
this.remove();
};
this.options = extend(Object.create(defaultOptions), options);
}
/**
* Adds the popup to a map.
*
* @param map - The MapLibre GL JS map to add the popup to.
* @example
* ```ts
* new Popup()
* .setLngLat([0, 0])
* .setHTML("<h1>Null Island</h1>")
* .addTo(map);
* ```
* @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup/)
* @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-hover/)
* @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-click/)
* @see [Show polygon information on click](https://maplibre.org/maplibre-gl-js/docs/examples/show-polygon-information-on-click/)
*/
addTo(map) {
if (this._map) this.remove();
this._map = map;
if (this.options.closeOnClick) this._map.on("click", this._onClose);
if (this.options.closeOnMove) this._map.on("move", this._onClose);
this._map.on("remove", this.remove);
this._map.on("terrain", this._update);
this._map.on("projectiontransition", this._update);
this._update();
this._focusFirstElement();
if (this._trackPointer) {
this._map.on("mousemove", this._update);
this._map.on("mouseup", this._update);
if (this._container) this._container.classList.add("maplibregl-popup-track-pointer");
this._map._canvasContainer.classList.add("maplibregl-track-pointer");
} else this._map.on("move", this._update);
this.fire(new PopupEvent("open"));
return this;
}
/**
* @returns `true` if the popup is open, `false` if it is closed.
*/
isOpen() {
return !!this._map;
}
/**
* Returns the geographical location of the popup's anchor.
*
* The longitude of the result may differ by a multiple of 360 degrees from the longitude previously
* set by `setLngLat` because `Popup` wraps the anchor longitude across copies of the world to keep
* the popup on screen.
*
* @returns The geographical location of the popup's anchor.
*/
getLngLat() {
return this._lngLat;
}
/**
* Sets the geographical location of the popup's anchor, and moves the popup to it. Replaces trackPointer() behavior.
*
* @param lnglat - The geographical location to set as the popup's anchor.
*/
setLngLat(lnglat) {
this._lngLat = LngLat.convert(lnglat);
this._pos = null;
this._flatPos = null;
this._trackPointer = false;
this._update();
if (this._map) {
this._map.on("move", this._update);
this._map.off("mousemove", this._update);
if (this._container) this._container.classList.remove("maplibregl-popup-track-pointer");
this._map._canvasContainer.classList.remove("maplibregl-track-pointer");
}
return this;
}
/**
* Tracks the popup anchor to the cursor position on screens with a pointer device (it will be hidden on touchscreens). Replaces the `setLngLat` behavior.
* For most use cases, set `closeOnClick` and `closeButton` to `false`.
* @example
* ```ts
* let popup = new Popup({ closeOnClick: false, closeButton: false })
* .setHTML("<h1>Hello World!</h1>")
* .trackPointer()
* .addTo(map);
* ```
*/
trackPointer() {
this._trackPointer = true;
this._pos = null;
this._flatPos = null;
this._update();
if (this._map) {
this._map.off("move", this._update);
this._map.on("mousemove", this._update);
this._map.on("drag", this._update);
if (this._container) this._container.classList.add("maplibregl-popup-track-pointer");
this._map._canvasContainer.classList.add("maplibregl-track-pointer");
}
return this;
}
/**
* Returns the `Popup`'s HTML element.
* @example
* Change the `Popup` element's font size
* ```ts
* let popup = new Popup()
* .setLngLat([-96, 37.8])
* .setHTML("<p>Hello World!</p>")
* .addTo(map);
* let popupElem = popup.getElement();
* popupElem.style.fontSize = "25px";
* ```
* @returns element
*/
getElement() {
return this._container;
}
/**
* Sets the popup's content to a string of text.
*
* This function creates a [Text](https://developer.mozilla.org/en-US/docs/Web/API/Text) node in the DOM,
* so it cannot insert raw HTML. Use this method for security against XSS
* if the popup content is user-provided.
*
* @param text - Textual content for the popup.
* @example
* ```ts
* let popup = new Popup()
* .setLngLat(e.lngLat)
* .setText('Hello, world!')
* .addTo(map);
* ```
*/
setText(text) {
return this.setDOMContent(document.createTextNode(text));
}
/**
* Sets the popup's content to the HTML provided as a string.
*
* This method does not perform HTML filtering or sanitization, and must be
* used only with trusted content. Consider {@link Popup.setText} if
* the content is an untrusted text string.
*
* @param html - A string representing HTML content for the popup.
* @example
* ```ts
* let popup = new Popup()
* .setLngLat(e.lngLat)
* .setHTML("<h1>Hello World!</h1>")
* .addTo(map);
* ```
* @see [Display a popup](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup/)
* @see [Display a popup on hover](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-hover/)
* @see [Display a popup on click](https://maplibre.org/maplibre-gl-js/docs/examples/display-a-popup-on-click/)
* @see [Attach a popup to a marker instance](https://maplibre.org/maplibre-gl-js/docs/examples/attach-a-popup-to-a-marker-instance/)
*/
setHTML(html) {
const frag = document.createDocumentFragment();
const temp = document.createElement("body");
let child;
temp.innerHTML = html;
while (true) {
child = temp.firstChild;
if (!child) break;
frag.appendChild(child);
}
return this.setDOMContent(frag);
}
/**
* Returns the popup's maximum width.
*
* @returns The maximum width of the popup.
*/
getMaxWidth() {
return this._container?.style.maxWidth;
}
/**
* Sets the popup's maximum width. This is setting the CSS property `max-width`.
* Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width
*
* @param maxWidth - A string representing the value for the maximum width.
*/
setMaxWidth(maxWidth) {
this.options.maxWidth = maxWidth;
this._update();
return this;
}
/**
* Sets the popup's content to the element provided as a DOM node.
*
* @param htmlNode - A DOM node to be used as content for the popup.
* @example
* Create an element with the popup content
* ```ts
* let div = document.createElement('div');
* div.innerHTML = 'Hello, world!';
* let popup = new Popup()
* .setLngLat(e.lngLat)
* .setDOMContent(div)
* .addTo(map);
* ```
*/
setDOMContent(htmlNode) {
if (this._content) {
while (this._content.hasChildNodes()) if (this._content.firstChild) this._content.removeChild(this._content.firstChild);
} else this._content = DOM.create("div", "maplibregl-popup-content", this._container);
this._content.appendChild(htmlNode);
this._createCloseButton();
this._update();
this._focusFirstElement();
return this;
}
/**
* Adds a CSS class to the popup container element.
*
* @param className - Non-empty string with CSS class name to add to popup container
*
* @example
* ```ts
* let popup = new Popup()
* popup.addClassName('some-class')
* ```
*/
addClassName(className) {
if (this._container) this._container.classList.add(className);
return this;
}
/**
* Removes a CSS class from the popup container element.
*
* @param className - Non-empty string with CSS class name to remove from popup container
*
* @example
* ```ts
* let popup = new Popup()
* popup.removeClassName('some-class')
* ```
*/
removeClassName(className) {
if (this._container) this._container.classList.remove(className);
return this;
}
/**
* Sets the popup's offset.
*
* @param offset - Sets the popup's offset.
*/
setOffset(offset) {
this.options.offset = offset;
this._update();
return this;
}
/**
* Add or remove the given CSS class on the popup container, depending on whether the container currently has that class.
*
* @param className - Non-empty string with CSS class name to add/remove
*
* @returns if the class was removed return false, if class was added, then return true, undefined if there is no container
*
* @example
* ```ts
* let popup = new Popup()
* popup.toggleClassName('toggleClass')
* ```
*/
toggleClassName(className) {
if (this._container) return this._container.classList.toggle(className);
}
/**
* Set the option to allow subpixel positioning of the popup by passing a boolean
*
* @param value - When boolean is true, subpixel positioning is enabled for the popup.
*
* @example
* ```ts
* let popup = new Popup()
* popup.setSubpixelPositioning(true);
* ```
*/
setSubpixelPositioning(value) {
this.options.subpixelPositioning = value;
}
/**
* Sets the popup's padding constraints for positioning.
*
* @param padding - The padding to apply as a {@link PaddingOptions} object.
* @example
* ```ts
* popup.setPadding({ top: 10, right: 20, bottom: 30, left: 40 });
* ```
*/
setPadding(padding) {
this.options.padding = padding;
this._update();
}
_createCloseButton() {
if (this.options.closeButton) {
this._closeButton = DOM.create("button", "maplibregl-popup-close-button", this._content);
this._closeButton.type = "button";
this._closeButton.innerHTML = "×";
this._closeButton.addEventListener("click", this._onClose);
}
}
_focusFirstElement() {
if (!this.options.focusAfterOpen || !this._container) return;
const firstFocusable = this._container.querySelector(focusQuerySelector);
if (firstFocusable) firstFocusable.focus();
}
};
function normalizeOffset(offset) {
if (!offset) return normalizeOffset(new Point(0, 0));
else if (typeof offset === "number") {
const cornerOffset = Math.round(Math.abs(offset) / Math.SQRT2);
return {
"center": new Point(0, 0),
"top": new Point(0, offset),
"top-left": new Point(cornerOffset, cornerOffset),
"top-right": new Point(-cornerOffset, cornerOffset),
"bottom": new Point(0, -offset),
"bottom-left": new Point(cornerOffset, -cornerOffset),
"bottom-right": new Point(-cornerOffset, -cornerOffset),
"left": new Point(offset, 0),
"right": new Point(-offset, 0)
};
} else if (offset instanceof Point || Array.isArray(offset)) {
const convertedOffset = Point.convert(offset);
return {
"center": convertedOffset,
"top": convertedOffset,
"top-left": convertedOffset,
"top-right": convertedOffset,
"bottom": convertedOffset,
"bottom-left": convertedOffset,
"bottom-right": convertedOffset,
"left": convertedOffset,
"right": convertedOffset
};
} else return {
"center": Point.convert(offset["center"] || [0, 0]),
"top": Point.convert(offset["top"] || [0, 0]),
"top-left": Point.convert(offset["top-left"] || [0, 0]),
"top-right": Point.convert(offset["top-right"] || [0, 0]),
"bottom": Point.convert(offset["bottom"] || [0, 0]),
"bottom-left": Point.convert(offset["bottom-left"] || [0, 0]),
"bottom-right": Point.convert(offset["bottom-right"] || [0, 0]),
"left": Point.convert(offset["left"] || [0, 0]),
"right": Point.convert(offset["right"] || [0, 0])
};
}
function normalizePadding(padding) {
if (!padding) return {
top: 0,
right: 0,
bottom: 0,
left: 0
};
return {
top: padding.top ?? 0,
right: padding.right ?? 0,
bottom: padding.bottom ?? 0,
left: padding.left ?? 0
};
}
//#endregion
//#region src/index.ts
const version = version$2;
/**
* Sets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text).
* Necessary for supporting the Arabic and Hebrew languages, which are written right-to-left.
*
* @param pluginURL - URL pointing to the Mapbox RTL text plugin source.
* @param lazy - If set to `true`, maplibre will defer loading the plugin until rtl text is encountered,
* rtl text will then be rendered only after the plugin finishes loading.
* @example
* ```ts
* setRTLTextPlugin('https://unpkg.com/@mapbox/mapbox-gl-rtl-text@0.3.0/dist/mapbox-gl-rtl-text.js', false);
* ```
* @see [Add support for right-to-left scripts](https://maplibre.org/maplibre-gl-js/docs/examples/add-support-for-right-to-left-scripts/)
* @see [Display and style rich text labels](https://maplibre.org/maplibre-gl-js/docs/examples/display-and-style-rich-text-labels/)
*/
function setRTLTextPlugin(pluginURL, lazy) {
return rtlMainThreadPluginFactory().setRTLTextPlugin(pluginURL, lazy);
}
/**
* Gets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text) status.
* The status can be `unavailable` (i.e. not requested or removed), `loading`, `loaded` or `error`.
* If the status is `loaded` and the plugin is requested again, an error will be thrown.
*
* @example
* ```ts
* const pluginStatus = getRTLTextPluginStatus();
* ```
*/
function getRTLTextPluginStatus() {
return rtlMainThreadPluginFactory().getRTLTextPluginStatus();
}
/**
* Returns the package version of the library
* @returns Package version of the library
*/
function getVersion() {
return version;
}
/**
* Gets the number of web workers instantiated on a page with GL JS maps.
* By default, workerCount is 1 except for Safari browser where it is set to half the number of CPU cores (capped at 3).
* Make sure to set this property before creating any map instances for it to have effect.
*
* @returns Number of workers currently configured.
* @example
* ```ts
* const workerCount = getWorkerCount()
* ```
*/
function getWorkerCount() {
return WorkerPool.workerCount;
}
/**
* Sets the number of web workers instantiated on a page with GL JS maps.
* By default, workerCount is 1 except for Safari browser where it is set to half the number of CPU cores (capped at 3).
* Make sure to set this property before creating any map instances for it to have effect.
*
* @example
* ```ts
* setWorkerCount(2);
* ```
*/
function setWorkerCount(count) {
WorkerPool.workerCount = count;
}
/**
* Gets and sets the maximum number of images (raster tiles, sprites, icons) to load in parallel,
* which affects performance in raster-heavy maps. 16 by default.
*
* @returns Number of parallel requests currently configured.
* @example
* ```ts
* getMaxParallelImageRequests();
* ```
*/
function getMaxParallelImageRequests() {
return config.MAX_PARALLEL_IMAGE_REQUESTS;
}
/**
* Sets the maximum number of images (raster tiles, sprites, icons) to load in parallel,
* which affects performance in raster-heavy maps. 16 by default.
*
* @example
* ```ts
* setMaxParallelImageRequests(10);
* ```
*/
function setMaxParallelImageRequests(numRequests) {
config.MAX_PARALLEL_IMAGE_REQUESTS = numRequests;
}
/**
* Gets the worker url
* @returns The worker url
*/
function getWorkerUrl() {
return config.WORKER_URL;
}
/**
* Sets the worker url
*/
function setWorkerUrl(value) {
config.WORKER_URL = value;
}
/**
* Allows loading javascript code in the worker thread.
* *Note* that since this is using some very internal classes and flows it is considered experimental and can break at any point.
*
* It can be useful for the following examples:
* 1. Using `self.addProtocol` in the worker thread - note that you might need to also register the protocol on the main thread.
* 2. Using `self.registerWorkerSource(workerSource: WorkerSource)` to register a worker source, which should come with `addSourceType` usually.
* 3. using `self.actor.registerMessageHandler` to override some internal worker operations
* @param workerUrl - the worker url e.g. a url of a javascript file to load in the worker
* @returns
*
* @example
* ```ts
* // below is an example of sending a js file to the worker to load the method there
* // Note that you'll need to call the global function `addProtocol` in the worker to register the protocol there.
* // add-protocol-worker.js
* async function loadFn(params, abortController) {
* const t = await fetch(`https://${params.url.split("://")[1]}`);
* if (t.status == 200) {
* const buffer = await t.arrayBuffer();
* return {data: buffer}
* } else {
* throw new Error(`Tile fetch error: ${t.statusText}`);
* }
* }
* self.addProtocol('custom', loadFn);
*
* // main.js
* importScriptInWorkers('add-protocol-worker.js');
* ```
*/
async function importScriptInWorkers(workerUrl) {
await getGlobalDispatcher().broadcast("IS", workerUrl);
}
//#endregion
export { AJAXError, AttributionControl, BoxZoomHandler, CanvasSource, CooperativeGesturesHandler, DoubleClickZoomHandler, DragPanHandler, DragRotateHandler, EXTENT, EdgeInsets, ErrorEvent, Event, Evented, FullscreenControl, FullscreenEvent, GPUInitializationError, GeoJSONSource, GeolocateControl, GeolocateErrorEvent, GeolocateEvent, GeolocatePositionEvent, GlobeControl, Hash, ImageSource, KeyboardHandler, LngLat, LngLatBounds, LogoControl, Map$1 as Map, Map$1 as MapLibreMap, MapBoxZoomEvent, MapContextEvent, MapLibreEvent, MapMouseEvent, MapMovementEvent, MapProjectionEvent, MapSourceDataEvent, MapStyleDataEvent, MapStyleImageMissingEvent, MapStyleLoadEvent, MapTerrainEvent, MapTouchEvent, MapWheelEvent, Marker, MarkerClickEvent, MarkerDragEvent, MercatorCoordinate, NavigationControl, Point, Popup, PopupEvent, RasterDEMTileSource, RasterTileSource, ScaleControl, ScrollZoomHandler, Style, TerrainControl, TwoFingersTouchPitchHandler, TwoFingersTouchRotateHandler, TwoFingersTouchZoomHandler, TwoFingersTouchZoomRotateHandler, VectorTileSource, VideoSource, addProtocol, addSourceType, clearPrewarmedResources, config, createTileMesh, getGlobalDispatcher, getMaxParallelImageRequests, getRTLTextPluginStatus, getVersion, getWorkerCount, getWorkerUrl, importScriptInWorkers, isTimeFrozen, now, prewarm, removeProtocol, restoreNow, setMaxParallelImageRequests, setNow, setRTLTextPlugin, setWorkerCount, setWorkerUrl };
//# sourceMappingURL=maplibre-gl-dev.mjs.map