"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.C3DTILES_LAYER_EVENTS = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
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 _classPrivateFieldGet2 = _interopRequireDefault(require("@babel/runtime/helpers/classPrivateFieldGet"));
var _classPrivateFieldSet2 = _interopRequireDefault(require("@babel/runtime/helpers/classPrivateFieldSet"));
var THREE = _interopRequireWildcard(require("three"));
var _GeometryLayer2 = _interopRequireDefault(require("./GeometryLayer"));
var _dTilesProcessing = require("../Process/3dTilesProcessing");
var _C3DTileset = _interopRequireDefault(require("../Core/3DTiles/C3DTileset"));
var _C3DTExtensions = _interopRequireDefault(require("../Core/3DTiles/C3DTExtensions"));
var _PointsMaterial = require("../Renderer/PointsMaterial");
var _Style = _interopRequireDefault(require("../Core/Style"));
var _C3DTFeature = _interopRequireDefault(require("../Core/3DTiles/C3DTFeature"));
var _ThreeUtils = require("../Utils/ThreeUtils");
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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
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; } }
function _classPrivateFieldInitSpec(obj, privateMap, value) { _checkPrivateRedeclaration(obj, privateMap); privateMap.set(obj, value); }
function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } } // eslint-disable-next-line no-unused-vars
var C3DTILES_LAYER_EVENTS = {
  /**
   * Fires when a tile content has been loaded
   * @event C3DTilesLayer#on-tile-content-loaded
   * @type {object}
   * @property {THREE.Object3D} tileContent - object3D of the tile
   */
  ON_TILE_CONTENT_LOADED: 'on-tile-content-loaded',
  /**
   * Fires when a tile is requested
   * @event C3DTilesLayer#on-tile-requested
   * @type {object}
   * @property {object} metadata - tile
   */
  ON_TILE_REQUESTED: 'on-tile-requested'
};
exports.C3DTILES_LAYER_EVENTS = C3DTILES_LAYER_EVENTS;
var _update = (0, _dTilesProcessing.process3dTilesNode)();
var _fillColorMaterialsBuffer = /*#__PURE__*/new WeakMap();
var C3DTilesLayer = /*#__PURE__*/function (_GeometryLayer) {
  (0, _inherits2["default"])(C3DTilesLayer, _GeometryLayer);
  var _super = _createSuper(C3DTilesLayer);
  /**
   * Constructs a new instance of 3d tiles layer.
   * @constructor
   * @extends GeometryLayer
   *
   * @example
   * // Create a new 3d-tiles layer from a web server
   * const l3dt = new C3DTilesLayer('3dtiles', {
   *      name: '3dtl',
   *      source: new C3DTilesSource({
   *           url: 'https://tileset.json'
   *      })
   * }, view);
   * View.prototype.addLayer.call(view, l3dt);
   *
   * // Create a new 3d-tiles layer from a Cesium ion server
   * const l3dt = new C3DTilesLayer('3dtiles', {
   *      name: '3dtl',
   *      source: new C3DTilesIonSource({
   *              accessToken: 'myAccessToken',
                  assetId: 12
   *      })
   * }, view);
   * View.prototype.addLayer.call(view, l3dt);
   *
   * @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      {object}  config   configuration, all elements in it
   * will be merged as is in the layer.
   * @param {C3TilesSource} config.source The source of 3d Tiles.
   *
   * name.
   * @param {Number} [config.sseThreshold=16] The [Screen Space Error](https://github.com/CesiumGS/3d-tiles/blob/main/specification/README.md#geometric-error)
   * threshold at which child nodes of the current node will be loaded and added to the scene.
   * @param {Number} [config.cleanupDelay=1000] The time (in ms) after which a tile content (and its children) are
   * removed from the scene.
   * @param {C3DTExtensions} [config.registeredExtensions] 3D Tiles extensions managers registered for this tileset.
   * @param {String} [config.pntsMode= PNTS_MODE.COLOR] {@link PointsMaterials} Point cloud coloring mode. Only 'COLOR' or 'CLASSIFICATION' are possible. COLOR uses RGB colors of the points, CLASSIFICATION uses a classification property of the batch table to color points.
   * @param {String} [config.pntsShape= PNTS_SHAPE.CIRCLE] Point cloud point shape. Only 'CIRCLE' or 'SQUARE' are possible.
   * @param {String} [config.pntsSizeMode= PNTS_SIZE_MODE.VALUE] {@link PointsMaterials} Point cloud size mode. Only 'VALUE' or 'ATTENUATED' are possible. VALUE use constant size, ATTENUATED compute size depending on distance from point to camera.
   * @param {Number} [config.pntsMinAttenuatedSize=3] Minimum scale used by 'ATTENUATED' size mode
   * @param {Number} [config.pntsMaxAttenuatedSize=10] Maximum scale used by 'ATTENUATED' size mode
   * @param {Style} [config.style=null] - style used for this layer
   * @param  {View}  view  The view
   */
  function C3DTilesLayer(id, config, view) {
    var _this;
    (0, _classCallCheck2["default"])(this, C3DTilesLayer);
    _this = _super.call(this, id, new THREE.Group(), {
      source: config.source
    });
    _classPrivateFieldInitSpec((0, _assertThisInitialized2["default"])(_this), _fillColorMaterialsBuffer, {
      writable: true,
      value: void 0
    });
    _this.isC3DTilesLayer = true;
    _this.sseThreshold = config.sseThreshold || 16;
    _this.cleanupDelay = config.cleanupDelay || 1000;
    _this.protocol = '3d-tiles';
    _this.name = config.name;
    _this.registeredExtensions = config.registeredExtensions || new _C3DTExtensions["default"]();
    _this.pntsMode = _PointsMaterial.PNTS_MODE.COLOR;
    _this.pntsShape = _PointsMaterial.PNTS_SHAPE.CIRCLE;
    _this.classification = config.classification;
    _this.pntsSizeMode = _PointsMaterial.PNTS_SIZE_MODE.VALUE;
    _this.pntsMinAttenuatedSize = config.pntsMinAttenuatedSize || 3;
    _this.pntsMaxAttenuatedSize = config.pntsMaxAttenuatedSize || 10;
    if (config.pntsMode) {
      var exists = Object.values(_PointsMaterial.PNTS_MODE).includes(config.pntsMode);
      if (!exists) {
        console.warn("The points cloud mode doesn't exist. Use 'COLOR' or 'CLASSIFICATION' instead.");
      } else {
        _this.pntsMode = config.pntsMode;
      }
    }
    if (config.pntsShape) {
      var _exists = Object.values(_PointsMaterial.PNTS_SHAPE).includes(config.pntsShape);
      if (!_exists) {
        console.warn("The points cloud point shape doesn't exist. Use 'CIRCLE' or 'SQUARE' instead.");
      } else {
        _this.pntsShape = config.pntsShape;
      }
    }
    if (config.pntsSizeMode) {
      var _exists2 = Object.values(_PointsMaterial.PNTS_SIZE_MODE).includes(config.pntsSizeMode);
      if (!_exists2) {
        console.warn("The points cloud size mode doesn't exist. Use 'VALUE' or 'ATTENUATED' instead.");
      } else {
        _this.pntsSizeMode = config.pntsSizeMode;
      }
    }

    /** @type {Style} */
    _this._style = config.style || null;

    /** @type {Map<string, THREE.MeshStandardMaterial>} */
    (0, _classPrivateFieldSet2["default"])((0, _assertThisInitialized2["default"])(_this), _fillColorMaterialsBuffer, new Map());

    /**
     * Map all C3DTFeature of the layer according their tileId and their batchId
     * Map< tileId, Map< batchId, C3DTFeature>>
     *
     * @type {Map<number, Map<number,C3DTFeature>>}
     */
    _this.tilesC3DTileFeatures = new Map();
    if (config.onTileContentLoaded) {
      console.warn('DEPRECATED onTileContentLoaded should not be passed at the contruction, use C3DTILES_LAYER_EVENTS.ON_TILE_CONTENT_LOADED event instead');
      _this.addEventListener(C3DTILES_LAYER_EVENTS.ON_TILE_CONTENT_LOADED, config.onTileContentLoaded);
    }
    if (config.overrideMaterials) {
      console.warn('overrideMaterials is deprecated, use style API instead');
      _this.overrideMaterials = config.overrideMaterials;
    }
    _this._cleanableTiles = [];
    var resolve = _this.addInitializationStep();
    _this.source.whenReady.then(function (tileset) {
      _this.tileset = new _C3DTileset["default"](tileset, _this.source.baseUrl, _this.registeredExtensions);
      // Verify that extensions of the tileset have been registered in the layer
      if (_this.tileset.extensionsUsed) {
        var _iterator = _createForOfIteratorHelper(_this.tileset.extensionsUsed),
          _step;
        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var extensionUsed = _step.value;
            // if current extension is not registered
            if (!_this.registeredExtensions.isExtensionRegistered(extensionUsed)) {
              // if it is required to load the tileset
              if (_this.tileset.extensionsRequired && _this.tileset.extensionsRequired.includes(extensionUsed)) {
                console.error("3D Tiles tileset required extension \"".concat(extensionUsed, "\" must be registered to the 3D Tiles layer of iTowns to be parsed and used."));
              } else {
                console.warn("3D Tiles tileset used extension \"".concat(extensionUsed, "\" must be registered to the 3D Tiles layer of iTowns to be parsed and used."));
              }
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
      }
      // TODO: Move all init3dTilesLayer code to constructor
      (0, _dTilesProcessing.init3dTilesLayer)(view, view.mainLoop.scheduler, (0, _assertThisInitialized2["default"])(_this), tileset.root).then(resolve);
    });
    return _this;
  }
  (0, _createClass2["default"])(C3DTilesLayer, [{
    key: "preUpdate",
    value: function preUpdate() {
      return _dTilesProcessing.pre3dTilesUpdate.bind(this)();
    }
  }, {
    key: "update",
    value: function update(context, layer, node) {
      return _update(context, layer, node);
    }
  }, {
    key: "getObjectToUpdateForAttachedLayers",
    value: function getObjectToUpdateForAttachedLayers(meta) {
      if (meta.content) {
        var result = [];
        meta.content.traverse(function (obj) {
          if (obj.isObject3D && obj.material && obj.layer == meta.layer) {
            result.push(obj);
          }
        });
        var p = meta.parent;
        if (p && p.content) {
          return {
            elements: result,
            parent: p.content
          };
        } else {
          return {
            elements: result
          };
        }
      }
    }

    /**
     * Finds the batch table of an object in a 3D Tiles layer. This is
     * for instance needed when picking because we pick the geometric
     * object which is not at the same level in the layer structure as
     * the batch table. More details here on itowns internal
     * organization of 3DTiles:
     *  https://github.com/MEPP-team/RICT/blob/master/Doc/iTowns/Doc.md#itowns-internal-organisation-of-3d-tiles-data
     * @param {THREE.Object3D} object - a 3D geometric object
     * @returns {C3DTBatchTable} - the batch table of the object
     */
  }, {
    key: "findBatchTable",
    value: function findBatchTable(object) {
      if (object.batchTable) {
        return object.batchTable;
      }
      if (object.parent) {
        return this.findBatchTable(object.parent);
      }
    }

    /**
     * Get the closest c3DTileFeature of an intersects array.
     * @param {Array} intersects - @return An array containing all
     * targets picked under specified coordinates. Intersects can be
     * computed with view.pickObjectsAt(..). See fillHTMLWithPickingInfo()
     * in 3dTilesHelper.js for an example.
     * @returns {C3DTileFeature} - the closest C3DTileFeature of the intersects array
     */
  }, {
    key: "getC3DTileFeatureFromIntersectsArray",
    value: function getC3DTileFeatureFromIntersectsArray(intersects) {
      // find closest intersect with an attributes _BATCHID + face != undefined
      var closestIntersect = null;
      for (var index = 0; index < intersects.length; index++) {
        var i = intersects[index];
        if (i.object.geometry && i.object.geometry.attributes._BATCHID && i.face &&
        // need face to get batch id
        i.layer == this // just to be sure that the right layer intersected
        ) {
          closestIntersect = i;
          break;
        }
      }
      if (!closestIntersect) {
        return null;
      }

      // function find the tile id from an object

      var tileId = function (object) {
        var currentObject = object;
        var result = currentObject.tileId;
        while (isNaN(result) && currentObject.parent) {
          currentObject = currentObject.parent;
          result = currentObject.tileId;
        }
        return result;
      }(closestIntersect.object);
      // face is a Face3 object of THREE which is a
      // triangular face. face.a is its first vertex
      var vertex = closestIntersect.face.a;
      var batchID = closestIntersect.object.geometry.attributes._BATCHID.array[vertex];
      return this.tilesC3DTileFeatures.get(tileId).get(batchID);
    }

    /**
     * Call by {@link 3dTilesProcessing} which handle load and unload of 3DTiles
     * @param {THREE.Object3D} tileContent - tile as THREE.Object3D
     */
  }, {
    key: "onTileContentLoaded",
    value: function onTileContentLoaded(tileContent) {
      this.initC3DTileFeatures(tileContent);

      // notify observer
      this.dispatchEvent({
        type: C3DTILES_LAYER_EVENTS.ON_TILE_CONTENT_LOADED,
        tileContent: tileContent
      });
    }

    /**
     * Initialize C3DTileFeatures from tileContent
     *
     * @param {THREE.Object3D} tileContent - tile as THREE.Object3D
     */
  }, {
    key: "initC3DTileFeatures",
    value: function initC3DTileFeatures(tileContent) {
      var _this2 = this;
      tileContent.traverse(function (child) {
        if (child.geometry && child.geometry.attributes._BATCHID) {
          _this2.tilesC3DTileFeatures.set(tileContent.tileId, new Map()); // initialize
          var batchTable = _this2.findBatchTable(child);
          if (!batchTable) {
            throw new Error('no batchTable');
          }
          var geometryAttributes = child.geometry.attributes;
          var currentBatchId = geometryAttributes._BATCHID.array[0];
          var start = 0;
          var count = 0;
          var registerBatchIdGroup = function () {
            if (_this2.tilesC3DTileFeatures.get(tileContent.tileId).has(currentBatchId)) {
              // already created
              var c3DTileFeature = _this2.tilesC3DTileFeatures.get(tileContent.tileId).get(currentBatchId);
              // add new group
              c3DTileFeature.groups.push({
                start: start,
                count: count
              });
            } else {
              // first occurence
              var _c3DTileFeature = new _C3DTFeature["default"](tileContent.tileId, currentBatchId, [{
                start: start,
                count: count
              }],
              // initialize with current group
              batchTable.getInfoById(currentBatchId));
              _this2.tilesC3DTileFeatures.get(tileContent.tileId).set(currentBatchId, _c3DTileFeature);
            }
          };
          for (var index = 0; index < geometryAttributes.position.array.length; index += geometryAttributes.position.itemSize) {
            var batchIndex = index / geometryAttributes.position.itemSize;
            var batchId = geometryAttributes._BATCHID.array[batchIndex];

            // check if batchId is currentBatchId
            if (currentBatchId !== batchId) {
              registerBatchIdGroup();

              // reset
              currentBatchId = batchId;
              start = batchIndex;
              count = 0;
            }

            // record this position in current C3DTileFeature
            count++;

            // check if end of the array
            if (index + geometryAttributes.position.itemSize >= geometryAttributes.position.array.length) {
              registerBatchIdGroup();
            }
          }
        }
      });
      this.updateStyle([tileContent.tileId]); // only update tile batchelement
    }

    /**
     * Compute world box 3 of a c3DTFeature
     *
     * @param {C3DTFeature} c3DTFeature - feature to compute world box3
     * @param {THREE.Box3} [target] - result instance
     * @returns {THREE.Box3}
     */
  }, {
    key: "computeWorldBox3",
    value: function computeWorldBox3(c3DTFeature) {
      var target = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new THREE.Box3();
      // reset
      target.max.x = -Infinity;
      target.max.y = -Infinity;
      target.max.z = -Infinity;
      target.min.x = Infinity;
      target.min.y = Infinity;
      target.min.z = Infinity;
      var tileContent = this.object3d.getObjectByProperty('tileId', c3DTFeature.tileId);
      tileContent.traverse(function (child) {
        if (child.geometry && child.geometry.attributes._BATCHID) {
          c3DTFeature.groups.forEach(function (group) {
            var positionIndexStart = group.start * 3;
            var positionIndexCount = (group.start + group.count) * 3;
            for (var index = positionIndexStart; index < positionIndexCount; index += 3) {
              var x = child.geometry.attributes.position.array[index];
              var y = child.geometry.attributes.position.array[index + 1];
              var z = child.geometry.attributes.position.array[index + 2];
              target.max.x = Math.max(x, target.max.x);
              target.max.y = Math.max(y, target.max.y);
              target.max.z = Math.max(z, target.max.z);
              target.min.x = Math.min(x, target.min.x);
              target.min.y = Math.min(y, target.min.y);
              target.min.z = Math.min(z, target.min.z);
            }
          });
          target.applyMatrix4(child.matrixWorld);
        }
      });
      return target;
    }

    /**
     * Update style of the C3DTFeatures, an allowList of tile id can be passed to only update certain tile.
     * Note that this function only update THREE.Object3D materials, in order to see style changes you should call view.notifyChange()
     *
     * @param {Array<number>|null} [allowTileIdList] - tile ids to allow in updateStyle computation if null all tiles are updated
     * @returns {boolean} true if style updated false otherwise
     */
  }, {
    key: "updateStyle",
    value: function updateStyle() {
      var _this3 = this;
      var allowTileIdList = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
      if (!this._style) {
        return false;
      }
      var currentMaterials = []; // list materials used for this update
      this.object3d.traverse(function (object) {
        if (_this3.tilesC3DTileFeatures.has(object.tileId)) {
          // object is a tile content
          var c3DTileFeatures = _this3.tilesC3DTileFeatures.get(object.tileId);
          object.traverse(function (child) {
            if (child.geometry && child.geometry.attributes._BATCHID) {
              // check if tile feature should be updated
              if (!(allowTileIdList && !allowTileIdList.includes(object.tileId))) {
                // clear
                child.geometry.clearGroups();
                child.material = [];

                // eslint-disable-next-line no-unused-vars
                var _iterator2 = _createForOfIteratorHelper(c3DTileFeatures),
                  _step2;
                try {
                  var _loop = function _loop() {
                    var _step2$value = (0, _slicedToArray2["default"])(_step2.value, 2),
                      batchId = _step2$value[0],
                      c3DTileFeature = _step2$value[1];
                    /** @type {THREE.Color} */
                    var color = null;
                    if (typeof _this3._style.fill.color === 'function') {
                      color = new THREE.Color(_this3._style.fill.color(c3DTileFeature));
                    } else {
                      color = new THREE.Color(_this3._style.fill.color);
                    }

                    /** @type {number} */
                    var opacity = null;
                    if (typeof _this3._style.fill.opacity === 'function') {
                      opacity = _this3._style.fill.opacity(c3DTileFeature);
                    } else {
                      opacity = _this3._style.fill.opacity;
                    }
                    var materialId = color.getHexString() + opacity;
                    var material = null;
                    if ((0, _classPrivateFieldGet2["default"])(_this3, _fillColorMaterialsBuffer).has(materialId)) {
                      material = (0, _classPrivateFieldGet2["default"])(_this3, _fillColorMaterialsBuffer).get(materialId);
                    } else {
                      material = new THREE.MeshStandardMaterial({
                        color: color,
                        opacity: opacity,
                        transparent: opacity < 1,
                        alphaTest: 0.09
                      });
                      (0, _classPrivateFieldGet2["default"])(_this3, _fillColorMaterialsBuffer).set(materialId, material); // bufferize
                    }

                    // compute materialIndex
                    var materialIndex = -1;
                    for (var index = 0; index < child.material.length; index++) {
                      var childMaterial = child.material[index];
                      if (material.uuid === childMaterial.uuid) {
                        materialIndex = index;
                        break;
                      }
                    }
                    if (materialIndex < 0) {
                      // not in child.material add it
                      child.material.push(material);
                      materialIndex = child.material.length - 1;
                    }

                    // materialIndex groups is computed
                    c3DTileFeature.groups.forEach(function (group) {
                      child.geometry.addGroup(group.start, group.count, materialIndex);
                    });
                  };
                  for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
                    _loop();
                  }
                } catch (err) {
                  _iterator2.e(err);
                } finally {
                  _iterator2.f();
                }
                (0, _ThreeUtils.optimizeGeometryGroups)(child);
              }

              // record material(s) used in child
              if (child.material instanceof Array) {
                child.material.forEach(function (material) {
                  if (!currentMaterials.includes(material)) {
                    currentMaterials.push(material);
                  }
                });
              } else if (!currentMaterials.includes(child.material)) {
                currentMaterials.push(child.material);
              }
            }
          });
        }
      });

      // remove buffered materials not in currentMaterials
      var _iterator3 = _createForOfIteratorHelper((0, _classPrivateFieldGet2["default"])(this, _fillColorMaterialsBuffer)),
        _step3;
      try {
        for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
          var _step3$value = (0, _slicedToArray2["default"])(_step3.value, 2),
            id = _step3$value[0],
            fillMaterial = _step3$value[1];
          if (!currentMaterials.includes(fillMaterial)) {
            fillMaterial.dispose();
            (0, _classPrivateFieldGet2["default"])(this, _fillColorMaterialsBuffer)["delete"](id);
          }
        }
      } catch (err) {
        _iterator3.e(err);
      } finally {
        _iterator3.f();
      }
      return true;
    }
  }, {
    key: "materialCount",
    get: function get() {
      return (0, _classPrivateFieldGet2["default"])(this, _fillColorMaterialsBuffer).size;
    }
  }, {
    key: "style",
    get: function get() {
      return this._style;
    },
    set: function set(value) {
      this._style = value;
      this.updateStyle();
    }
  }]);
  return C3DTilesLayer;
}(_GeometryLayer2["default"]);
var _default = C3DTilesLayer;
exports["default"] = _default;