addMorphTargets function

dynamic addMorphTargets(
  1. dynamic geometry,
  2. dynamic targets,
  3. dynamic parser
)

Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets

@param {BufferGeometry} geometry @param {Array<GLTF.Target>} targets @param {GLTFParser} parser @return {Promise

Implementation

addMorphTargets(geometry, targets, parser) async {
  var hasMorphPosition = false;
  var hasMorphNormal = false;
  var hasMorphColor = false;

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

    if (target["POSITION"] != null) hasMorphPosition = true;
    if (target["NORMAL"] != null) hasMorphNormal = true;
    if (target["COLOR_0"] != null) hasMorphColor = true;

    if (hasMorphPosition && hasMorphNormal && hasMorphColor) break;
  }

  if (!hasMorphPosition && !hasMorphNormal && !hasMorphColor) return geometry;

  List<BufferAttribute> morphPositions = [];
  List<BufferAttribute> morphNormals = [];
  List<BufferAttribute> morphColors = [];

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

    if (hasMorphPosition) {
      var position = target["POSITION"] != null
          ? await parser.getDependency('accessor', target["POSITION"])
          : geometry.attributes["position"];

      morphPositions.add(position);
    }

    if (hasMorphNormal) {
      var normal = target["NORMAL"] != null
          ? await parser.getDependency('accessor', target["NORMAL"])
          : geometry.attributes["normal"];

      morphNormals.add(normal);
    }

    if (hasMorphColor) {
      var color = target["COLOR_0"] != null
          ? await parser.getDependency('accessor', target["COLOR_0"])
          : geometry.attributes["color"];

      morphColors.add(color);
    }
  }

  if (hasMorphPosition) geometry.morphAttributes["position"] = morphPositions;
  if (hasMorphNormal) geometry.morphAttributes["normal"] = morphNormals;
  if (hasMorphColor) geometry.morphAttributes["color"] = morphColors;

  geometry.morphTargetsRelative = true;

  return geometry;
}