findAccessorMinMax.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import getAccessorByteStride from "./getAccessorByteStride.js";
  2. import getComponentReader from "./getComponentReader.js";
  3. import numberOfComponentsForType from "./numberOfComponentsForType.js";
  4. import arrayFill from "../../Core/arrayFill.js";
  5. import ComponentDatatype from "../../Core/ComponentDatatype.js";
  6. import defined from "../../Core/defined.js";
  7. /**
  8. * Finds the min and max values of the accessor.
  9. *
  10. * @param {Object} gltf A javascript object containing a glTF asset.
  11. * @param {Object} accessor The accessor object from the glTF asset to read.
  12. * @returns {{min: Array, max: Array}} min holding the array of minimum values and max holding the array of maximum values.
  13. *
  14. * @private
  15. */
  16. function findAccessorMinMax(gltf, accessor) {
  17. const bufferViews = gltf.bufferViews;
  18. const buffers = gltf.buffers;
  19. const bufferViewId = accessor.bufferView;
  20. const numberOfComponents = numberOfComponentsForType(accessor.type);
  21. // According to the spec, when bufferView is not defined, accessor must be initialized with zeros
  22. if (!defined(accessor.bufferView)) {
  23. return {
  24. min: arrayFill(new Array(numberOfComponents), 0.0),
  25. max: arrayFill(new Array(numberOfComponents), 0.0),
  26. };
  27. }
  28. const min = arrayFill(
  29. new Array(numberOfComponents),
  30. Number.POSITIVE_INFINITY
  31. );
  32. const max = arrayFill(
  33. new Array(numberOfComponents),
  34. Number.NEGATIVE_INFINITY
  35. );
  36. const bufferView = bufferViews[bufferViewId];
  37. const bufferId = bufferView.buffer;
  38. const buffer = buffers[bufferId];
  39. const source = buffer.extras._pipeline.source;
  40. const count = accessor.count;
  41. const byteStride = getAccessorByteStride(gltf, accessor);
  42. let byteOffset =
  43. accessor.byteOffset + bufferView.byteOffset + source.byteOffset;
  44. const componentType = accessor.componentType;
  45. const componentTypeByteLength =
  46. ComponentDatatype.getSizeInBytes(componentType);
  47. const dataView = new DataView(source.buffer);
  48. const components = new Array(numberOfComponents);
  49. const componentReader = getComponentReader(componentType);
  50. for (let i = 0; i < count; i++) {
  51. componentReader(
  52. dataView,
  53. byteOffset,
  54. numberOfComponents,
  55. componentTypeByteLength,
  56. components
  57. );
  58. for (let j = 0; j < numberOfComponents; j++) {
  59. const value = components[j];
  60. min[j] = Math.min(min[j], value);
  61. max[j] = Math.max(max[j], value);
  62. }
  63. byteOffset += byteStride;
  64. }
  65. return {
  66. min: min,
  67. max: max,
  68. };
  69. }
  70. export default findAccessorMinMax;