"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.computeMikkTSpaceTangents = computeMikkTSpaceTangents;
exports.computeMorphedAttributes = computeMorphedAttributes;
exports.deepCloneAttribute = deepCloneAttribute;
exports.deinterleaveAttribute = deinterleaveAttribute;
exports.deinterleaveGeometry = deinterleaveGeometry;
exports.estimateBytesUsed = estimateBytesUsed;
exports.interleaveAttributes = interleaveAttributes;
exports.mergeAttributes = mergeAttributes;
exports.mergeBufferAttributes = mergeBufferAttributes;
exports.mergeBufferGeometries = mergeBufferGeometries;
exports.mergeGeometries = mergeGeometries;
exports.mergeGroups = mergeGroups;
exports.mergeVertices = mergeVertices;
exports.toCreasedNormals = toCreasedNormals;
exports.toTrianglesDrawMode = toTrianglesDrawMode;
var _three = require("three");
function computeMikkTSpaceTangents(geometry, MikkTSpace) {
  var negateSign = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  if (!MikkTSpace || !MikkTSpace.isReady) {
    throw new Error('BufferGeometryUtils: Initialized MikkTSpace library required.');
  }
  if (!geometry.hasAttribute('position') || !geometry.hasAttribute('normal') || !geometry.hasAttribute('uv')) {
    throw new Error('BufferGeometryUtils: Tangents require "position", "normal", and "uv" attributes.');
  }
  function getAttributeArray(attribute) {
    if (attribute.normalized || attribute.isInterleavedBufferAttribute) {
      var dstArray = new Float32Array(attribute.count * attribute.itemSize);
      for (var i = 0, j = 0; i < attribute.count; i++) {
        dstArray[j++] = attribute.getX(i);
        dstArray[j++] = attribute.getY(i);
        if (attribute.itemSize > 2) {
          dstArray[j++] = attribute.getZ(i);
        }
      }
      return dstArray;
    }
    if (attribute.array instanceof Float32Array) {
      return attribute.array;
    }
    return new Float32Array(attribute.array);
  }

  // MikkTSpace algorithm requires non-indexed input.

  var _geometry = geometry.index ? geometry.toNonIndexed() : geometry;

  // Compute vertex tangents.

  var tangents = MikkTSpace.generateTangents(getAttributeArray(_geometry.attributes.position), getAttributeArray(_geometry.attributes.normal), getAttributeArray(_geometry.attributes.uv));

  // Texture coordinate convention of glTF differs from the apparent
  // default of the MikkTSpace library; .w component must be flipped.

  if (negateSign) {
    for (var i = 3; i < tangents.length; i += 4) {
      tangents[i] *= -1;
    }
  }

  //

  _geometry.setAttribute('tangent', new _three.BufferAttribute(tangents, 4));
  if (geometry !== _geometry) {
    geometry.copy(_geometry);
  }
  return geometry;
}

/**
 * @param  {Array<BufferGeometry>} geometries
 * @param  {Boolean} useGroups
 * @return {BufferGeometry}
 */
function mergeGeometries(geometries) {
  var useGroups = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  var isIndexed = geometries[0].index !== null;
  var attributesUsed = new Set(Object.keys(geometries[0].attributes));
  var morphAttributesUsed = new Set(Object.keys(geometries[0].morphAttributes));
  var attributes = {};
  var morphAttributes = {};
  var morphTargetsRelative = geometries[0].morphTargetsRelative;
  var mergedGeometry = new _three.BufferGeometry();
  var offset = 0;
  for (var i = 0; i < geometries.length; ++i) {
    var geometry = geometries[i];
    var attributesCount = 0;

    // ensure that all geometries are indexed, or none

    if (isIndexed !== (geometry.index !== null)) {
      console.error('THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.');
      return null;
    }

    // gather attributes, exit early if they're different

    for (var name in geometry.attributes) {
      if (!attributesUsed.has(name)) {
        console.error('THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure "' + name + '" attribute exists among all geometries, or in none of them.');
        return null;
      }
      if (attributes[name] === undefined) attributes[name] = [];
      attributes[name].push(geometry.attributes[name]);
      attributesCount++;
    }

    // ensure geometries have the same number of attributes

    if (attributesCount !== attributesUsed.size) {
      console.error('THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.');
      return null;
    }

    // gather morph attributes, exit early if they're different

    if (morphTargetsRelative !== geometry.morphTargetsRelative) {
      console.error('THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.');
      return null;
    }
    for (var _name in geometry.morphAttributes) {
      if (!morphAttributesUsed.has(_name)) {
        console.error('THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '.  .morphAttributes must be consistent throughout all geometries.');
        return null;
      }
      if (morphAttributes[_name] === undefined) morphAttributes[_name] = [];
      morphAttributes[_name].push(geometry.morphAttributes[_name]);
    }
    if (useGroups) {
      var count = void 0;
      if (isIndexed) {
        count = geometry.index.count;
      } else if (geometry.attributes.position !== undefined) {
        count = geometry.attributes.position.count;
      } else {
        console.error('THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute');
        return null;
      }
      mergedGeometry.addGroup(offset, count, i);
      offset += count;
    }
  }

  // merge indices

  if (isIndexed) {
    var indexOffset = 0;
    var mergedIndex = [];
    for (var _i = 0; _i < geometries.length; ++_i) {
      var index = geometries[_i].index;
      for (var j = 0; j < index.count; ++j) {
        mergedIndex.push(index.getX(j) + indexOffset);
      }
      indexOffset += geometries[_i].attributes.position.count;
    }
    mergedGeometry.setIndex(mergedIndex);
  }

  // merge attributes

  for (var _name2 in attributes) {
    var mergedAttribute = mergeAttributes(attributes[_name2]);
    if (!mergedAttribute) {
      console.error('THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the ' + _name2 + ' attribute.');
      return null;
    }
    mergedGeometry.setAttribute(_name2, mergedAttribute);
  }

  // merge morph attributes

  for (var _name3 in morphAttributes) {
    var numMorphTargets = morphAttributes[_name3][0].length;
    if (numMorphTargets === 0) break;
    mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
    mergedGeometry.morphAttributes[_name3] = [];
    for (var _i2 = 0; _i2 < numMorphTargets; ++_i2) {
      var morphAttributesToMerge = [];
      for (var _j = 0; _j < morphAttributes[_name3].length; ++_j) {
        morphAttributesToMerge.push(morphAttributes[_name3][_j][_i2]);
      }
      var mergedMorphAttribute = mergeAttributes(morphAttributesToMerge);
      if (!mergedMorphAttribute) {
        console.error('THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the ' + _name3 + ' morphAttribute.');
        return null;
      }
      mergedGeometry.morphAttributes[_name3].push(mergedMorphAttribute);
    }
  }
  return mergedGeometry;
}

/**
 * @param {Array<BufferAttribute>} attributes
 * @return {BufferAttribute}
 */
function mergeAttributes(attributes) {
  var TypedArray;
  var itemSize;
  var normalized;
  var gpuType = -1;
  var arrayLength = 0;
  for (var i = 0; i < attributes.length; ++i) {
    var attribute = attributes[i];
    if (attribute.isInterleavedBufferAttribute) {
      console.error('THREE.BufferGeometryUtils: .mergeAttributes() failed. InterleavedBufferAttributes are not supported.');
      return null;
    }
    if (TypedArray === undefined) TypedArray = attribute.array.constructor;
    if (TypedArray !== attribute.array.constructor) {
      console.error('THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.');
      return null;
    }
    if (itemSize === undefined) itemSize = attribute.itemSize;
    if (itemSize !== attribute.itemSize) {
      console.error('THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.');
      return null;
    }
    if (normalized === undefined) normalized = attribute.normalized;
    if (normalized !== attribute.normalized) {
      console.error('THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.');
      return null;
    }
    if (gpuType === -1) gpuType = attribute.gpuType;
    if (gpuType !== attribute.gpuType) {
      console.error('THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes.');
      return null;
    }
    arrayLength += attribute.array.length;
  }
  var array = new TypedArray(arrayLength);
  var offset = 0;
  for (var _i3 = 0; _i3 < attributes.length; ++_i3) {
    array.set(attributes[_i3].array, offset);
    offset += attributes[_i3].array.length;
  }
  var result = new _three.BufferAttribute(array, itemSize, normalized);
  if (gpuType !== undefined) {
    result.gpuType = gpuType;
  }
  return result;
}

/**
 * @param {BufferAttribute}
 * @return {BufferAttribute}
 */
function deepCloneAttribute(attribute) {
  if (attribute.isInstancedInterleavedBufferAttribute || attribute.isInterleavedBufferAttribute) {
    return deinterleaveAttribute(attribute);
  }
  if (attribute.isInstancedBufferAttribute) {
    return new _three.InstancedBufferAttribute().copy(attribute);
  }
  return new _three.BufferAttribute().copy(attribute);
}

/**
 * @param {Array<BufferAttribute>} attributes
 * @return {Array<InterleavedBufferAttribute>}
 */
function interleaveAttributes(attributes) {
  // Interleaves the provided attributes into an InterleavedBuffer and returns
  // a set of InterleavedBufferAttributes for each attribute
  var TypedArray;
  var arrayLength = 0;
  var stride = 0;

  // calculate the length and type of the interleavedBuffer
  for (var i = 0, l = attributes.length; i < l; ++i) {
    var attribute = attributes[i];
    if (TypedArray === undefined) TypedArray = attribute.array.constructor;
    if (TypedArray !== attribute.array.constructor) {
      console.error('AttributeBuffers of different types cannot be interleaved');
      return null;
    }
    arrayLength += attribute.array.length;
    stride += attribute.itemSize;
  }

  // Create the set of buffer attributes
  var interleavedBuffer = new _three.InterleavedBuffer(new TypedArray(arrayLength), stride);
  var offset = 0;
  var res = [];
  var getters = ['getX', 'getY', 'getZ', 'getW'];
  var setters = ['setX', 'setY', 'setZ', 'setW'];
  for (var j = 0, _l = attributes.length; j < _l; j++) {
    var _attribute = attributes[j];
    var itemSize = _attribute.itemSize;
    var count = _attribute.count;
    var iba = new _three.InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, _attribute.normalized);
    res.push(iba);
    offset += itemSize;

    // Move the data for each attribute into the new interleavedBuffer
    // at the appropriate offset
    for (var c = 0; c < count; c++) {
      for (var k = 0; k < itemSize; k++) {
        iba[setters[k]](c, _attribute[getters[k]](c));
      }
    }
  }
  return res;
}

// returns a new, non-interleaved version of the provided attribute
function deinterleaveAttribute(attribute) {
  var cons = attribute.data.array.constructor;
  var count = attribute.count;
  var itemSize = attribute.itemSize;
  var normalized = attribute.normalized;
  var array = new cons(count * itemSize);
  var newAttribute;
  if (attribute.isInstancedInterleavedBufferAttribute) {
    newAttribute = new _three.InstancedBufferAttribute(array, itemSize, normalized, attribute.meshPerAttribute);
  } else {
    newAttribute = new _three.BufferAttribute(array, itemSize, normalized);
  }
  for (var i = 0; i < count; i++) {
    newAttribute.setX(i, attribute.getX(i));
    if (itemSize >= 2) {
      newAttribute.setY(i, attribute.getY(i));
    }
    if (itemSize >= 3) {
      newAttribute.setZ(i, attribute.getZ(i));
    }
    if (itemSize >= 4) {
      newAttribute.setW(i, attribute.getW(i));
    }
  }
  return newAttribute;
}

// deinterleaves all attributes on the geometry
function deinterleaveGeometry(geometry) {
  var attributes = geometry.attributes;
  var morphTargets = geometry.morphTargets;
  var attrMap = new Map();
  for (var key in attributes) {
    var attr = attributes[key];
    if (attr.isInterleavedBufferAttribute) {
      if (!attrMap.has(attr)) {
        attrMap.set(attr, deinterleaveAttribute(attr));
      }
      attributes[key] = attrMap.get(attr);
    }
  }
  for (var _key in morphTargets) {
    var _attr = morphTargets[_key];
    if (_attr.isInterleavedBufferAttribute) {
      if (!attrMap.has(_attr)) {
        attrMap.set(_attr, deinterleaveAttribute(_attr));
      }
      morphTargets[_key] = attrMap.get(_attr);
    }
  }
}

/**
 * @param {Array<BufferGeometry>} geometry
 * @return {number}
 */
function estimateBytesUsed(geometry) {
  // Return the estimated memory used by this geometry in bytes
  // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  // for InterleavedBufferAttributes.
  var mem = 0;
  for (var name in geometry.attributes) {
    var attr = geometry.getAttribute(name);
    mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  }
  var indices = geometry.getIndex();
  mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  return mem;
}

/**
 * @param {BufferGeometry} geometry
 * @param {number} tolerance
 * @return {BufferGeometry}
 */
function mergeVertices(geometry) {
  var tolerance = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1e-4;
  tolerance = Math.max(tolerance, Number.EPSILON);

  // Generate an index buffer if the geometry doesn't have one, or optimize it
  // if it's already available.
  var hashToIndex = {};
  var indices = geometry.getIndex();
  var positions = geometry.getAttribute('position');
  var vertexCount = indices ? indices.count : positions.count;

  // next value for triangle indices
  var nextIndex = 0;

  // attributes and new attribute arrays
  var attributeNames = Object.keys(geometry.attributes);
  var tmpAttributes = {};
  var tmpMorphAttributes = {};
  var newIndices = [];
  var getters = ['getX', 'getY', 'getZ', 'getW'];
  var setters = ['setX', 'setY', 'setZ', 'setW'];

  // Initialize the arrays, allocating space conservatively. Extra
  // space will be trimmed in the last step.
  for (var i = 0, l = attributeNames.length; i < l; i++) {
    var name = attributeNames[i];
    var attr = geometry.attributes[name];
    tmpAttributes[name] = new _three.BufferAttribute(new attr.array.constructor(attr.count * attr.itemSize), attr.itemSize, attr.normalized);
    var morphAttr = geometry.morphAttributes[name];
    if (morphAttr) {
      tmpMorphAttributes[name] = new _three.BufferAttribute(new morphAttr.array.constructor(morphAttr.count * morphAttr.itemSize), morphAttr.itemSize, morphAttr.normalized);
    }
  }

  // convert the error tolerance to an amount of decimal places to truncate to
  var decimalShift = Math.log10(1 / tolerance);
  var shiftMultiplier = Math.pow(10, decimalShift);
  for (var _i4 = 0; _i4 < vertexCount; _i4++) {
    var index = indices ? indices.getX(_i4) : _i4;

    // Generate a hash for the vertex attributes at the current index 'i'
    var hash = '';
    for (var j = 0, _l2 = attributeNames.length; j < _l2; j++) {
      var _name4 = attributeNames[j];
      var attribute = geometry.getAttribute(_name4);
      var itemSize = attribute.itemSize;
      for (var k = 0; k < itemSize; k++) {
        // double tilde truncates the decimal value
        hash += "".concat(~~(attribute[getters[k]](index) * shiftMultiplier), ",");
      }
    }

    // Add another reference to the vertex if it's already
    // used by another index
    if (hash in hashToIndex) {
      newIndices.push(hashToIndex[hash]);
    } else {
      // copy data to the new index in the temporary attributes
      for (var _j2 = 0, _l3 = attributeNames.length; _j2 < _l3; _j2++) {
        var _name5 = attributeNames[_j2];
        var _attribute2 = geometry.getAttribute(_name5);
        var _morphAttr = geometry.morphAttributes[_name5];
        var _itemSize = _attribute2.itemSize;
        var newarray = tmpAttributes[_name5];
        var newMorphArrays = tmpMorphAttributes[_name5];
        for (var _k = 0; _k < _itemSize; _k++) {
          var getterFunc = getters[_k];
          var setterFunc = setters[_k];
          newarray[setterFunc](nextIndex, _attribute2[getterFunc](index));
          if (_morphAttr) {
            for (var m = 0, ml = _morphAttr.length; m < ml; m++) {
              newMorphArrays[m][setterFunc](nextIndex, _morphAttr[m][getterFunc](index));
            }
          }
        }
      }
      hashToIndex[hash] = nextIndex;
      newIndices.push(nextIndex);
      nextIndex++;
    }
  }

  // generate result BufferGeometry
  var result = geometry.clone();
  for (var _name6 in geometry.attributes) {
    var tmpAttribute = tmpAttributes[_name6];
    result.setAttribute(_name6, new _three.BufferAttribute(tmpAttribute.array.slice(0, nextIndex * tmpAttribute.itemSize), tmpAttribute.itemSize, tmpAttribute.normalized));
    if (!(_name6 in tmpMorphAttributes)) continue;
    for (var _j3 = 0; _j3 < tmpMorphAttributes[_name6].length; _j3++) {
      var tmpMorphAttribute = tmpMorphAttributes[_name6][_j3];
      result.morphAttributes[_name6][_j3] = new _three.BufferAttribute(tmpMorphAttribute.array.slice(0, nextIndex * tmpMorphAttribute.itemSize), tmpMorphAttribute.itemSize, tmpMorphAttribute.normalized);
    }
  }

  // indices

  result.setIndex(newIndices);
  return result;
}

/**
 * @param {BufferGeometry} geometry
 * @param {number} drawMode
 * @return {BufferGeometry}
 */
function toTrianglesDrawMode(geometry, drawMode) {
  if (drawMode === _three.TrianglesDrawMode) {
    console.warn('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.');
    return geometry;
  }
  if (drawMode === _three.TriangleFanDrawMode || drawMode === _three.TriangleStripDrawMode) {
    var index = geometry.getIndex();

    // generate index if not present

    if (index === null) {
      var indices = [];
      var position = geometry.getAttribute('position');
      if (position !== undefined) {
        for (var i = 0; i < position.count; i++) {
          indices.push(i);
        }
        geometry.setIndex(indices);
        index = geometry.getIndex();
      } else {
        console.error('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.');
        return geometry;
      }
    }

    //

    var numberOfTriangles = index.count - 2;
    var newIndices = [];
    if (drawMode === _three.TriangleFanDrawMode) {
      // gl.TRIANGLE_FAN

      for (var _i5 = 1; _i5 <= numberOfTriangles; _i5++) {
        newIndices.push(index.getX(0));
        newIndices.push(index.getX(_i5));
        newIndices.push(index.getX(_i5 + 1));
      }
    } else {
      // gl.TRIANGLE_STRIP

      for (var _i6 = 0; _i6 < numberOfTriangles; _i6++) {
        if (_i6 % 2 === 0) {
          newIndices.push(index.getX(_i6));
          newIndices.push(index.getX(_i6 + 1));
          newIndices.push(index.getX(_i6 + 2));
        } else {
          newIndices.push(index.getX(_i6 + 2));
          newIndices.push(index.getX(_i6 + 1));
          newIndices.push(index.getX(_i6));
        }
      }
    }
    if (newIndices.length / 3 !== numberOfTriangles) {
      console.error('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.');
    }

    // build final geometry

    var newGeometry = geometry.clone();
    newGeometry.setIndex(newIndices);
    newGeometry.clearGroups();
    return newGeometry;
  } else {
    console.error('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode);
    return geometry;
  }
}

/**
 * Calculates the morphed attributes of a morphed/skinned BufferGeometry.
 * Helpful for Raytracing or Decals.
 * @param {Mesh | Line | Points} object An instance of Mesh, Line or Points.
 * @return {Object} An Object with original position/normal attributes and morphed ones.
 */
function computeMorphedAttributes(object) {
  var _vA = new _three.Vector3();
  var _vB = new _three.Vector3();
  var _vC = new _three.Vector3();
  var _tempA = new _three.Vector3();
  var _tempB = new _three.Vector3();
  var _tempC = new _three.Vector3();
  var _morphA = new _three.Vector3();
  var _morphB = new _three.Vector3();
  var _morphC = new _three.Vector3();
  function _calculateMorphedAttributeData(object, attribute, morphAttribute, morphTargetsRelative, a, b, c, modifiedAttributeArray) {
    _vA.fromBufferAttribute(attribute, a);
    _vB.fromBufferAttribute(attribute, b);
    _vC.fromBufferAttribute(attribute, c);
    var morphInfluences = object.morphTargetInfluences;
    if (morphAttribute && morphInfluences) {
      _morphA.set(0, 0, 0);
      _morphB.set(0, 0, 0);
      _morphC.set(0, 0, 0);
      for (var _i7 = 0, _il = morphAttribute.length; _i7 < _il; _i7++) {
        var influence = morphInfluences[_i7];
        var morph = morphAttribute[_i7];
        if (influence === 0) continue;
        _tempA.fromBufferAttribute(morph, a);
        _tempB.fromBufferAttribute(morph, b);
        _tempC.fromBufferAttribute(morph, c);
        if (morphTargetsRelative) {
          _morphA.addScaledVector(_tempA, influence);
          _morphB.addScaledVector(_tempB, influence);
          _morphC.addScaledVector(_tempC, influence);
        } else {
          _morphA.addScaledVector(_tempA.sub(_vA), influence);
          _morphB.addScaledVector(_tempB.sub(_vB), influence);
          _morphC.addScaledVector(_tempC.sub(_vC), influence);
        }
      }
      _vA.add(_morphA);
      _vB.add(_morphB);
      _vC.add(_morphC);
    }
    if (object.isSkinnedMesh) {
      object.applyBoneTransform(a, _vA);
      object.applyBoneTransform(b, _vB);
      object.applyBoneTransform(c, _vC);
    }
    modifiedAttributeArray[a * 3 + 0] = _vA.x;
    modifiedAttributeArray[a * 3 + 1] = _vA.y;
    modifiedAttributeArray[a * 3 + 2] = _vA.z;
    modifiedAttributeArray[b * 3 + 0] = _vB.x;
    modifiedAttributeArray[b * 3 + 1] = _vB.y;
    modifiedAttributeArray[b * 3 + 2] = _vB.z;
    modifiedAttributeArray[c * 3 + 0] = _vC.x;
    modifiedAttributeArray[c * 3 + 1] = _vC.y;
    modifiedAttributeArray[c * 3 + 2] = _vC.z;
  }
  var geometry = object.geometry;
  var material = object.material;
  var a, b, c;
  var index = geometry.index;
  var positionAttribute = geometry.attributes.position;
  var morphPosition = geometry.morphAttributes.position;
  var morphTargetsRelative = geometry.morphTargetsRelative;
  var normalAttribute = geometry.attributes.normal;
  var morphNormal = geometry.morphAttributes.position;
  var groups = geometry.groups;
  var drawRange = geometry.drawRange;
  var i, j, il, jl;
  var group;
  var start, end;
  var modifiedPosition = new Float32Array(positionAttribute.count * positionAttribute.itemSize);
  var modifiedNormal = new Float32Array(normalAttribute.count * normalAttribute.itemSize);
  if (index !== null) {
    // indexed buffer geometry

    if (Array.isArray(material)) {
      for (i = 0, il = groups.length; i < il; i++) {
        group = groups[i];
        start = Math.max(group.start, drawRange.start);
        end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
        for (j = start, jl = end; j < jl; j += 3) {
          a = index.getX(j);
          b = index.getX(j + 1);
          c = index.getX(j + 2);
          _calculateMorphedAttributeData(object, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition);
          _calculateMorphedAttributeData(object, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal);
        }
      }
    } else {
      start = Math.max(0, drawRange.start);
      end = Math.min(index.count, drawRange.start + drawRange.count);
      for (i = start, il = end; i < il; i += 3) {
        a = index.getX(i);
        b = index.getX(i + 1);
        c = index.getX(i + 2);
        _calculateMorphedAttributeData(object, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition);
        _calculateMorphedAttributeData(object, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal);
      }
    }
  } else {
    // non-indexed buffer geometry

    if (Array.isArray(material)) {
      for (i = 0, il = groups.length; i < il; i++) {
        group = groups[i];
        start = Math.max(group.start, drawRange.start);
        end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
        for (j = start, jl = end; j < jl; j += 3) {
          a = j;
          b = j + 1;
          c = j + 2;
          _calculateMorphedAttributeData(object, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition);
          _calculateMorphedAttributeData(object, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal);
        }
      }
    } else {
      start = Math.max(0, drawRange.start);
      end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
      for (i = start, il = end; i < il; i += 3) {
        a = i;
        b = i + 1;
        c = i + 2;
        _calculateMorphedAttributeData(object, positionAttribute, morphPosition, morphTargetsRelative, a, b, c, modifiedPosition);
        _calculateMorphedAttributeData(object, normalAttribute, morphNormal, morphTargetsRelative, a, b, c, modifiedNormal);
      }
    }
  }
  var morphedPositionAttribute = new _three.Float32BufferAttribute(modifiedPosition, 3);
  var morphedNormalAttribute = new _three.Float32BufferAttribute(modifiedNormal, 3);
  return {
    positionAttribute: positionAttribute,
    normalAttribute: normalAttribute,
    morphedPositionAttribute: morphedPositionAttribute,
    morphedNormalAttribute: morphedNormalAttribute
  };
}
function mergeGroups(geometry) {
  if (geometry.groups.length === 0) {
    console.warn('THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge.');
    return geometry;
  }
  var groups = geometry.groups;

  // sort groups by material index

  groups = groups.sort(function (a, b) {
    if (a.materialIndex !== b.materialIndex) return a.materialIndex - b.materialIndex;
    return a.start - b.start;
  });

  // create index for non-indexed geometries

  if (geometry.getIndex() === null) {
    var positionAttribute = geometry.getAttribute('position');
    var indices = [];
    for (var i = 0; i < positionAttribute.count; i += 3) {
      indices.push(i, i + 1, i + 2);
    }
    geometry.setIndex(indices);
  }

  // sort index

  var index = geometry.getIndex();
  var newIndices = [];
  for (var _i8 = 0; _i8 < groups.length; _i8++) {
    var group = groups[_i8];
    var groupStart = group.start;
    var groupLength = groupStart + group.count;
    for (var j = groupStart; j < groupLength; j++) {
      newIndices.push(index.getX(j));
    }
  }
  geometry.dispose(); // Required to force buffer recreation
  geometry.setIndex(newIndices);

  // update groups indices

  var start = 0;
  for (var _i9 = 0; _i9 < groups.length; _i9++) {
    var _group = groups[_i9];
    _group.start = start;
    start += _group.count;
  }

  // merge groups

  var currentGroup = groups[0];
  geometry.groups = [currentGroup];
  for (var _i10 = 1; _i10 < groups.length; _i10++) {
    var _group2 = groups[_i10];
    if (currentGroup.materialIndex === _group2.materialIndex) {
      currentGroup.count += _group2.count;
    } else {
      currentGroup = _group2;
      geometry.groups.push(currentGroup);
    }
  }
  return geometry;
}

// Creates a new, non-indexed geometry with smooth normals everywhere except faces that meet at
// an angle greater than the crease angle.
function toCreasedNormals(geometry) {
  var creaseAngle = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Math.PI / 3;
  var creaseDot = Math.cos(creaseAngle);
  var hashMultiplier = (1 + 1e-10) * 1e2;

  // reusable vertors
  var verts = [new _three.Vector3(), new _three.Vector3(), new _three.Vector3()];
  var tempVec1 = new _three.Vector3();
  var tempVec2 = new _three.Vector3();
  var tempNorm = new _three.Vector3();
  var tempNorm2 = new _three.Vector3();

  // hashes a vector
  function hashVertex(v) {
    var x = ~~(v.x * hashMultiplier);
    var y = ~~(v.y * hashMultiplier);
    var z = ~~(v.z * hashMultiplier);
    return "".concat(x, ",").concat(y, ",").concat(z);
  }
  var resultGeometry = geometry.toNonIndexed();
  var posAttr = resultGeometry.attributes.position;
  var vertexMap = {};

  // find all the normals shared by commonly located vertices
  for (var i = 0, l = posAttr.count / 3; i < l; i++) {
    var i3 = 3 * i;
    var a = verts[0].fromBufferAttribute(posAttr, i3 + 0);
    var b = verts[1].fromBufferAttribute(posAttr, i3 + 1);
    var c = verts[2].fromBufferAttribute(posAttr, i3 + 2);
    tempVec1.subVectors(c, b);
    tempVec2.subVectors(a, b);

    // add the normal to the map for all vertices
    var normal = new _three.Vector3().crossVectors(tempVec1, tempVec2).normalize();
    for (var n = 0; n < 3; n++) {
      var vert = verts[n];
      var hash = hashVertex(vert);
      if (!(hash in vertexMap)) {
        vertexMap[hash] = [];
      }
      vertexMap[hash].push(normal);
    }
  }

  // average normals from all vertices that share a common location if they are within the
  // provided crease threshold
  var normalArray = new Float32Array(posAttr.count * 3);
  var normAttr = new _three.BufferAttribute(normalArray, 3, false);
  for (var _i11 = 0, _l4 = posAttr.count / 3; _i11 < _l4; _i11++) {
    // get the face normal for this vertex
    var _i12 = 3 * _i11;
    var _a = verts[0].fromBufferAttribute(posAttr, _i12 + 0);
    var _b = verts[1].fromBufferAttribute(posAttr, _i12 + 1);
    var _c = verts[2].fromBufferAttribute(posAttr, _i12 + 2);
    tempVec1.subVectors(_c, _b);
    tempVec2.subVectors(_a, _b);
    tempNorm.crossVectors(tempVec1, tempVec2).normalize();

    // average all normals that meet the threshold and set the normal value
    for (var _n = 0; _n < 3; _n++) {
      var _vert = verts[_n];
      var _hash = hashVertex(_vert);
      var otherNormals = vertexMap[_hash];
      tempNorm2.set(0, 0, 0);
      for (var k = 0, lk = otherNormals.length; k < lk; k++) {
        var otherNorm = otherNormals[k];
        if (tempNorm.dot(otherNorm) > creaseDot) {
          tempNorm2.add(otherNorm);
        }
      }
      tempNorm2.normalize();
      normAttr.setXYZ(_i12 + _n, tempNorm2.x, tempNorm2.y, tempNorm2.z);
    }
  }
  resultGeometry.setAttribute('normal', normAttr);
  return resultGeometry;
}
function mergeBufferGeometries(geometries) {
  var useGroups = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  console.warn('THREE.BufferGeometryUtils: mergeBufferGeometries() has been renamed to mergeGeometries().'); // @deprecated, r151
  return mergeGeometries(geometries, useGroups);
}
function mergeBufferAttributes(attributes) {
  console.warn('THREE.BufferGeometryUtils: mergeBufferAttributes() has been renamed to mergeAttributes().'); // @deprecated, r151
  return mergeAttributes(attributes);
}