Search code examples
javascripttypescriptthree.jsweb-worker

How to build Float32Array from ArrayBuffer


Consider I have an ArrayBuffer, as shown in next screenshot)

Screenshot from google developers console

//recompute object from vertices and normals
const verticesBuffer:ArrayBuffer = e.data.verticesBufferArray;
const normalsBuffer:ArrayBuffer = e.data.normalsBufferArray;

const vertices = new Float32Array(verticesBuffer);
const normals = new Float32Array(normalsBuffer);

But at this point vertices and normals are undefined. So, variables vertices and normals are undefined while verticesBuffer and normalBuffer are ok.

On the conversion I get following error

const vertices = new Float32Array(verticesBuffer);

Uncaught RangeError: Invalid typed array length: 39744

So question is how to pass from verticesBuffer:ArrayBuffer to vertices:Float32Array ?

Thanks!


Solution

  •   const vertexCount = verticesBuffer.byteLength / 4;
      const normalCount = normalsBuffer.byteLength / 4;
    
      const vertices = Float32Array.from(verticesBuffer, 0, vertexCount);
      const normals = Float32Array.from(normalsBuffer, 0, normalCount);