Reading binary file to vbo in OpenGL

Started by
2 comments, last by Brother Bob 11 years, 3 months ago

I am currently having trouble trying to create and load binary files of model vertex data into the vbo in OpenGL.

Here is the code for a simple test that I have done by writing 2D triangle data into a *.bin file:


	glm::vec2 points[6] =
	{
		glm::vec2( -0.5, -0.5 ), glm::vec2( 0.5, -0.5 ),
		glm::vec2( 0.5, 0.5 ), glm::vec2( 0.5, 0.5 ),
		glm::vec2( -0.5, 0.5 ), glm::vec2( -0.5, -0.5 )
	};
	
	std::ofstream fs("model.bin", std::ios::out | std::ios::binary | std::ios::app);
        for(int i = 0; i<6; i++)
	{
		fs.write((const char*)&points[i].x, sizeof(points[i].x));
		fs.write((const char*)&points[i].y, sizeof(points[i].y));
	}
	fs.close();

and here is the code for copying the data into the vbo:


	int length;
	char* data;
	ifstream is;
	is.open("model.bin", ios::binary);
	is.seekg(0, ios::end);
	length = is.tellg();
	is.seekg(0, ios::beg);
	data = new char[length];
	is.read(data, length);
	is.close();
 
	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW);

All I am getting is a blank screen, instead of a large colored square at the centre of the window. What am I doing wrong?

Advertisement

sizeof() returns the size of the expression passed to it; you pass a pointer and so it returns the size of the pointer which is probably 4 of 8 bytes. The problem is that pointers do not carry information about the size of the memory they point to, and furthermore, sizeof() is a compile-time expression but the size of the buffer is run-time dynamic. Pass length instead since that value reflects the size of the data.

it works!

Thanks Bob.

Now I guess I need to test what's the fastest method of doing this: ifstream vs fopen.

The significant performance issue is going to be the physical disk IO and not which logical method you use. Just don't make some stupid performance test where you don't take the physical disk IO into account and just keeps reading from any of the multiple levels of cache along the way to come to an irrelevant conclusion.

This topic is closed to new replies.

Advertisement