-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathOGC3DTile.js
925 lines (806 loc) · 36.1 KB
/
OGC3DTile.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
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
import * as THREE from 'three';
import { OBB } from "../geometry/obb";
import { TileLoader } from "./TileLoader";
import { v4 as uuidv4 } from "uuid";
import * as path from "path-browserify"
import { clamp } from "three/src/math/MathUtils";
import { Octree } from 'three/addons/math/Octree.js';
import {resolveImplicite} from './implicit/ImplicitTileResolver.js';
//import { OctreeHelper } from 'three/addons/helpers/OctreeHelper.js';
var averageTime = 0;
var numTiles = 0;
var copyrightDiv;
const tempSphere = new THREE.Sphere(new THREE.Vector3(0, 0, 0), 1);
const tempVec1 = new THREE.Vector3(0, 0, 0);
const tempVec2 = new THREE.Vector3(0, 0, 0);
const upVector = new THREE.Vector3(0, 1, 0);
const rendererSize = new THREE.Vector2(1000, 1000);
const tempQuaternion = new THREE.Quaternion();
const copyright = {};
class OGC3DTile extends THREE.Object3D {
/**
* @param {Object} [properties] - the properties for this tileset
* @param {THREE.Renderer} [properties.renderer] - the renderer used to display the tileset
* @param {String} [properties.url] - the url to the parent tileset.json
* @param {String} [properties.queryParams] - optional, path params to add to individual tile urls (starts with "?").
* @param {Number} [properties.geometricErrorMultiplier] - the geometric error of the parent. 1.0 by default corresponds to a maxScreenSpaceError of 16
* @param {Boolean} [properties.loadOutsideView] - if truthy, tiles otside the camera frustum will be loaded with the least possible amount of detail
* @param {TileLoader} [properties.tileLoader] - A tile loader that can be shared among tilesets in order to share a common cache.
* @param {Function} [properties.meshCallback] - A callback function that will be called on every mesh
* @param {Function} [properties.pointsCallback] - A callback function that will be called on every points
* @param {Function} [properties.onLoadCallback] - A callback function that will be called when the root tile has been loaded
* @param {OcclusionCullingService} [properties.occlusionCullingService] - A service that handles occlusion culling
* @param {Boolean} [properties.centerModel] - If true, the tileset will be centered on 0,0,0 and in the case of georeferenced tilesets that use the "region" bounding volume, it will also be rotated so that the up axis matched the world y axis.
* @param {Boolean} [properties.static] - If true, the tileset is considered static which improves performance but the matrices aren't automatically updated
* @param {String} [properties.rootPath] - optional the root path for fetching children
* @param {String} [properties.json] - optional json object representing the tileset sub-tree
* @param {Number} [properties.parentGeometricError] - optional geometric error of the parent
* @param {Object} [properties.parentBoundingVolume] - optional bounding volume of the parent
* @param {String} [properties.parentRefine] - optional refine strategy of the parent of the parent
* @param {THREE.Camera} [properties.cameraOnLoad] - optional the camera used when loading this particular sub-tile
* @param {OGC3DTile} [properties.parentTile] - optional the OGC3DTile object that loaded this tile as a child
* @param {String} [properties.proxy] - optional the url to a proxy service. Instead of fetching tiles via a GET request, a POST will be sent to the proxy url with the real tile address in the body of the request.
* @param {Boolean} [properties.displayErrors] - optional value indicating that errors should be shown on screen.
*/
constructor(properties) {
super();
const self = this;
this.proxy = properties.proxy;
this.displayErrors = properties.displayErrors;
this.displayCopyright = properties.displayCopyright;
if (properties.queryParams) {
this.queryParams = { ...properties.queryParams };
}
this.uuid = uuidv4();
if (!!properties.tileLoader) {
this.tileLoader = properties.tileLoader;
} else {
const tileLoaderOptions = {};
tileLoaderOptions.meshCallback = !properties.meshCallback ? (mesh, geometricError) => {
mesh.material.wireframe = false;
mesh.material.side = THREE.DoubleSide;
} : properties.meshCallback;
tileLoaderOptions.pointsCallback = !properties.pointsCallback ? (points, geometricError) => {
points.material.size = Math.pow(geometricError, 0.33);
points.material.sizeAttenuation = true;
} : properties.pointsCallback;
tileLoaderOptions.proxy = this.proxy;
tileLoaderOptions.renderer = properties.renderer;
this.tileLoader = new TileLoader(tileLoaderOptions);
}
this.displayCopyright = !!properties.displayCopyright;
// set properties general to the entire tileset
this.geometricErrorMultiplier = !!properties.geometricErrorMultiplier ? properties.geometricErrorMultiplier : 1.0;
this.renderer = properties.renderer;
this.meshCallback = properties.meshCallback;
this.loadOutsideView = properties.loadOutsideView;
this.cameraOnLoad = properties.cameraOnLoad;
this.parentTile = properties.parentTile;
this.occlusionCullingService = properties.occlusionCullingService;
this.static = properties.static;
if (this.occlusionCullingService) {
this.color = new THREE.Color();
this.color.setHex(Math.random() * 0xffffff);
this.colorID = clamp(self.color.r * 255, 0, 255) << 16 ^ clamp(self.color.g * 255, 0, 255) << 8 ^ clamp(self.color.b * 255, 0, 255) << 0;
}
if (this.static) {
this.matrixAutoUpdate = false;
}
// declare properties specific to the tile for clarity
this.childrenTiles = [];
this.meshContent = [];
this.tileContent;
this.refine; // defaults to "REPLACE"
this.rootPath;
this.geometricError;
this.boundingVolume;
this.json; // the json corresponding to this tile
this.materialVisibility = false;
this.inFrustum = true;
this.level = properties.level ? properties.level : 0;
this.hasMeshContent = 0; // true when the provided json has a content field pointing to a B3DM file
this.hasUnloadedJSONContent = 0; // true when the provided json has a content field pointing to a JSON file that is not yet loaded
this.centerModel = properties.centerModel;
this.abortController = new AbortController();
//this.layers.disable(0);
//this.octree = new Octree();
if (!!properties.json) { // If this tile is created as a child of another tile, properties.json is not null
self.setup(properties);
} else if (properties.url) { // If only the url to the tileset.json is provided
var url = properties.url;
if (self.queryParams) {
var props = "";
for (let key in self.queryParams) {
if (self.queryParams.hasOwnProperty(key)) {
props += "&" + key + "=" + self.queryParams[key];
}
}
if (url.includes("?")) {
url += props;
} else {
url += "?" + props.substring(1);
}
}
var fetchFunction;
if (self.proxy) {
fetchFunction = () => {
return fetch(self.proxy,
{
method: 'POST',
body: url,
signal: self.abortController.signal
}
);
}
} else {
fetchFunction = () => {
return fetch(url, { signal: self.abortController.signal });
}
}
fetchFunction().then(result => {
if (!result.ok) {
throw new Error(`couldn't load "${properties.url}". Request failed with status ${result.status} : ${result.statusText}`);
}
result.json().then(json=>{return resolveImplicite(json, url)}).then(json => {
self.setup({ rootPath: path.dirname(properties.url), json: json, onLoadCallback: properties.onLoadCallback });
});
}).catch(e => { if (self.displayErrors) showError(e) });
}
}
async setup(properties) {
const self = this;
if (!!properties.json.root) {
self.json = properties.json.root;
if (!self.json.refine) self.json.refine = properties.json.refine;
if (!self.json.geometricError) self.json.geometricError = properties.json.geometricError;
if (!self.json.transform) self.json.transform = properties.json.transform;
if (!self.json.boundingVolume) self.json.boundingVolume = properties.json.boundingVolume;
} else {
self.json = properties.json;
}
if (!self.json.children) {
if (self.json.getChildren) {
self.json.children = await self.json.getChildren();
} else {
self.json.children = [];
}
}
self.rootPath = !!properties.json.rootPath ? properties.json.rootPath : properties.rootPath;
// decode refine
if (!!self.json.refine) {
self.refine = self.json.refine;
} else {
self.refine = properties.parentRefine;
}
// decode geometric error
if (!!self.json.geometricError) {
self.geometricError = self.json.geometricError;
} else {
self.geometricError = properties.parentGeometricError;
}
// decode transform
if (!!self.json.transform && !self.centerModel) {
let mat = new THREE.Matrix4();
mat.elements = self.json.transform;
self.applyMatrix4(mat);
}
// decode volume
if (!!self.json.boundingVolume) {
if (!!self.json.boundingVolume.box) {
self.boundingVolume = new OBB(self.json.boundingVolume.box);
} else if (!!self.json.boundingVolume.region) {
const region = self.json.boundingVolume.region;
self.transformWGS84ToCartesian(region[0], region[1], region[4], tempVec1);
self.transformWGS84ToCartesian(region[2], region[3], region[5], tempVec2);
tempVec1.lerp(tempVec2, 0.5);
self.boundingVolume = new THREE.Sphere(new THREE.Vector3(tempVec1.x, tempVec1.y, tempVec1.z), tempVec1.distanceTo(tempVec2));
} else if (!!self.json.boundingVolume.sphere) {
const sphere = self.json.boundingVolume.sphere;
self.boundingVolume = new THREE.Sphere(new THREE.Vector3(sphere[0], sphere[1], sphere[2]), sphere[3]);
} else {
self.boundingVolume = properties.parentBoundingVolume;
}
} else {
self.boundingVolume = properties.parentBoundingVolume;
}
function checkContent(e) {
if (!!e.uri && e.uri.includes("json")) {
self.hasUnloadedJSONContent++;
} else if (!!e.url && e.url.includes("json")) {
self.hasUnloadedJSONContent++;
} else {
self.hasMeshContent++;
}
}
if (!!self.json.content) { //if there is a content, json or otherwise, schedule it to be loaded
checkContent(self.json.content);
self.load();
} else if (!!self.json.contents) { //if there is a content, json or otherwise, schedule it to be loaded
self.json.contents.forEach(e => checkContent(e))
self.load();
//scheduleLoadTile(this);
}
if (!!self.centerModel) {
const tempSphere = new THREE.Sphere();
if (self.boundingVolume instanceof OBB) {
// box
tempSphere.copy(self.boundingVolume.sphere);
} else if (self.boundingVolume instanceof THREE.Sphere) {
//sphere
tempSphere.copy(self.boundingVolume);
}
//tempSphere.applyMatrix4(self.matrixWorld);
if (!!this.json.boundingVolume.region) {
this.transformWGS84ToCartesian(
(this.json.boundingVolume.region[0] + this.json.boundingVolume.region[2]) * 0.5,
(this.json.boundingVolume.region[1] + this.json.boundingVolume.region[3]) * 0.5,
(this.json.boundingVolume.region[4] + this.json.boundingVolume.region[5]) * 0.5,
tempVec1);
tempQuaternion.setFromUnitVectors(tempVec1.normalize(), upVector.normalize());
self.applyQuaternion(tempQuaternion);
}
self.translateX(-tempSphere.center.x * self.scale.x);
self.translateY(-tempSphere.center.y * self.scale.y);
self.translateZ(-tempSphere.center.z * self.scale.z);
}
if (properties.onLoadCallback) properties.onLoadCallback(self);
self.isSetup = true;
}
assembleURL(root, relative) {
// Append a slash to the root URL if it doesn't already have one
if (!root.endsWith('/')) {
root += '/';
}
const rootUrl = new URL(root);
let rootParts = rootUrl.pathname.split('/').filter(p => p !== '');
let relativeParts = relative.split('/').filter(p => p !== '');
for (let i = 1; i <= rootParts.length; i++) {
if (i >= relativeParts.length) break;
const rootToken = rootParts.slice(rootParts.length - i, rootParts.length).join('/');
const relativeToken = relativeParts.slice(0, i).join('/');
if (rootToken === relativeToken) {
for (let j = 0; j < i; j++) {
rootParts.pop();
}
break;
}
}
while (relativeParts.length > 0 && relativeParts[0] === '..') {
rootParts.pop();
relativeParts.shift();
}
return `${rootUrl.protocol}//${rootUrl.host}/${[...rootParts, ...relativeParts].join('/')}`;
}
extractQueryParams(url, params) {
const urlObj = new URL(url);
// Iterate over all the search parameters
for (let [key, value] of urlObj.searchParams) {
params[key] = value;
}
// Remove the query string
urlObj.search = '';
return urlObj.toString();
}
async load() {
var self = this;
if (self.deleted) return;
if (!!self.json.content) {
await loadContent(self.json.content, null);
} else if (!!self.json.contents) {
let promises = self.json.contents.map((content, index) => loadContent(content, index));
Promise.all(promises)
//self.json.contents.forEach(content=> loadContent(content, i))
}
async function loadContent(content, contentIndex) {
let url;
if (!!content.uri) {
url = content.uri;
} else if (!!content.url) {
url = content.url;
}
const urlRegex = /^(?:http|https|ftp|tcp|udp):\/\/\S+/;
if (urlRegex.test(self.rootPath)) { // url
if (!urlRegex.test(url)) {
url = self.assembleURL(self.rootPath, url);
}
} else { //path
if (path.isAbsolute(self.rootPath)) {
url = self.rootPath + path.sep + url;
}
}
url = self.extractQueryParams(url, self.queryParams);
if (self.queryParams) {
var props = "";
for (let key in self.queryParams) {
if (self.queryParams.hasOwnProperty(key)) { // This check is necessary to skip properties from the object's prototype chain
props += "&" + key + "=" + self.queryParams[key];
}
}
if (url.includes("?")) {
url += props;
} else {
url += "?" + props.substring(1);
}
}
if (!!url) {
if (url.includes(".b3dm") || url.includes(".glb") || url.includes(".gltf")) {
self.contentURL = url;
try {
self.tileLoader.get(self.abortController, self.uuid, url, mesh => {
if (!!self.deleted) return;
if (mesh.asset && mesh.asset.copyright) {
mesh.asset.copyright.split(';').forEach(s => {
if (!!copyright[s]) {
copyright[s]++;
} else {
copyright[s] = 1;
}
});
if (self.displayCopyright) {
updateCopyrightLabel();
}
}
mesh.traverse((o) => {
if (o.isMesh || o.isPoints) {
o.layers.disable(0);
if (self.static) {
o.matrixAutoUpdate = false;
}
//if(o.material.transparent) o.layers.enable(31);
}
if (o.isMesh) {
if (self.occlusionCullingService) {
const position = o.geometry.attributes.position;
const colors = [];
for (let i = 0; i < position.count; i++) {
colors.push(self.color.r, self.color.g, self.color.b);
}
o.geometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
}
//o.material.visible = false;
}
});
let s = Date.now();
//self.octree.fromGraphNode( mesh );
/*averageTime*=numTiles;
averageTime+=Date.now()-s;
numTiles++;
averageTime/=numTiles;
console.log(averageTime);*/
self.add(mesh);
self.updateWorldMatrix(false, true);
// mesh.layers.disable(0);
self.meshContent.push(mesh);
}, !self.cameraOnLoad ? () => 0 : () => {
return self.calculateDistanceToCamera(self.cameraOnLoad);
}, () => self.getSiblings(),
self.level,
!!self.json.boundingVolume.region ? false : true,
!!self.json.boundingVolume.region,
self.geometricError
);
} catch (e) {
if (self.displayErrors) showError(e)
}
} else if (url.includes(".json")) {
self.tileLoader.get(self.abortController, self.uuid, url, async json => {
if (!!self.deleted) return;
json.rootPath = path.dirname(url);
self.json.children.push(json);
if (contentIndex == null) {
delete self.json.content;
} else {
delete self.json.contents.splice(contentIndex, 1);
}
self.hasUnloadedJSONContent--;
});
}
}
}
}
dispose() {
const self = this;
self.meshContent.forEach(mc => {
if (!!mc && !!mc.asset && mc.asset.copyright) {
mc.asset.copyright.split(';').forEach(s => {
if (!!copyright[s]) {
copyright[s]--;
}
});
if (self.displayCopyright) {
updateCopyrightLabel();
}
}
})
self.childrenTiles.forEach(tile => tile.dispose());
self.deleted = true;
this.traverse(function (element) {
if (!!element.contentURL) {
self.tileLoader.invalidate(element.contentURL, element.uuid);
}
if (!!element.abortController) { // abort tile request
element.abortController.abort();
}
});
this.parent = null;
this.parentTile = null;
this.dispatchEvent({ type: 'removed' });
}
disposeChildren() {
var self = this;
self.childrenTiles.forEach(tile => tile.dispose());
self.childrenTiles = [];
self.children = [];
if (self.meshContent.length > 0) {
self.meshContent.forEach(mc => {
self.children.push(mc);
});
}
}
update(camera) {
const frustum = new THREE.Frustum();
frustum.setFromProjectionMatrix(new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));
this._update(camera, frustum);
}
_update(camera, frustum) {
const self = this;
if(!self.isSetup) return;
// let dist = self.boundingVolume.distanceToPoint(new THREE.Vector3(3980, 4980.416656099139, 3.2851604304346775));
// if (dist< 1) {
// self.changeContentVisibility(false);
// console.log(dist+" "+self.level)
// }
const visibilityBeforeUpdate = self.materialVisibility;
if (!!self.boundingVolume && !!self.geometricError) {
self.metric = self.calculateUpdateMetric(camera, frustum);
}
self.childrenTiles.forEach(child => child._update(camera, frustum));
updateNodeVisibility(self.metric);
updateTree(self.metric);
trimTree(self.metric, visibilityBeforeUpdate);
function updateTree(metric) {
// If this tile does not have mesh content but it has children
if (metric < 0 && self.hasMeshContent) return;
if (self.occlusionCullingService && self.hasMeshContent && !self.occlusionCullingService.hasID(self.colorID)) {
return;
}
if (!self.hasMeshContent || (metric < self.geometricErrorMultiplier * self.geometricError && self.meshContent.length > 0)) {
if (!!self.json && !!self.json.children && self.childrenTiles.length != self.json.children.length) {
loadJsonChildren();
return;
}
}
}
function updateNodeVisibility(metric) {
//doesn't have a mesh content
if (!self.hasMeshContent) return;
// mesh content not yet loaded
if (self.meshContent < self.hasMeshContent) {
return;
}
// outside frustum
if (metric < 0) {
self.inFrustum = false;
self.changeContentVisibility(!!self.loadOutsideView);
return;
} else {
self.inFrustum = true;
}
// has no children
if (self.childrenTiles.length == 0) {
self.changeContentVisibility(true);
return;
}
// has children
if (metric >= self.geometricErrorMultiplier * self.geometricError) { // Ideal LOD or before ideal lod
self.changeContentVisibility(true);
} else if (metric < self.geometricErrorMultiplier * self.geometricError) { // Ideal LOD is past this one
// if children are visible and have been displayed, can be hidden
if (self.refine == "REPLACE") {
let allChildrenReady = true;
self.childrenTiles.every(child => {
if (!child.isReady()) {
allChildrenReady = false;
return false;
}
return true;
});
if (allChildrenReady) {
self.changeContentVisibility(false);
}
}
}
}
function trimTree(metric, visibilityBeforeUpdate) {
if (!self.hasMeshContent) return;
if (!self.inFrustum) { // outside frustum
self.disposeChildren();
updateNodeVisibility(metric);
return;
}
if (self.occlusionCullingService &&
!visibilityBeforeUpdate &&
self.hasMeshContent &&
self.meshContent.length > 0 &&
self.meshDisplayed &&
self.areAllChildrenLoadedAndHidden()) {
self.disposeChildren();
updateNodeVisibility(metric);
return;
}
if (metric >= self.geometricErrorMultiplier * self.geometricError) {
self.disposeChildren();
updateNodeVisibility(metric);
return;
}
}
function loadJsonChildren() {
for (let i = self.json.children.length - 1; i >= 0; i--) {
if (!self.json.children[i].root && !self.json.children[i].children && !self.json.children[i].getChildren && !self.json.children[i].content && !self.json.children[i].contents) {
self.json.children.splice(i, 1);
}
}
self.json.children.forEach(childJSON => {
let childTile = new OGC3DTile({
parentTile: self,
queryParams: self.queryParams,
parentGeometricError: self.geometricError,
parentBoundingVolume: self.boundingVolume,
parentRefine: self.refine,
json: childJSON,
rootPath: self.rootPath,
geometricErrorMultiplier: self.geometricErrorMultiplier,
loadOutsideView: self.loadOutsideView,
level: self.level + 1,
tileLoader: self.tileLoader,
cameraOnLoad: camera,
occlusionCullingService: self.occlusionCullingService,
renderer: self.renderer,
static: self.static,
centerModel: false,
displayErrors: self.displayErrors,
displayCopyright: self.displayCopyright
});
self.childrenTiles.push(childTile);
self.add(childTile);
});
}
}
areAllChildrenLoadedAndHidden() {
let allLoadedAndHidden = true;
const self = this;
this.childrenTiles.every(child => {
if (child.hasMeshContent) {
if (child.childrenTiles.length > 0) {
allLoadedAndHidden = false;
return false;
}
if (!child.inFrustum) {
return true;
};
if (!child.materialVisibility || child.meshDisplayed) {
allLoadedAndHidden = false;
return false;
} else if (self.occlusionCullingService.hasID(child.colorID)) {
allLoadedAndHidden = false;
return false;
}
} else {
if (!child.areAllChildrenLoadedAndHidden()) {
allLoadedAndHidden = false;
return false;
}
}
return true;
});
return allLoadedAndHidden;
}
/**
* Node is ready if it is outside frustum, if it was drawn at least once or if all it's children are ready
* @returns true if ready
*/
isReady() {
// if outside frustum
if (!this.inFrustum) {
return true;
}
// if json is not done loading
if (this.hasUnloadedJSONContent) {
return false;
}
// if this tile has no mesh content or if it's marked as visible false, look at children
if ((!this.hasMeshContent || this.meshContent.length == 0 || !this.materialVisibility)) {
if (this.children.length > 0) {
var allChildrenReady = true;
this.childrenTiles.every(child => {
if (!child.isReady()) {
allChildrenReady = false;
return false;
}
return true;
});
return allChildrenReady;
} else {
return false
}
}
// if this tile has no mesh content
if (!this.hasMeshContent) {
return true;
}
// if mesh content not yet loaded
if (this.meshContent.length < this.hasMeshContent) {
return false;
}
// if this tile has been marked to hide it's content
if (!this.materialVisibility) {
return false;
}
// if all meshes have been displayed once
if (this.meshDisplayed) {
return true;
}
return false;
}
changeContentVisibility(visibility) {
const self = this;
if (self.hasMeshContent && self.meshContent.length > 0) {
if (visibility) {
self.meshContent.forEach(mc => {
mc.traverse((o) => {
if (o.isMesh || o.isPoints) {
o.layers.enable(0);
}
});
})
} else {
self.meshContent.forEach(mc => {
mc.traverse((o) => {
if (o.isMesh || o.isPoints) {
o.layers.disable(0);
}
});
})
}
}
if (self.materialVisibility == visibility) {
return;
}
self.materialVisibility = visibility
self.meshDisplayed = true;
}
calculateUpdateMetric(camera, frustum) {
////// return -1 if not in frustum
if (this.boundingVolume instanceof OBB) {
// box
tempSphere.copy(this.boundingVolume.sphere);
tempSphere.applyMatrix4(this.matrixWorld);
if (!frustum.intersectsSphere(tempSphere)) return -1;
} else if (this.boundingVolume instanceof THREE.Sphere) {
//sphere
tempSphere.copy(this.boundingVolume);
tempSphere.applyMatrix4(this.matrixWorld);
if (!frustum.intersectsSphere(tempSphere)) return -1;
} else {
console.error("unsupported shape");
return -1
}
/////// return metric based on geometric error and distance
const distance = Math.max(0, camera.position.distanceTo(tempSphere.center) - tempSphere.radius);
if (distance == 0) {
return 0;
}
const scale = this.matrixWorld.getMaxScaleOnAxis();
if (!!this.renderer) {
this.renderer.getDrawingBufferSize(rendererSize);
}
let s = rendererSize.y;
let fov = camera.fov;
if (camera.aspect < 1) {
fov *= camera.aspect;
s = rendererSize.x;
}
let lambda = 2.0 * Math.tan(0.5 * fov * 0.01745329251994329576923690768489) * distance;
return (window.devicePixelRatio * 16 * lambda) / (s * scale);
}
getSiblings() {
const self = this;
const tiles = [];
if (!self.parentTile) return tiles;
let p = self.parentTile;
while (!p.hasMeshContent && !!p.parentTile) {
p = p.parentTile;
}
p.childrenTiles.forEach(child => {
if (!!child && child != self) {
while (!child.hasMeshContent && !!child.childrenTiles[0]) {
child = child.childrenTiles[0];
}
tiles.push(child);
}
});
return tiles;
}
calculateDistanceToCamera(camera) {
if (this.boundingVolume instanceof OBB) {
// box
tempSphere.copy(this.boundingVolume.sphere);
tempSphere.applyMatrix4(this.matrixWorld);
//if (!frustum.intersectsSphere(tempSphere)) return -1;
} else if (this.boundingVolume instanceof THREE.Sphere) {
//sphere
tempSphere.copy(this.boundingVolume);
tempSphere.applyMatrix4(this.matrixWorld);
//if (!frustum.intersectsSphere(tempSphere)) return -1;
}
else {
console.error("unsupported shape")
}
return Math.max(0, camera.position.distanceTo(tempSphere.center) - tempSphere.radius);
}
setGeometricErrorMultiplier(geometricErrorMultiplier) {
this.geometricErrorMultiplier = geometricErrorMultiplier;
this.childrenTiles.forEach(child => child.setGeometricErrorMultiplier(geometricErrorMultiplier));
}
transformWGS84ToCartesian(lon, lat, h, sfct) {
const a = 6378137.0;
const e = 0.006694384442042;
const N = a / (Math.sqrt(1.0 - (e * Math.pow(Math.sin(lat), 2))));
const cosLat = Math.cos(lat);
const cosLon = Math.cos(lon);
const sinLat = Math.sin(lat);
const sinLon = Math.sin(lon);
const nPh = (N + h);
const x = nPh * cosLat * cosLon;
const y = nPh * cosLat * sinLon;
const z = (0.993305615557957 * N + h) * sinLat;
sfct.set(x, y, z);
}
}
export { OGC3DTile };
function showError(error) {
// Create a new div element
var errorDiv = document.createElement("div");
// Set its text content
errorDiv.textContent = error;
// Set styles
errorDiv.style.position = 'fixed'; // Fix position to the viewport
errorDiv.style.top = '10px'; // Set top position
errorDiv.style.left = '50%'; // Center horizontally
errorDiv.style.transform = 'translateX(-50%)'; // Make sure it's centered accurately
errorDiv.style.padding = '10px'; // Add some padding
errorDiv.style.backgroundColor = '#ff8800'; // Set a background color
errorDiv.style.color = '#ffffff'; // Set a text color
errorDiv.style.zIndex = '9999'; // Make sure it's on top of other elements
// Append the new div to the body
document.body.appendChild(errorDiv);
// After 3 seconds, remove the error message
setTimeout(function () {
errorDiv.remove();
}, 8000);
}
function updateCopyrightLabel() {
// Create a new div
if (!copyrightDiv) {
copyrightDiv = document.createElement('div');
}
// Join the array elements with a comma and a space
var list = "";
for (let key in copyright) {
if (copyright.hasOwnProperty(key) && copyright[key] > 0) { // This checks if the key is actually part of the object and not its prototype.
list += key + ", ";
}
}
// Set the text content of the div
copyrightDiv.textContent = list;
// Style the div
copyrightDiv.style.position = 'fixed';
copyrightDiv.style.bottom = '20px';
copyrightDiv.style.left = '20px';
copyrightDiv.style.color = 'white';
copyrightDiv.style.textShadow = '2px 2px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000';
copyrightDiv.style.padding = '10px';
copyrightDiv.style.backgroundColor = 'rgba(0, 0, 0, 0.1)'; // semi-transparent black background
// Append the div to the body of the document
document.body.appendChild(copyrightDiv);
}