1

Why does the buffer also change when I change positionView and colorView?

var buffer = new ArrayBuffer(nbrOfVertices * vertexSizeInBytes);
var positionView = new Float32Array(buffer);
var colorView = new Uint8Array(buffer);
3
  • What do you mean by changed? Seems to stay the same for me… Commented Apr 19, 2015 at 13:47
  • 1
    Both of the views write to the same underlying buffer. Copy it if you need them to be separate. Commented Apr 19, 2015 at 13:55
  • Oh, you mean, when you actually assign values to positionView or colorView. Commented Apr 19, 2015 at 13:58

1 Answer 1

2

All typed array structures are views upon an ArrayBuffer. They allow you to access and modify the underlying binary data within the ArrayBuffer in a choosen layout such as 32bit floats.

If you want to create separate buffers you could just create your position- and colorbuffers by using the number of vertices multiplied by the number of components as argument, this implicitly creates an underlying ArrayBuffer accessable via the buffer property of the view.

var numVertices = 4;
var positions = new Float32Array(numVertices * 3 /*position: x, y, z*/);
var colors = new Uint8Array(numVertices * 4 /*color: r, g, b, a*/);

If you're trying to set up an interlaced VertexBuffer with the layout: f32pX,f32pY,f32pZ,ui8cR,ui8cG,ui8cB,ui8cA "on the fly" your colorView also "views" the float data, so you have to offset your writings by 12 byte.

var positionOffset = 3 * 4;//3 positions with 4 byte each
var bufferOffset = positionOffset+4;//each color component is 1 byte
for (
  var colorStart = positionOffset;
  colorStart < colorView.length;
  colorStart += bufferOffset
) {
  colorView[colorStart]=r;
  colorView[colorStart+1]=g;
  colorView[colorStart+2]=b;
  colorView[colorStart+3]=a;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.