"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _typeof = require("@babel/runtime/helpers/typeof");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _get2 = _interopRequireDefault(require("@babel/runtime/helpers/get"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var THREE = _interopRequireWildcard(require("three"));

var _TiledGeometryLayer2 = _interopRequireDefault(require("../../../Layer/TiledGeometryLayer"));

var _Ellipsoid = require("../../Math/Ellipsoid");

var _Extent = require("../../Geographic/Extent");

var _BuilderEllipsoidTile = _interopRequireDefault(require("./BuilderEllipsoidTile"));

var _LayeredMaterialNodeProcessing = require("../../../Process/LayeredMaterialNodeProcessing");

var _Crs = _interopRequireDefault(require("../../Geographic/Crs"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

// matrix to convert sphere to ellipsoid
var worldToScaledEllipsoid = new THREE.Matrix4(); // camera's position in worldToScaledEllipsoid system

var cameraPosition = new THREE.Vector3();
var magnitudeSquared = 0.0; // vectors for operation purpose

var scaledHorizonCullingPoint = new THREE.Vector3();
/**
 * @property {boolean} isGlobeLayer - Used to checkout whether this layer is a
 * GlobeLayer. Default is true. You should not change this, as it is used
 * internally for optimisation.
 */

var GlobeLayer = /*#__PURE__*/function (_TiledGeometryLayer) {
  (0, _inherits2["default"])(GlobeLayer, _TiledGeometryLayer);

  var _super = _createSuper(GlobeLayer);

  /**
   * A {@link TiledGeometryLayer} to use with a {@link GlobeView}. It has
   * specific method for updating and subdivising its grid.
   *
   * @constructor
   * @extends TiledGeometryLayer
   *
   * @param {string} id - The id of the layer, that should be unique. It is
   * not mandatory, but an error will be emitted if this layer is added a
   * {@link View} that already has a layer going by that id.
   * @param {THREE.Object3d} [object3d=THREE.Group] - The object3d used to
   * contain the geometry of the TiledGeometryLayer. It is usually a
   * `THREE.Group`, but it can be anything inheriting from a `THREE.Object3d`.
   * @param {Object} [config] - Optional configuration, all elements in it
   * will be merged as is in the layer. For example, if the configuration
   * contains three elements `name, protocol, extent`, these elements will be
   * available using `layer.name` or something else depending on the property
   * name.
   * @param {number} [config.minSubdivisionLevel=2] - Minimum subdivision
   * level for this tiled layer.
   * @param {number} [config.maxSubdivisionLevel=18] - Maximum subdivision
   * level for this tiled layer.
   * @param {number} [config.sseSubdivisionThreshold=1] - Threshold level for
   * the SSE.
   * @param {number} [config.maxDeltaElevationLevel=4] - Maximum delta between
   * two elevations tile.
   *
   * @throws {Error} `object3d` must be a valid `THREE.Object3d`.
   */
  function GlobeLayer(id, object3d) {
    var _this;

    var config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    (0, _classCallCheck2["default"])(this, GlobeLayer);

    // Configure tiles
    var scheme = _Extent.schemeTiles.get(_Crs["default"].tms_4326);

    var schemeTile = _Extent.globalExtentTMS.get('EPSG:4326').subdivisionByScheme(scheme); // Supported tile matrix set for color/elevation layer


    config.tileMatrixSets = [_Crs["default"].tms_4326, _Crs["default"].tms_3857];
    var uvCount = config.tileMatrixSets.length;
    var builder = new _BuilderEllipsoidTile["default"]({
      crs: 'EPSG:4978',
      uvCount: uvCount
    });
    _this = _super.call(this, id, object3d || new THREE.Group(), schemeTile, builder, config);
    _this.isGlobeLayer = true;
    _this.options.defaultPickingRadius = 5;
    _this.minSubdivisionLevel = _this.minSubdivisionLevel == undefined ? 2 : _this.minSubdivisionLevel;
    _this.maxSubdivisionLevel = _this.maxSubdivisionLevel == undefined ? 19 : _this.maxSubdivisionLevel;
    _this.maxDeltaElevation = _this.maxDeltaElevation || 4.0;
    _this.extent = _this.schemeTile[0].clone();

    for (var i = 1; i < _this.schemeTile.length; i++) {
      _this.extent.union(_this.schemeTile[i]);
    } // We're going to use the method described here:
    //    https://cesiumjs.org/2013/04/25/Horizon-culling/
    // This method assumes that the globe is a unit sphere at 0,0,0 so
    // we setup a world-to-scaled-ellipsoid matrix4


    worldToScaledEllipsoid.copy(_this.object3d.matrixWorld).invert();
    worldToScaledEllipsoid.premultiply(new THREE.Matrix4().makeScale(1 / _Ellipsoid.ellipsoidSizes.x, 1 / _Ellipsoid.ellipsoidSizes.y, 1 / _Ellipsoid.ellipsoidSizes.z));
    return _this;
  }

  (0, _createClass2["default"])(GlobeLayer, [{
    key: "preUpdate",
    value: function preUpdate(context, changeSources) {
      // pre-horizon culling
      cameraPosition.copy(context.camera.camera3D.position).applyMatrix4(worldToScaledEllipsoid);
      magnitudeSquared = cameraPosition.lengthSq() - 1.0;
      return (0, _get2["default"])((0, _getPrototypeOf2["default"])(GlobeLayer.prototype), "preUpdate", this).call(this, context, changeSources);
    }
  }, {
    key: "countColorLayersTextures",
    value: function countColorLayersTextures() {
      var occupancy = 0;

      for (var _len = arguments.length, layers = new Array(_len), _key = 0; _key < _len; _key++) {
        layers[_key] = arguments[_key];
      }

      for (var _i = 0, _layers = layers; _i < _layers.length; _i++) {
        var layer = _layers[_i];
        var crs = layer.crs || layer.source.crs; // 'EPSG:3857' occupies the maximum 3 textures on tiles
        // 'EPSG:4326' occupies 1 textures on tile

        occupancy += crs == 'EPSG:3857' ? 3 : 1;
      }

      return occupancy;
    }
  }, {
    key: "subdivision",
    value: function subdivision(context, layer, node) {
      if (node.level == 5) {
        var row = node.getExtentsByProjection(_Crs["default"].tms_4326)[0].row;

        if (row == 31 || row == 0) {
          // doesn't subdivise the pole
          return false;
        }
      }

      return (0, _get2["default"])((0, _getPrototypeOf2["default"])(GlobeLayer.prototype), "subdivision", this).call(this, context, layer, node);
    }
  }, {
    key: "culling",
    value: function culling(node, camera) {
      if ((0, _get2["default"])((0, _getPrototypeOf2["default"])(GlobeLayer.prototype), "culling", this).call(this, node, camera)) {
        return true;
      }

      if (node.level < this.minSubdivisionLevel) {
        return false;
      }

      return GlobeLayer.horizonCulling(node.horizonCullingPointElevationScaled);
    }
  }, {
    key: "computeTileZoomFromDistanceCamera",
    value: function computeTileZoomFromDistanceCamera(distance, camera) {
      var preSinus = _LayeredMaterialNodeProcessing.SIZE_DIAGONAL_TEXTURE * (this.sseSubdivisionThreshold * 0.5) / camera._preSSE / _Ellipsoid.ellipsoidSizes.x;
      var sinus = distance * preSinus;
      var zoom = Math.log(Math.PI / (2.0 * Math.asin(sinus))) / Math.log(2);
      var delta = Math.PI / Math.pow(2, zoom);
      var circleChord = 2.0 * _Ellipsoid.ellipsoidSizes.x * Math.sin(delta * 0.5);
      // adjust with bounding sphere rayon
      sinus = (distance - circleChord * 0.5) * preSinus;
      zoom = Math.log(Math.PI / (2.0 * Math.asin(sinus))) / Math.log(2);
      return isNaN(zoom) ? 0 : Math.round(zoom);
    }
  }, {
    key: "computeDistanceCameraFromTileZoom",
    value: function computeDistanceCameraFromTileZoom(zoom, camera) {
      var delta = Math.PI / Math.pow(2, zoom);
      var circleChord = 2.0 * _Ellipsoid.ellipsoidSizes.x * Math.sin(delta * 0.5);
      var radius = circleChord * 0.5;
      return camera._preSSE * (radius / _LayeredMaterialNodeProcessing.SIZE_DIAGONAL_TEXTURE) / (this.sseSubdivisionThreshold * 0.5) + radius;
    }
  }], [{
    key: "horizonCulling",
    value: function horizonCulling(point) {
      // see https://cesiumjs.org/2013/04/25/Horizon-culling/
      scaledHorizonCullingPoint.copy(point).applyMatrix4(worldToScaledEllipsoid);
      scaledHorizonCullingPoint.sub(cameraPosition);
      var vtMagnitudeSquared = scaledHorizonCullingPoint.lengthSq();
      var dot = -scaledHorizonCullingPoint.dot(cameraPosition);
      var isOccluded = magnitudeSquared < 0 ? dot > 0 : magnitudeSquared < dot && magnitudeSquared < dot * dot / vtMagnitudeSquared;
      return isOccluded;
    }
  }]);
  return GlobeLayer;
}(_TiledGeometryLayer2["default"]);

var _default = GlobeLayer;
exports["default"] = _default;