"use strict";

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

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

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

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 _engine = require("@luma.gl/engine");

var _constants = require("@luma.gl/constants");

var _attribute = _interopRequireDefault(require("../lib/attribute/attribute"));

var _attributeTransitionUtils = require("../lib/attribute/attribute-transition-utils");

var _transition = _interopRequireDefault(require("./transition"));

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

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; }

var GPUInterpolationTransition = function () {
  function GPUInterpolationTransition(_ref) {
    var device = _ref.device,
        attribute = _ref.attribute,
        timeline = _ref.timeline;
    (0, _classCallCheck2.default)(this, GPUInterpolationTransition);
    this.device = void 0;
    this.type = 'interpolation';
    this.attributeInTransition = void 0;
    this.settings = void 0;
    this.attribute = void 0;
    this.transition = void 0;
    this.currentStartIndices = void 0;
    this.currentLength = void 0;
    this.transform = void 0;
    this.buffers = void 0;
    this.device = device;
    this.transition = new _transition.default(timeline);
    this.attribute = attribute;
    this.attributeInTransition = new _attribute.default(device, attribute.settings);

    if (ArrayBuffer.isView(attribute.value)) {
      this.attributeInTransition.setData(attribute.value);
    }

    this.currentStartIndices = attribute.startIndices;
    this.currentLength = 0;
    this.transform = getTransform(device, attribute);
    var bufferOpts = {
      byteLength: attribute.buffer.byteLength,
      usage: 35050
    };
    this.buffers = [device.createBuffer(bufferOpts), device.createBuffer(bufferOpts)];
  }

  var _proto = GPUInterpolationTransition.prototype;

  _proto.start = function start(transitionSettings, numInstances) {
    if (transitionSettings.duration <= 0) {
      this.transition.cancel();
      return;
    }

    this.settings = transitionSettings;
    var buffers = this.buffers,
        attribute = this.attribute;
    (0, _attributeTransitionUtils.cycleBuffers)(buffers);
    var padBufferOpts = {
      numInstances: numInstances,
      attribute: attribute,
      fromLength: this.currentLength,
      fromStartIndices: this.currentStartIndices,
      getData: transitionSettings.enter
    };

    var _iterator = _createForOfIteratorHelper(buffers.entries()),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _step$value = (0, _slicedToArray2.default)(_step.value, 2),
            index = _step$value[0],
            buffer = _step$value[1];

        var paddedBuffer = (0, _attributeTransitionUtils.padBuffer)(_objectSpread({
          buffer: buffer
        }, padBufferOpts));

        if (buffer !== paddedBuffer) {
          buffer.destroy();
          buffers[index] = paddedBuffer;
          console.warn("[GPUInterpolationTransition] Replaced buffer ".concat(buffer.id, " (").concat(buffer.byteLength, " bytes) \u2192 ") + "".concat(paddedBuffer.id, " (").concat(paddedBuffer.byteLength, " bytes)"));
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    this.currentStartIndices = attribute.startIndices;
    this.currentLength = (0, _attributeTransitionUtils.getAttributeBufferLength)(attribute, numInstances);
    this.attributeInTransition.setData({
      buffer: buffers[1],
      value: attribute.value
    });
    this.transition.start(transitionSettings);
    this.transform.model.setVertexCount(Math.floor(this.currentLength / attribute.size));
    this.transform.model.setAttributes(attribute.getBuffer() ? {
      aFrom: buffers[0],
      aTo: attribute.getBuffer()
    } : {
      aFrom: buffers[0]
    });
    this.transform.transformFeedback.setBuffers({
      vCurrent: buffers[1]
    });
  };

  _proto.update = function update() {
    var updated = this.transition.update();

    if (updated) {
      var _ref2 = this.settings,
          duration = _ref2.duration,
          easing = _ref2.easing;
      var time = this.transition.time;
      var t = time / duration;

      if (easing) {
        t = easing(t);
      }

      this.transform.model.setUniforms({
        time: t
      });
      this.transform.run();
    }

    return updated;
  };

  _proto.cancel = function cancel() {
    this.transition.cancel();
    this.transform.delete();

    var _iterator2 = _createForOfIteratorHelper(this.buffers),
        _step2;

    try {
      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
        var buffer = _step2.value;
        buffer.delete();
      }
    } catch (err) {
      _iterator2.e(err);
    } finally {
      _iterator2.f();
    }

    this.buffers.length = 0;
  };

  (0, _createClass2.default)(GPUInterpolationTransition, [{
    key: "inProgress",
    get: function get() {
      return this.transition.inProgress;
    }
  }]);
  return GPUInterpolationTransition;
}();

exports.default = GPUInterpolationTransition;
var vs = "#version 300 es\n#define SHADER_NAME interpolation-transition-vertex-shader\n\nuniform float time;\nin ATTRIBUTE_TYPE aFrom;\nin ATTRIBUTE_TYPE aTo;\nout ATTRIBUTE_TYPE vCurrent;\n\nvoid main(void) {\n  vCurrent = mix(aFrom, aTo, time);\n  gl_Position = vec4(0.0);\n}\n";

function getTransform(device, attribute) {
  var attributeType = (0, _attributeTransitionUtils.getAttributeTypeFromSize)(attribute.size);
  var format = (0, _attributeTransitionUtils.getFloat32VertexFormat)(attribute.size);
  return new _engine.BufferTransform(device, {
    vs: vs,
    bufferLayout: [{
      name: 'aFrom',
      format: format
    }, {
      name: 'aTo',
      format: format
    }],
    defines: {
      ATTRIBUTE_TYPE: attributeType
    },
    varyings: ['vCurrent']
  });
}
//# sourceMappingURL=gpu-interpolation-transition.js.map