15832144755
2022-01-06 7b4c8991dca9cf2a809a95e239d144697d3afb56
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
import Cartesian3 from "../Core/Cartesian3.js";
import Check from "../Core/Check.js";
import clone from "../Core/clone.js";
import combine from "../Core/combine.js";
import defaultValue from "../Core/defaultValue.js";
import defined from "../Core/defined.js";
import destroyObject from "../Core/destroyObject.js";
import CesiumMath from "../Core/Math.js";
import HilbertOrder from "../Core/HilbertOrder.js";
import Matrix3 from "../Core/Matrix3.js";
import Rectangle from "../Core/Rectangle.js";
import S2Cell from "../Core/S2Cell.js";
import when from "../ThirdParty/when.js";
import ImplicitSubtree from "./ImplicitSubtree.js";
import ImplicitTileMetadata from "./ImplicitTileMetadata.js";
import hasExtension from "./hasExtension.js";
import MetadataSemantic from "./MetadataSemantic.js";
import parseBoundingVolumeSemantics from "./parseBoundingVolumeSemantics.js";
 
/**
 * A specialized {@link Cesium3DTileContent} that lazily evaluates an implicit
 * tileset. It is somewhat similar in operation to a
 * {@link Tileset3DTileContent} in that once the content is constructed, it
 * updates the tileset tree with more tiles. However, unlike external tilesets,
 * child subtrees are represented as additional placeholder nodes with
 * Implicit3DTileContent.
 * <p>
 * Implements the {@link Cesium3DTileContent} interface.
 * </p>
 *
 * @alias Implicit3DTileContent
 * @constructor
 *
 * @param {Cesium3DTileset} tileset The tileset this content belongs to
 * @param {Cesium3DTile} tile The tile this content belongs to.
 * @param {Resource} resource The resource for the tileset
 * @param {ArrayBuffer} arrayBuffer The array buffer that stores the content payload
 * @param {Number} [byteOffset=0] The offset into the array buffer
 * @private
 * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
 */
export default function Implicit3DTileContent(
  tileset,
  tile,
  resource,
  arrayBuffer,
  byteOffset
) {
  //>>includeStart('debug', pragmas.debug);
  Check.defined("tile.implicitTileset", tile.implicitTileset);
  Check.defined("tile.implicitCoordinates", tile.implicitCoordinates);
  //>>includeEnd('debug');
 
  var implicitTileset = tile.implicitTileset;
  var implicitCoordinates = tile.implicitCoordinates;
 
  this._implicitTileset = implicitTileset;
  this._implicitCoordinates = implicitCoordinates;
  this._implicitSubtree = undefined;
  this._tileset = tileset;
  this._tile = tile;
  this._resource = resource;
  this._readyPromise = when.defer();
 
  this.featurePropertiesDirty = false;
  this._groupMetadata = undefined;
 
  var templateValues = implicitCoordinates.getTemplateValues();
  var subtreeResource = implicitTileset.subtreeUriTemplate.getDerivedResource({
    templateValues: templateValues,
  });
  this._url = subtreeResource.getUrlComponent(true);
 
  initialize(this, arrayBuffer, byteOffset);
}
 
Object.defineProperties(Implicit3DTileContent.prototype, {
  featuresLength: {
    get: function () {
      return 0;
    },
  },
 
  pointsLength: {
    get: function () {
      return 0;
    },
  },
 
  trianglesLength: {
    get: function () {
      return 0;
    },
  },
 
  geometryByteLength: {
    get: function () {
      return 0;
    },
  },
 
  texturesByteLength: {
    get: function () {
      return 0;
    },
  },
 
  batchTableByteLength: {
    get: function () {
      return 0;
    },
  },
 
  innerContents: {
    get: function () {
      return undefined;
    },
  },
 
  readyPromise: {
    get: function () {
      return this._readyPromise.promise;
    },
  },
 
  tileset: {
    get: function () {
      return this._tileset;
    },
  },
 
  tile: {
    get: function () {
      return this._tile;
    },
  },
 
  url: {
    get: function () {
      return this._url;
    },
  },
 
  batchTable: {
    get: function () {
      return undefined;
    },
  },
 
  groupMetadata: {
    get: function () {
      return this._groupMetadata;
    },
    set: function (value) {
      this._groupMetadata = value;
    },
  },
});
 
/**
 * Initialize the implicit content by parsing the subtree resource and setting
 * up a promise chain to expand the immediate subtree.
 *
 * @param {Implicit3DTileContent} content The implicit content
 * @param {ArrayBuffer} arrayBuffer The ArrayBuffer containing a subtree binary
 * @param {Number} [byteOffset=0] The byte offset into the arrayBuffer
 * @private
 */
function initialize(content, arrayBuffer, byteOffset) {
  // Parse the subtree file
  byteOffset = defaultValue(byteOffset, 0);
  var uint8Array = new Uint8Array(arrayBuffer, byteOffset);
  var subtree = new ImplicitSubtree(
    content._resource,
    uint8Array,
    content._implicitTileset,
    content._implicitCoordinates
  );
  content._implicitSubtree = subtree;
 
  subtree.readyPromise
    .then(function () {
      expandSubtree(content, subtree);
      content._readyPromise.resolve();
    })
    .otherwise(function (error) {
      content._readyPromise.reject(error);
    });
}
 
/**
 * Expand a single subtree placeholder tile. This transcodes the subtree into
 * a tree of {@link Cesium3DTile}. The root of this tree is stored in
 * the placeholder tile's children array. This method also creates placeholder
 * tiles for the child subtrees to be lazily expanded as needed.
 *
 * @param {Implicit3DTileContent} content The content
 * @param {ImplicitSubtree} subtree The parsed subtree
 * @private
 */
function expandSubtree(content, subtree) {
  var placeholderTile = content._tile;
 
  // Parse the tiles inside this immediate subtree
  var childIndex = content._implicitCoordinates.childIndex;
  var results = transcodeSubtreeTiles(
    content,
    subtree,
    placeholderTile,
    childIndex
  );
 
  // Link the new subtree to the existing placeholder tile.
  placeholderTile.children.push(results.rootTile);
 
  // for each child subtree, make new placeholder tiles
  var childSubtrees = listChildSubtrees(content, subtree, results.bottomRow);
  for (var i = 0; i < childSubtrees.length; i++) {
    var subtreeLocator = childSubtrees[i];
    var leafTile = subtreeLocator.tile;
    var implicitChildTile = makePlaceholderChildSubtree(
      content,
      leafTile,
      subtreeLocator.childIndex
    );
    leafTile.children.push(implicitChildTile);
  }
}
 
/**
 * A pair of (tile, childIndex) used for finding child subtrees.
 *
 * @typedef {Object} ChildSubtreeLocator
 * @property {Cesium3DTile} tile One of the tiles in the bottommost row of the subtree.
 * @property {Number} childIndex The morton index of the child tile relative to its parent
 * @private
 */
 
/**
 * Determine what child subtrees exist and return a list of information
 *
 * @param {Implicit3DTileContent} content The implicit content
 * @param {ImplicitSubtree} subtree The subtree for looking up availability
 * @param {Array<Cesium3DTile|undefined>} bottomRow The bottom row of tiles in a transcoded subtree
 * @returns {ChildSubtreeLocator[]} A list of identifiers for the child subtrees.
 * @private
 */
function listChildSubtrees(content, subtree, bottomRow) {
  var results = [];
  var branchingFactor = content._implicitTileset.branchingFactor;
  for (var i = 0; i < bottomRow.length; i++) {
    var leafTile = bottomRow[i];
    if (!defined(leafTile)) {
      continue;
    }
 
    for (var j = 0; j < branchingFactor; j++) {
      var index = i * branchingFactor + j;
      if (subtree.childSubtreeIsAvailableAtIndex(index)) {
        results.push({
          tile: leafTile,
          childIndex: j,
        });
      }
    }
  }
  return results;
}
 
/**
 * Results of transcodeSubtreeTiles, containing the root tile of the
 * subtree and the bottom row of nodes for further processing.
 *
 * @typedef {Object} TranscodedSubtree
 * @property {Cesium3DTile} rootTile The transcoded root tile of the subtree
 * @property {Array<Cesium3DTile|undefined>} bottomRow The bottom row of transcoded tiles. This is helpful for processing child subtrees
 * @private
 */
 
/**
 * Transcode the implicitly-defined tiles within this subtree and generate
 * explicit {@link Cesium3DTile} objects. This function only transcode tiles,
 * child subtrees are handled separately.
 *
 * @param {Implicit3DTileContent} content The implicit content
 * @param {ImplicitSubtree} subtree The subtree to get availability information
 * @param {Cesium3DTile} placeholderTile The placeholder tile, used for constructing the subtree root tile
 * @param {Number} childIndex The Morton index of the root tile relative to parentOfRootTile
 * @returns {TranscodedSubtree} The newly created subtree of tiles
 * @private
 */
function transcodeSubtreeTiles(content, subtree, placeholderTile, childIndex) {
  var rootBitIndex = 0;
  var rootParentIsPlaceholder = true;
  var rootTile = deriveChildTile(
    content,
    subtree,
    placeholderTile,
    childIndex,
    rootBitIndex,
    rootParentIsPlaceholder
  );
 
  // Sliding window over the levels of the tree.
  // Each row is branchingFactor * length of previous row
  // Tiles within a row are ordered by Morton index.
  var parentRow = [rootTile];
  var currentRow = [];
 
  var implicitTileset = content._implicitTileset;
  for (var level = 1; level < implicitTileset.subtreeLevels; level++) {
    var levelOffset = subtree.getLevelOffset(level);
    var numberOfChildren = implicitTileset.branchingFactor * parentRow.length;
    for (
      var childMortonIndex = 0;
      childMortonIndex < numberOfChildren;
      childMortonIndex++
    ) {
      var childBitIndex = levelOffset + childMortonIndex;
 
      if (!subtree.tileIsAvailableAtIndex(childBitIndex)) {
        currentRow.push(undefined);
        continue;
      }
 
      var parentMortonIndex = subtree.getParentMortonIndex(childMortonIndex);
      var parentTile = parentRow[parentMortonIndex];
      var childChildIndex = childMortonIndex % implicitTileset.branchingFactor;
      var childTile = deriveChildTile(
        content,
        subtree,
        parentTile,
        childChildIndex,
        childBitIndex
      );
      parentTile.children.push(childTile);
      currentRow.push(childTile);
    }
 
    parentRow = currentRow;
    currentRow = [];
  }
 
  return {
    rootTile: rootTile,
    // At the end of the last loop, bottomRow was moved to parentRow
    bottomRow: parentRow,
  };
}
 
function getGeometricError(tileMetadata, implicitTileset, implicitCoordinates) {
  var semantic = MetadataSemantic.TILE_GEOMETRIC_ERROR;
 
  if (defined(tileMetadata) && tileMetadata.hasPropertyBySemantic(semantic)) {
    return tileMetadata.getPropertyBySemantic(semantic);
  }
 
  return (
    implicitTileset.geometricError / Math.pow(2, implicitCoordinates.level)
  );
}
 
/**
 * Given a parent tile and information about which child to create, derive
 * the properties of the child tile implicitly.
 * <p>
 * This creates a real tile for rendering, not a placeholder tile like some of
 * the other methods of ImplicitTileset.
 * </p>
 *
 * @param {Implicit3DTileContent} implicitContent The implicit content
 * @param {ImplicitSubtree} subtree The subtree the child tile belongs to
 * @param {Cesium3DTile} parentTile The parent of the new child tile
 * @param {Number} childIndex The morton index of the child tile relative to its parent
 * @param {Number} childBitIndex The index of the child tile within the tile's availability information.
 * @param {Boolean} [parentIsPlaceholderTile=false] True if parentTile is a placeholder tile. This is true for the root of each subtree.
 * @returns {Cesium3DTile} The new child tile.
 * @private
 */
function deriveChildTile(
  implicitContent,
  subtree,
  parentTile,
  childIndex,
  childBitIndex,
  parentIsPlaceholderTile
) {
  var implicitTileset = implicitContent._implicitTileset;
  var implicitCoordinates;
  if (defaultValue(parentIsPlaceholderTile, false)) {
    implicitCoordinates = parentTile.implicitCoordinates;
  } else {
    implicitCoordinates = parentTile.implicitCoordinates.getChildCoordinates(
      childIndex
    );
  }
 
  // Parse metadata and bounding volume semantics at the beginning
  // as the bounding volumes are needed below.
  var tileMetadata;
  var tileBounds;
  var contentBounds;
  if (defined(subtree.metadataExtension)) {
    var metadataTable = subtree.metadataTable;
    tileMetadata = new ImplicitTileMetadata({
      class: metadataTable.class,
      implicitCoordinates: implicitCoordinates,
      implicitSubtree: subtree,
    });
 
    var boundingVolumeSemantics = parseBoundingVolumeSemantics(tileMetadata);
    tileBounds = boundingVolumeSemantics.tile;
    contentBounds = boundingVolumeSemantics.content;
  }
 
  var boundingVolume = getTileBoundingVolume(
    implicitTileset,
    implicitCoordinates,
    childIndex,
    parentIsPlaceholderTile,
    parentTile,
    tileBounds
  );
 
  var contentJsons = [];
  for (var i = 0; i < implicitTileset.contentCount; i++) {
    if (!subtree.contentIsAvailableAtIndex(childBitIndex, i)) {
      continue;
    }
    var childContentTemplate = implicitTileset.contentUriTemplates[i];
    var childContentUri = childContentTemplate.getDerivedResource({
      templateValues: implicitCoordinates.getTemplateValues(),
    }).url;
    var contentJson = {
      uri: childContentUri,
    };
 
    var contentBoundingVolume = getContentBoundingVolume(
      boundingVolume,
      contentBounds
    );
 
    if (defined(contentBoundingVolume)) {
      contentJson.boundingVolume = contentBoundingVolume;
    }
 
    // combine() is used to pass through any additional properties the
    // user specified such as extras or extensions
    contentJsons.push(combine(contentJson, implicitTileset.contentHeaders[i]));
  }
 
  var childGeometricError = getGeometricError(
    tileMetadata,
    implicitTileset,
    implicitCoordinates
  );
 
  var tileJson = {
    boundingVolume: boundingVolume,
    geometricError: childGeometricError,
    refine: implicitTileset.refine,
  };
 
  if (contentJsons.length === 1) {
    tileJson.content = contentJsons[0];
  } else if (contentJsons.length > 1) {
    tileJson.extensions = {
      "3DTILES_multiple_contents": {
        content: contentJsons,
      },
    };
  }
 
  // combine() is used to pass through any additional properties the
  // user specified such as extras or extensions.
  var deep = true;
  var rootHeader = clone(implicitTileset.tileHeader, deep);
  delete rootHeader.boundingVolume;
  var combinedTileJson = combine(tileJson, rootHeader, deep);
 
  var childTile = makeTile(
    implicitContent,
    implicitTileset.baseResource,
    combinedTileJson,
    parentTile
  );
  childTile.implicitCoordinates = implicitCoordinates;
  childTile.implicitSubtree = subtree;
  childTile.metadata = tileMetadata;
 
  return childTile;
}
 
/**
 * Checks whether the bounding volume's heights can be updated.
 * Returns true if the minimumHeight/maximumHeight parameter
 * is defined and the bounding volume is a region or S2 cell.
 *
 * @param {Object} [boundingVolume] The bounding voume
 * @param {Object} [tileBounds] The tile bounds
 * @param {Number} [tileBounds.minimumHeight] The minimum height
 * @param {Number} [tileBounds.maximumHeight] The maximum height
 * @returns {Boolean} Whether the bounding volume's heights can be updated
 * @private
 */
function canUpdateHeights(boundingVolume, tileBounds) {
  return (
    defined(boundingVolume) &&
    defined(tileBounds) &&
    (defined(tileBounds.minimumHeight) || defined(tileBounds.maximumHeight)) &&
    (hasExtension(boundingVolume, "3DTILES_bounding_volume_S2") ||
      defined(boundingVolume.region))
  );
}
 
/**
 * Update the minimum and maximum height of the bounding volume.
 * This is typically used to tighten a bounding volume using the
 * <code>TILE_MINIMUM_HEIGHT</code> and <code>TILE_MAXIMUM_HEIGHT</code>
 * semantics. Heights are only updated if the respective
 * minimumHeight/maximumHeight parameter is defined and the
 * bounding volume is a region or S2 cell.
 *
 * @param {Object} boundingVolume The bounding voume
 * @param {Object} [tileBounds] The tile bounds
 * @param {Number} [tileBounds.minimumHeight] The new minimum height
 * @param {Number} [tileBounds.maximumHeight] The new maximum height
 * @private
 */
function updateHeights(boundingVolume, tileBounds) {
  if (
    hasExtension(boundingVolume, "3DTILES_bounding_volume_S2") &&
    defined(tileBounds)
  ) {
    updateS2CellHeights(
      boundingVolume.extensions["3DTILES_bounding_volume_S2"],
      tileBounds.minimumHeight,
      tileBounds.maximumHeight
    );
  } else if (defined(boundingVolume.region) && defined(tileBounds)) {
    updateRegionHeights(
      boundingVolume.region,
      tileBounds.minimumHeight,
      tileBounds.maximumHeight
    );
  }
}
 
/**
 * For a bounding region, update the minimum and maximum height. This
 * is typically used to tighten a bounding volume using the
 * <code>TILE_MINIMUM_HEIGHT</code> and <code>TILE_MAXIMUM_HEIGHT</code>
 * semantics. Heights are only updated if the respective
 * minimumHeight/maximumHeight parameter is defined.
 *
 * @param {Array} region A 6-element array describing the bounding region
 * @param {Number} [minimumHeight] The new minimum height
 * @param {Number} [maximumHeight] The new maximum height
 * @private
 */
function updateRegionHeights(region, minimumHeight, maximumHeight) {
  if (defined(minimumHeight)) {
    region[4] = minimumHeight;
  }
 
  if (defined(maximumHeight)) {
    region[5] = maximumHeight;
  }
}
 
/**
 * For a bounding S2 cell, update the minimum and maximum height. This
 * is typically used to tighten a bounding volume using the
 * <code>TILE_MINIMUM_HEIGHT</code> and <code>TILE_MAXIMUM_HEIGHT</code>
 * semantics. Heights are only updated if the respective
 * minimumHeight/maximumHeight parameter is defined.
 *
 * @param {Object} s2CellVolume An object describing the S2 cell
 * @param {Number} [minimumHeight] The new minimum height
 * @param {Number} [maximumHeight] The new maximum height
 * @private
 */
function updateS2CellHeights(s2CellVolume, minimumHeight, maximumHeight) {
  if (defined(minimumHeight)) {
    s2CellVolume.minimumHeight = minimumHeight;
  }
 
  if (defined(maximumHeight)) {
    s2CellVolume.maximumHeight = maximumHeight;
  }
}
 
/**
 * Gets the tile's bounding volume, which may be specified via
 * metadata semantics such as TILE_BOUNDING_BOX or implicitly
 * derived from the implicit root tile's bounding volume.
 * <p>
 * Priority of bounding volume types:
 * <ol>
 * <li>Explicit min/max height
 *   <ol>
 *     <li>With explicit region</li>
 *     <li>With implicit S2</li>
 *     <li>With implicit region</li>
 *   </ol>
 * </li>
 * <li>Explicit box</li>
 * <li>Explicit region</li>
 * <li>Explicit sphere</li>
 * <li>Implicit S2</li>
 * <li>Implicit box</li>
 * <li>Implicit region</li>
 * </ol>
 * </p>
 *
 * @param {ImplicitTileset} implicitTileset The implicit tileset struct which holds the root bounding volume
 * @param {ImplicitTileCoordinates} implicitCoordinates The coordinates of the child tile
 * @param {Number} childIndex The morton index of the child tile relative to its parent
 * @param {Boolean} parentIsPlaceholderTile True if parentTile is a placeholder tile. This is true for the root of each subtree.
 * @param {Cesium3DTile} parentTile The parent of the new child tile
 * @param {Object} [tileBounds] The tile bounds
 * @returns {Object} An object containing the JSON for a bounding volume
 * @private
 */
function getTileBoundingVolume(
  implicitTileset,
  implicitCoordinates,
  childIndex,
  parentIsPlaceholderTile,
  parentTile,
  tileBounds
) {
  var boundingVolume;
 
  if (
    !defined(tileBounds) ||
    !defined(tileBounds.boundingVolume) ||
    (!canUpdateHeights(tileBounds.boundingVolume, tileBounds) &&
      canUpdateHeights(implicitTileset.boundingVolume, tileBounds))
  ) {
    boundingVolume = deriveBoundingVolume(
      implicitTileset,
      implicitCoordinates,
      childIndex,
      defaultValue(parentIsPlaceholderTile, false),
      parentTile
    );
  } else {
    boundingVolume = tileBounds.boundingVolume;
  }
 
  // The TILE_MINIMUM_HEIGHT and TILE_MAXIMUM_HEIGHT metadata semantics
  // can be used to tighten the bounding volume
  updateHeights(boundingVolume, tileBounds);
 
  return boundingVolume;
}
 
/**
 * Gets the content bounding volume, which may be specified via
 * metadata semantics such as CONTENT_BOUNDING_BOX.
 * <p>
 * Priority of bounding volume types:
 * <ol>
 * <li>Explicit min/max height
 *   <ol>
 *     <li>With explicit region</li>
 *     <li>With tile bounding volume (S2 or region)</li>
 *   </ol>
 * </li>
 * <li>Explicit box</li>
 * <li>Explicit region</li>
 * <li>Explicit sphere</li>
 * <li>Tile bounding volume (when content.boundingVolume is undefined)</li>
 * </ol>
 * </p>
 *
 * @param {Object} tileBoundingVolume An object containing the JSON for the tile's bounding volume
 * @param {Object} [contentBounds] The content bounds
 * @returns {Object|undefined} An object containing the JSON for a bounding volume, or <code>undefined</code> if there is no bounding volume
 * @private
 */
function getContentBoundingVolume(tileBoundingVolume, contentBounds) {
  // content bounding volumes can only be specified via
  // metadata semantics such as CONTENT_BOUNDING_BOX
  var contentBoundingVolume;
  if (defined(contentBounds)) {
    contentBoundingVolume = contentBounds.boundingVolume;
  }
 
  // The CONTENT_MINIMUM_HEIGHT and CONTENT_MAXIMUM_HEIGHT metadata semantics
  // can be used to tighten the bounding volume
  if (canUpdateHeights(contentBoundingVolume, contentBounds)) {
    updateHeights(contentBoundingVolume, contentBounds);
  } else if (canUpdateHeights(tileBoundingVolume, contentBounds)) {
    contentBoundingVolume = clone(tileBoundingVolume, true);
    updateHeights(contentBoundingVolume, contentBounds);
  }
 
  return contentBoundingVolume;
}
 
/**
 * Given the coordinates of a tile, derive its bounding volume from the root.
 *
 * @param {ImplicitTileset} implicitTileset The implicit tileset struct which holds the root bounding volume
 * @param {ImplicitTileCoordinates} implicitCoordinates The coordinates of the child tile
 * @param {Number} childIndex The morton index of the child tile relative to its parent
 * @param {Boolean} parentIsPlaceholderTile True if parentTile is a placeholder tile. This is true for the root of each subtree.
 * @param {Cesium3DTile} parentTile The parent of the new child tile
 * @returns {Object} An object containing the JSON for a bounding volume
 * @private
 */
function deriveBoundingVolume(
  implicitTileset,
  implicitCoordinates,
  childIndex,
  parentIsPlaceholderTile,
  parentTile
) {
  var rootBoundingVolume = implicitTileset.boundingVolume;
 
  if (hasExtension(rootBoundingVolume, "3DTILES_bounding_volume_S2")) {
    return deriveBoundingVolumeS2(
      parentIsPlaceholderTile,
      parentTile,
      childIndex,
      implicitCoordinates.level,
      implicitCoordinates.x,
      implicitCoordinates.y,
      implicitCoordinates.z
    );
  }
 
  if (defined(rootBoundingVolume.region)) {
    var childRegion = deriveBoundingRegion(
      rootBoundingVolume.region,
      implicitCoordinates.level,
      implicitCoordinates.x,
      implicitCoordinates.y,
      implicitCoordinates.z
    );
 
    return {
      region: childRegion,
    };
  }
 
  var childBox = deriveBoundingBox(
    rootBoundingVolume.box,
    implicitCoordinates.level,
    implicitCoordinates.x,
    implicitCoordinates.y,
    implicitCoordinates.z
  );
 
  return {
    box: childBox,
  };
}
 
/**
 * Derive a bounding volume for a descendant tile (child, grandchild, etc.),
 * assuming a quadtree or octree implicit tiling scheme. The (level, x, y, [z])
 * coordinates are given to select the descendant tile and compute its position
 * and dimensions.
 * <p>
 * If z is present, octree subdivision is used. Otherwise, quadtree subdivision
 * is used. Quadtrees are always divided at the midpoint of the the horizontal
 * dimensions, i.e. (x, y), leaving the z axis unchanged.
 * </p>
 *
 * @param {Boolean} parentIsPlaceholderTile True if parentTile is a placeholder tile. This is true for the root of each subtree.
 * @param {Cesium3DTile} parentTile The parent of the new child tile
 * @param {Number} childIndex The morton index of the child tile relative to its parent
 * @param {Number} level The level of the descendant tile relative to the root implicit tile
 * @param {Number} x The x coordinate of the descendant tile
 * @param {Number} y The y coordinate of the descendant tile
 * @param {Number} [z] The z coordinate of the descendant tile (octree only)
 * @returns {Object} An object with the 3DTILES_bounding_volume_S2 extension.
 * @private
 */
function deriveBoundingVolumeS2(
  parentIsPlaceholderTile,
  parentTile,
  childIndex,
  level,
  x,
  y,
  z
) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.bool("parentIsPlaceholderTile", parentIsPlaceholderTile);
  Check.typeOf.object("parentTile", parentTile);
  Check.typeOf.number("childIndex", childIndex);
  Check.typeOf.number("level", level);
  Check.typeOf.number("x", x);
  Check.typeOf.number("y", y);
  if (defined(z)) {
    Check.typeOf.number("z", z);
  }
  //>>includeEnd('debug');
 
  var boundingVolumeS2 = parentTile._boundingVolume;
 
  // Handle the placeholder tile case, where we just duplicate the placeholder's bounding volume.
  if (parentIsPlaceholderTile) {
    return {
      extensions: {
        "3DTILES_bounding_volume_S2": {
          token: S2Cell.getTokenFromId(boundingVolumeS2.s2Cell._cellId),
          minimumHeight: boundingVolumeS2.minimumHeight,
          maximumHeight: boundingVolumeS2.maximumHeight,
        },
      },
    };
  }
 
  // Extract the first 3 face bits from the 64-bit S2 cell ID.
  // eslint-disable-next-line
  var face = Number(parentTile._boundingVolume.s2Cell._cellId >> BigInt(61));
  // The Hilbert curve is rotated for the "odd" faces on the S2 Earthcube.
  // See http://s2geometry.io/devguide/img/s2cell_global.jpg
  var position =
    face % 2 === 0
      ? HilbertOrder.encode2D(level, x, y)
      : HilbertOrder.encode2D(level, y, x);
  // eslint-disable-next-line
  var cell = S2Cell.fromFacePositionLevel(face, BigInt(position), level);
 
  var minHeight, maxHeight;
  if (defined(z)) {
    var midpointHeight =
      (boundingVolumeS2.maximumHeight + boundingVolumeS2.minimumHeight) / 2;
    minHeight =
      childIndex < 4 ? boundingVolumeS2.minimumHeight : midpointHeight;
    maxHeight =
      childIndex < 4 ? midpointHeight : boundingVolumeS2.maximumHeight;
  } else {
    minHeight = boundingVolumeS2.minimumHeight;
    maxHeight = boundingVolumeS2.maximumHeight;
  }
 
  return {
    extensions: {
      "3DTILES_bounding_volume_S2": {
        token: S2Cell.getTokenFromId(cell._cellId),
        minimumHeight: minHeight,
        maximumHeight: maxHeight,
      },
    },
  };
}
 
var scratchScaleFactors = new Cartesian3();
var scratchRootCenter = new Cartesian3();
var scratchCenter = new Cartesian3();
var scratchHalfAxes = new Matrix3();
/**
 * Derive a bounding volume for a descendant tile (child, grandchild, etc.),
 * assuming a quadtree or octree implicit tiling scheme. The (level, x, y, [z])
 * coordinates are given to select the descendant tile and compute its position
 * and dimensions.
 * <p>
 * If z is present, octree subdivision is used. Otherwise, quadtree subdivision
 * is used. Quadtrees are always divided at the midpoint of the the horizontal
 * dimensions, i.e. (x, y), leaving the z axis unchanged.
 * </p>
 * <p>
 * This computes the child volume directly from the root bounding volume rather
 * than recursively subdividing to minimize floating point error.
 * </p>
 *
 * @param {Number[]} rootBox An array of 12 numbers representing the bounding box of the root tile
 * @param {Number} level The level of the descendant tile relative to the root implicit tile
 * @param {Number} x The x coordinate of the descendant tile
 * @param {Number} y The y coordinate of the descendant tile
 * @param {Number} [z] The z coordinate of the descendant tile (octree only)
 * @returns {Number[]} An array of 12 numbers representing the bounding box of the descendant tile.
 * @private
 */
function deriveBoundingBox(rootBox, level, x, y, z) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("rootBox", rootBox);
  Check.typeOf.number("level", level);
  Check.typeOf.number("x", x);
  Check.typeOf.number("y", y);
  if (defined(z)) {
    Check.typeOf.number("z", z);
  }
  //>>includeEnd('debug');
 
  if (level === 0) {
    return rootBox;
  }
 
  var rootCenter = Cartesian3.unpack(rootBox, 0, scratchRootCenter);
  var rootHalfAxes = Matrix3.unpack(rootBox, 3, scratchHalfAxes);
 
  var tileScale = Math.pow(2, -level);
  var modelSpaceX = -1 + (2 * x + 1) * tileScale;
  var modelSpaceY = -1 + (2 * y + 1) * tileScale;
 
  var modelSpaceZ = 0;
  var scaleFactors = Cartesian3.fromElements(
    tileScale,
    tileScale,
    1,
    scratchScaleFactors
  );
 
  if (defined(z)) {
    modelSpaceZ = -1 + (2 * z + 1) * tileScale;
    scaleFactors.z = tileScale;
  }
 
  var center = Cartesian3.fromElements(
    modelSpaceX,
    modelSpaceY,
    modelSpaceZ,
    scratchCenter
  );
  center = Matrix3.multiplyByVector(rootHalfAxes, center, scratchCenter);
  center = Cartesian3.add(center, rootCenter, scratchCenter);
 
  var halfAxes = Matrix3.clone(rootHalfAxes);
  halfAxes = Matrix3.multiplyByScale(halfAxes, scaleFactors, halfAxes);
 
  var childBox = new Array(12);
  Cartesian3.pack(center, childBox);
  Matrix3.pack(halfAxes, childBox, 3);
  return childBox;
}
 
var scratchRectangle = new Rectangle();
/**
 * Derive a bounding volume for a descendant tile (child, grandchild, etc.),
 * assuming a quadtree or octree implicit tiling scheme. The (level, x, y, [z])
 * coordinates are given to select the descendant tile and compute its position
 * and dimensions.
 * <p>
 * If z is present, octree subdivision is used. Otherwise, quadtree subdivision
 * is used. Quadtrees are always divided at the midpoint of the the horizontal
 * dimensions, i.e. (mid_longitude, mid_latitude), leaving the height values
 * unchanged.
 * </p>
 * <p>
 * This computes the child volume directly from the root bounding volume rather
 * than recursively subdividing to minimize floating point error.
 * </p>
 * @param {Number[]} rootRegion An array of 6 numbers representing the root implicit tile
 * @param {Number} level The level of the descendant tile relative to the root implicit tile
 * @param {Number} x The x coordinate of the descendant tile
 * @param {Number} y The x coordinate of the descendant tile
 * @param {Number} [z] The z coordinate of the descendant tile (octree only)
 * @returns {Number[]} An array of 6 numbers representing the bounding region of the descendant tile
 * @private
 */
function deriveBoundingRegion(rootRegion, level, x, y, z) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("rootRegion", rootRegion);
  Check.typeOf.number("level", level);
  Check.typeOf.number("x", x);
  Check.typeOf.number("y", y);
  if (defined(z)) {
    Check.typeOf.number("z", z);
  }
  //>>includeEnd('debug');
 
  if (level === 0) {
    return rootRegion.slice();
  }
 
  var rectangle = Rectangle.unpack(rootRegion, 0, scratchRectangle);
  var rootMinimumHeight = rootRegion[4];
  var rootMaximumHeight = rootRegion[5];
  var tileScale = Math.pow(2, -level);
 
  var childWidth = tileScale * rectangle.width;
  var west = CesiumMath.negativePiToPi(rectangle.west + x * childWidth);
  var east = CesiumMath.negativePiToPi(west + childWidth);
 
  var childHeight = tileScale * rectangle.height;
  var south = CesiumMath.negativePiToPi(rectangle.south + y * childHeight);
  var north = CesiumMath.negativePiToPi(south + childHeight);
 
  // Height is only subdivided for octrees; It remains constant for quadtrees.
  var minimumHeight = rootMinimumHeight;
  var maximumHeight = rootMaximumHeight;
  if (defined(z)) {
    var childThickness = tileScale * (rootMaximumHeight - rootMinimumHeight);
    minimumHeight += z * childThickness;
    maximumHeight = minimumHeight + childThickness;
  }
 
  return [west, south, east, north, minimumHeight, maximumHeight];
}
 
/**
 * Create a placeholder 3D Tile whose content will be an Implicit3DTileContent
 * for lazy evaluation of a child subtree.
 *
 * @param {Implicit3DTileContent} content The content object.
 * @param {Cesium3DTile} parentTile The parent of the new child subtree.
 * @param {Number} childIndex The morton index of the child tile relative to its parent
 * @returns {Cesium3DTile} The new placeholder tile
 * @private
 */
function makePlaceholderChildSubtree(content, parentTile, childIndex) {
  var implicitTileset = content._implicitTileset;
  var implicitCoordinates = parentTile.implicitCoordinates.getChildCoordinates(
    childIndex
  );
 
  var childBoundingVolume = deriveBoundingVolume(
    implicitTileset,
    implicitCoordinates,
    childIndex,
    false,
    parentTile
  );
 
  // Ignore tile metadata when computing geometric error for the placeholder tile
  // since the child subtree's metadata hasn't been loaded yet.
  // The actual geometric error will be computed in deriveChildTile.
  var childGeometricError = getGeometricError(
    undefined,
    implicitTileset,
    implicitCoordinates
  );
 
  var childContentUri = implicitTileset.subtreeUriTemplate.getDerivedResource({
    templateValues: implicitCoordinates.getTemplateValues(),
  }).url;
  var tileJson = {
    boundingVolume: childBoundingVolume,
    geometricError: childGeometricError,
    refine: implicitTileset.refine,
    content: {
      uri: childContentUri,
    },
  };
 
  var tile = makeTile(
    content,
    implicitTileset.baseResource,
    tileJson,
    parentTile
  );
  tile.implicitTileset = implicitTileset;
  tile.implicitCoordinates = implicitCoordinates;
  return tile;
}
 
/**
 * Make a {@link Cesium3DTile}. This uses the content's tile's constructor instead
 * of importing Cesium3DTile. This is to avoid a circular dependency between
 * this file and Cesium3DTile.js
 * @param {Implicit3DTileContent} content The implicit content
 * @param {Resource} baseResource The base resource for the tileset
 * @param {Object} tileJson The JSON header for the tile
 * @param {Cesium3DTile} parentTile The parent of the new tile
 * @returns {Cesium3DTile} The newly created tile.
 * @private
 */
function makeTile(content, baseResource, tileJson, parentTile) {
  var Cesium3DTile = content._tile.constructor;
  return new Cesium3DTile(content._tileset, baseResource, tileJson, parentTile);
}
 
/**
 * Part of the {@link Cesium3DTileContent} interface.  <code>Implicit3DTileContent</code>
 * always returns <code>false</code> since a tile of this type does not have any features.
 * @private
 */
Implicit3DTileContent.prototype.hasProperty = function (batchId, name) {
  return false;
};
 
/**
 * Part of the {@link Cesium3DTileContent} interface.  <code>Implicit3DTileContent</code>
 * always returns <code>undefined</code> since a tile of this type does not have any features.
 * @private
 */
Implicit3DTileContent.prototype.getFeature = function (batchId) {
  return undefined;
};
 
Implicit3DTileContent.prototype.applyDebugSettings = function (
  enabled,
  color
) {};
 
Implicit3DTileContent.prototype.applyStyle = function (style) {};
 
Implicit3DTileContent.prototype.update = function (tileset, frameState) {};
 
Implicit3DTileContent.prototype.isDestroyed = function () {
  return false;
};
 
Implicit3DTileContent.prototype.destroy = function () {
  this._implicitSubtree =
    this._implicitSubtree && this._implicitSubtree.destroy();
  return destroyObject(this);
};
 
// Exposed for testing
Implicit3DTileContent._deriveBoundingBox = deriveBoundingBox;
Implicit3DTileContent._deriveBoundingRegion = deriveBoundingRegion;
Implicit3DTileContent._deriveBoundingVolumeS2 = deriveBoundingVolumeS2;