我尝试为我的 Android NDK 游戏项目编写加载屏幕 - 以预加载所有纹理。 如果在其他线程中创建纹理,我会正确设置纹理宽度等值,但只会得到黑色 Sprite 而不是纹理 Sprite ,即使 glGetError 返回 0。在同一线程中一切正常,所以假设 Sprite 或纹理代码没有错误.
我认为这是因为我尝试从另一个线程调用 opengl es 2.0 函数,而没有 EGL 提供的上下文。但是,如何从用 Java (Android) 创建的 EGL 获取 opengl es 2.0 上下文并将其绑定(bind)以在 native C 中的 opengl es 2.0 函数中使用?
Java(安卓)
public class OGLES2View extends GLSurfaceView
{
private static final int OGLES_VERSION = 2;
public OGLES2View(Context context)
{
super(context);
setEGLContextClientVersion(OGLES_VERSION);
setRenderer(new OGLES2Renderer());
}
private GLSurfaceView ogles2SurfaceView = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ogles2SurfaceView = new OGLES2View(this);
setContentView(ogles2SurfaceView);
}
C
#define TRUE 1
#define FALSE 0
typedef unsigned char bool;
typedef struct game_data
{
bool loaded;
tex* t;
}game_data;
static void* loader_thread_func(void* arg)
{
JavaVM* jvm = get_java_vm(); //get java VM to detach in the end
JNIEnv* env = get_jni_env(); //== attach current thread
game_data* to_load = (game_data*) arg;
to_load->t = malloc(sizeof(tex));
set_tex(to_load->t,"textures/bonus.png");//textures width and height set correctly
to_load->loaded = TRUE;
(*jvm)->DetachCurrentThread(jvm);
return NULL;
}
void load_game_data(game_data* res)
{
pthread_t loader_thread;
pthread_create(&loader_thread, NULL, loader_thread_func, res);
}
/*in render manager file*/
static game_data* g_d = NULL;
/*in onInit func*/
g_d = malloc(sizeof(game_data));
g_d->loaded = FALSE;
load_game_data(g_d);
/*in onDraw function*/
if(g_d->loaded)
/*draw sprite*/
最佳答案
要从另一个线程调用 OpenGL ES 函数,您必须在 2 个线程之间创建一个共享的 OpenGL ES 上下文。
有一个更简单的解决方案 - 将事件发送到拥有 OpenGL ES 上下文的线程,以便在第二个线程中加载纹理后立即更新纹理。
关于java - Android NDK - 从其他线程加载纹理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11675551/