function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _instanceof(left, right) { if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { return right[Symbol.hasInstance](left); } else { return left instanceof right; } }

function _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }

function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

// Copyright (c) 2015 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import { Layer } from '@deck.gl/core';
import { GL, Model, Geometry, Texture2D, loadTextures, fp64 } from 'luma.gl';
var fp64LowPart = fp64.fp64LowPart;
import vs from './icon-layer-vertex.glsl';
import fs from './icon-layer-fragment.glsl';
var DEFAULT_COLOR = [0, 0, 0, 255];
var DEFAULT_TEXTURE_MIN_FILTER = GL.LINEAR_MIPMAP_LINEAR; // GL.LINEAR is the default value but explicitly set it here

var DEFAULT_TEXTURE_MAG_FILTER = GL.LINEAR;
/*
 * @param {object} props
 * @param {Texture2D | string} props.iconAtlas - atlas image url or texture
 * @param {object} props.iconMapping - icon names mapped to icon definitions
 * @param {object} props.iconMapping[icon_name].x - x position of icon on the atlas image
 * @param {object} props.iconMapping[icon_name].y - y position of icon on the atlas image
 * @param {object} props.iconMapping[icon_name].width - width of icon on the atlas image
 * @param {object} props.iconMapping[icon_name].height - height of icon on the atlas image
 * @param {object} props.iconMapping[icon_name].anchorX - x anchor of icon on the atlas image,
 *   default to width / 2
 * @param {object} props.iconMapping[icon_name].anchorY - y anchor of icon on the atlas image,
 *   default to height / 2
 * @param {object} props.iconMapping[icon_name].mask - whether icon is treated as a transparency
 *   mask. If true, user defined color is applied. If false, original color from the image is
 *   applied. Default to false.
 * @param {number} props.size - icon size in pixels
 * @param {func} props.getPosition - returns anchor position of the icon, in [lng, lat, z]
 * @param {func} props.getIcon - returns icon name as a string
 * @param {func} props.getSize - returns icon size multiplier as a number
 * @param {func} props.getColor - returns color of the icon in [r, g, b, a]. Only works on icons
 *   with mask: true.
 * @param {func} props.getAngle - returns rotating angle (in degree) of the icon.
 */

var defaultProps = {
  iconAtlas: null,
  iconMapping: {},
  sizeScale: 1,
  fp64: false,
  getPosition: function getPosition(x) {
    return x.position;
  },
  getIcon: function getIcon(x) {
    return x.icon;
  },
  getColor: function getColor(x) {
    return x.color || DEFAULT_COLOR;
  },
  getSize: function getSize(x) {
    return x.size || 1;
  },
  getAngle: function getAngle(x) {
    return x.angle || 0;
  }
};

var IconLayer =
/*#__PURE__*/
function (_Layer) {
  _inherits(IconLayer, _Layer);

  function IconLayer() {
    _classCallCheck(this, IconLayer);

    return _possibleConstructorReturn(this, (IconLayer.__proto__ || Object.getPrototypeOf(IconLayer)).apply(this, arguments));
  }

  _createClass(IconLayer, [{
    key: "getShaders",
    value: function getShaders() {
      var projectModule = this.is64bitEnabled() ? 'project64' : 'project32';
      return {
        vs: vs,
        fs: fs,
        modules: [projectModule, 'picking']
      };
    }
  }, {
    key: "initializeState",
    value: function initializeState() {
      var attributeManager = this.getAttributeManager();
      /* eslint-disable max-len */

      attributeManager.addInstanced({
        instancePositions: {
          size: 3,
          transition: true,
          accessor: 'getPosition'
        },
        instancePositions64xyLow: {
          size: 2,
          accessor: 'getPosition',
          update: this.calculateInstancePositions64xyLow
        },
        instanceSizes: {
          size: 1,
          transition: true,
          accessor: 'getSize',
          defaultValue: 1
        },
        instanceOffsets: {
          size: 2,
          accessor: 'getIcon',
          update: this.calculateInstanceOffsets
        },
        instanceIconFrames: {
          size: 4,
          accessor: 'getIcon',
          update: this.calculateInstanceIconFrames
        },
        instanceColorModes: {
          size: 1,
          type: GL.UNSIGNED_BYTE,
          accessor: 'getIcon',
          update: this.calculateInstanceColorMode
        },
        instanceColors: {
          size: 4,
          type: GL.UNSIGNED_BYTE,
          transition: true,
          accessor: 'getColor',
          defaultValue: DEFAULT_COLOR
        },
        instanceAngles: {
          size: 1,
          transition: true,
          accessor: 'getAngle',
          defaultValue: 0
        }
      });
      /* eslint-enable max-len */
    }
  }, {
    key: "updateState",
    value: function updateState(_ref) {
      var _this = this;

      var oldProps = _ref.oldProps,
          props = _ref.props,
          changeFlags = _ref.changeFlags;

      _get(IconLayer.prototype.__proto__ || Object.getPrototypeOf(IconLayer.prototype), "updateState", this).call(this, {
        props: props,
        oldProps: oldProps,
        changeFlags: changeFlags
      });

      var iconAtlas = props.iconAtlas,
          iconMapping = props.iconMapping;

      if (oldProps.iconMapping !== iconMapping) {
        var attributeManager = this.getAttributeManager();
        attributeManager.invalidate('instanceOffsets');
        attributeManager.invalidate('instanceIconFrames');
        attributeManager.invalidate('instanceColorModes');
      }

      if (oldProps.iconAtlas !== iconAtlas) {
        if (_instanceof(iconAtlas, Texture2D)) {
          var _iconAtlas$setParamet;

          iconAtlas.setParameters((_iconAtlas$setParamet = {}, _defineProperty(_iconAtlas$setParamet, GL.TEXTURE_MIN_FILTER, DEFAULT_TEXTURE_MIN_FILTER), _defineProperty(_iconAtlas$setParamet, GL.TEXTURE_MAG_FILTER, DEFAULT_TEXTURE_MAG_FILTER), _iconAtlas$setParamet));
          this.setState({
            iconsTexture: iconAtlas
          });
        } else if (typeof iconAtlas === 'string') {
          loadTextures(this.context.gl, {
            urls: [iconAtlas]
          }).then(function (_ref2) {
            var _texture$setParameter;

            var _ref3 = _slicedToArray(_ref2, 1),
                texture = _ref3[0];

            texture.setParameters((_texture$setParameter = {}, _defineProperty(_texture$setParameter, GL.TEXTURE_MIN_FILTER, DEFAULT_TEXTURE_MIN_FILTER), _defineProperty(_texture$setParameter, GL.TEXTURE_MAG_FILTER, DEFAULT_TEXTURE_MAG_FILTER), _texture$setParameter));

            _this.setState({
              iconsTexture: texture
            });
          });
        }
      }

      if (props.fp64 !== oldProps.fp64) {
        var gl = this.context.gl;

        if (this.state.model) {
          this.state.model.delete();
        }

        this.setState({
          model: this._getModel(gl)
        });
        this.state.attributeManager.invalidateAll();
      }
    }
  }, {
    key: "draw",
    value: function draw(_ref4) {
      var uniforms = _ref4.uniforms;
      var sizeScale = this.props.sizeScale;
      var iconsTexture = this.state.iconsTexture;

      if (iconsTexture) {
        this.state.model.render(Object.assign({}, uniforms, {
          iconsTexture: iconsTexture,
          iconsTextureDim: [iconsTexture.width, iconsTexture.height],
          sizeScale: sizeScale
        }));
      }
    }
  }, {
    key: "_getModel",
    value: function _getModel(gl) {
      var positions = [-1, -1, 0, -1, 1, 0, 1, 1, 0, 1, -1, 0];
      return new Model(gl, Object.assign({}, this.getShaders(), {
        id: this.props.id,
        geometry: new Geometry({
          drawMode: GL.TRIANGLE_FAN,
          attributes: {
            positions: new Float32Array(positions)
          }
        }),
        isInstanced: true,
        shaderCache: this.context.shaderCache
      }));
    }
    /*
    calculateInstancePositions(attribute) {
      const {data, getPosition} = this.props;
      const {value} = attribute;
      let i = 0;
      for (const object of data) {
        const position = getPosition(object);
        value[i++] = position[0];
        value[i++] = position[1];
        value[i++] = position[2] || 0;
      }
    }
     calculateInstanceSizes(attribute) {
      const {data, getSize} = this.props;
      const {value} = attribute;
      let i = 0;
      for (const object of data) {
        value[i++] = getSize(object);
      }
    }
     calculateInstanceAngles(attribute) {
      const {data, getAngle} = this.props;
      const {value} = attribute;
      let i = 0;
      for (const object of data) {
        value[i++] = getAngle(object);
      }
    }
     calculateInstanceColors(attribute) {
      const {data, getColor} = this.props;
      const {value} = attribute;
      let i = 0;
      for (const object of data) {
        const color = getColor(object);
         value[i++] = color[0];
        value[i++] = color[1];
        value[i++] = color[2];
        value[i++] = isNaN(color[3]) ? 255 : color[3];
      }
    }
    */

  }, {
    key: "calculateInstancePositions64xyLow",
    value: function calculateInstancePositions64xyLow(attribute) {
      var isFP64 = this.is64bitEnabled();
      attribute.isGeneric = !isFP64;

      if (!isFP64) {
        attribute.value = new Float32Array(2);
        return;
      }

      var _this$props = this.props,
          data = _this$props.data,
          getPosition = _this$props.getPosition;
      var value = attribute.value;
      var i = 0;
      var _iteratorNormalCompletion = true;
      var _didIteratorError = false;
      var _iteratorError = undefined;

      try {
        for (var _iterator = data[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
          var point = _step.value;
          var position = getPosition(point);
          value[i++] = fp64LowPart(position[0]);
          value[i++] = fp64LowPart(position[1]);
        }
      } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion && _iterator.return != null) {
            _iterator.return();
          }
        } finally {
          if (_didIteratorError) {
            throw _iteratorError;
          }
        }
      }
    }
  }, {
    key: "calculateInstanceOffsets",
    value: function calculateInstanceOffsets(attribute) {
      var _this$props2 = this.props,
          data = _this$props2.data,
          iconMapping = _this$props2.iconMapping,
          getIcon = _this$props2.getIcon;
      var value = attribute.value;
      var i = 0;
      var _iteratorNormalCompletion2 = true;
      var _didIteratorError2 = false;
      var _iteratorError2 = undefined;

      try {
        for (var _iterator2 = data[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
          var object = _step2.value;
          var icon = getIcon(object);
          var rect = iconMapping[icon] || {};
          value[i++] = rect.width / 2 - rect.anchorX || 0;
          value[i++] = rect.height / 2 - rect.anchorY || 0;
        }
      } catch (err) {
        _didIteratorError2 = true;
        _iteratorError2 = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
            _iterator2.return();
          }
        } finally {
          if (_didIteratorError2) {
            throw _iteratorError2;
          }
        }
      }
    }
  }, {
    key: "calculateInstanceColorMode",
    value: function calculateInstanceColorMode(attribute) {
      var _this$props3 = this.props,
          data = _this$props3.data,
          iconMapping = _this$props3.iconMapping,
          getIcon = _this$props3.getIcon;
      var value = attribute.value;
      var i = 0;
      var _iteratorNormalCompletion3 = true;
      var _didIteratorError3 = false;
      var _iteratorError3 = undefined;

      try {
        for (var _iterator3 = data[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
          var object = _step3.value;
          var icon = getIcon(object);
          var colorMode = iconMapping[icon] && iconMapping[icon].mask;
          value[i++] = colorMode ? 1 : 0;
        }
      } catch (err) {
        _didIteratorError3 = true;
        _iteratorError3 = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
            _iterator3.return();
          }
        } finally {
          if (_didIteratorError3) {
            throw _iteratorError3;
          }
        }
      }
    }
  }, {
    key: "calculateInstanceIconFrames",
    value: function calculateInstanceIconFrames(attribute) {
      var _this$props4 = this.props,
          data = _this$props4.data,
          iconMapping = _this$props4.iconMapping,
          getIcon = _this$props4.getIcon;
      var value = attribute.value;
      var i = 0;
      var _iteratorNormalCompletion4 = true;
      var _didIteratorError4 = false;
      var _iteratorError4 = undefined;

      try {
        for (var _iterator4 = data[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
          var object = _step4.value;
          var icon = getIcon(object);
          var rect = iconMapping[icon] || {};
          value[i++] = rect.x || 0;
          value[i++] = rect.y || 0;
          value[i++] = rect.width || 0;
          value[i++] = rect.height || 0;
        }
      } catch (err) {
        _didIteratorError4 = true;
        _iteratorError4 = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
            _iterator4.return();
          }
        } finally {
          if (_didIteratorError4) {
            throw _iteratorError4;
          }
        }
      }
    }
  }]);

  return IconLayer;
}(Layer);

export { IconLayer as default };
IconLayer.layerName = 'IconLayer';
IconLayer.defaultProps = defaultProps;
//# sourceMappingURL=icon-layer.js.map