<template>
  <div class="app-container home">
    <div id="cesiumContainer"></div>
  </div>
</template>
<script>
export default {
  name: "cesium",
  data() {
    return {};
  },
  created() {
    var that = this;
    this.$nextTick(() => {
      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI2ZmY5ZWUyZS00MjQwLTQzZjUtYTBjZi02ZWZiYzJhMmY2NTYiLCJpZCI6MTMxMzY5LCJpYXQiOjE3NDE2NzY4Mzh9.QD-8cQI_VqPG2t-S8KxLyMFux0R429lfTdhQWrdeWhE";
      const viewer = new Cesium.Viewer("cesiumContainer", {
        homeButton: false,
        sceneModePicker: false,
        baseLayerPicker: false,
        animation: false,
        infoBox: false,
        selectionIndicator: false,
        geocoder: false,
        timeline: false,
        fullscreenButton: false,
        shouldAnimate: false,
        scene3DOnly: true,
        navigationHelpButton: false,
      });
      viewer.cesiumWidget.creditContainer.style.display = "none";

      // 使用 fromUrl 方法加载模型
      Cesium.Cesium3DTileset.fromUrl("/terra_b3dms/tileset.json")
        .then((tileset) => {
          viewer.scene.primitives.add(tileset);
          viewer.zoomTo(tileset);

          // 调整模型高度
          var heightOffset = -330.0; // 调整这个值以匹配地形高度
          var boundingSphere = tileset.boundingSphere;
          var cartographic = Cesium.Cartographic.fromCartesian(
            boundingSphere.center
          );

          var surface = Cesium.Cartesian3.fromRadians(
            cartographic.longitude,
            cartographic.latitude,
            0.0
          );

          var offset = Cesium.Cartesian3.fromRadians(
            cartographic.longitude,
            cartographic.latitude,
            cartographic.height + heightOffset
          );

          var translation = Cesium.Cartesian3.subtract(
            offset,
            surface,
            new Cesium.Cartesian3()
          );

          tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);

          tileset.maximumMemoryUsage = 1024 * 1024;
          tileset.maximumScreenSpaceError = 4;

          // 开启地形深度检测
          viewer.scene.globe.depthTestAgainstTerrain = true;
        })
        .catch((error) => {
          console.error("模型加载失败:", error);
        });
    });
  },
  methods: {},
};
</script>

<style scoped lang="scss">
.home {
  width: 100%;
  height: 100%;
  #cesiumContainer {
    width: 100%;
    height: 100%;
  }
}
</style>
