Multithreaded OpenGL

Hi all!
I’m programming an app that uses a separate thread when loading maps, models, and textures, so I can display a ‘Loading’ graphic with a progress bar. The problem is, after everything is loaded, none of the textures show up. I tried coding it wihtout multi-threading, and it worked perfectly, but I really want my progress bar! Does anybody know why OpenGL texture loading doesn’t work in a separate thread? I’ve tried everything, including checking for created rc, pixel formats, and all sorts of other crap. This is really starting to get annoying…

Tim

You must call all gl-Functions in the same rendering context.Try loading textures in separate thread and uploading in the rendering thread.

The rendering context is the same! I’m just calling the gl-functions from a different thread. Does it really matter?

Tim

Yes, it does matter. You can only use a context with one thread at a time. If you want to use two OpenGL threads, you need to create two contexts and bind them – in different threads – to the same window, and then watch out for synchronization hazards.

  • Matt

Thanks Matt, I’ll try it right away. Is this done so the video card can sync everything?

Tim

No, it’s because OpenGL drivers have no built-in synchronization of GL commands. Taking a critical section every time you called a GL entry point would be extremely expensive.

It is also rather uninteresting to have two threads talk to one GC, seeing as OpenGL is a state-based API.

  • Matt

Ah, I understand.

Well, I tried it, and it didn’t work. Right now I’m doing this:

WinMain()
{
MainRC=wglCreateContext(…);
LoadingRC=wglCreateContext(…);
wglMakeCurrent(MainRC);
ThreadHandle=CreateThread(0,0,&LoadThread,0,CREATE_SUSPENDED,&tid);

//code taken out for brevity

ResumeThread(LoadThread);
}
DWORD WINAPI LoadThread(LPVOID arg1)
{
HDC thedc;
thedc=GetDC(WindowHWND);
if(LoadingRC==NULL)
return 0;
wglMakeCurrent(thedc,LoadingRC);
TestLand.LoadMap(“Data\maps\TestMap.txt”);
AllDataLoaded=TRUE;
LoadThreadHandle=NULL;
return 0;
}

I delete both contexts in WM_DESTROY. Is this right?

Tim

[This message has been edited by teenytim (edited 02-09-2001).]

[This message has been edited by teenytim (edited 02-09-2001).]

I’d suggest using the exact same DC and making sure that your app has a CS_OWNDC window.

Beyond that, I wouldn’t know. I write drivers, not apps.

  • Matt

I got it working! I also found a texture loading bug that cause multiple texture uploads to the same texture.

Anyways, thanks Matt and zangel for answering.

Tim