// Use this code in for example Cesium Sandcastle to view your landscape in the
// Cesium globe. It will clip the Cesium World Terrain and insert your landscape.
// It will also increase the texture memory limit to support the amount of textures
// required.

// See README.TXT for how to import the landscape into Cesium ion.
// Replace <ACCESS_TOKEN> with an access token created in your Cesium ion account
// and replace <ASSET_ID> with the identification number of your imported asset.


function clipTerrain(viewer, polygon) {
  var clippingPlanes = [];
  var numPoints = polygon.length;
  for (var i = 0; i < numPoints; ++i) {
    var currentPoint = polygon[i];
    var nextPoint = polygon[i === numPoints - 1 ? 0 : i + 1];
    var avgPoint = new Cesium.Cartesian3();
    Cesium.Cartesian3.add(currentPoint, nextPoint, avgPoint);
    Cesium.Cartesian3.multiplyByScalar(avgPoint, 0.5, avgPoint);

    var up = new Cesium.Cartesian3();
    Cesium.Cartesian3.normalize(avgPoint, up);
    var right = new Cesium.Cartesian3();
    Cesium.Cartesian3.subtract(nextPoint, avgPoint, right);
    Cesium.Cartesian3.normalize(right, right);

    var normal = new Cesium.Cartesian3();
    Cesium.Cartesian3.cross(right, up, normal);
    Cesium.Cartesian3.normalize(normal, normal);

    var distance = Cesium.Plane.getPointDistance(
      new Cesium.Plane(normal, 0.0),
      avgPoint
    );

    clippingPlanes.push(new Cesium.ClippingPlane(normal, distance));
  }

  viewer.scene.globe.clippingPlanes = new Cesium.ClippingPlaneCollection({
    planes: clippingPlanes,
    enabled: true
  });
}

const viewer = new Cesium.Viewer("cesiumContainer", {
  terrain: Cesium.Terrain.fromWorldTerrain()
});

clipTerrain(viewer, [
  new Cesium.Cartesian3(3231726.712678371, 908013.7563155404, 5405107.713075958),
  new Cesium.Cartesian3(3230743.145144949, 911633.8773825126, 5405086.481049389),
  new Cesium.Cartesian3(3229715.0716260737, 911358.4059146766, 5405742.876912364),
  new Cesium.Cartesian3(3230698.6351332776, 907738.2837685784, 5405764.11149235)
]);

Cesium.Ion.defaultAccessToken = '<ACCESS_TOKEN>';

try {
  const tileset = await Cesium.Cesium3DTileset.fromIonAssetId(<ASSET_ID>, {
    maximumMemoryUsage: 2048
  });
  viewer.scene.primitives.add(tileset);

  viewer.zoomTo(
    tileset,
    new Cesium.HeadingPitchRange(0.0, -0.5, tileset.boundingSphere.radius * 2.0)
  );
}
catch (err) {
  console.error(`Error loading tileset: ${err}`);
}
