title: How to properly mix drawing calls and changes of a sampler value with a single shader program?
body: <p>I'm trying to draw two objects using two different textures with one shader program in OpenGL ES 2.0 for Android. The first object should have <code>texture0</code> and the second sould have <code>texture1</code>.</p>
  
  <p>In fragment shader I have:</p>
  
  <pre><code>uniform sampler2D tex;
  </code></pre>
  
  <p>and in java code:</p>
  
  <pre class="lang-java prettyprint-override"><code>int tiu0 = 0;
  int tiu1 = 1;
  int texLoc = glGetUniformLocation(program, "tex");
  
  glUseProgram(program);
  
  // bind texture0 to texture image unit 0
  glActiveTexture(GL_TEXTURE0 + tiu0);
  glBindTexture(GL_TEXTURE_2D, texture0);
  
  // bind texture1 to texture image unit 1
  glActiveTexture(GL_TEXTURE0 + tiu1);
  glBindTexture(GL_TEXTURE_2D, texture1);
  
  glUniform1i(texLoc, tiu0);
  // success: glGetError returns GL_NO_ERROR, glGetUniformiv returns 0 for texLoc
  
  drawFirstObject(); // should have texture0
  
  glUniform1i(texLoc, tiu1);
  // success: glGetError returns GL_NO_ERROR, glGetUniformiv returns 1 for texLoc
  
  drawSecondObject(); // should have texture1
  </code></pre>
  
  <p>Running on Samsung Galaxy Ace with Android 2.3.3 both objects have the same <code>texture0</code>. Similar code runs correctly in OpenGL 2.0 on my desktop computer.</p>
  
  <p>If I remove <code>drawFirstObject</code>, the second object will have <code>texture1</code>.</p>
  
  <p>If I remove <code>drawSecondObject</code>, the first object will have <code>texture0</code>.</p>
  
  <p>If somewhere between <code>drawFirstObject</code> and <code>drawSecondObject</code> I change the program for a while:</p>
  
  <pre class="lang-java prettyprint-override"><code>glUseProgram(0); // can be also any valid program other than the program from the next call
  glUseProgram(program);
  </code></pre>
  
  <p>then both objects will have <code>texture1</code>.</p>
  
  <p>Values of uniforms different from <code>sampler2D</code> are always set correctly.</p>
  
  <p>I know I can draw the two objects with different textures using only one texture image unit and binding appropriate texture to that texture image unit before drawing the object, but I also want to know what's going on here.</p>
  
  <p>Is something wrong with my code? Is it possible in OpenGL ES 2.0 to draw the objects with different textures by only switching between texture image units as I shown in the code? If it's impossible, is that difference between OpenGL 2.0 (where it's possible) and OpenGL ES 2.0 documented anywhere? I can't find it.</p>