31

I'm finding a way to understand why glActiveTexture is needed. I have the code below:

glGenTextures(1, &textureId);
glBindTexture(GL_TEXTURE_2D, textureId);

If I imagine that the GL_TEXTURE_2D is a picture's frame hanging on the wall and textureId is the real picture, the glBindTexture is the only command for assigning a real picture to the frame, so, what are GL_TEXTURE0 and glActiveTexture?

Will my code below work fine?

glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &textureId);
glBindTexture(GL_TEXTURE_2D, textureId);

glActiveTexture(GL_TEXTURE1);
glTexImage2D(GL_TEXTURE_2D, .....)
glTexParameteri(GL_TEXTURE_2D, ...)

I'm currently working with OpenGL2.1.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Bình Nguyên
  • 2,252
  • 6
  • 32
  • 47

2 Answers2

37

If I imagine that the GL_TEXTURE_2D is a picture's frame hangging on the wall and textureId is the real picture,

Actually a very good analogy :)

so, what GL_TEXTURE0 and glActiveTexture are?

Think about a wall with multiple picture frames, the first frame being labeled GL_TEXTURE0, the second GL_TEXTURE1 and so on.

Marco A.
  • 43,032
  • 26
  • 132
  • 246
datenwolf
  • 159,371
  • 13
  • 185
  • 298
  • so, when setting up the texture (`glTexParrameteri`, `glTexImage2D`, ...) are we need to call `glActiveTexture`? – Bình Nguyên Jan 09 '13 at 09:20
  • 2
    Yes, because there is no parameter in glTexImage2D to say if you're talking about GL_TEXTURE0 or GL_TEXTURE1. – Calvin1602 Jan 09 '13 at 11:02
  • @datenwolf: One more question :D: If I use more than one texture in fragment shader (IE `uniform sampler2D tex1; uniform sampler2D tex2; ...` then how I call `glActiveTexture`? – Bình Nguyên Jan 12 '13 at 13:25
  • 4
    @BìnhNguyên: You use glActiveTexture units to put "images" into their "unit" frame `GL_TEXTURE0 + n`, and in the shader you set the sampler to just the value `n`. Yes, this is an inconsistency, but who cares? Just put a `GL_TEXTURE0+` into all calls of `glActiveTexture`, it's no big deal. – datenwolf Jan 12 '13 at 21:31
23

OpenGL introduced multitexturing at some point (which is basically using more than one texture on one geometry pass); in order to keep older code working, they couldn't just add additional parameter to all the functions. That's why you have to explicitly specify which texture unit you are addressing.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
  • So, Are we need to call `glEnable(GL_TEXTURE_2D)` or `glEnable(GL_TEXTURE_CUBE_MAP)`, ... before using them in new OpenGL version (2.1+)? – Bình Nguyên Jan 09 '13 at 15:35
  • Well, yes, because each texture unit can be of any type from previous versions. – Bartek Banachewicz Jan 09 '13 at 21:33
  • 3
    @BìnhNguyên: Only if you're using the fixed function pipeline. If you're using shaders the use of texture sampling is determined by the shader program. – datenwolf Jan 12 '13 at 21:29