Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 | 47x 47x 47x 47x 47x 3x 3x 3x 47x 2x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 1x 5x 5x 65x 56x 9x 9x 9x 9x 1x 1x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 5x 5x 5x 5x 5x 5x 5x 76x 81x 81x 12x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 26x 26x 26x 26x 1x 89x 1x 1x 1x 36x 36x 36x 36x 36x 36x 36x 36x 12x 12x 25x 25x 25x 25x 25x 16x 16x 16x 9x 9x 9x 25x 25x 25x 25x 25x 25x 80x 81x 81x 81x 81x 81x 81x 81x 86x 86x 86x 86x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 86x 86x 6x 80x 25x 80x 34x 34x 34x 22x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 81x 81x 81x 81x 81x 81x 81x 1x 80x 80x 80x 80x 80x 80x 80x 80x 80x 68x 12x 4x 12x 80x 80x 80x 80x 104x 104x 104x 86x 104x 6x 80x 80x 80x 104x 104x 104x 104x 104x 26x 26x 26x 26x 26x 26x 26x 26x 156x 156x 156x 26x 26x 26x 32x 32x 32x 32x 32x 32x 26x 26x 26x 26x 26x 26x 26x 26x 16x 14x 14x 26x 26x 26x 26x 6x 5x 5x 6x 6x 6x 5x 5x 26x 26x 1x 81x 81x 81x 81x 81x 81x 81x 81x 18x 18x 18x 18x 18x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 12x 12x 12x 12x 18x 81x 81x 81x 18x 81x 81x 16x 6x 6x 81x 81x 81x 81x 81x 81x 18x 18x 18x 72x 81x 81x 81x 16x 16x 16x 16x 16x 16x 16x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 16x 16x 16x 2x 2x 2x 2x 2x 2x 2x 2x | import Cartesian2 from "../Core/Cartesian2.js";
import Cartesian3 from "../Core/Cartesian3.js";
import CesiumMath from "../Core/Math.js";
import CullingVolume from "../Core/CullingVolume.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import DoubleEndedPriorityQueue from "../Core/DoubleEndedPriorityQueue.js";
import getTimestamp from "../Core/getTimestamp.js";
import KeyframeNode from "./KeyframeNode.js";
import MetadataType from "./MetadataType.js";
import Megatexture from "./Megatexture.js";
import PixelFormat from "../Core/PixelFormat.js";
import PixelDatatype from "../Renderer/PixelDatatype.js";
import Sampler from "../Renderer/Sampler.js";
import SpatialNode from "./SpatialNode.js";
import Texture from "../Renderer/Texture.js";
import TextureMagnificationFilter from "../Renderer/TextureMagnificationFilter.js";
import TextureMinificationFilter from "../Renderer/TextureMinificationFilter.js";
import VoxelMetadataOrder from "./VoxelMetadataOrder.js";
/**
* Handles tileset traversal, tile requests, and GPU resources. Intended to be
* private and paired with a {@link VoxelPrimitive}, which has a user-facing API.
*
* @alias VoxelTraversal
* @constructor
*
* @param {VoxelPrimitive} primitive The voxel primitive for which this traversal will be used.
* @param {Context} context The context in which to create GPU resources.
* @param {number} keyframeCount The number of keyframes in the tileset.
* @param {number} [maximumTextureMemoryByteLength] The maximum amount of memory to use for textures.
*
* @private
*/
function VoxelTraversal(
primitive,
context,
keyframeCount,
maximumTextureMemoryByteLength,
) {
const { provider, dimensions, paddingBefore, paddingAfter } = primitive;
const { types, componentTypes, metadataOrder } = provider;
const inputDimensions = Cartesian3.add(
dimensions,
paddingBefore,
new Cartesian3(),
);
Cartesian3.add(inputDimensions, paddingAfter, inputDimensions);
if (metadataOrder === VoxelMetadataOrder.Y_UP) {
const inputDimensionsY = inputDimensions.y;
inputDimensions.y = inputDimensions.z;
inputDimensions.z = inputDimensionsY;
}
if (
!defined(maximumTextureMemoryByteLength) &&
defined(provider.maximumTileCount)
) {
maximumTextureMemoryByteLength = getApproximateTextureMemoryByteLength(
provider.maximumTileCount,
inputDimensions,
types,
componentTypes,
);
}
/**
* @type {VoxelPrimitive}
* @private
*/
this._primitive = primitive;
/**
* @type {number}
* @private
*/
this.textureMemoryByteLength = 0;
/**
* @type {Megatexture[]}
* @readonly
*/
this.megatextures = new Array(types.length);
// TODO make sure to split the maximumTextureMemoryByteLength across all the megatextures
for (let i = 0; i < types.length; i++) {
const type = types[i];
const componentCount = MetadataType.getComponentCount(type);
const componentType = componentTypes[i];
this.megatextures[i] = new Megatexture(
context,
inputDimensions,
componentCount,
componentType,
maximumTextureMemoryByteLength,
);
this.textureMemoryByteLength +=
this.megatextures[i].textureMemoryByteLength;
}
const maximumTileCount = this.megatextures[0].maximumTileCount;
/**
* @type {number}
* @private
*/
this._simultaneousRequestCount = 0;
/**
* @type {boolean}
* @private
*/
this._debugPrint = false;
/**
* @type {boolean}
* @private
*/
this._calculateStatistics = this._primitive._calculateStatistics ?? false;
/**
* @type {number}
* @private
*/
this._frameNumber = 0;
const shape = primitive._shape;
/**
* @type {SpatialNode}
* @readonly
*/
this.rootNode = new SpatialNode(0, 0, 0, 0, undefined, shape, dimensions);
/**
* @type {DoubleEndedPriorityQueue}
* @private
*/
this._priorityQueue = new DoubleEndedPriorityQueue({
maximumLength: maximumTileCount,
comparator: KeyframeNode.priorityComparator,
});
/**
* @type {KeyframeNode[]}
* @private
*/
this._highPriorityKeyframeNodes = new Array(maximumTileCount);
/**
* @type {number}
* @private
*/
this._highPriorityKeyframeNodeCount = 0;
/**
* @type {KeyframeNode[]}
* @private
*/
this._keyframeNodesInMegatexture = new Array(maximumTileCount);
/**
* @type {number}
* @private
*/
this._keyframeCount = keyframeCount;
/**
* @type {number}
* @private
*/
this._sampleCount = undefined;
/**
* @type {number}
* @private
*/
this._keyframeLocation = 0;
/**
* @type {number[]}
* @private
*/
this._binaryTreeKeyframeWeighting = new Array(keyframeCount);
/**
* @type {boolean}
* @private
*/
this._initialTilesLoaded = false;
const binaryTreeKeyframeWeighting = this._binaryTreeKeyframeWeighting;
binaryTreeKeyframeWeighting[0] = 0;
binaryTreeKeyframeWeighting[keyframeCount - 1] = 0;
binaryTreeWeightingRecursive(
binaryTreeKeyframeWeighting,
1,
keyframeCount - 2,
0,
);
const internalNodeTexelCount = 9;
const internalNodeTextureDimensionX = 2048;
const internalNodeTilesPerRow = Math.floor(
internalNodeTextureDimensionX / internalNodeTexelCount,
);
const internalNodeTextureDimensionY = Math.ceil(
maximumTileCount / internalNodeTilesPerRow,
);
/**
* @type {Texture}
* @readonly
*/
this.internalNodeTexture = new Texture({
context: context,
pixelFormat: PixelFormat.RGBA,
pixelDatatype: PixelDatatype.UNSIGNED_BYTE,
flipY: false,
width: internalNodeTextureDimensionX,
height: internalNodeTextureDimensionY,
sampler: new Sampler({
minificationFilter: TextureMinificationFilter.NEAREST,
magnificationFilter: TextureMagnificationFilter.NEAREST,
}),
});
/**
* @type {number}
* @readonly
*/
this.internalNodeTilesPerRow = internalNodeTilesPerRow;
/**
* @type {Cartesian2}
* @readonly
*/
this.internalNodeTexelSizeUv = new Cartesian2(
1.0 / internalNodeTextureDimensionX,
1.0 / internalNodeTextureDimensionY,
);
/**
* Only generated when there are two or more samples.
* @type {Texture}
* @readonly
*/
this.leafNodeTexture = undefined;
/**
* Only generated when there are two or more samples.
* @type {number}
* @readonly
*/
this.leafNodeTilesPerRow = undefined;
/**
* Only generated when there are two or more samples.
* @type {Cartesian2}
* @readonly
*/
this.leafNodeTexelSizeUv = new Cartesian2();
}
/**
* Finds a keyframe node in the traversal
*
* @param {number} megatextureIndex
* @returns {KeyframeNode}
*/
VoxelTraversal.prototype.findKeyframeNode = function (megatextureIndex) {
return this._keyframeNodesInMegatexture.find(function (keyframeNode) {
return keyframeNode.megatextureIndex === megatextureIndex;
});
};
function binaryTreeWeightingRecursive(arr, start, end, depth) {
if (start > end) {
return;
}
const mid = Math.floor((start + end) / 2);
arr[mid] = depth;
binaryTreeWeightingRecursive(arr, start, mid - 1, depth + 1);
binaryTreeWeightingRecursive(arr, mid + 1, end, depth + 1);
}
VoxelTraversal.simultaneousRequestCountMaximum = 50;
/**
* @param {FrameState} frameState
* @param {number} keyframeLocation
* @param {boolean} recomputeBoundingVolumes
* @param {boolean} pauseUpdate
*/
VoxelTraversal.prototype.update = function (
frameState,
keyframeLocation,
recomputeBoundingVolumes,
pauseUpdate,
) {
const primitive = this._primitive;
const context = frameState.context;
const maximumTileCount = this.megatextures[0].maximumTileCount;
const keyframeCount = this._keyframeCount;
const levelBlendFactor = primitive._levelBlendFactor;
const hasLevelBlendFactor = levelBlendFactor > 0.0;
const hasKeyframes = keyframeCount > 1;
const sampleCount = (hasLevelBlendFactor ? 2 : 1) * (hasKeyframes ? 2 : 1);
this._sampleCount = sampleCount;
const useLeafNodes = sampleCount >= 2;
if (useLeafNodes && !defined(this.leafNodeTexture)) {
const leafNodeTexelCount = 2;
const leafNodeTextureDimensionX = 1024;
const leafNodeTilesPerRow = Math.floor(
leafNodeTextureDimensionX / leafNodeTexelCount,
);
const leafNodeTextureDimensionY = Math.ceil(
maximumTileCount / leafNodeTilesPerRow,
);
this.leafNodeTexture = new Texture({
context: context,
pixelFormat: PixelFormat.RGBA,
pixelDatatype: PixelDatatype.UNSIGNED_BYTE,
flipY: false,
width: leafNodeTextureDimensionX,
height: leafNodeTextureDimensionY,
sampler: new Sampler({
minificationFilter: TextureMinificationFilter.NEAREST,
magnificationFilter: TextureMagnificationFilter.NEAREST,
}),
});
this.leafNodeTexelSizeUv = Cartesian2.fromElements(
1.0 / leafNodeTextureDimensionX,
1.0 / leafNodeTextureDimensionY,
this.leafNodeTexelSizeUv,
);
this.leafNodeTilesPerRow = leafNodeTilesPerRow;
} else Iif (!useLeafNodes && defined(this.leafNodeTexture)) {
this.leafNodeTexture = this.leafNodeTexture.destroy();
}
this._keyframeLocation = CesiumMath.clamp(
keyframeLocation,
0.0,
keyframeCount - 1,
);
if (recomputeBoundingVolumes) {
recomputeBoundingVolumesRecursive(this, this.rootNode);
}
Iif (pauseUpdate) {
return;
}
this._frameNumber = frameState.frameNumber;
const timestamp0 = getTimestamp();
selectKeyframeNodes(this, frameState);
updateKeyframeNodes(this, frameState);
const timestamp1 = getTimestamp();
generateOctree(this, sampleCount, levelBlendFactor);
const timestamp2 = getTimestamp();
const checkEventListeners =
primitive.loadProgress.numberOfListeners > 0 ||
primitive.allTilesLoaded.numberOfListeners > 0 ||
primitive.initialTilesLoaded.numberOfListeners > 0;
if (this._debugPrint || this._calculateStatistics || checkEventListeners) {
const loadAndUnloadTimeMs = timestamp1 - timestamp0;
const generateOctreeTimeMs = timestamp2 - timestamp1;
const totalTimeMs = timestamp2 - timestamp0;
postPassesUpdate(
this,
frameState,
loadAndUnloadTimeMs,
generateOctreeTimeMs,
totalTimeMs,
);
}
};
/**
* Check if a node is renderable.
* @param {SpatialNode} tile
* @returns {boolean}
*/
VoxelTraversal.prototype.isRenderable = function (tile) {
return tile.isRenderable(this._frameNumber);
};
/**
* Returns true if this object was destroyed; otherwise, false.
* <br /><br />
* If this object was destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
*
* @returns {boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
*
* @see VoxelTraversal#destroy
*/
VoxelTraversal.prototype.isDestroyed = function () {
return false;
};
/**
* Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
* release of WebGL resources, instead of relying on the garbage collector to destroy this object.
* <br /><br />
* Once an object is destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
* assign the return value (<code>undefined</code>) to the object as done in the example.
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
* @see VoxelTraversal#isDestroyed
*
* @example
* voxelTraversal = voxelTraversal && voxelTraversal.destroy();
*/
VoxelTraversal.prototype.destroy = function () {
const megatextures = this.megatextures;
const megatextureLength = megatextures.length;
for (let i = 0; i < megatextureLength; i++) {
megatextures[i] = megatextures[i] && megatextures[i].destroy();
}
this.textureMemoryByteLength = 0;
this.internalNodeTexture =
this.internalNodeTexture && this.internalNodeTexture.destroy();
this.leafNodeTexture = this.leafNodeTexture && this.leafNodeTexture.destroy();
return destroyObject(this);
};
/**
* @function
*
* @param {VoxelTraversal} that
* @param {SpatialNode} node
*
* @private
*/
function recomputeBoundingVolumesRecursive(that, node) {
node.computeBoundingVolumes(that._primitive._shape);
Iif (defined(node.children)) {
for (let i = 0; i < 8; i++) {
const child = node.children[i];
recomputeBoundingVolumesRecursive(that, child);
}
}
}
/**
* @function
*
* @param {VoxelTraversal} that
* @param {KeyframeNode} keyframeNode
*
* @private
*/
function requestData(that, keyframeNode) {
Iif (
that._simultaneousRequestCount >=
VoxelTraversal.simultaneousRequestCountMaximum
) {
return;
}
const primitive = that._primitive;
const provider = primitive.provider;
const { keyframe, spatialNode } = keyframeNode;
Iif (
defined(provider.availableLevels) &&
spatialNode.level >= provider.availableLevels
) {
return;
}
function postRequestSuccess(result) {
that._simultaneousRequestCount--;
keyframeNode.content = result;
keyframeNode.state = defined(result)
? KeyframeNode.LoadState.PROCESSING
: KeyframeNode.LoadState.UNAVAILABLE;
}
function postRequestFailure(error) {
that._simultaneousRequestCount--;
keyframeNode.state = KeyframeNode.LoadState.FAILED;
that._primitive.tileFailed.raiseEvent();
}
const requestParameters = {
tileLevel: spatialNode.level,
tileX: spatialNode.x,
tileY: spatialNode.y,
tileZ: spatialNode.z,
keyframe: keyframe,
};
const promise = provider.requestData(requestParameters);
Iif (!defined(promise)) {
return;
}
that._simultaneousRequestCount++;
keyframeNode.state = KeyframeNode.LoadState.RECEIVING;
promise.then(postRequestSuccess).catch(postRequestFailure);
}
/**
* @function
*
* @param {number} x
* @returns {number}
*
* @private
*/
function mapInfiniteRangeToZeroOne(x) {
return x / (1.0 + x);
}
/**
* @param {VoxelTraversal} that
* @param {FrameState} frameState
*
* @private
*/
function selectKeyframeNodes(that, frameState) {
const frameNumber = that._frameNumber;
const priorityQueue = that._priorityQueue;
// Add all the nodes to the queue, to sort them by priority.
priorityQueue.reset();
addToQueueRecursive(
that.rootNode,
CullingVolume.MASK_INDETERMINATE,
that,
frameState,
);
// Move the nodes from the queue to array of high priority nodes.
const highPriorityKeyframeNodes = that._highPriorityKeyframeNodes;
let highPriorityKeyframeNodeCount = 0;
let highPriorityKeyframeNode;
while (priorityQueue.length > 0) {
highPriorityKeyframeNode = priorityQueue.removeMaximum();
highPriorityKeyframeNode.highPriorityFrameNumber = frameNumber;
highPriorityKeyframeNodes[highPriorityKeyframeNodeCount] =
highPriorityKeyframeNode;
highPriorityKeyframeNodeCount++;
}
that._highPriorityKeyframeNodeCount = highPriorityKeyframeNodeCount;
}
/**
* @param {VoxelTraversal} that
* @param {FrameState} frameState
*
* @private
*/
function updateKeyframeNodes(that, frameState) {
const megatexture = that.megatextures[0];
const keyframeNodesInMegatextureCount = megatexture.occupiedCount;
// Sort the list of keyframe nodes in the megatexture by priority, so
// we can remove the lowest priority nodes if we need space.
const keyframeNodesInMegatexture = that._keyframeNodesInMegatexture;
keyframeNodesInMegatexture.length = keyframeNodesInMegatextureCount;
keyframeNodesInMegatexture.sort(keyframeNodeSort);
// Add the high priority nodes to the megatexture,
// removing existing lower-priority nodes if necessary.
const highPriorityKeyframeNodes = that._highPriorityKeyframeNodes;
const highPriorityKeyframeNodeCount = that._highPriorityKeyframeNodeCount;
let destroyedCount = 0;
let addedCount = 0;
for (
let highPriorityKeyframeNodeIndex = 0;
highPriorityKeyframeNodeIndex < highPriorityKeyframeNodeCount;
highPriorityKeyframeNodeIndex++
) {
const highPriorityKeyframeNode =
highPriorityKeyframeNodes[highPriorityKeyframeNodeIndex];
if (
highPriorityKeyframeNode.state === KeyframeNode.LoadState.LOADED ||
highPriorityKeyframeNode.spatialNode === undefined
) {
// Already loaded, so nothing to do.
// Or destroyed when adding a higher priority node
continue;
}
if (highPriorityKeyframeNode.state === KeyframeNode.LoadState.UNLOADED) {
requestData(that, highPriorityKeyframeNode);
}
if (highPriorityKeyframeNode.state === KeyframeNode.LoadState.PROCESSING) {
const { content } = highPriorityKeyframeNode;
content.update(that._primitive, frameState);
if (!content.ready) {
continue;
}
Iif (!validateMetadata(content.metadata, that)) {
highPriorityKeyframeNode.content = undefined;
highPriorityKeyframeNode.state = KeyframeNode.LoadState.FAILED;
that._primitive.tileFailed.raiseEvent();
continue;
}
let addNodeIndex = 0;
Iif (megatexture.isFull()) {
// If the megatexture is full, try removing a discardable node with the lowest priority.
addNodeIndex = keyframeNodesInMegatextureCount - 1 - destroyedCount;
destroyedCount++;
const discardNode = keyframeNodesInMegatexture[addNodeIndex];
that._primitive.tileUnload.raiseEvent();
discardNode.spatialNode.destroyKeyframeNode(
discardNode,
that.megatextures,
);
} else {
addNodeIndex = keyframeNodesInMegatextureCount + addedCount;
addedCount++;
}
highPriorityKeyframeNode.spatialNode.addKeyframeNodeToMegatextures(
highPriorityKeyframeNode,
that.megatextures,
);
highPriorityKeyframeNode.state = KeyframeNode.LoadState.LOADED;
keyframeNodesInMegatexture[addNodeIndex] = highPriorityKeyframeNode;
that._primitive.tileLoad.raiseEvent();
}
}
}
function keyframeNodeSort(a, b) {
if (a.highPriorityFrameNumber === b.highPriorityFrameNumber) {
return b.priority - a.priority;
}
return b.highPriorityFrameNumber - a.highPriorityFrameNumber;
}
/**
* Check if an array of metadata is of the expected type and size
*
* @param {TypedArray[]} metadata The metadata to validate
* @param {VoxelTraversal} traversal The traversal to validate against
* @returns {boolean} <code>true</code> if the metadata is valid, <code>false</code> otherwise
*
* @private
*/
function validateMetadata(metadata, traversal) {
const length = traversal._primitive.provider.types.length;
Iif (!Array.isArray(metadata) || metadata.length !== length) {
return false;
}
const { megatextures } = traversal;
for (let i = 0; i < length; i++) {
const { voxelCountPerTile, channelCount } = megatextures[i];
const { x, y, z } = voxelCountPerTile;
const tileVoxelCount = x * y * z;
const data = metadata[i];
const expectedLength = tileVoxelCount * channelCount;
Iif (data.length !== expectedLength) {
return false;
}
}
return true;
}
/**
* @param {SpatialNode} spatialNode
* @param {number} visibilityPlaneMask
* @param {VoxelTraversal} that
* @param {FrameState} frameState
*
* @private
*/
function addToQueueRecursive(
spatialNode,
visibilityPlaneMask,
that,
frameState,
) {
const { camera, context, pixelRatio, frameNumber } = frameState;
const { positionWC, frustum } = camera;
const screenHeight = context.drawingBufferHeight / pixelRatio;
const screenSpaceErrorMultiplier = screenHeight / frustum.sseDenominator;
spatialNode.computeScreenSpaceError(positionWC, screenSpaceErrorMultiplier);
visibilityPlaneMask = spatialNode.visibility(frameState, visibilityPlaneMask);
if (visibilityPlaneMask === CullingVolume.MASK_OUTSIDE) {
return;
}
spatialNode.visitedFrameNumber = frameNumber;
const primitive = that._primitive;
const shape = primitive._shape;
const targetScreenSpaceError = primitive.screenSpaceError;
const priorityQueue = that._priorityQueue;
const keyframeCount = that._keyframeCount;
const previousKeyframe = CesiumMath.clamp(
Math.floor(that._keyframeLocation),
0,
keyframeCount - 2,
);
const nextKeyframe = previousKeyframe + 1;
// Create keyframe nodes at the playhead.
// If they already exist, nothing will be created.
if (keyframeCount === 1) {
spatialNode.createKeyframeNode(0);
} else if (spatialNode.keyframeNodes.length !== keyframeCount) {
for (let k = 0; k < keyframeCount; k++) {
spatialNode.createKeyframeNode(k);
}
}
const { screenSpaceError, keyframeNodes } = spatialNode;
const ssePriority = mapInfiniteRangeToZeroOne(screenSpaceError);
let hasLoadedKeyframe = false;
for (let i = 0; i < keyframeNodes.length; i++) {
const keyframeNode = keyframeNodes[i];
keyframeNode.priority =
10.0 * ssePriority +
keyframePriority(
previousKeyframe,
keyframeNode.keyframe,
nextKeyframe,
that,
);
if (
keyframeNode.state !== KeyframeNode.LoadState.UNAVAILABLE &&
keyframeNode.state !== KeyframeNode.LoadState.FAILED &&
keyframeNode.priority !== -Number.MAX_VALUE
) {
priorityQueue.insert(keyframeNode);
}
if (keyframeNode.state === KeyframeNode.LoadState.LOADED) {
hasLoadedKeyframe = true;
}
}
Eif (screenSpaceError < targetScreenSpaceError || !hasLoadedKeyframe) {
// Free up memory
spatialNode.children = undefined;
return;
}
if (!defined(spatialNode.children)) {
spatialNode.constructChildNodes(shape);
}
for (let childIndex = 0; childIndex < 8; childIndex++) {
const child = spatialNode.children[childIndex];
addToQueueRecursive(child, visibilityPlaneMask, that, frameState);
}
}
/**
* Compute a priority for a keyframe node.
*
* @private
* @param {number} previousKeyframe
* @param {number} keyframe
* @param {number} nextKeyframe
* @param {VoxelTraversal} traversal
* @returns {number} The computed priority
*/
function keyframePriority(previousKeyframe, keyframe, nextKeyframe, traversal) {
const keyframeDifference = Math.min(
Math.abs(keyframe - previousKeyframe),
Math.abs(keyframe - nextKeyframe),
);
const maxKeyframeDifference = Math.max(
previousKeyframe,
traversal._keyframeCount - nextKeyframe - 1,
1,
);
const keyframeFactor = Math.pow(
1.0 - keyframeDifference / maxKeyframeDifference,
4.0,
);
const binaryTreeFactor = Math.exp(
-traversal._binaryTreeKeyframeWeighting[keyframe],
);
return CesiumMath.lerp(
binaryTreeFactor,
keyframeFactor,
0.15 + 0.85 * keyframeFactor,
);
}
/**
* @function
*
* @param {VoxelTraversal} that
*
* @private
*/
function postPassesUpdate(
that,
frameState,
loadAndUnloadTimeMs,
generateOctreeTimeMs,
totalTimeMs,
) {
const keyframeCount = that._keyframeCount;
const rootNode = that.rootNode;
const loadStateCount = Object.keys(KeyframeNode.LoadState).length;
const loadStatesByKeyframe = new Array(loadStateCount);
const loadStateByCount = new Array(loadStateCount);
let nodeCountTotal = 0;
for (
let loadStateIndex = 0;
loadStateIndex < loadStateCount;
loadStateIndex++
) {
const keyframeArray = new Array(keyframeCount).fill(0);
loadStatesByKeyframe[loadStateIndex] = keyframeArray;
loadStateByCount[loadStateIndex] = 0;
}
/**
* @param {SpatialNode} node
*/
function traverseRecursive(node) {
const keyframeNodes = node.keyframeNodes;
for (
let keyframeIndex = 0;
keyframeIndex < keyframeNodes.length;
keyframeIndex++
) {
const keyframeNode = keyframeNodes[keyframeIndex];
const keyframe = keyframeNode.keyframe;
const state = keyframeNode.state;
loadStatesByKeyframe[state][keyframe] += 1;
loadStateByCount[state] += 1;
nodeCountTotal++;
}
Iif (defined(node.children)) {
for (let childIndex = 0; childIndex < 8; childIndex++) {
const child = node.children[childIndex];
traverseRecursive(child);
}
}
}
traverseRecursive(rootNode);
that._primitive.statistics.numberOfTilesWithContentReady =
loadStateByCount[KeyframeNode.LoadState.LOADED];
that._primitive.statistics.visited = nodeCountTotal;
const numberOfPendingRequests =
loadStateByCount[KeyframeNode.LoadState.RECEIVING];
const numberOfTilesProcessing =
loadStateByCount[KeyframeNode.LoadState.PROCESSING];
const progressChanged =
numberOfPendingRequests !==
that._primitive.statistics.numberOfPendingRequests ||
numberOfTilesProcessing !==
that._primitive.statistics.numberOfTilesProcessing;
if (progressChanged) {
frameState.afterRender.push(function () {
that._primitive.loadProgress.raiseEvent(
numberOfPendingRequests,
numberOfTilesProcessing,
);
return true;
});
}
that._primitive.statistics.numberOfPendingRequests = numberOfPendingRequests;
that._primitive.statistics.numberOfTilesProcessing = numberOfTilesProcessing;
const tilesLoaded =
numberOfPendingRequests === 0 && numberOfTilesProcessing === 0;
// Events are raised (added to the afterRender queue) here since promises
// may resolve outside of the update loop that then raise events, e.g.,
// model's readyEvent
if (progressChanged && tilesLoaded) {
frameState.afterRender.push(function () {
that._primitive.allTilesLoaded.raiseEvent();
return true;
});
Eif (!that._initialTilesLoaded) {
that._initialTilesLoaded = true;
frameState.afterRender.push(function () {
that._primitive.initialTilesLoaded.raiseEvent();
return true;
});
}
}
Eif (!that._debugPrint) {
return;
}
const loadedKeyframeStatistics = `KEYFRAMES: ${
loadStatesByKeyframe[KeyframeNode.LoadState.LOADED]
}`;
const loadStateStatistics =
`UNLOADED: ${loadStateByCount[KeyframeNode.LoadState.UNLOADED]} | ` +
`RECEIVING: ${loadStateByCount[KeyframeNode.LoadState.RECEIVING]} | ` +
`PROCESSING: ${loadStateByCount[KeyframeNode.LoadState.PROCESSING]} | ` +
`LOADED: ${loadStateByCount[KeyframeNode.LoadState.LOADED]} | ` +
`FAILED: ${loadStateByCount[KeyframeNode.LoadState.FAILED]} | ` +
`UNAVAILABLE: ${loadStateByCount[KeyframeNode.LoadState.UNAVAILABLE]} | ` +
`TOTAL: ${nodeCountTotal}`;
const loadAndUnloadTimeMsRounded =
Math.round(loadAndUnloadTimeMs * 100) / 100;
const generateOctreeTimeMsRounded =
Math.round(generateOctreeTimeMs * 100) / 100;
const totalTimeMsRounded = Math.round(totalTimeMs * 100) / 100;
const timerStatistics =
`LOAD: ${loadAndUnloadTimeMsRounded} | ` +
`OCT: ${generateOctreeTimeMsRounded} | ` +
`ALL: ${totalTimeMsRounded}`;
console.log(
`${loadedKeyframeStatistics} || ${loadStateStatistics} || ${timerStatistics}`,
);
}
// GPU Octree Layout
// (shown as binary tree instead of octree for demonstration purposes)
//
// Tree representation:
// 0
// / \
// / \
// / \
// 1 3
// / \ / \
// L0 2 L3 L4
// / \
// L1 L2
//
//
// Array representation:
// L = leaf index
// * = index to parent node
// index: 0_______ 1________ 2________ 3_________
// array: [*0, 1, 3, *0, L0, 2, *1 L1, L2, *0, L3, L4]
//
// The array is generated from a depth-first traversal. The end result could be an unbalanced tree,
// so the parent index is stored at each node to make it possible to traverse upwards.
const GpuOctreeFlag = {
// Data is an octree index.
INTERNAL: 0,
// Data is a leaf node.
LEAF: 1,
// When leaf data is packed in the octree and there's a node that is forced to
// render but has no data of its own (such as when its siblings are renderable but it
// is not), signal that it's using its parent's data.
PACKED_LEAF_FROM_PARENT: 2,
};
/**
* @function
*
* @param {VoxelTraversal} that
* @param {number} sampleCount
* @param {number} levelBlendFactor
* @private
*/
function generateOctree(that, sampleCount, levelBlendFactor) {
const targetSse = that._primitive._screenSpaceError;
const keyframeLocation = that._keyframeLocation;
const frameNumber = that._frameNumber;
const useLeafNodes = sampleCount >= 2;
let internalNodeCount = 0;
let leafNodeCount = 0;
const internalNodeOctreeData = [];
const leafNodeOctreeData = [];
/**
* @param {SpatialNode} node
* @param {number} childOctreeIndex
* @param {number} childEntryIndex
* @param {number} parentOctreeIndex
* @param {number} parentEntryIndex
*/
function buildOctree(
node,
childOctreeIndex,
childEntryIndex,
parentOctreeIndex,
parentEntryIndex,
) {
let hasRenderableChildren = false;
Iif (defined(node.children)) {
for (let c = 0; c < 8; c++) {
const childNode = node.children[c];
childNode.computeSurroundingRenderableKeyframeNodes(keyframeLocation);
if (childNode.isRenderable(frameNumber)) {
hasRenderableChildren = true;
}
}
}
Iif (hasRenderableChildren) {
// Point the parent and child octree indexes at each other
internalNodeOctreeData[parentEntryIndex] =
(GpuOctreeFlag.INTERNAL << 16) | childOctreeIndex;
internalNodeOctreeData[childEntryIndex] = parentOctreeIndex;
internalNodeCount++;
// Recurse over children
parentOctreeIndex = childOctreeIndex;
parentEntryIndex = parentOctreeIndex * 9 + 1;
for (let cc = 0; cc < 8; cc++) {
const child = node.children[cc];
childOctreeIndex = internalNodeCount;
childEntryIndex = childOctreeIndex * 9 + 0;
buildOctree(
child,
childOctreeIndex,
childEntryIndex,
parentOctreeIndex,
parentEntryIndex + cc,
);
}
} else {
// Store the leaf node information instead
// Recursion stops here because there are no renderable children
that._primitive.tileVisible.raiseEvent();
if (useLeafNodes) {
const baseIdx = leafNodeCount * 5;
const keyframeNode = node.renderableKeyframeNodePrevious;
const levelDifference = node.level - keyframeNode.spatialNode.level;
const parentNode = keyframeNode.spatialNode.parent;
const parentKeyframeNode = defined(parentNode)
? parentNode.renderableKeyframeNodePrevious
: keyframeNode;
const lodLerp = getLodLerp(node, targetSse, levelBlendFactor);
const levelDifferenceChild = levelDifference;
const levelDifferenceParent = 1;
const megatextureIndexChild = keyframeNode.megatextureIndex;
const megatextureIndexParent = parentKeyframeNode.megatextureIndex;
leafNodeOctreeData[baseIdx + 0] = lodLerp;
leafNodeOctreeData[baseIdx + 1] = levelDifferenceChild;
leafNodeOctreeData[baseIdx + 2] = levelDifferenceParent;
leafNodeOctreeData[baseIdx + 3] = megatextureIndexChild;
leafNodeOctreeData[baseIdx + 4] = megatextureIndexParent;
internalNodeOctreeData[parentEntryIndex] =
(GpuOctreeFlag.LEAF << 16) | leafNodeCount;
} else {
const keyframeNode = node.renderableKeyframeNodePrevious;
const levelDifference = node.level - keyframeNode.spatialNode.level;
const flag =
levelDifference === 0
? GpuOctreeFlag.LEAF
: GpuOctreeFlag.PACKED_LEAF_FROM_PARENT;
internalNodeOctreeData[parentEntryIndex] =
(flag << 16) | keyframeNode.megatextureIndex;
}
leafNodeCount++;
}
}
const rootNode = that.rootNode;
rootNode.computeSurroundingRenderableKeyframeNodes(keyframeLocation);
if (rootNode.isRenderable(frameNumber)) {
buildOctree(rootNode, 0, 0, 0, 0);
}
copyToInternalNodeTexture(
internalNodeOctreeData,
9,
that.internalNodeTilesPerRow,
that.internalNodeTexture,
);
if (useLeafNodes) {
copyToLeafNodeTexture(
leafNodeOctreeData,
2,
that.leafNodeTilesPerRow,
that.leafNodeTexture,
);
}
}
/**
* Compute an interpolation factor between a node and its parent
* @param {SpatialNode} node
* @param {number} targetSse
* @param {number} levelBlendFactor
* @returns {number}
* @private
*/
function getLodLerp(node, targetSse, levelBlendFactor) {
Eif (node.parent === undefined) {
return 0.0;
}
const sse = node.screenSpaceError;
const parentSse = node.parent.screenSpaceError;
const lodLerp = (targetSse - sse) / (parentSse - sse);
const blended = (lodLerp + levelBlendFactor - 1.0) / levelBlendFactor;
return CesiumMath.clamp(blended, 0.0, 1.0);
}
/**
*
* @param {number[]} data
* @param {number} texelsPerTile
* @param {number} tilesPerRow
* @param {Texture} texture
* @private
*/
function copyToInternalNodeTexture(data, texelsPerTile, tilesPerRow, texture) {
const channelCount = PixelFormat.componentsLength(texture.pixelFormat);
const tileCount = Math.ceil(data.length / texelsPerTile);
const copyWidth = Math.max(
1,
texelsPerTile * Math.min(tileCount, tilesPerRow),
);
const copyHeight = Math.max(1, Math.ceil(tileCount / tilesPerRow));
const textureData = new Uint8Array(copyWidth * copyHeight * channelCount);
for (let i = 0; i < data.length; i++) {
const val = data[i];
const startIndex = i * channelCount;
for (let j = 0; j < channelCount; j++) {
textureData[startIndex + j] = (val >>> (j * 8)) & 0xff;
}
}
const source = {
arrayBufferView: textureData,
width: copyWidth,
height: copyHeight,
};
const copyOptions = {
source: source,
xOffset: 0,
yOffset: 0,
};
texture.copyFrom(copyOptions);
}
/**
*
* @param {number[]} data
* @param {number} texelsPerTile
* @param {number} tilesPerRow
* @param {Texture} texture
* @private
*/
function copyToLeafNodeTexture(data, texelsPerTile, tilesPerRow, texture) {
const channelCount = PixelFormat.componentsLength(texture.pixelFormat);
const datasPerTile = 5;
const tileCount = Math.ceil(data.length / datasPerTile);
const copyWidth = Math.max(
1,
texelsPerTile * Math.min(tileCount, tilesPerRow),
);
const copyHeight = Math.max(1, Math.ceil(tileCount / tilesPerRow));
const textureData = new Uint8Array(copyWidth * copyHeight * channelCount);
for (let tileIndex = 0; tileIndex < tileCount; tileIndex++) {
const timeLerp = data[tileIndex * datasPerTile + 0];
const previousKeyframeLevelsAbove = data[tileIndex * datasPerTile + 1];
const nextKeyframeLevelsAbove = data[tileIndex * datasPerTile + 2];
const previousKeyframeMegatextureIndex = data[tileIndex * datasPerTile + 3];
const nextKeyframeMegatextureIndex = data[tileIndex * datasPerTile + 4];
const timeLerpCompressed = CesiumMath.clamp(
Math.floor(65536 * timeLerp),
0,
65535,
);
textureData[tileIndex * 8 + 0] = (timeLerpCompressed >>> 0) & 0xff;
textureData[tileIndex * 8 + 1] = (timeLerpCompressed >>> 8) & 0xff;
textureData[tileIndex * 8 + 2] = previousKeyframeLevelsAbove & 0xff;
textureData[tileIndex * 8 + 3] = nextKeyframeLevelsAbove & 0xff;
textureData[tileIndex * 8 + 4] =
(previousKeyframeMegatextureIndex >>> 0) & 0xff;
textureData[tileIndex * 8 + 5] =
(previousKeyframeMegatextureIndex >>> 8) & 0xff;
textureData[tileIndex * 8 + 6] =
(nextKeyframeMegatextureIndex >>> 0) & 0xff;
textureData[tileIndex * 8 + 7] =
(nextKeyframeMegatextureIndex >>> 8) & 0xff;
}
const source = {
arrayBufferView: textureData,
width: copyWidth,
height: copyHeight,
};
const copyOptions = {
source: source,
xOffset: 0,
yOffset: 0,
};
texture.copyFrom(copyOptions);
}
/**
* @param {number} tileCount
* @param {Cartesian3} dimensions
* @param {MetadataType[]} types
* @param {MetadataComponentType[]} componentTypes
* @private
*/
function getApproximateTextureMemoryByteLength(
tileCount,
dimensions,
types,
componentTypes,
) {
let textureMemoryByteLength = 0;
const length = types.length;
for (let i = 0; i < length; i++) {
const type = types[i];
const componentType = componentTypes[i];
const componentCount = MetadataType.getComponentCount(type);
textureMemoryByteLength +=
Megatexture.getApproximateTextureMemoryByteLength(
tileCount,
dimensions,
componentCount,
componentType,
);
}
return textureMemoryByteLength;
}
export default VoxelTraversal;
|