-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy paththree.ts
More file actions
537 lines (461 loc) · 15.1 KB
/
Copy paththree.ts
File metadata and controls
537 lines (461 loc) · 15.1 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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
/**
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
DirectionalLight,
Euler,
HemisphereLight,
Intersection,
MathUtils,
Matrix4,
Object3D,
PCFSoftShadowMap,
PerspectiveCamera,
Quaternion,
Raycaster,
RaycasterParameters,
REVISION,
Scene,
Vector2,
Vector3,
WebGLRenderer,
} from "three";
import { latLngToVector3Relative, toLatLngAltitudeLiteral } from "./util";
import type { LatLngTypes } from "./util";
// Since r162, the sRGBEncoding constant is no longer exported from three.
// The value is kept here to keep compatibility with older three.js versions.
// This will be removed with the next major release.
const sRGBEncoding = 3001;
const DEFAULT_UP = new Vector3(0, 0, 1);
export interface RaycastOptions {
/**
* Set to true to also test children of the specified objects for
* intersections.
*
* @default false
*/
recursive?: boolean;
/**
* Update the inverse-projection-matrix before casting the ray (set this
* to false if you need to run multiple raycasts for the same frame).
*
* @default true
*/
updateMatrix?: boolean;
/**
* Additional parameters to pass to the three.js raycaster.
*
* @see https://threejs.org/docs/#api/en/core/Raycaster.params
*/
raycasterParameters?: RaycasterParameters;
}
export interface ThreeJSOverlayViewOptions {
/**
* The anchor for the scene.
*
* @default {lat: 0, lng: 0, altitude: 0}
*/
anchor?: LatLngTypes;
/**
* The axis pointing up in the scene. Can be specified as "Z", "Y" or a
* Vector3, in which case the normalized vector will become the up-axis.
*
* @default "Z"
*/
upAxis?: "Z" | "Y" | Vector3;
/**
* The map the overlay will be added to.
* Can be set at initialization or by calling `setMap(map)`.
*/
map?: google.maps.Map;
/**
* The scene object to render in the overlay. If no scene is specified, a
* new scene is created and can be accessed via `overlay.scene`.
*/
scene?: Scene;
/**
* The animation mode controls when the overlay will redraw, either
* continuously (`always`) or on demand (`ondemand`). When using the
* on demand mode, the overlay will re-render whenever the map renders
* (camera movements) or when `requestRedraw()` is called.
*
* To achieve animations in this mode, you can either use an outside
* animation-loop that calls `requestRedraw()` as long as needed or call
* `requestRedraw()` from within the `onBeforeRender` function to
*
* @default "ondemand"
*/
animationMode?: "always" | "ondemand";
/**
* Add default lighting to the scene.
* @default true
*/
addDefaultLighting?: boolean;
}
/* eslint-disable @typescript-eslint/no-empty-function */
/**
* Add a [three.js](https://threejs.org) scene as a [Google Maps WebGLOverlayView](http://goo.gle/WebGLOverlayView-ref).
*/
export class ThreeJSOverlayView implements google.maps.WebGLOverlayView {
/** {@inheritDoc ThreeJSOverlayViewOptions.scene} */
public readonly scene: Scene;
/** {@inheritDoc ThreeJSOverlayViewOptions.animationMode} */
public animationMode: "always" | "ondemand" = "ondemand";
/** {@inheritDoc ThreeJSOverlayViewOptions.anchor} */
protected anchor: google.maps.LatLngAltitudeLiteral;
protected readonly camera: PerspectiveCamera;
protected readonly rotationArray: Float32Array = new Float32Array(3);
protected readonly rotationInverse: Quaternion = new Quaternion();
protected readonly projectionMatrixInverse = new Matrix4();
protected readonly overlay: google.maps.WebGLOverlayView;
protected renderer: WebGLRenderer;
protected raycaster: Raycaster = new Raycaster();
constructor(options: ThreeJSOverlayViewOptions = {}) {
const {
anchor = { lat: 0, lng: 0, altitude: 0 },
upAxis = "Z",
scene,
map,
animationMode = "ondemand",
addDefaultLighting = true,
} = options;
this.overlay = new google.maps.WebGLOverlayView();
this.renderer = null;
this.camera = null;
this.animationMode = animationMode;
this.setAnchor(anchor);
this.setUpAxis(upAxis);
this.scene = scene ?? new Scene();
if (addDefaultLighting) this.initSceneLights();
this.overlay.onAdd = this.onAdd.bind(this);
this.overlay.onRemove = this.onRemove.bind(this);
this.overlay.onContextLost = this.onContextLost.bind(this);
this.overlay.onContextRestored = this.onContextRestored.bind(this);
this.overlay.onStateUpdate = this.onStateUpdate.bind(this);
this.overlay.onDraw = this.onDraw.bind(this);
this.camera = new PerspectiveCamera();
if (map) {
this.setMap(map);
}
}
/**
* Sets the anchor-point.
* @param anchor
*/
public setAnchor(anchor: LatLngTypes) {
this.anchor = toLatLngAltitudeLiteral(anchor);
}
/**
* Sets the axis to use as "up" in the scene.
* @param axis
*/
public setUpAxis(axis: "Y" | "Z" | Vector3): void {
const upVector = new Vector3(0, 0, 1);
if (typeof axis !== "string") {
upVector.copy(axis);
} else {
if (axis.toLowerCase() === "y") {
upVector.set(0, 1, 0);
} else if (axis.toLowerCase() !== "z") {
console.warn(`invalid value '${axis}' specified as upAxis`);
}
}
upVector.normalize();
const q = new Quaternion();
q.setFromUnitVectors(upVector, DEFAULT_UP);
// inverse rotation is needed in latLngAltitudeToVector3()
this.rotationInverse.copy(q).invert();
// copy to rotationArray for transformer.fromLatLngAltitude()
const euler = new Euler().setFromQuaternion(q, "XYZ");
this.rotationArray[0] = MathUtils.radToDeg(euler.x);
this.rotationArray[1] = MathUtils.radToDeg(euler.y);
this.rotationArray[2] = MathUtils.radToDeg(euler.z);
}
/**
* Runs raycasting for the specified screen-coordinates against all objects
* in the scene.
*
* @param p normalized screenspace coordinates of the
* mouse-cursor. x/y are in range [-1, 1], y is pointing up.
* @param options raycasting options. In this case the `recursive` option
* has no effect as it is always recursive.
* @return the list of intersections
*/
public raycast(p: Vector2, options?: RaycastOptions): Intersection[];
/**
* Runs raycasting for the specified screen-coordinates against the specified
* list of objects.
*
* Note for typescript users: the returned Intersection objects can only be
* properly typed for non-recursive lookups (this is handled by the internal
* signature below).
*
* @param p normalized screenspace coordinates of the
* mouse-cursor. x/y are in range [-1, 1], y is pointing up.
* @param objects list of objects to test
* @param options raycasting options.
*/
public raycast(
p: Vector2,
objects: Object3D[],
options?: RaycastOptions & { recursive: true }
): Intersection[];
// additional signature to enable typings in returned objects when possible
public raycast<T extends Object3D>(
p: Vector2,
objects: T[],
options?:
| Omit<RaycastOptions, "recursive">
| (RaycastOptions & { recursive: false })
): Intersection<T>[];
// implemetation
public raycast(
p: Vector2,
optionsOrObjects?: Object3D[] | RaycastOptions,
options: RaycastOptions = {}
): Intersection[] {
let objects: Object3D[];
if (Array.isArray(optionsOrObjects)) {
objects = optionsOrObjects || null;
} else {
objects = [this.scene];
options = { ...optionsOrObjects, recursive: true };
}
const {
updateMatrix = true,
recursive = false,
raycasterParameters,
} = options;
// when `raycast()` is called from within the `onBeforeRender()` callback,
// the mvp-matrix for this frame has already been computed and stored in
// `this.camera.projectionMatrix`.
// The mvp-matrix transforms world-space meters to clip-space
// coordinates. The inverse matrix created here does the exact opposite
// and converts clip-space coordinates to world-space.
if (updateMatrix) {
this.projectionMatrixInverse.copy(this.camera.projectionMatrix).invert();
}
// create two points (with different depth) from the mouse-position and
// convert them into world-space coordinates to set up the ray.
this.raycaster.ray.origin
.set(p.x, p.y, 0)
.applyMatrix4(this.projectionMatrixInverse);
this.raycaster.ray.direction
.set(p.x, p.y, 0.5)
.applyMatrix4(this.projectionMatrixInverse)
.sub(this.raycaster.ray.origin)
.normalize();
// back up the raycaster parameters
const oldRaycasterParams = this.raycaster.params;
if (raycasterParameters) {
this.raycaster.params = raycasterParameters;
}
const results = this.raycaster.intersectObjects(objects, recursive);
// reset raycaster params to whatever they were before
this.raycaster.params = oldRaycasterParams;
return results;
}
/**
* Overwrite this method to handle any GL state updates outside the
* render animation frame.
* @param options
*/
public onStateUpdate(options: google.maps.WebGLStateOptions): void;
public onStateUpdate(): void {}
/**
* Overwrite this method to fetch or create intermediate data structures
* before the overlay is drawn that don’t require immediate access to the
* WebGL rendering context.
*/
public onAdd(): void {}
/**
* Overwrite this method to update your scene just before a new frame is
* drawn.
*/
public onBeforeDraw(): void {}
/**
* This method is called when the overlay is removed from the map with
* `overlay.setMap(null)`, and is where you can remove all intermediate
* objects created in onAdd.
*/
public onRemove(): void {}
/**
* Triggers the map to update GL state.
*/
public requestStateUpdate(): void {
this.overlay.requestStateUpdate();
}
/**
* Triggers the map to redraw a frame.
*/
public requestRedraw(): void {
this.overlay.requestRedraw();
}
/**
* Returns the map the overlay is added to.
*/
public getMap(): google.maps.Map {
return this.overlay.getMap();
}
/**
* Adds the overlay to the map.
* @param map The map to access the div, model and view state.
*/
public setMap(map: google.maps.Map): void {
this.overlay.setMap(map);
}
/**
* Adds the given listener function to the given event name. Returns an
* identifier for this listener that can be used with
* <code>google.maps.event.removeListener</code>.
*/
public addListener(
eventName: string,
handler: (...args: unknown[]) => void
): google.maps.MapsEventListener {
return this.overlay.addListener(eventName, handler);
}
/**
* This method is called once the rendering context is available. Use it to
* initialize or bind any WebGL state such as shaders or buffer objects.
* @param options that allow developers to restore the GL context.
*/
public onContextRestored({ gl }: google.maps.WebGLStateOptions) {
this.renderer = new WebGLRenderer({
canvas: gl.canvas,
context: gl,
...gl.getContextAttributes(),
});
this.renderer.autoClear = false;
this.renderer.autoClearDepth = false;
this.renderer.shadowMap.enabled = true;
this.renderer.shadowMap.type = PCFSoftShadowMap;
// Since r152, default outputColorSpace is SRGB
// Deprecated outputEncoding kept for backwards compatibility
if (Number(REVISION) < 152) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(this.renderer as any).outputEncoding = sRGBEncoding;
}
const { width, height } = gl.canvas;
this.renderer.setViewport(0, 0, width, height);
}
/**
* This method is called when the rendering context is lost for any reason,
* and is where you should clean up any pre-existing GL state, since it is
* no longer needed.
*/
public onContextLost() {
if (!this.renderer) {
return;
}
this.renderer.dispose();
this.renderer = null;
}
/**
* Implement this method to draw WebGL content directly on the map. Note
* that if the overlay needs a new frame drawn then call {@link
* ThreeJSOverlayView.requestRedraw}.
* @param options that allow developers to render content to an associated
* Google basemap.
*/
public onDraw({ gl, transformer }: google.maps.WebGLDrawOptions): void {
this.camera.projectionMatrix.fromArray(
transformer.fromLatLngAltitude(this.anchor, this.rotationArray)
);
gl.disable(gl.SCISSOR_TEST);
this.onBeforeDraw();
this.renderer.render(this.scene, this.camera);
this.renderer.resetState();
if (this.animationMode === "always") this.requestRedraw();
}
/**
* Convert coordinates from WGS84 Latitude Longitude to world-space
* coordinates while taking the origin and orientation into account.
*/
public latLngAltitudeToVector3(
position: LatLngTypes,
target = new Vector3()
) {
latLngToVector3Relative(
toLatLngAltitudeLiteral(position),
this.anchor,
target
);
target.applyQuaternion(this.rotationInverse);
return target;
}
// MVCObject interface forwarded to the overlay
/**
* Binds a View to a Model.
*/
public bindTo(
key: string,
target: google.maps.MVCObject,
targetKey?: string,
noNotify?: boolean
): void {
this.overlay.bindTo(key, target, targetKey, noNotify);
}
/**
* Gets a value.
*/
public get(key: string) {
return this.overlay.get(key);
}
/**
* Notify all observers of a change on this property. This notifies both
* objects that are bound to the object's property as well as the object
* that it is bound to.
*/
public notify(key: string): void {
this.overlay.notify(key);
}
/**
* Sets a value.
*/
public set(key: string, value: unknown): void {
this.overlay.set(key, value);
}
/**
* Sets a collection of key-value pairs.
*/
public setValues(values?: object): void {
this.overlay.setValues(values);
}
/**
* Removes a binding. Unbinding will set the unbound property to the current
* value. The object will not be notified, as the value has not changed.
*/
public unbind(key: string): void {
this.overlay.unbind(key);
}
/**
* Removes all bindings.
*/
public unbindAll(): void {
this.overlay.unbindAll();
}
/**
* Creates lights (directional and hemisphere light) to illuminate the model
* (roughly approximates the lighting of buildings in maps)
*/
private initSceneLights() {
const hemiLight = new HemisphereLight(0xffffff, 0x444444, 1);
hemiLight.position.set(0, -0.2, 1).normalize();
const dirLight = new DirectionalLight(0xffffff);
dirLight.position.set(0, 10, 100);
this.scene.add(hemiLight, dirLight);
}
}