-
Notifications
You must be signed in to change notification settings - Fork 400
Expand file tree
/
Copy pathgoogleMapsExample.js
More file actions
432 lines (302 loc) · 11.7 KB
/
Copy pathgoogleMapsExample.js
File metadata and controls
432 lines (302 loc) · 11.7 KB
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
import {
WGS84_ELLIPSOID,
CAMERA_FRAME,
GeoUtils,
GlobeControls,
CameraTransitionManager,
TilesRenderer,
} from '3d-tiles-renderer';
import {
TilesFadePlugin,
UpdateOnChangePlugin,
TileCompressionPlugin,
UnloadTilesPlugin,
GLTFExtensionsPlugin,
BatchedTilesPlugin,
CesiumIonAuthPlugin,
} from '3d-tiles-renderer/plugins';
import {
Scene,
WebGLRenderer,
PerspectiveCamera,
MathUtils,
OrthographicCamera,
} from 'three';
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
import Stats from 'three/addons/libs/stats.module.js';
import { TopoLinesPlugin } from './src/plugins/topolines/TopoLinesPlugin.js';
let controls, scene, renderer, tiles, transition;
let statsContainer, stats;
const params = {
orthographic: false,
optimizedLoadStrategy: false,
loadSiblings: true,
enableCacheDisplay: false,
enableRendererStats: false,
useBatchedMesh: Boolean( new URLSearchParams( window.location.hash.replace( /^#/, '' ) ).get( 'batched' ) ),
useFadePlugin: true,
displayTopoLines: false,
errorTarget: 20,
reload: reinstantiateTiles,
};
init();
animate();
function reinstantiateTiles() {
if ( tiles ) {
scene.remove( tiles.group );
tiles.dispose();
tiles = null;
}
tiles = new TilesRenderer();
tiles.lruCache.minSize = 0;
tiles.registerPlugin( new CesiumIonAuthPlugin( { apiToken: import.meta.env.VITE_ION_KEY, assetId: '2275207', autoRefreshToken: true } ) );
tiles.registerPlugin( new TileCompressionPlugin() );
tiles.registerPlugin( new UpdateOnChangePlugin() );
tiles.registerPlugin( new UnloadTilesPlugin() );
tiles.registerPlugin( new TopoLinesPlugin( { projection: 'ellipsoid' } ) );
tiles.registerPlugin( new GLTFExtensionsPlugin( {
// Note the DRACO compression files need to be supplied via an explicit source.
// We use unpkg here but in practice should be provided by the application.
dracoLoader: new DRACOLoader().setDecoderPath( 'https://unpkg.com/three@0.153.0/examples/jsm/libs/draco/gltf/' )
} ) );
tiles.optimizedLoadStrategy = params.optimizedLoadStrategy;
tiles.loadSiblings = params.loadSiblings;
if ( params.useFadePlugin ) {
tiles.registerPlugin( new TilesFadePlugin() );
}
if ( params.useBatchedMesh ) {
tiles.registerPlugin( new BatchedTilesPlugin( {
renderer,
discardOriginalContent: false,
instanceCount: 250,
} ) );
}
tiles.group.rotation.x = - Math.PI / 2;
scene.add( tiles.group );
tiles.setResolutionFromRenderer( transition.camera, renderer );
tiles.setCamera( transition.camera );
controls.setEllipsoid( tiles.ellipsoid, tiles.group );
}
function init() {
// renderer
renderer = new WebGLRenderer( { antialias: true } );
renderer.setClearColor( 0x151c1f );
document.body.appendChild( renderer.domElement );
// scene
scene = new Scene();
// camera and transition set up
transition = new CameraTransitionManager(
new PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 160000000 ),
new OrthographicCamera( - 1, 1, 1, - 1, 1, 160000000 ),
);
transition.perspectiveCamera.position.set( 4800000, 2570000, 14720000 );
transition.perspectiveCamera.lookAt( 0, 0, 0 );
transition.autoSync = false;
transition.addEventListener( 'camera-change', ( { camera, prevCamera } ) => {
tiles.deleteCamera( prevCamera );
tiles.setCamera( camera );
controls.setCamera( camera );
} );
// disable adjusting the orthographic camera position for zoom since globe controls will do this
transition.orthographicPositionalZoom = false;
// controls
controls = new GlobeControls( scene, transition.camera, renderer.domElement, null );
controls.enableDamping = true;
controls.enableFlight = true;
controls.flightSpeed = 0.5;
controls.maxAltitude = Math.PI / 2;
// initialize tiles
reinstantiateTiles();
onWindowResize();
window.addEventListener( 'resize', onWindowResize, false );
window.addEventListener( 'hashchange', initFromHash );
// GUI
const gui = new GUI();
gui.width = 300;
gui.add( params, 'orthographic' ).onChange( v => {
controls.getPivotPoint( transition.fixedPoint );
// don't update the cameras if they are already being animated
if ( ! transition.animating ) {
// sync the camera positions and then adjust the camera views
transition.syncCameras();
controls.adjustCamera( transition.perspectiveCamera );
controls.adjustCamera( transition.orthographicCamera );
}
transition.toggle();
} );
const mapsOptions = gui.addFolder( 'Google Photorealistic Tiles' );
if ( new URLSearchParams( window.location.search ).has( 'showOptimizedSettings' ) ) {
params.optimizedLoadStrategy = true;
tiles.optimizedLoadStrategy = true;
mapsOptions.add( params, 'optimizedLoadStrategy' ).listen();
mapsOptions.add( params, 'loadSiblings' ).listen();
}
mapsOptions.add( params, 'useBatchedMesh' ).listen();
mapsOptions.add( params, 'useFadePlugin' ).listen();
mapsOptions.add( params, 'reload' );
const exampleOptions = gui.addFolder( 'Example Options' );
exampleOptions.add( params, 'displayTopoLines' ).listen();
exampleOptions.add( params, 'enableCacheDisplay' );
exampleOptions.add( params, 'enableRendererStats' );
exampleOptions.add( params, 'errorTarget', 5, 100, 1 ).onChange( () => {
tiles.getPluginByName( 'UPDATE_ON_CHANGE_PLUGIN' ).needsUpdate = true;
} );
// add stats
statsContainer = document.createElement( 'div' );
document.getElementById( 'info' ).appendChild( statsContainer );
// Stats
stats = new Stats();
stats.showPanel( 0 );
document.body.appendChild( stats.dom );
// run hash functions
initFromHash();
setInterval( updateHash, 100 );
}
function onWindowResize() {
const { perspectiveCamera, orthographicCamera } = transition;
const aspect = window.innerWidth / window.innerHeight;
perspectiveCamera.aspect = aspect;
perspectiveCamera.updateProjectionMatrix();
orthographicCamera.left = - orthographicCamera.top * aspect;
orthographicCamera.right = - orthographicCamera.left;
orthographicCamera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setPixelRatio( window.devicePixelRatio );
}
function updateHash() {
if ( ! tiles ) {
return;
}
if ( transition.mode !== 'perspective' && ! transition.animating ) {
controls.getPivotPoint( transition.fixedPoint );
transition.syncCameras();
}
const camera = transition.perspectiveCamera;
const cartographicResult = {};
const tilesMatInv = tiles.group.matrixWorld.clone().invert();
const localCameraMat = camera.matrixWorld.clone().premultiply( tilesMatInv );
// get the data
WGS84_ELLIPSOID.getCartographicFromObjectFrame( localCameraMat, cartographicResult, CAMERA_FRAME );
// convert to DEG
cartographicResult.azimuth *= MathUtils.RAD2DEG;
cartographicResult.elevation *= MathUtils.RAD2DEG;
cartographicResult.roll *= MathUtils.RAD2DEG;
cartographicResult.lat *= MathUtils.RAD2DEG;
cartographicResult.lon *= MathUtils.RAD2DEG;
// update hash
const urlParams = new URLSearchParams();
urlParams.set( 'lat', cartographicResult.lat.toFixed( 4 ) );
urlParams.set( 'lon', cartographicResult.lon.toFixed( 4 ) );
urlParams.set( 'height', cartographicResult.height.toFixed( 2 ) );
urlParams.set( 'az', cartographicResult.azimuth.toFixed( 2 ) );
urlParams.set( 'el', cartographicResult.elevation.toFixed( 2 ) );
urlParams.set( 'roll', cartographicResult.roll.toFixed( 2 ) );
if ( params.useBatchedMesh ) {
urlParams.set( 'batched', 1 );
}
window.history.replaceState( undefined, undefined, `#${ urlParams }` );
}
function initFromHash() {
const hash = window.location.hash.replace( /^#/, '' );
const urlParams = new URLSearchParams( hash );
if ( urlParams.has( 'batched' ) ) {
params.useBatchedMesh = Boolean( urlParams.get( 'batched' ) );
}
if ( ! urlParams.has( 'lat' ) && ! urlParams.has( 'lon' ) ) {
return;
}
// update the tiles matrix world so we can use it
tiles.group.updateMatrixWorld();
// get the position fields
const camera = transition.perspectiveCamera;
const lat = parseFloat( urlParams.get( 'lat' ) );
const lon = parseFloat( urlParams.get( 'lon' ) );
const height = parseFloat( urlParams.get( 'height' ) ) || 1000;
if ( urlParams.has( 'az' ) && urlParams.has( 'el' ) ) {
// get the az el fields for rotation if present
const az = parseFloat( urlParams.get( 'az' ) );
const el = parseFloat( urlParams.get( 'el' ) );
const roll = parseFloat( urlParams.get( 'roll' ) ) || 0;
// extract the east-north-up frame into matrix world
WGS84_ELLIPSOID.getObjectFrame(
lat * MathUtils.DEG2RAD, lon * MathUtils.DEG2RAD, height,
az * MathUtils.DEG2RAD, el * MathUtils.DEG2RAD, roll * MathUtils.DEG2RAD,
camera.matrixWorld, CAMERA_FRAME,
);
// apply the necessary tiles transform
camera.matrixWorld.premultiply( tiles.group.matrixWorld );
camera.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
} else {
// default to looking down if no az el are present
WGS84_ELLIPSOID.getCartographicToPosition( lat * MathUtils.DEG2RAD, lon * MathUtils.DEG2RAD, height, camera.position );
camera.position.applyMatrix4( tiles.group.matrixWorld );
camera.lookAt( 0, 0, 0 );
}
if ( transition.mode !== 'perspective' ) {
const currentMode = transition.mode;
transition.mode = 'perspective';
transition.syncCameras();
transition.mode = currentMode;
}
}
function animate() {
requestAnimationFrame( animate );
if ( ! tiles ) return;
// ensure transforms are up to date for controls update
scene.updateMatrixWorld();
controls.enabled = ! transition.animating;
controls.update();
transition.update();
// update options
const camera = transition.camera;
tiles.setResolutionFromRenderer( camera, renderer );
tiles.setCamera( camera );
const plugin = tiles.getPluginByName( 'TOPO_LINES_PLUGIN' );
plugin.topoOpacity = params.displayTopoLines ? 0.5 : 0;
plugin.cartoOpacity = params.displayTopoLines ? 0.5 : 0;
// update tiles
camera.updateMatrixWorld();
tiles.errorTarget = params.errorTarget;
tiles.update();
renderer.render( scene, camera );
stats.update();
updateHtml();
}
function updateHtml() {
// render html text updates
let str = '';
if ( params.enableCacheDisplay ) {
const lruCache = tiles.lruCache;
const cacheFullness = lruCache.cachedBytes / lruCache.maxBytesSize;
str += `Queued: ${ tiles.stats.queued } Downloading: ${ tiles.stats.downloading } Parsing: ${ tiles.stats.parsing } Loaded: ${ tiles.stats.loaded }<br/>Visible: ${ tiles.visibleTiles.size } Active: ${ tiles.activeTiles.size }<br/>`;
str += `Cache: ${ ( 100 * cacheFullness ).toFixed( 2 ) }% ~${ ( lruCache.cachedBytes / 1000 / 1000 ).toFixed( 2 ) }mb<br/>`;
}
if ( params.enableRendererStats ) {
const memory = renderer.info.memory;
const render = renderer.info.render;
const programCount = renderer.info.programs.length;
str += `Geometries: ${ memory.geometries } Textures: ${ memory.textures } Programs: ${ programCount } Draw Calls: ${ render.calls }`;
const batchPlugin = tiles.getPluginByName( 'BATCHED_TILES_PLUGIN' );
const fadePlugin = tiles.getPluginByName( 'FADE_TILES_PLUGIN' );
if ( batchPlugin ) {
let tot = 0;
batchPlugin.batchedMesh?._instanceInfo.forEach( info => {
if ( info.visible && info.active ) tot ++;
} );
fadePlugin?.batchedMesh?._instanceInfo.forEach( info => {
if ( info.visible && info.active ) tot ++;
} );
str += ', Batched: ' + tot;
}
}
if ( statsContainer.innerHTML !== str ) {
statsContainer.innerHTML = str;
}
const mat = tiles.group.matrixWorld.clone().invert();
const vec = transition.camera.position.clone().applyMatrix4( mat );
const res = {};
WGS84_ELLIPSOID.getPositionToCartographic( vec, res );
const attributions = tiles.getAttributions()[ 0 ]?.value || '';
document.getElementById( 'credits' ).innerText = GeoUtils.toLatLonString( res.lat, res.lon ) + '\n' + attributions;
}