GPU upload
Using the GPU requires three main steps: input, process, and output.
Input (upload)
- Generate data on CPU
- Make buffer on GPU
- Allocate and send CPU data to GPU
- Build and upload shader program to GPU
Process
- Run shader program on GPU
Output
- Display results on screen or
- Send results back to CPU
All upload steps must take place before rendering. First allocate CPU side:
GLfloat positions[10] = {-1,-1, 1,1, -0.5,-0.366, 0,0.5, 0.5,-0.366};
Prepare an OpenGL buffer object.
// Generate a GPU side buffer
glGenBuffers(1, &positionBuffer);
You can allocate several buffers at once with
glGenBuffers(count,dest_array)
, where count is how many you want and
dest_array is where the handles go.
Next, activate the buffer so OpenGL knows which to use. Afterwards, all buffer operations will use the bound buffer.
// Tell OpenGL we want to work with the buffer we just made
glBindBuffer(GL_ARRAY_BUFFER, positionBuffer);
Finally, allocate space on the GPU and upload the data.
// Alloate and upload data to GPU
glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW);
Now the data is on the GPU!
API details: glBufferData(target, size, data_ptr, usage)
.
- target: what part of OpenGL we are changing
- size: size in bytes
- data: pointer to CPU data
- usage: hint on how we will use the data