forked from nytimes/aframe-loader-3dtiles-component
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
268 lines (248 loc) · 8.87 KB
/
index.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
import { Loader3DTiles, PointCloudColoring } from './lib/three-loader-3dtiles';
import './textarea';
import { Vector3 } from 'three';
if (typeof AFRAME === 'undefined') {
throw new Error('Component attempted to register before AFRAME was available.');
}
const POINT_CLOUD_COLORING = {
white: PointCloudColoring.White,
intensity: PointCloudColoring.Intensity,
classification: PointCloudColoring.Classification,
elevation: PointCloudColoring.Elevation,
rgb: PointCloudColoring.RGB
};
/**
* 3D Tiles component for A-Frame.
*/
AFRAME.registerComponent('loader-3dtiles', {
schema: {
url: { type: 'string' },
cameraEl: { type: 'selector' },
maximumSSE: { type: 'int', default: 16 },
maximumMem: { type: 'int', default: 32 },
distanceScale: { type: 'number', default: 1.0 },
pointcloudColoring: { type: 'string', default: 'white' },
pointcloudElevationRange: { type: 'array', default: ['0', '400'] },
wireframe: { type: 'boolean', default: false },
showStats: { type: 'boolean', default: false },
cesiumIONToken: { type: 'string' },
googleApiKey: { type: 'string' },
lat: { type: 'number' },
long: { type: 'number' },
height: { type: 'number', default: 0 },
copyrightEl: { type: 'selector' },
emitPostProcess: { type: 'boolean', default: false }
},
init: async function () {
const sceneEl = this.el.sceneEl;
const data = this.data;
this.camera = data.cameraEl?.object3D.children[0] ?? document.querySelector('a-scene').camera;
if (!this.camera) {
throw new Error('3D Tiles: Please add an active camera or specify the target camera via the cameraEl property');
}
this.viewport = {
width: sceneEl.clientWidth,
height: sceneEl.clientHeight,
devicePixelRatio: window.devicePixelRatio
};
const { model, runtime } = await this._initTileset();
this.el.setObject3D('tileset', model);
this.runtime = runtime;
this.originalCamera = this.camera;
sceneEl.addEventListener('camera-set-active', (e) => {
// TODO: For some reason after closing the inspector this event is fired with an empty camera,
// so revert to the original camera used.
//
// TODO: Does not provide the right Inspector perspective camera
this.camera = e.detail.cameraEl.object3D.children[0] ?? this.originalCamera;
});
this.el.addEventListener('cameraChange', (e) => {
this.camera = e.detail;
if (this.camera.type === 'OrthographicCamera') {
if (this.camera.rotation.x < -1) {
// Plan View mode
// raise the camera to increase the field of view and update a larger area of tiles
this.camera.position.y = 100;
} else {
// Cross Section mode
this.camera.position.y = 10; // default value for ortho camera in Editor
}
}
this.runtime.setViewport(this.viewport);
});
sceneEl.addEventListener('enter-vr', (e) => {
this.originalCamera = this.camera;
try {
this.camera = sceneEl.renderer.xr.getCamera(this.camera);
// FOV Code from https://github.com/mrdoob/three.js/issues/21869
sceneEl.renderer.xr.getSession().requestAnimationFrame((time, frame) => {
const ref = sceneEl.renderer.xr.getReferenceSpace();
const pose = frame.getViewerPose(ref);
if (pose) {
const fovi = pose.views[0].projectionMatrix[5];
this.camera.fov = Math.atan2(1, fovi) * 2 * 180 / Math.PI;
}
});
} catch (e) {
console.warn('Could not get VR camera');
}
});
sceneEl.addEventListener('exit-vr', (e) => {
this.camera = this.originalCamera;
});
if (data.showStats) {
this.stats = this._initStats();
}
if (THREE.Cache.enabled) {
console.warn('3D Tiles loader cannot work with THREE.Cache, disabling.');
THREE.Cache.enabled = false;
}
await this._nextFrame();
this.runtime = runtime;
this.runtime.setElevationRange(data.pointcloudElevationRange.map(n => Number(n)));
window.addEventListener('resize', this.onWindowResize.bind(this));
if (AFRAME.INSPECTOR && AFRAME.INSPECTOR.opened) {
// set active inspector camera
this.camera = AFRAME.INSPECTOR.camera;
// emit play event to start load tiles in aframe-inspector
this.play();
}
if ((this.data.lat && this.data.long) || this.data.height) {
this.runtime.orientToGeocoord({
lat: Number(this.data.lat),
long: Number(this.data.long),
height: Number(this.data.height)
});
}
},
onWindowResize: function () {
const sceneEl = this.el.sceneEl;
this.camera.aspect = sceneEl.clientWidth / sceneEl.clientHeight;
this.camera.updateProjectionMatrix();
this.viewport = {
width: sceneEl.clientWidth,
height: sceneEl.clientHeight,
devicePixelRatio: window.devicePixelRatio
};
this.runtime.setViewport(this.viewport);
},
update: async function (oldData) {
if (oldData.url !== this.data.url) {
if (this.runtime) {
this.runtime.dispose();
this.runtime = null;
}
const { model, runtime } = await this._initTileset();
this.el.setObject3D('tileset', model);
await this._nextFrame();
this.runtime = runtime;
} else if (this.runtime) {
this.runtime.setPointCloudColoring(this._resolvePointcloudColoring(this.data.pointCloudColoring));
this.runtime.setWireframe(this.data.wireframe);
this.runtime.setViewDistanceScale(this.data.distanceScale);
this.runtime.setElevationRange(this.data.pointcloudElevationRange.map(n => Number(n)));
}
if (this.data.showStats && !this.stats) {
this.stats = this._initStats();
}
if (!this.data.showStats && this.stats) {
this.el.sceneEl.removeChild(this.stats);
this.stats = null;
}
// set parameters for google 3dtiles API
if ((this.data.lat && this.data.long) || this.data.height) {
this.runtime.orientToGeocoord({
lat: Number(this.data.lat),
long: Number(this.data.long),
height: Number(this.data.height)
});
}
},
tick: function (t, dt) {
if (this.runtime) {
this.runtime.update(dt, this.camera);
if (this.stats) {
const worldPos = new Vector3();
this.camera.getWorldPosition(worldPos);
const stats = this.runtime.getStats();
this.stats.setAttribute(
'textarea',
'text',
Object.values(stats.stats).map(s => `${s.name}: ${s.count}`).join('\n')
);
const newPos = new Vector3();
newPos.copy(worldPos);
newPos.z -= 2;
this.stats.setAttribute('position', newPos);
}
if (this.data.copyrightEl) {
this.data.copyrightEl.innerHTML = this.runtime.getDataAttributions() ?? '';
}
}
},
remove: function () {
if (this.runtime) {
this.runtime.dispose();
}
},
_resolvePointcloudColoring () {
const pointCloudColoring = POINT_CLOUD_COLORING[this.data.pointcloudColoring];
if (!pointCloudColoring) {
console.warn('Invalid value for point cloud coloring');
return PointCloudColoring.White;
} else {
return pointCloudColoring;
}
},
_initTileset: async function () {
const pointCloudColoring = this._resolvePointcloudColoring(this.data.pointcloudColoring);
// optionally pass callback to LoaderOptions.contentPostProcess
let postProcessCallback;
if (this.data.emitPostProcess) {
const thatEl = this.el;
postProcessCallback = function (mesh, cloud) {
thatEl.emit('contentPostProcess', { mesh: mesh, cloud: cloud });
};
}
return Loader3DTiles.load({
url: this.data.url,
renderer: this.el.sceneEl.renderer,
options: {
googleApiKey: this.data.googleApiKey,
cesiumIONToken: this.data.cesiumIONToken,
dracoDecoderPath: 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/libs/draco',
basisTranscoderPath: 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/libs/basis',
maximumScreenSpaceError: this.data.maximumSSE,
maximumMemoryUsage: this.data.maximumMem,
memoryCacheOverflow: 128,
pointCloudColoring: pointCloudColoring,
viewDistanceScale: this.data.distanceScale,
wireframe: this.data.wireframe,
updateTransforms: true,
contentPostProcess: postProcessCallback
},
viewport: this.viewport
});
},
_initStats: function () {
const stats = document.createElement('a-entity');
this.el.sceneEl.appendChild(stats);
stats.setAttribute('position', '-0.5 0 -1');
stats.setAttribute('textarea', {
cols: 30,
rows: 15,
text: '',
color: 'white',
disabledBackgroundColor: '#0c1e2c',
disabled: true
});
return stats;
},
_nextFrame: async function () {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 0);
});
}
});