Java – opengl rendering to texture coordinates
I want to be able to render to textures (for shaders, fonts), but I have a problem with correctly positioning quads (the frame buffer itself does what it should do) The resulting (copied) texture is displayed in the upper left corner in most cases, and the rest is cropped This is even worse for rectangular textures and has little effect on square textures (so I haven't realized this behavior for days)
Example code:
public Texture copy(final Texture tex) { final int tempTex = glGenTextures(); Draw.bindTexture(tempTex); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D,GL_RGBA,tex.getImageWidth(),tex.getImageHeight(),GL_RGB,GL_UNSIGNED_BYTE,(ByteBuffer)null); // Adjust projection matrix glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glViewport(0,tex.getImageHeight()); // Change blendmode to ignore the transparent background Draw.blendingMode(GL_ONE,GL_ONE_MINUS_SRC_ALPHA); // Prepare fbo,add the texture as backend and clear it final int fbo = glGenFramebuffers(); glBindFramebuffer(GL_FRAMEBUFFER,fbo); glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,tempTex,0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Finally draw Draw.bindTexture(tex.getId()); glBegin(GL_QUADS); { glTexCoord2f(0,0); glVertex2f(-1,-1); glTexCoord2f(1,0); glVertex2f(1,1); glVertex2f(1,1); glTexCoord2f(0,1); glVertex2f(-1,1); } glEnd(); // Unbind framebuffer glBindFramebuffer(GL_FRAMEBUFFER,0); // Reset projection matrix glViewport(0,1920,1080); // TODO Don't hardcode glPopMatrix(); return new Texture(tempTex,tex.getImageHeight()); }
Sample image:
The upper is the original image rendered below the copied version
What on earth did I do wrong?
Update: now it looks like the texture has been downsampled
Solution
You should not pass the actual texture width and height to textcoords The texture coordinates range from 0 (bottom and left) to 1 (top and right) You do not hard code the actual texture size into texture coordinates
Try replacing getWidth / getHeight in the textcoord function with '1'