Hi, my goal is to display a RenderTexture full screen on a separate window from Unity.
I have built a plugin for Unity where I make an OpenGL window and try to draw a RenderTexture on it. If I build my own application around this code, I am able to display my own (dynamic) texture on it. However I am stuck when I try to display a RenderTexture using GetNativeTexturePtr().
In fact, I am not even sure exactly what is coming out of GetNativeTexturePtr():
- If I run Unity normally, I can sometimes see garbage pixels (that do not seem related to the RenderTexture.GetNativeTexturePtr() that I sent). These pixels seem to be texture related, but not to the given RenderTexture. My guess is I am looking at random data in the GPU memory. Code below.
- If I run Unity as OpenGL, the best I can get is for it to not crash but I presume that this doesn’t work because according to the docs, Unity sends the gl texture “name” in this case, but because I am creating my own OpenGL context my understanding is that each context creates its own list of texture names hence the texture names I get are not meaningful to my external window.
Below is my attempt that at least displays garbage pixels, but sometimes crashes. I know something is definitely wrong but I am at a loss of how to actually USE the data inside GetNativeTexturePtr(). I have looked at the Unity plugin example but that only shows how to write to the texture. Is it even possible to read from it? Or is the pointer only meant for writing?
I am a novice in OpenGL, any help or pointers (har har) are greatly appreciated.
public RenderTexture rTex;
[DllImport("unityCaster")]
public static extern void update(int w, int h, System.IntPtr texPtr);
//...
void Update()
{
update(rTex.width, rTex.height, rTex.GetNativeTexturePtr());
}
void unityCaster::update(int w, int h, unsigned char * texData)
{
if (!instance)
return;
if (texData == 0)
{
glClear(GL_COLOR_BUFFER_BIT);
}
else
{
glEnable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glBindTexture(GL_TEXTURE_2D, instance->texHandle);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, texData);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// Draw a textured quad to the whole screen
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex3f(0, 0, 0);
glTexCoord2f(0, 1); glVertex3f(0, instance->height, 0);
glTexCoord2f(1, 1); glVertex3f(instance->width, instance->height, 0);
glTexCoord2f(1, 0); glVertex3f(instance->width, 0, 0);
glEnd();
glFlush();
glDisable(GL_TEXTURE_2D);
}
SDL_GL_SwapWindow(instance->window); //im using SDL to get my openGL context
glFinish(); //draw to screen
}