"use strict";

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

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

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

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

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

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

var _engine = require("@luma.gl/engine");

var _webgl = require("@luma.gl/webgl");

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

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

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

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

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

var GPUSpringTransition = function () {
  function GPUSpringTransition(_ref) {
    var device = _ref.device,
        attribute = _ref.attribute,
        timeline = _ref.timeline;
    (0, _classCallCheck2.default)(this, GPUSpringTransition);
    this.device = void 0;
    this.type = 'spring';
    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.texture = void 0;
    this.framebuffer = void 0;
    this.transform = void 0;
    this.buffers = void 0;
    this.device = device;
    this.type = 'spring';
    this.transition = new _transition.default(timeline);
    this.attribute = attribute;
    this.attributeInTransition = new _attribute.default(device, _objectSpread(_objectSpread({}, attribute.settings), {}, {
      normalized: false
    }));
    this.currentStartIndices = attribute.startIndices;
    this.currentLength = 0;
    this.texture = getTexture(device);
    this.framebuffer = getFramebuffer(device, this.texture);
    var bufferOpts = {
      byteLength: 0,
      usage: 35050
    };
    this.buffers = [device.createBuffer(bufferOpts), device.createBuffer(bufferOpts), device.createBuffer(bufferOpts)];
    this.transform = getTransform(device, attribute, this.buffers);
  }

  var _proto = GPUSpringTransition.prototype;

  _proto.start = function start(transitionSettings, numInstances) {
    var buffers = this.buffers,
        attribute = this.attribute;
    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("[GPUSpringTransition] 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.settings = transitionSettings;
    this.currentStartIndices = attribute.startIndices;
    this.currentLength = (0, _attributeTransitionUtils.getAttributeBufferLength)(attribute, numInstances);
    this.attributeInTransition.setData({
      buffer: buffers[1],
      value: attribute.value
    });
    this.transition.start(_objectSpread(_objectSpread({}, transitionSettings), {}, {
      duration: Infinity
    }));
    this.transform.model.setVertexCount(Math.floor(this.currentLength / attribute.size));
    this.transform.model.setAttributes({
      aTo: attribute.buffer
    });
  };

  _proto.update = function update() {
    var buffers = this.buffers,
        transform = this.transform,
        framebuffer = this.framebuffer,
        transition = this.transition;
    var updated = transition.update();

    if (!updated) {
      return false;
    }

    var settings = this.settings;
    this.transform.model.setAttributes({
      aPrev: buffers[0],
      aCur: buffers[1]
    });
    this.transform.transformFeedback.setBuffers({
      vNext: buffers[2]
    });
    transform.model.setUniforms({
      stiffness: settings.stiffness,
      damping: settings.damping
    });
    transform.run({
      framebuffer: framebuffer,
      discard: false,
      parameters: {
        viewport: [0, 0, 1, 1]
      },
      clearColor: [0, 0, 0, 0]
    });
    (0, _attributeTransitionUtils.cycleBuffers)(buffers);
    this.attributeInTransition.setData({
      buffer: buffers[1],
      value: this.attribute.value
    });
    var isTransitioning = (0, _webgl.readPixelsToArray)(framebuffer)[0] > 0;

    if (!isTransitioning) {
      transition.end();
    }

    return true;
  };

  _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;
    this.texture.delete();
    this.framebuffer.delete();
  };

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

exports.default = GPUSpringTransition;
var vs = "#version 300 es\n#define SHADER_NAME spring-transition-vertex-shader\n\n#define EPSILON 0.00001\n\nuniform float stiffness;\nuniform float damping;\nin ATTRIBUTE_TYPE aPrev;\nin ATTRIBUTE_TYPE aCur;\nin ATTRIBUTE_TYPE aTo;\nout ATTRIBUTE_TYPE vNext;\nout float vIsTransitioningFlag;\n\nATTRIBUTE_TYPE getNextValue(ATTRIBUTE_TYPE cur, ATTRIBUTE_TYPE prev, ATTRIBUTE_TYPE dest) {\n  ATTRIBUTE_TYPE velocity = cur - prev;\n  ATTRIBUTE_TYPE delta = dest - cur;\n  ATTRIBUTE_TYPE spring = delta * stiffness;\n  ATTRIBUTE_TYPE damper = velocity * -1.0 * damping;\n  return spring + damper + velocity + cur;\n}\n\nvoid main(void) {\n  bool isTransitioning = length(aCur - aPrev) > EPSILON || length(aTo - aCur) > EPSILON;\n  vIsTransitioningFlag = isTransitioning ? 1.0 : 0.0;\n\n  vNext = getNextValue(aCur, aPrev, aTo);\n  gl_Position = vec4(0, 0, 0, 1);\n  gl_PointSize = 100.0;\n}\n";
var fs = "#version 300 es\n#define SHADER_NAME spring-transition-is-transitioning-fragment-shader\n\nin float vIsTransitioningFlag;\n\nout vec4 fragColor;\n\nvoid main(void) {\n  if (vIsTransitioningFlag == 0.0) {\n    discard;\n  }\n  fragColor = vec4(1.0);\n}";

function getTransform(device, attribute, buffers) {
  var attributeType = (0, _attributeTransitionUtils.getAttributeTypeFromSize)(attribute.size);
  var format = (0, _attributeTransitionUtils.getFloat32VertexFormat)(attribute.size);
  return new _engine.BufferTransform(device, {
    vs: vs,
    fs: fs,
    attributes: {
      aPrev: buffers[0],
      aCur: buffers[1]
    },
    bufferLayout: [{
      name: 'aPrev',
      format: format
    }, {
      name: 'aCur',
      format: format
    }, {
      name: 'aTo',
      format: format
    }],
    feedbackBuffers: {
      vNext: buffers[2]
    },
    varyings: ['vNext'],
    defines: {
      ATTRIBUTE_TYPE: attributeType
    },
    parameters: {
      depthCompare: 'always',
      blendColorOperation: 'max',
      blendColorSrcFactor: 'one',
      blendColorDstFactor: 'one',
      blendAlphaOperation: 'max',
      blendAlphaSrcFactor: 'one',
      blendAlphaDstFactor: 'one'
    }
  });
}

function getTexture(device) {
  return device.createTexture({
    data: new Uint8Array(4),
    format: 'rgba8unorm',
    mipmaps: false,
    width: 1,
    height: 1
  });
}

function getFramebuffer(device, texture) {
  return device.createFramebuffer({
    id: 'spring-transition-is-transitioning-framebuffer',
    width: 1,
    height: 1,
    colorAttachments: [texture]
  });
}
//# sourceMappingURL=gpu-spring-transition.js.map