Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change vertex buffer dynamically in WebGL

I'm developing a cloth simulator in WebGL, got all the physics and the animation ready but I just can't render it. I am used to use glVertex in Opengl, so in every iteration I can change the position of the vertex and it will move, but in WebGL (OpenGL ES) there is not such method.

This is my code:

//Initialization:
    puntosBuffer= gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, puntosBuffer);
    telaVertices3=new Array(12);
    telaVertices3=[
    0.0,0.0,0.0,
    2.0,0.0,0.0,
    1.0,1.7,0.0,
    0.0,1.0,0.0
    ];
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(telaVertices3), gl.DYNAMIC_DRAW);

//loop:
    posx=posx+0.2;
    telaVertices3[0]=posx;
    gl.bindBuffer(gl.ARRAY_BUFFER, puntosBuffer);
    gl.bufferSubData(gl.ARRAY_BUFFER, 0, new Float32Array(telaVertices3));

But it always renders at the same points!!!

like image 852
Sebastian Breit Avatar asked Aug 23 '11 20:08

Sebastian Breit


1 Answers

I use additional calls to gl.bufferData(...) instead of gl.bufferSubData(...). I don't know if this matters or not, but I think it's the only thing I'm doing differently from your example.

You can see my current implementation of buffer management at jax/buffer.js#L48 and an older version at webgl/buffer.js#L26. As you can see, I'm not doing anything special:

gl.bindBuffer(self.bufferType, buffer);
gl.bufferData(self.bufferType, instance, self.drawType);

You can see the animation in a live demo at webgldemos/md2.

However

If you're planning to update a lot of vertices at once then this is probably not the best method. Instead, I'd propose sending the relevant data down to the video card and performing animation directly within GLSL, so that you aren't limited by JavaScript slowness and can take advantage of hardware acceleration. In fact, I'm transitioning most of my code to work this way. Two live examples of vertex manipulation on the video card are available at jax/blobular and jax/meadow. The source code for those demos is freely available here and here, respectively.

I hope this was helpful to you.

like image 73
sinisterchipmunk Avatar answered Oct 17 '22 03:10

sinisterchipmunk