forked from tangrams/heightmapper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
445 lines (385 loc) · 15.4 KB
/
main.js
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/*jslint browser: true*/
/*global Tangram, gui */
map = (function () {
'use strict';
var map_start_location = [0, 0, 2];
var global_min = 0;
var global_max = 8900;
var uminValue, umaxValue; // storage
var scene_loaded = false;
var moving = false;
var analysing = false;
var done = false;
var tempCanvas;
var spread = 1;
var lastumax = null;
var diff = null;
var stopped = false; // emergency brake
var widening = false;
var tempFactor = 8; // size of tempCanvas relative to main canvas: 1/n
/*** URL parsing ***/
// leaflet-style URL hash pattern:
// #[zoom],[lat],[lng]
var url_hash = window.location.hash.slice(1, window.location.hash.length).split('/');
if (url_hash.length == 3) {
map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
// convert from strings
map_start_location = map_start_location.map(Number);
}
var query = splitQueryParams();
// { language: 'en', this: 'no'}
function splitQueryParams () {
var str = window.location.search;
var kvArray = str.slice(1).split('&');
// ['language=en', 'this=no']
var obj = {};
for (var i = 0, j=kvArray.length; i<j; i++) {
var value = kvArray[i].split('=');
var k = window.decodeURIComponent(value[0]);
var v = window.decodeURIComponent(value[1]);
obj[k] = v;
}
return obj;
}
/*** Map ***/
var map = L.map('map',
{"keyboardZoomOffset" : .05,
"inertiaDeceleration" : 10000,
"zoomSnap" : .001}
);
var layer = Tangram.leafletLayer({
scene: 'scene.yaml',
attribution: 'Map by <a href="https://mapzen.com/tangram" target="_blank">Tangram</a> | <a href="https://github.com/tangram/heightmapper" target="_blank">Fork This</a>',
postUpdate: function() {
if (gui.autoexpose && !stopped) {
// three stages:
// 1) start analysis
if (!analysing && !done) {
expose();
}
// 2) continue analysis
else if (analysing && !done) {
start_analysis();
}
// 3) stop analysis and reset
else if (done) {
done = false;
}
}
}
});
// from https://davidwalsh.name/javascript-debounce-function
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
function linkFromBlob(blob) {
var urlCreator = window.URL || window.webkitURL;
return urlCreator.createObjectURL( blob );
}
function expose() {
analysing = true;
if (typeof gui != 'undefined' && gui.autoexpose == false) return false;
if (scene_loaded) {
start_analysis();
} else {
// wait for scene to initialize first
scene.initializing.then(function() {
start_analysis();
});
}
}
function updateGUI() {
// update dat.gui controllers
for (var i in gui.__controllers) {
gui.__controllers[i].updateDisplay();
}
}
function start_analysis() {
// set levels
var levels = analyse();
diff = levels.max - lastumax;
if (typeof levels.max !== 'undefined') lastumax = levels.max;
else diff = 1;
// was the last change a widening or narrowing?
widening = diff < 0 ? false : true;
if (levels) {
scene.styles.hillshade.shaders.uniforms.u_min = levels.min;
scene.styles.hillshade.shaders.uniforms.u_max = levels.max;
}
scene.requestRedraw();
}
function analyse() {
var ctx = tempCanvas.getContext("2d"); // Get canvas 2d context
ctx.clearRect(0, 0, tempCanvas.width, tempCanvas.height);
// redraw canvas smaller in testing canvas, for speed
ctx.drawImage(scene.canvas,0,0,scene.canvas.width/tempFactor,scene.canvas.height/tempFactor);
// get all the pixels
var pixels = ctx.getImageData(0,0, tempCanvas.width, tempCanvas.height);
var val;
var counts = {};
var empty = true;
var max = 0, min = 255;
// only check every nth pixel (vary with browser size)
// var stride = Math.round(img.height * img.width / 1000000);
// 4 = only sample the red value in [R, G, B, A]
for (var i = 0; i < tempCanvas.height * tempCanvas.width * 4; i += 4) {
val = pixels.data[i];
var alpha = pixels.data[i+3];
if (alpha === 0) { // empty pixel, skip to the next one
continue;
}
// if we got this far, we found at least one non-empty pixel!
empty = false;
// update counts, to get a histogram
counts[val] = counts[val] ? counts[val]+1 : 1;
// update min and max so far
min = Math.min(min, val);
max = Math.max(max, val);
}
if (empty) {
// no pixels found, skip the analysis
return false;
}
if (max > 253 && min < 4 && !widening ) {
// looks good, done
analysing = false;
done = true;
spread = 2;
return false;
}
if (max > 252 && min < 4 && widening) {
// over-exposed, widen the range
spread *= 2;
// cap spread
spread = Math.min(spread, 512)
// console.log("WIDEN >", spread, " diff:", diff)
max += spread;
min -= spread;
}
// calculate adjusted elevation settings based on current pixel
// values and elevation settings
var range = (gui.u_max - gui.u_min);
var minadj = (min / 255) * range + gui.u_min;
var maxadj = (max / 255) * range + gui.u_min;
// keep levels in range
minadj = Math.max(minadj, -11000);
maxadj = Math.min(maxadj, 8900);
// only let the minimum value go below 0 if ocean data is included
minadj = gui.include_oceans ? minadj : Math.max(minadj, 0);
// keep min and max separated
if (minadj === maxadj) maxadj += 10;
// get the width of the current view in meters
// compare to the current elevation range in meters
// the ratio is the "height" of the current scene compared to its width –
// multiply it by the width of your 3D mesh to get the height
var zrange = (gui.u_max - gui.u_min);
var xscale = zrange / scene.view.size.meters.x;
gui.scaleFactor = xscale +''; // convert to string to make the display read-only
scene.styles.hillshade.shaders.uniforms.u_min = minadj;
scene.styles.hillshade.shaders.uniforms.u_max = maxadj;
// update dat.gui controllers
gui.u_min = minadj;
gui.u_max = maxadj;
updateGUI();
return {max: maxadj, min: minadj}
}
window.layer = layer;
var scene = layer.scene;
window.scene = scene;
// setView expects format ([lat, long], zoom)
map.setView(map_start_location.slice(0, 3), map_start_location[2]);
var hash = new L.Hash(map);
// Create dat GUI
var gui;
function addGUI () {
gui.domElement.parentNode.style.zIndex = 5; // make sure GUI is on top of map
window.gui = gui;
gui.u_max = 8848.;
gui.add(gui, 'u_max', -10916., 8848).name("max elevation").onChange(function(value) {
scene.styles.hillshade.shaders.uniforms.u_max = value;
scene.requestRedraw();
});
// gui.u_min = -10916.;
gui.u_min = 0.;
gui.add(gui, 'u_min', -10916., 8848).name("min elevation").onChange(function(value) {
scene.styles.hillshade.shaders.uniforms.u_min = value;
scene.requestRedraw();
});
gui.scaleFactor = 1 +'';
gui.add(gui, 'scaleFactor').name("z:x scale factor");
gui.autoexpose = true;
gui.add(gui, 'autoexpose').name("auto-exposure").onChange(function(value) {
sliderState(!value);
if (value) {
// store slider values
uminValue = gui.u_min;
umaxValue = gui.u_max;
// force widening value to trigger redraw
lastumax = 0;
expose();
} else if (typeof uminValue != 'undefined') {
// retrieve slider values
scene.styles.hillshade.shaders.uniforms.u_min = uminValue;
scene.styles.hillshade.shaders.uniforms.u_max = umaxValue;
scene.requestRedraw();
gui.u_min = uminValue;
gui.u_max = umaxValue;
updateGUI();
}
});
gui.include_oceans = false;
gui.add(gui, 'include_oceans').name("include ocean data").onChange(function(value) {
if (value) global_min = -11000;
else global_min = 0;
gui.u_min = global_min;
scene.styles.hillshade.shaders.uniforms.u_min = global_min;
expose();
});
gui.map_lines = false;
gui.add(gui, 'map_lines').name("map lines").onChange(function(value) {
toggleLines(value);
});
gui.map_labels = false;
gui.add(gui, 'map_labels').name("map labels").onChange(function(value) {
toggleLabels(value);
});
// gui.API_KEY = query.api_key || 'mapzen-XXXXXX';
// gui.add(gui, 'API_KEY').name("API KEY").onChange(function(value) {
// scene.config.sources["elevation-high"].url_params.api_key = value;
// scene.config.layers["terrain-high"].enabled = true;
// scene.updateConfig();
// });
gui.export = function () {
return scene.screenshot().then(function(screenshot) {
// if (gui.API_KEY === 'mapzen-XXXXXX') {
// alert('Please enter your API key!')
// scene.config.layers["terrain-high"].enabled = false;
// scene.updateConfig();
// } else if (gui.API_KEY === scene.config.sources.elevation.url_params.api_key) {
// alert('Please enter your own API key!')
// scene.config.layers["terrain-high"].enabled = false;
// scene.updateConfig();
// } else {
// uses FileSaver.js: https://github.com/eligrey/FileSaver.js/
saveAs(screenshot.blob, 'heightmapper-' + (+new Date()) + '.png');
// }
});
}
gui.add(gui, 'export');
gui.help = function () {
// show help screen and input blocker
toggleHelp(true);
}
gui.add(gui, 'help');
// set scale factor text field to be uneditable but still selectable (for copying)
gui.__controllers[2].domElement.firstChild.setAttribute("readonly", true);
}
function stop() {
console.log('stopping')
stopped = true;
console.log('stopping:', stopped)
}
function go() {
stopped = false;
}
window.stop = stop;
window.go = go;
// disable sliders when autoexpose is on
function sliderState(active) {
var pointerEvents = active ? "auto" : "none";
var opacity = active ? 1. : .5;
gui.__controllers[0].domElement.parentElement.style.pointerEvents = pointerEvents;
gui.__controllers[0].domElement.parentElement.style.opacity = opacity;
gui.__controllers[1].domElement.parentElement.style.pointerEvents = pointerEvents;
gui.__controllers[1].domElement.parentElement.style.opacity = opacity;
}
// show and hide help screen
function toggleHelp(active) {
var visibility = active ? "visible" : "hidden";
document.getElementById('help').style.visibility = visibility;
// help-blocker prevents map interaction while help is visible
document.getElementById('help-blocker').style.visibility = visibility;
}
// show and hide new alert
function toggleNew(active) {
var visibility = active ? "visible" : "hidden";
document.getElementById('new').style.visibility = visibility;
// help-blocker prevents map interaction while help is visible
document.getElementById('help-blocker').style.visibility = visibility;
}
// draw boundary and water lines
function toggleLines(active) {
// scene.config.layers.water.visible = active;
scene.styles.togglelines.shaders.uniforms.u_alpha = active ? 1. : 0.;
scene.requestRedraw();
}
// draw labels
function toggleLabels(active) {
// scene.config.layers.water.visible = active;
scene.styles.toggletext.shaders.uniforms.u_alpha = active ? 1. : 0.;
scene.requestRedraw();
}
document.onkeydown = function (e) {
e = e || window.event;
// listen for 'h'
if (e.which == 72 && document.activeElement != document.getElementsByClassName('leaflet-pelias-input')[0]) {
// toggle UI
var display = map._controlContainer.style.display;
map._controlContainer.style.display = (display === "none") ? "block" : "none";
document.getElementsByClassName('dg')[0].style.display = (display === "none") ? "block" : "none";
// listen for 'esc'
} else if (e.which == 27) {
toggleHelp(false);
}
};
/***** Render loop *****/
window.addEventListener('load', function () {
// Scene initialized
layer.on('init', function() {
gui = new dat.GUI({ autoPlace: true, hideable: true, width: 300 });
addGUI();
// resetViewComplete();
scene.subscribe({
// will be triggered when tiles are finished loading
// and also manually by the moveend event
view_complete: function() {
}
});
scene_loaded = true;
sliderState(false);
tempCanvas = document.createElement("canvas");
// document.body.appendChild(tempCanvas);
// tempCanvas.style.position = "absolute";
// tempCanvas.style.zIndex = 10000;
tempCanvas.width = scene.canvas.width/tempFactor;
tempCanvas.height = scene.canvas.height/tempFactor;
});
layer.addTo(map);
// bind help div onclicks
document.getElementById('help').onclick = function(){toggleHelp(false)};
document.getElementById('new').onclick = function(){toggleNew(false)};
document.getElementById('help-blocker').onclick = function(){toggleHelp(false);toggleNew(false);};
// debounce moveend event
var moveend = debounce(function(e) {
moving = false;
// manually reset view_complete
scene.resetViewComplete();
scene.requestRedraw();
}, 250);
map.on("movestart", function (e) { moving = true; });
map.on("moveend", function (e) { moveend(e) });
// toggleNew(true);
});
return map;
}());