Help with threading in OpenGL

Started by
2 comments, last by nlraley 12 years, 8 months ago
I'm having trouble now that I am trying to load some of the textures in a background thread.

I know you need to create/set the Context but I'm sort of lost in doing so.

I define my thread such as:
loadTextures = new Thread(new ParameterizedThreadStart(Texture.LoadTextures));

I start the thread with the following call passing it a list of filenames of extra textures I need to load:
loadTextures.Start(texturesToLoad);

Finally my Thread execution is a single one shot thread execution:
public void LoadTexture()
{
GL.GenTextures(1, out glTexture);
GL.BindTexture(TextureTarget.Texture2D, GLTexture);

Bitmap bmp = new Bitmap(Bitmap.FromFile(filename));
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);

GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmpData.Width, bmpData.Height, 0,
OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmpData.Scan0);
GL.GenerateMipmap(GenerateMipmapTarget.Texture2D);

bmp.UnlockBits(bmpData);
bmp.Dispose();

Loaded = true;
}

public static void LoadTextures(object list)
{
List<Texture> textures = (List<Texture>)list;
foreach (Texture texture in textures)
texture.LoadTexture();
}


I've trying setting the glControl from the main form's CurrentContext(null) and all sorts of things but I just can't figure this out.

All I'm wanting to be able to do is to load/unload the extra textures from this simple thread. What am I doing wrong?
Advertisement
Queue up your loaded bitmaps and upload them to OpenGL on your main thread.
You can have any one GL context active only for exactly one thread at any given time. This means that you either have to make your GL context current for texture loading thread (meaning that your rendering thread can't use it meanwhile), or you can load images in a background thread and then make your rendering thread create textures from them.
WBW, capricorn
Okay, the approach I decided to use was to use a background worker to load the Bitmap and BitmapData and call the lockBits for the bitmap for each of the textures I need to load.

On the WorkComplete for the background worker I then call my OpenGL calls; however, whenever I have to load any additional textures via this method all I get is a black screen with a big red X across it.

Is the WorkComplete for the background worker not running from the main thread and therefore causing the issue?

This topic is closed to new replies.

Advertisement