forked from fanvanzh/3dtiles
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
868 lines (756 loc) · 34.9 KB
/
index.html
File metadata and controls
868 lines (756 loc) · 34.9 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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3D Tiles Indoor Viewer</title>
<script src="https://cesium.com/downloads/cesiumjs/releases/1.113/Build/Cesium/Cesium.js"></script>
<link href="https://cesium.com/downloads/cesiumjs/releases/1.113/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
<style>
html, body, #cesiumContainer {
width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden; font-family: sans-serif;
}
/* Left Panel: Inspector */
#inspector-wrapper {
position: absolute;
top: 10px; left: 10px;
width: 360px; /* Increased from 300px to fit content */
z-index: 100;
background: rgba(42, 42, 42, 0.9);
border: 1px solid #444;
border-radius: 4px;
color: #eee;
}
#inspector-header {
padding: 8px;
background: rgba(60, 60, 60, 0.9);
cursor: move; /* Changed to move cursor */
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid #555;
font-weight: bold;
user-select: none; /* Prevent text selection while dragging */
}
#inspector-container {
max-height: 500px;
overflow-y: auto;
overflow-x: hidden; /* Disable horizontal scroll */
padding: 5px;
display: block; /* Toggled via JS */
}
/* Cesium Inspector internal styling overrides */
.cesium-cesium3DTilesInspector {
display: block !important;
border: none;
background: transparent;
color: white;
}
.cesium-cesium3DTilesInspector-sectionHeader {
background: rgba(60, 60, 60, 0.8);
padding: 5px;
margin-top: 5px;
cursor: pointer;
}
/* Right Panel: Properties */
#properties-panel {
position: absolute;
top: 50px; /* Moved down to avoid Cesium Toolbar */
right: 10px;
width: 320px;
max-height: 80%;
overflow-y: auto;
background: rgba(42, 42, 42, 0.95);
border: 1px solid #555;
border-radius: 4px;
color: #eee;
z-index: 100;
padding: 15px;
display: none; /* Hidden by default */
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
#properties-panel h3 {
margin-top: 0;
border-bottom: 1px solid #666;
padding-bottom: 10px;
font-size: 16px;
display: flex;
justify-content: space-between;
align-items: center;
cursor: move; /* Allow dragging from header */
user-select: none;
}
#properties-panel table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
margin-top: 10px;
}
#properties-panel th, #properties-panel td {
text-align: left;
padding: 6px;
border-bottom: 1px solid #555;
word-break: break-word;
}
#properties-panel th {
color: #aaa;
width: 40%;
}
.close-btn {
cursor: pointer;
font-weight: bold;
color: #aaa;
font-size: 18px;
}
.close-btn:hover {
color: white;
}
/* Bottom Panel: Status Bar */
#status-bar {
position: absolute;
bottom: 0; left: 0;
width: 100%;
height: 30px;
background: rgba(30, 30, 30, 0.9);
color: #ccc;
z-index: 100;
display: flex;
align-items: center;
padding: 0 20px;
font-size: 12px;
box-sizing: border-box;
border-top: 1px solid #555;
}
#status-bar span {
margin-right: 30px;
}
</style>
</head>
<body>
<div id="cesiumContainer"></div>
<!-- Left: 3D Tiles Inspector -->
<div id="inspector-wrapper">
<div id="inspector-header">
<span style="flex-grow: 1;" onclick="toggleInspector()">3D Tiles Inspector</span>
<span id="inspector-toggle" style="cursor: pointer;" onclick="toggleInspector()">▼</span>
</div>
<!-- Custom Stats & Debug Panel -->
<div id="custom-stats" style="padding: 10px; border-bottom: 1px solid #555; background: rgba(30,30,30,0.5); display:block;">
<div style="margin-bottom:5px; font-weight:bold; color:#88ccff; font-size: 12px;">Real-time Metrics (Visible | Loaded)</div>
<div style="display:grid; grid-template-columns: 1fr 1fr; gap: 4px; font-size: 11px;">
<span>FPS: <b id="stat-fps">--</b></span>
<span>Draw Calls: <b id="stat-draws">--</b></span>
<span>Triangles: <b id="stat-tris">--</b></span>
<span>Vertices: <b id="stat-verts">--</b></span>
<span>Materials: <b id="stat-mats">--</b></span>
<span>Mem: <b id="stat-mem">--</b> MB</span>
<span>Tiles: <b id="stat-tiles">--</b></span>
</div>
<!-- Tileset Info Section -->
<div style="margin-top:8px; border-top:1px solid #555; padding-top:5px; font-size:11px;">
<div style="font-weight:bold; color:#88ccff; margin-bottom:3px;">Tileset Info</div>
<div>Version: <span id="tileset-version" style="color:#ddd;">Loading...</span></div>
<div>GLB Used: <span id="glb-extensions-used" style="color:#ddd; word-break: break-all;">Loading...</span></div>
<div>GLB Req: <span id="glb-extensions-req" style="color:#ddd; word-break: break-all;">Loading...</span></div>
<div>Tex Exts: <span id="glb-tex-extensions" style="color:#ddd; word-break: break-all;">Loading...</span></div>
<div>Textures: <span id="glb-textures" style="color:#ddd;">Loading...</span></div>
</div>
<div style="margin-top:8px; border-top:1px solid #555; padding-top:5px; font-size:11px;">
<label style="display:block; margin-bottom:3px; cursor:pointer;" title="Directly toggles debugShowBoundingVolume">
<input type="checkbox" id="chk-debug-bounds"> Show Bounding Volume (Box)
</label>
<label style="display:block; margin-bottom:3px; cursor:pointer;" title="Directly toggles debugWireframe">
<input type="checkbox" id="chk-debug-wire"> Show Content Wireframe
</label>
<label style="display:block; margin-bottom:3px; cursor:pointer;" title="Show Geometric Error Heatmap">
<input type="checkbox" id="chk-debug-colorize"> Colorize Levels
</label>
<button onclick="flyToRoot()" style="margin-top:5px; width:100%;">Fly to Root Tile</button>
<button onclick="debugMoveToOrigin()" style="margin-top:5px; width:100%; color: orange;">Debug: Move to Origin (Check Jitter)</button>
</div>
</div>
<div id="inspector-container"></div>
</div>
<!-- Right: Properties Panel -->
<div id="properties-panel">
<h3 id="properties-header">
<span style="flex-grow: 1;">Feature Properties</span>
<span class="close-btn" onclick="document.getElementById('properties-panel').style.display='none'">×</span>
</h3>
<div id="properties-content">
<p>Click on a 3D Tile feature to view properties.</p>
</div>
</div>
<!-- Bottom: Status Bar -->
<div id="status-bar">
<span id="coords">Lon: - Lat: - Height: -</span>
<span id="zoom">Camera Height: -</span>
</div>
<script>
// Initialize Viewer
const viewer = new Cesium.Viewer('cesiumContainer', {
terrainProvider: undefined,
baseLayerPicker: false,
geocoder: false,
animation: false,
timeline: false,
fullscreenButton: false,
infoBox: false, // Disable default info box as we use custom panel
selectionIndicator: true
});
// Set fixed time to 10:00 AM (UTC+8) to ensure good lighting
// 10:00 AM China Standard Time is 02:00 UTC
const date = new Date();
date.setUTCHours(2, 0, 0, 0);
viewer.clock.currentTime = Cesium.JulianDate.fromDate(date);
viewer.clock.shouldAnimate = false;
// 1. Optimize for Indoor Navigation
viewer.scene.screenSpaceCameraController.enableCollisionDetection = false;
viewer.scene.logarithmicDepthBuffer = true; // Better depth precision
viewer.camera.frustum.near = 0.1; // 10cm near plane
viewer.scene.globe.depthTestAgainstTerrain = false;
// Configure Mouse Inputs per user request:
// 1. Left Click: Pick (Handled in handler below)
// 2. Left Drag: Rotate (Orbit)
// 3. Middle Drag: Pan (Move)
// 4. Right Drag: Zoom
viewer.scene.screenSpaceCameraController.rotateEventTypes = Cesium.CameraEventType.LEFT_DRAG;
viewer.scene.screenSpaceCameraController.zoomEventTypes = [
Cesium.CameraEventType.RIGHT_DRAG,
Cesium.CameraEventType.WHEEL,
Cesium.CameraEventType.PINCH
];
// Re-map Tilt to Ctrl + Drag to free up Middle Button for Pan
viewer.scene.screenSpaceCameraController.tiltEventTypes = [
{ eventType: Cesium.CameraEventType.LEFT_DRAG, modifier: Cesium.KeyboardEventModifier.CTRL },
{ eventType: Cesium.CameraEventType.RIGHT_DRAG, modifier: Cesium.KeyboardEventModifier.CTRL }
];
// Map Middle Drag to Pan (Translate)
viewer.scene.screenSpaceCameraController.translateEventTypes = Cesium.CameraEventType.MIDDLE_DRAG;
// Toolbar functions
function toggleInspector() {
const container = document.getElementById('inspector-container');
const toggle = document.getElementById('inspector-toggle');
if (container.style.display === 'none') {
container.style.display = 'block';
toggle.innerText = '▼';
} else {
container.style.display = 'none';
toggle.innerText = '▶';
}
}
// 2. Initialize 3D Tiles Inspector on the left
try {
const inspectorContainer = document.getElementById('inspector-container');
const inspector = new Cesium.Cesium3DTilesInspector(inspectorContainer, viewer.scene);
console.log("Inspector initialized");
} catch (e) {
console.error("Failed to initialize inspector", e);
}
// 3. Load Tileset
let tileset;
async function loadTileset() {
try {
tileset = await Cesium.Cesium3DTileset.fromUrl('./output/tileset.json', {
maximumScreenSpaceError: 16,
skipLevelOfDetail: true,
baseScreenSpaceError: 1024,
skipScreenSpaceErrorFactor: 16,
skipLevels: 1,
immediatelyLoadDesiredLevelOfDetail: false,
loadSiblings: false,
cullWithChildrenBounds: true
});
viewer.scene.primitives.add(tileset);
// 4. Auto-Correction: Check if model is at Earth's Center (Local Coordinates)
// If the bounding sphere is near (0,0,0), it means the data lacks a geolocation transform.
// We move it to a default surface location to allow proper rotation/navigation.
const center = tileset.boundingSphere.center;
if (Cesium.Cartesian3.magnitude(center) < 6000000) { // Earth radius is ~6,371km
console.warn("⚠️ Model detected at Earth's Center (Local Coordinates). Moving to surface (0,0) for viewing.");
// Move to Null Island (0,0) at height 0
const position = Cesium.Cartesian3.fromDegrees(121.5, 31.2, 0.0); // Default to Shanghai for better context than (0,0)
const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(position);
tileset.modelMatrix = modelMatrix;
}
// Fly to tileset
await viewer.flyTo(tileset, {
duration: 1.5,
offset: new Cesium.HeadingPitchRange(0, -0.5, 0)
});
console.log('Tileset loaded');
} catch (error) {
console.error('Error loading tileset:', error);
}
}
loadTileset();
// 4. Feature Picking & Property Window (Right Side)
const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
// Highlight logic
let selectedFeature;
const selectedOriginalColor = new Cesium.Color();
handler.setInputAction(function(movement) {
const pickedFeature = viewer.scene.pick(movement.position);
const propPanel = document.getElementById('properties-panel');
const propContent = document.getElementById('properties-content');
// Restore previous highlight
if (Cesium.defined(selectedFeature)) {
try {
selectedFeature.color = selectedOriginalColor;
} catch(e) {
// Feature might be destroyed if tileset reloaded
}
selectedFeature = undefined;
}
if (Cesium.defined(pickedFeature) && pickedFeature instanceof Cesium.Cesium3DTileFeature) {
// Apply Highlight
selectedFeature = pickedFeature;
Cesium.Color.clone(pickedFeature.color, selectedOriginalColor);
pickedFeature.color = Cesium.Color.YELLOW.withAlpha(0.8);
propPanel.style.display = 'block';
let html = '<table>';
const propertyIds = pickedFeature.getPropertyIds();
const length = propertyIds.length;
if (length === 0) {
html += '<tr><td colspan="2">No properties found</td></tr>';
} else {
for (let i = 0; i < length; ++i) {
const propertyId = propertyIds[i];
const value = pickedFeature.getProperty(propertyId);
html += `<tr><th>${propertyId}</th><td>${value}</td></tr>`;
}
}
html += '</table>';
propContent.innerHTML = html;
} else {
// Clicked on nothing or non-feature
// Optionally hide or clear
// propPanel.style.display = 'none';
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
// 5. Status Bar (Coordinates & Zoom/Height)
const coordsDiv = document.getElementById('coords');
const zoomDiv = document.getElementById('zoom');
// Mouse Move to update coordinates
handler.setInputAction(function(movement) {
// Try picking position on 3D tiles or other objects first
let position = viewer.scene.pickPosition(movement.endPosition);
// If no 3D object picked, pick on ellipsoid
if (!position) {
position = viewer.camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid);
}
if (position) {
const cartographic = Cesium.Cartographic.fromCartesian(position);
const longitude = Cesium.Math.toDegrees(cartographic.longitude).toFixed(6);
const latitude = Cesium.Math.toDegrees(cartographic.latitude).toFixed(6);
const height = cartographic.height.toFixed(2);
coordsDiv.textContent = `Lon: ${longitude}° Lat: ${latitude}° Height: ${height}m`;
} else {
coordsDiv.textContent = `Lon: - Lat: - Height: -`;
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
// Camera Move End to update "Zoom" (Camera Height)
function updateCameraStatus() {
const height = Math.ceil(viewer.camera.positionCartographic.height);
// Heading/Pitch could also be useful
const heading = Cesium.Math.toDegrees(viewer.camera.heading).toFixed(1);
const pitch = Cesium.Math.toDegrees(viewer.camera.pitch).toFixed(1);
zoomDiv.textContent = `Camera Height: ${height}m (H: ${heading}°, P: ${pitch}°)`;
}
viewer.camera.moveEnd.addEventListener(updateCameraStatus);
// Also update on tick or moveStart if smoother updates needed, but moveEnd is efficient
viewer.scene.postRender.addEventListener(updateCameraStatus); // Update constantly for smoothness
// 6. Make Panels Draggable
function makeDraggable(elementId, headerId) {
const element = document.getElementById(elementId);
const header = document.getElementById(headerId);
let isDragging = false;
let startX, startY, initialLeft, initialTop;
header.onmousedown = function(e) {
e.preventDefault();
isDragging = true;
startX = e.clientX;
startY = e.clientY;
// Get computed style to handle percentage or auto values correctly
const style = window.getComputedStyle(element);
initialLeft = parseInt(style.left, 10) || 0;
initialTop = parseInt(style.top, 10) || 0;
// If right is set and left is auto, we need to convert to left-based positioning
if (style.left === 'auto' && style.right !== 'auto') {
const rect = element.getBoundingClientRect();
initialLeft = rect.left;
element.style.right = 'auto'; // Clear right
element.style.left = initialLeft + 'px'; // Set left
}
document.onmousemove = function(e) {
if (!isDragging) return;
const dx = e.clientX - startX;
const dy = e.clientY - startY;
element.style.top = (initialTop + dy) + "px";
element.style.left = (initialLeft + dx) + "px";
};
document.onmouseup = function() {
isDragging = false;
document.onmousemove = null;
document.onmouseup = null;
};
};
}
// Initialize draggable panels
makeDraggable("inspector-wrapper", "inspector-header");
makeDraggable("properties-panel", "properties-header");
// ==========================================
// CUSTOM METRICS & DEBUG LOGIC
// ==========================================
viewer.scene.debugShowFramesPerSecond = true; // Enable standard Cesium FPS overlay
// FPS Calculation for custom panel
let lastFrameTime = performance.now();
let frameCount = 0;
let fps = 0;
// Helper to format numbers with K/M
function formatNum(num) {
if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
return num.toString();
}
// Traversal for All Loaded Stats
// We only traverse once per second to avoid performance hit
let lastTraverseTime = 0;
let cachedLoadedStats = { tiles: 0, triangles: 0, vertices: 0, materials: 0, draws: 0 };
// Helper to extract stats from a Model (supports both Legacy and New Cesium Model architectures)
function getModelStats(model) {
const stats = { triangles: 0, vertices: 0, materials: 0 };
if (!model) return stats;
// 1. Legacy Model (Cesium < 1.97)
if (typeof model._trianglesLength === 'number' && model._trianglesLength > 0) {
stats.triangles = model._trianglesLength;
stats.vertices = model._verticesLength || (stats.triangles * 3);
if (model._runtime && model._runtime.materials) {
stats.materials = model._runtime.materials.length;
} else if (model.materials) {
stats.materials = model.materials.length;
}
return stats;
}
// 2. New Model Architecture (Cesium 1.97+) via SceneGraph
if (model.sceneGraph && model.sceneGraph._runtimeNodes) {
const nodes = model.sceneGraph._runtimeNodes;
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (node.runtimePrimitives) {
for (let j = 0; j < node.runtimePrimitives.length; j++) {
const runPrim = node.runtimePrimitives[j];
const primitive = runPrim.primitive;
if (primitive) {
// Triangles
if (primitive.indices) {
stats.triangles += (primitive.indices.count / 3);
} else if (primitive.attributes && primitive.attributes.length > 0) {
stats.triangles += (primitive.attributes[0].count / 3);
}
// Vertices
if (primitive.attributes) {
// attributes is array in new architecture
let posAttr = null;
if (Array.isArray(primitive.attributes)) {
posAttr = primitive.attributes.find(a => a.semantic === 'POSITION');
if (!posAttr && primitive.attributes.length > 0) posAttr = primitive.attributes[0];
}
if (posAttr) {
stats.vertices += posAttr.count;
}
}
}
}
}
}
// Materials
// Strategy A: Check SceneGraph Components (Standard for new architecture)
if (model.sceneGraph.components && model.sceneGraph.components.materials && model.sceneGraph.components.materials.length > 0) {
stats.materials = model.sceneGraph.components.materials.length;
}
// Strategy B: Check internal Loader (If accessible)
else if (model._loader && model._loader._gltf && model._loader._gltf.materials) {
stats.materials = model._loader._gltf.materials.length;
}
// Strategy C: Count unique materials used by primitives
else {
const uniqueMaterials = new Set();
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if (node.runtimePrimitives) {
for (let j = 0; j < node.runtimePrimitives.length; j++) {
const runPrim = node.runtimePrimitives[j];
// In new architecture, primitive.material is the runtime material
if (runPrim.primitive && runPrim.primitive.material) {
uniqueMaterials.add(runPrim.primitive.material);
}
}
}
}
if (uniqueMaterials.size > 0) {
stats.materials = uniqueMaterials.size;
}
}
return stats;
}
return stats;
}
function getLoadedStats(root) {
const now = performance.now();
if (now - lastTraverseTime < 1000) return cachedLoadedStats;
lastTraverseTime = now;
const stats = { tiles: 0, triangles: 0, vertices: 0, materials: 0, draws: 0 };
function traverse(tile) {
// Count if content is ready (loaded in memory)
if (tile.contentReady) {
stats.tiles++;
const content = tile.content;
if (content && content._model) {
const model = content._model;
const mStats = getModelStats(model);
stats.triangles += mStats.triangles;
stats.vertices += mStats.vertices;
stats.materials += mStats.materials;
// Draw Calls (Potential)
if (model._drawCommands) {
stats.draws += model._drawCommands.length;
}
}
}
// Recurse
if (tile.children) {
for (let i = 0; i < tile.children.length; i++) {
traverse(tile.children[i]);
}
}
}
if (root) traverse(root);
cachedLoadedStats = stats;
return stats;
}
function updateCustomStats() {
// Calculate FPS
const now = performance.now();
frameCount++;
if (now - lastFrameTime >= 1000) {
fps = frameCount;
frameCount = 0;
lastFrameTime = now;
document.getElementById('stat-fps').innerText = fps;
}
if (tileset) {
// Memory
const memMB = (tileset.totalMemoryUsageInBytes / (1024 * 1024)).toFixed(0);
document.getElementById('stat-mem').innerText = memMB;
// --- VISIBLE STATS ---
// Draw Calls (Visible)
let drawsVisible = 0;
if (viewer.scene._frameState && viewer.scene._frameState.commandList) {
drawsVisible = viewer.scene._frameState.commandList.length;
}
// Selected Tiles (Visible)
const selectedTiles = tileset._selectedTiles || [];
// Geometry & Materials Stats (Visible)
let trisVisible = 0;
let vertsVisible = 0;
let matsVisible = 0;
for (let i = 0; i < selectedTiles.length; i++) {
const tile = selectedTiles[i];
const content = tile.content;
if (content && content._model) {
const model = content._model;
const mStats = getModelStats(model);
trisVisible += mStats.triangles;
vertsVisible += mStats.vertices;
matsVisible += mStats.materials;
}
}
// --- LOADED STATS (ALL IN MEMORY) ---
const loadedStats = getLoadedStats(tileset.root);
// Helper to set text and tooltip
const setStat = (id, visible, loaded) => {
const el = document.getElementById(id);
el.innerText = `${formatNum(visible)} | ${formatNum(loaded)}`;
el.title = `Visible: ${visible.toLocaleString()}\nLoaded: ${loaded.toLocaleString()}`;
el.style.cursor = 'help'; // Visual cue
el.style.borderBottom = '1px dotted #888'; // Visual cue
};
// Update DOM with "Visible | Loaded" format
setStat('stat-draws', drawsVisible, loadedStats.draws);
setStat('stat-tris', trisVisible, loadedStats.triangles);
setStat('stat-verts', vertsVisible, loadedStats.vertices);
setStat('stat-mats', matsVisible, loadedStats.materials);
setStat('stat-tiles', selectedTiles.length, loadedStats.tiles);
}
}
viewer.scene.postRender.addEventListener(updateCustomStats);
// Bind Checkboxes
document.getElementById('chk-debug-bounds').addEventListener('change', function(e) {
if (tileset) {
tileset.debugShowBoundingVolume = e.target.checked;
// Also force update to ensure render happens
viewer.scene.requestRender();
if (e.target.checked) {
console.log("Enabled Bounding Volume Debugging");
console.log("Root BV:", tileset.root.boundingVolume);
console.log("Root BV jsonstr", JSON.stringify(tileset.root.boundingVolume))
// Fix for 'Triangular Lines' if caused by wireframe confusion
// We ensure wireframe is NOT implicitly on, but we don't force it off unless requested.
}
}
});
document.getElementById('chk-debug-wire').addEventListener('change', function(e) {
if (tileset) {
tileset.debugWireframe = e.target.checked;
viewer.scene.requestRender();
}
});
document.getElementById('chk-debug-colorize').addEventListener('change', function(e) {
if (tileset) {
tileset.debugColorizeTiles = e.target.checked;
viewer.scene.requestRender();
}
});
// Fly to Root helper
window.flyToRoot = function() {
if (tileset) {
console.log("Flying to tileset root...");
// Log transform details
console.log("Tileset ModelMatrix:", tileset.modelMatrix);
console.log("Root Transform:", tileset.root.transform);
// Check for RTC in content (internal access)
if (tileset.root.content && tileset.root.content._rtcCenter) {
console.log("Root Content RTC Center:", tileset.root.content._rtcCenter);
} else {
console.log("Root Content RTC Center: Not found (might be undefined or 0)");
}
viewer.flyTo(tileset, {
duration: 1.5
});
}
};
// Debug: Move to Origin
window.debugMoveToOrigin = function() {
if (tileset) {
console.log("Moving tileset to origin (0,0,0) to check for precision issues...");
// Save original transform if needed (omitted for simple debug)
// Clear model matrix
tileset.modelMatrix = Cesium.Matrix4.IDENTITY;
// Clear root transform if it exists
if (tileset.root && tileset.root.transform) {
tileset.root.transform = Cesium.Matrix4.IDENTITY;
}
viewer.zoomTo(tileset);
console.log("Tileset moved to origin. If 'Triangular Lines' or Jitter disappears, the issue is Floating Point Precision (missing RTC).");
}
};
// ==========================================
// TILESET INFO & GLB EXTENSIONS FETCHER
// ==========================================
async function fetchTilesetInfo() {
try {
// 1. Fetch tileset.json
const response = await fetch('./output/tileset.json');
if (!response.ok) throw new Error('Failed to fetch tileset.json');
const tilesetJson = await response.json();
// Display Version
const version = tilesetJson.asset && tilesetJson.asset.version ? tilesetJson.asset.version : 'Unknown';
document.getElementById('tileset-version').innerText = version;
// 2. Find a B3DM file
let b3dmUrl = null;
// Simple traversal to find first content uri
function findContent(node) {
if (node.content && node.content.uri) {
if (node.content.uri.endsWith('.b3dm')) return node.content.uri;
}
if (node.children) {
for (const child of node.children) {
const res = findContent(child);
if (res) return res;
}
}
return null;
}
b3dmUrl = findContent(tilesetJson.root);
if (b3dmUrl) {
// Resolve path relative to tileset.json
// Assuming tileset.json is at ./output/tileset.json and uris are relative to it
const fullUrl = './output/' + b3dmUrl;
const b3dmResp = await fetch(fullUrl);
if (!b3dmResp.ok) throw new Error('Failed to fetch B3DM');
const buffer = await b3dmResp.arrayBuffer();
// Parse B3DM
// Header: magic(4), version(4), byteLength(4), featureTableJSONByteLength(4), featureTableBinaryByteLength(4), batchTableJSONByteLength(4), batchTableBinaryByteLength(4)
// Total header = 28 bytes
const dataView = new DataView(buffer);
const magic = String.fromCharCode(dataView.getUint8(0), dataView.getUint8(1), dataView.getUint8(2), dataView.getUint8(3));
if (magic !== 'b3dm') {
document.getElementById('glb-extensions-used').innerText = 'Not a valid b3dm';
return;
}
const version = dataView.getUint32(4, true);
const featureTableJsonLen = dataView.getUint32(12, true);
const featureTableBinLen = dataView.getUint32(16, true);
const batchTableJsonLen = dataView.getUint32(20, true);
const batchTableBinLen = dataView.getUint32(24, true);
const glbStart = 28 + featureTableJsonLen + featureTableBinLen + batchTableJsonLen + batchTableBinLen;
// GLB Header: magic(4), version(4), length(4)
// Check if we have enough data
if (buffer.byteLength < glbStart + 12) {
document.getElementById('glb-extensions-used').innerText = 'Incomplete B3DM';
return;
}
const glbMagic = String.fromCharCode(dataView.getUint8(glbStart), dataView.getUint8(glbStart+1), dataView.getUint8(glbStart+2), dataView.getUint8(glbStart+3));
if (glbMagic !== 'glTF') {
document.getElementById('glb-extensions-used').innerText = 'No GLB found';
return;
}
// Chunk 0: JSON
// Chunk Header: length(4), type(4)
const chunk0Len = dataView.getUint32(glbStart + 12, true);
const chunk0Type = dataView.getUint32(glbStart + 16, true); // 0x4E4F534A for JSON
if (chunk0Type !== 0x4E4F534A) {
document.getElementById('glb-extensions-used').innerText = 'First chunk not JSON';
return;
}
const jsonStart = glbStart + 20;
const jsonBytes = new Uint8Array(buffer, jsonStart, chunk0Len);
const jsonStr = new TextDecoder().decode(jsonBytes);
const gltfJson = JSON.parse(jsonStr);
const extensionsUsed = gltfJson.extensionsUsed || [];
const extensionsRequired = gltfJson.extensionsRequired || [];
const textureCount = gltfJson.textures ? gltfJson.textures.length : 0;
// Scan texture extensions
const texExtensions = new Set();
if (gltfJson.textures) {
for (const tex of gltfJson.textures) {
if (tex.extensions) {
for (const extName of Object.keys(tex.extensions)) {
texExtensions.add(extName);
}
}
}
}
const texExtArray = Array.from(texExtensions);
document.getElementById('glb-extensions-used').innerText = extensionsUsed.length > 0 ? extensionsUsed.join(', ') : 'None';
document.getElementById('glb-extensions-req').innerText = extensionsRequired.length > 0 ? extensionsRequired.join(', ') : 'None';
document.getElementById('glb-tex-extensions').innerText = texExtArray.length > 0 ? texExtArray.join(', ') : 'None';
document.getElementById('glb-textures').innerText = textureCount;
} else {
document.getElementById('glb-extensions-used').innerText = 'No B3DM found';
}
} catch (e) {
console.error(e);
document.getElementById('tileset-version').innerText = 'Error';
document.getElementById('glb-extensions-used').innerText = 'Error';
document.getElementById('glb-extensions-req').innerText = 'Error';
document.getElementById('glb-tex-extensions').innerText = 'Error';
document.getElementById('glb-textures').innerText = 'Error';
}
}
// Call it
fetchTilesetInfo();
</script>
</body>
</html>