-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathdem-source.ts
254 lines (239 loc) · 7.13 KB
/
dem-source.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import { LocalDemManager } from "./local-dem-manager";
import { decodeOptions, encodeOptions, getOptionsForZoom } from "./utils";
import RemoteDemManager from "./remote-dem-manager";
import type {
DemManager,
DemTile,
GlobalContourTileOptions,
Timing,
} from "./types";
import type WorkerDispatch from "./worker-dispatch";
import Actor from "./actor";
import { Timer } from "./performance";
if (!Blob.prototype.arrayBuffer) {
Blob.prototype.arrayBuffer = function arrayBuffer() {
return new Promise<ArrayBuffer>((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onload = (event) =>
resolve(event.target?.result as ArrayBuffer);
fileReader.onerror = reject;
fileReader.readAsArrayBuffer(this);
});
};
}
// for maplibre interop
type RequestParameters = {
url: string;
headers?: any;
method?: "GET" | "POST" | "PUT";
body?: string;
type?: "string" | "json" | "arrayBuffer" | "image";
credentials?: "same-origin" | "include";
collectResourceTiming?: boolean;
};
type ExpiryData = {
cacheControl?: string | null;
expires?: Date | string | null;
};
type GetResourceResponse<T> = ExpiryData & {
data: T;
};
type AddProtocolAction = (
requestParameters: RequestParameters,
abortController: AbortController,
) => Promise<GetResourceResponse<ArrayBuffer>>;
// for legacy maplibre-3 interop
type ResponseCallbackV3 = (
error?: Error | undefined,
data?: any | undefined,
cacheControl?: string | undefined,
expires?: string | undefined,
) => void;
type V3OrV4Protocol = <
T extends AbortController | ResponseCallbackV3,
R = T extends AbortController
? Promise<GetResourceResponse<ArrayBuffer>>
: { cancel: () => void },
>(
requestParameters: RequestParameters,
arg2: T,
) => R;
const v3compat =
(v4: AddProtocolAction): V3OrV4Protocol =>
(requestParameters, arg2) => {
if (arg2 instanceof AbortController) {
return v4(requestParameters, arg2) as any;
} else {
const abortController = new AbortController();
v4(requestParameters, abortController)
.then(
(result) =>
arg2(
undefined,
result.data,
result.cacheControl as any,
result.expires as any,
),
(err) => arg2(err),
)
.catch((err) => arg2(err));
return { cancel: () => abortController.abort() };
}
};
const used = new Set<string>();
/**
* A remote source of DEM tiles that can be connected to maplibre.
*/
export class DemSource {
sharedDemProtocolId: string;
contourProtocolId: string;
contourProtocolUrlBase: string;
manager: DemManager;
sharedDemProtocolUrl: string;
timingCallbacks: Array<(timing: Timing) => void> = [];
constructor({
url,
cacheSize = 100,
id = "dem",
encoding = "terrarium",
maxzoom = 12,
worker = true,
timeoutMs = 10_000,
actor,
}: {
/** Remote DEM tile url using `{z}` `{x}` and `{y}` placeholders */
url: string;
/** Number of most-recently-used tiles to cache */
cacheSize?: number;
/** Prefix for the maplibre protocol */
id?: string;
encoding?: "terrarium" | "mapbox";
/** Maximum zoom of tiles contained in the source */
maxzoom: number;
timeoutMs?: number;
/** Handle requests in a shared web worker to reduce UI-thread jank */
worker?: boolean;
actor?: Actor<WorkerDispatch>;
}) {
let protocolPrefix = id;
let i = 1;
while (used.has(protocolPrefix)) {
protocolPrefix = id + i++;
}
used.add(protocolPrefix);
this.sharedDemProtocolId = `${protocolPrefix}-shared`;
this.contourProtocolId = `${protocolPrefix}-contour`;
this.sharedDemProtocolUrl = `${this.sharedDemProtocolId}://{z}/{x}/{y}`;
this.contourProtocolUrlBase = `${this.contourProtocolId}://{z}/{x}/{y}`;
const ManagerClass = worker ? RemoteDemManager : LocalDemManager;
this.manager = new ManagerClass({
demUrlPattern: url,
cacheSize,
encoding,
maxzoom,
timeoutMs,
actor,
});
}
/** Registers a callback to be invoked with a performance report after each tile is requested. */
onTiming = (callback: (timing: Timing) => void) => {
this.timingCallbacks.push(callback);
};
getDemTile(
z: number,
x: number,
y: number,
abortController?: AbortController,
): Promise<DemTile> {
return this.manager.fetchAndParseTile(
z,
x,
y,
abortController || new AbortController(),
);
}
/**
* Adds contour and shared DEM protocol handlers to maplibre.
*
* @param maplibre maplibre global object
*/
setupMaplibre = (maplibre: {
addProtocol: (id: string, protcol: V3OrV4Protocol) => void;
}) => {
maplibre.addProtocol(this.sharedDemProtocolId, this.sharedDemProtocol);
maplibre.addProtocol(this.contourProtocolId, this.contourProtocol);
};
parseUrl(url: string): [number, number, number] {
const [, z, x, y] = /\/\/(\d+)\/(\d+)\/(\d+)/.exec(url) || [];
return [Number(z), Number(x), Number(y)];
}
/**
* Callback to be used with maplibre addProtocol to re-use cached DEM tiles across sources.
*/
sharedDemProtocolV4: AddProtocolAction = async (
request: RequestParameters,
abortController: AbortController,
) => {
const [z, x, y] = this.parseUrl(request.url);
const timer = new Timer("main");
let timing: Timing;
try {
const data = await this.manager.fetchTile(
z,
x,
y,
abortController,
timer,
);
timing = timer.finish(request.url);
const arrayBuffer: ArrayBuffer = await data.data.arrayBuffer();
return {
data: arrayBuffer,
cacheControl: data.cacheControl,
expires: data.expires,
};
} catch (error) {
timing = timer.error(request.url);
throw error;
} finally {
this.timingCallbacks.forEach((cb) => cb(timing));
}
};
/**
* Callback to be used with maplibre addProtocol to generate contour vector tiles according
* to options encoded in the tile URL pattern generated by `contourProtocolUrl`.
*/
contourProtocolV4: AddProtocolAction = async (
request: RequestParameters,
abortController: AbortController,
) => {
const timer = new Timer("main");
let timing: Timing;
try {
const [z, x, y] = this.parseUrl(request.url);
const options = decodeOptions(request.url);
const data = await this.manager.fetchContourTile(
z,
x,
y,
getOptionsForZoom(options, z),
abortController,
timer,
);
timing = timer.finish(request.url);
return { data: data.arrayBuffer };
} catch (error) {
timing = timer.error(request.url);
throw error;
} finally {
this.timingCallbacks.forEach((cb) => cb(timing));
}
};
contourProtocol: V3OrV4Protocol = v3compat(this.contourProtocolV4);
sharedDemProtocol: V3OrV4Protocol = v3compat(this.sharedDemProtocolV4);
/**
* Returns a URL with the correct maplibre protocol prefix and all `option` encoded in request parameters.
*/
contourProtocolUrl = (options: GlobalContourTileOptions) =>
`${this.contourProtocolUrlBase}?${encodeOptions(options)}`;
}