mergeVertices method

dynamic mergeVertices({
  1. int precisionPoints = 4,
})

Implementation

mergeVertices({int precisionPoints = 4}) {
  var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  List<three.Vector3> unique = [];
  var changes = List.filled(vertices.length, 0);

  var precision = three.Math.pow(10, precisionPoints);

  for (var i = 0, il = vertices.length; i < il; i++) {
    var v = vertices[i];
    var key =
        '${three.Math.round(v.x * precision)}_${three.Math.round(v.y * precision)}_${three.Math.round(v.z * precision)}';

    if (verticesMap[key] == null) {
      verticesMap[key] = i;
      unique.add(vertices[i]);
      changes[i] = unique.length - 1;
    } else {
      //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
      changes[i] = changes[verticesMap[key]];
    }
  }

  // if faces are completely degenerate after merging vertices, we
  // have to remove them from the geometry.
  var faceIndicesToRemove = [];

  for (var i = 0, il = faces.length; i < il; i++) {
    var face = faces[i];

    face.a = changes[face.a];
    face.b = changes[face.b];
    face.c = changes[face.c];

    var indices = [face.a, face.b, face.c];

    // if any duplicate vertices are found in a Face3
    // we have to remove the face as nothing can be saved
    for (var n = 0; n < 3; n++) {
      if (indices[n] == indices[(n + 1) % 3]) {
        faceIndicesToRemove.add(i);
        break;
      }
    }
  }

  for (var i = faceIndicesToRemove.length - 1; i >= 0; i--) {
    var idx = faceIndicesToRemove[i];

    faces.sublist(idx, idx + 1);

    for (var j = 0, jl = faceVertexUvs.length; j < jl; j++) {
      faceVertexUvs[j]?.sublist(idx, idx + 1);
    }
  }

  // Use unique set of vertices

  var diff = vertices.length - unique.length;
  vertices = unique;
  return diff;
}