异步纹理加载iPhone OpenGL ES 2

时间:2012-07-07 00:22:02

标签: iphone opengl-es asynchronous textures nsthread

我正在创建和加载大量纹理(由字符串组成)。为了使动画顺利运行,我将工作卸载到单独的工作线程。它似乎或多或少地按照我想要的方式工作,但在旧设备(iPhone 3GS)上,我有时会注意到很长(1秒)的延迟。它有时只会发生。现在我想知道我是否正确地做了这个或者是否存在任何概念问题。我粘贴下面的源代码。

我还应该提到我不想使用GLKit TextureLoader,因为我还想将纹理生成工作卸载到另一个线程,而不仅仅是加载部分。

如果你想知道我需要这些纹理,请看一下这个视频:http://youtu.be/U03p4ZhLjvY?hd=1

NSLock*                     _textureLock;
NSMutableDictionary*        _texturesWithString;
NSMutableArray*             _texturesWithStringLoading;

// This is called when I request a new texture from the drawing routine. 
// If this function returns 0, it means the texture is not ready and Im not displaying it.

-(unsigned int)getTextureWithString:(NSString*)string {
    Texture2D* _texture = [_texturesWithString objectForKey:string];
    if (_texture==nil){
        if (![_texturesWithStringLoading containsObject:string]){
            [_texturesWithStringLoading addObject:string];
            NSDictionary* dic = [[NSDictionary alloc] initWithObjectsAndKeys:string,@"string", nil];
            NSThread* thread = [[NSThread alloc] initWithTarget:self selector:@selector(loadTextureWithDictionary:)object:dic];
            thread.threadPriority = 0.01;
            [thread start];
            [thread release];
        }
        return 0;
    }
    return _texture.name;
}

// This is executed on a separate worker thread.
// The lock makes sure that there are not hundreds of separate threads all creating a texture at the same time and therefore slowing everything down. 
// There must be a smarter way of doing that. Please let me know if you know how! ;-)
-(void)loadTextureWithOptions:(NSDictionary*)_dic{
    [_textureLock lock];
    EAGLContext* context = [[SharegroupManager defaultSharegroup] getNewContext];
    [EAGLContext setCurrentContext: context];

    NSString* string = [_dic objectForKey:@"string"];
    Texture2D* _texture = [[Texture2D alloc] initWithStringModified:string];

    if (_texture!=nil) {
        NSDictionary* _newdic = [[NSDictionary alloc] initWithObjectsAndKeys:_texture,@"texture",string,@"string", nil];
        [self performSelectorOnMainThread:@selector(doneLoadingTexture:) withObject:_newdic waitUntilDone:NO];
        [_newdic release];
        [_texture release];
    }
    [EAGLContext setCurrentContext: nil];
    [context release];
    [_textureLock unlock];
}

// This callback is executed on the main thread and marks adds the texture to the texture cache. 
-(void)doneLoadingTextureWithDictionary:(NSDictionary*)_dic{
    [_texturesWithString setValue:[_dic objectForKey:@"texture"] forKey:[_dic objectForKey:@"string"]];
    [_texturesWithStringLoading removeObject:[_dic objectForKey:@"string"]];
}

1 个答案:

答案 0 :(得分:0)

问题是同时启动了太多线程。现在我使用NSOperationQueue而不是NSThreads。这允许我设置maxConcurrentOperationCount并且只运行一个额外的后台线程来执行纹理加载。