drawing a texture

Started by josephdoss, June 21, 2017, 12:45:55

Previous topic - Next topic

josephdoss

Hey,
I could use some help with texturing. I'm drawing a square for each of my character's eyes and I want to draw a little eye picture on it. I seem to be loading the image correctly and even binding it to the texture, but when I try to draw the texture, I get nothing... Except for that one time I got two white squares. I think my problem is either in my shader or where I set my glVertexAttribPointer. If anyone out there can see where I'm messing up, please let me know. Attached is the entire class file. Below are the parts I think are most relevant for this.

Before you tell me to go look at the demos and simply google it, I have... every day... for the last three months. Whatever I'm missing I haven't been able to work out from the examples and documentation out there.

From outside this class, there are only three ways it's used.
When it's constructed, when the 4 vertices are updated, and when draw() is called.
So, to follow the opengl logic you can start with glConstruct() and draw().

Right now my character's eyes look like this, so you understand why I'm wanting textures.




Here is most of the relevant code. If you want to see it all, see the attached file.


public class human2_eye_textured
{
   int[] skinEyeIndicesDraw = {   
         0, 2,1               
         , 0, 3,2//
   };

   float[] skinEyeVerticesDraw = {
         // vertices            //textures
         0f, 0f, 0f,             0f,0f,  // 0 Bottom Right   , outward bottom left
         0f, 0f, 0f,             0f,1f,  // 1 top right      , outward top left
         10f, 10f, 0f,           1f,1f,  // 2  top left      , outward top right
         -10f, -30f, 0f          ,1f,0f  // 3 bottom left     , outward bottom right
   };
   
   int skinEyeVAOID = -1;
   int skinEyeVBOID = -1;
   int skinEyeVBOIID = -1;
   int textureID = -1;

   public int skinEyeGLMVPUniformLocation;
   public int skinEyeGLRGBAUniformLocation;

   public FloatBuffer skinEyeFB = BufferUtils.createFloatBuffer(20);//(16);

   public int skinEyeProgramId;
   public int skinEyeVertexShaderId;
   public int skinEyeFragmentShaderId;
   public int skinEyeGLTextureCoordLocation;
   public int skinEyeGLTextureImageUniform;

   boolean isSkinEyeIndexBound = false;

   public Matrix4f MVP;

   FloatBuffer verticesBufferSkinEye;

   float distTR, distTL, distBR, distBL;

   float eyeColorRed = 0.545f;
   float eyeColorGreen = 0.271f;
   float eyeColorBlue = 0.075f;

   Vector3f topLeftVertex;
   Vector3f topRightVertex;
   Vector3f botLeftVertex;
   Vector3f botRightVertex;

   Vector3f topLeftRotate;
   Vector3f topRightRotate;
   Vector3f botLeftRotate;
   Vector3f botRightRotate;

   IntBuffer textureWidth = BufferUtils.createIntBuffer(1);
   IntBuffer textureHeight = BufferUtils.createIntBuffer(1);
   IntBuffer textureComponents = BufferUtils.createIntBuffer(1);
   ByteBuffer textureData;

   String textureSourceLeft = "resources" + File.separatorChar + "states" + File.separatorChar + "human2" + File.separatorChar + "eyes" + File.separatorChar + "tester.png";// "eye-default-left.png";
   String textureSourceRight = "resources" + File.separatorChar + "states" + File.separatorChar + "human2" + File.separatorChar + "eyes" + File.separatorChar +"tester.jpg";// "eye-default-Right.jpg";

   public human2_eye_textured(String lr) {
      System.out.println("human2_eye_textured just entered constructor with arg:" + lr);
      String textureSource;
      if (lr == "left") {
         textureSource = textureSourceLeft;
      } else {
         textureSource = textureSourceRight;
      }
      
      System.out.println("human2_eye_textured using this value for textureSource:"+textureSource);
      
      try {
         textureData = stbi_load_from_memory(ioResourceToByteBuffer(textureSource, 20*1024), textureWidth, textureHeight, textureComponents, 4);
      } catch (Exception e) {
         System.out.println("human2_eye_textured constructor : error thrown making the texture message:" + e.getMessage() + " stacktrace:" + e.getStackTrace());
      }
      
      try{
      glConstruct();
      }catch(Exception e)
      {System.out.println("error caught in human2_eye_textured constructor around glConstruct() message:"+e.getMessage()+" stacktrace:"+e.getStackTrace());}
   }

   
   public float[] actionJoints() {

      float[] vertices = skinEyeVerticesDraw;
      int index = 0;

      vertices[index++] = botRightVertex.x;
      vertices[index++] = botRightVertex.y;
      vertices[index++] = botRightVertex.z;
      vertices[index++]=0f;
      vertices[index++]=0f;

      vertices[index++] = topRightVertex.x;
      vertices[index++] = topRightVertex.y;
      vertices[index++] = topRightVertex.z;
      vertices[index++]=0f;
      vertices[index++]=1f;

      vertices[index++] = topLeftVertex.x;
      vertices[index++] = topLeftVertex.y;
      vertices[index++] = topLeftVertex.z;
      vertices[index++]=1f;
      vertices[index++]=1f;

      vertices[index++] = botLeftVertex.x;
      vertices[index++] = botLeftVertex.y;
      vertices[index++] = botLeftVertex.z;
      vertices[index++]=1f;
      vertices[index++]=0f;

      return vertices;
   }

   public void bindSkinEyeVertexData() {
      // if (isDrawChange)
      {

         if (true) {
            if (verticesBufferSkinEye == null) {
               verticesBufferSkinEye = BufferUtils.createFloatBuffer(skinEyeVerticesDraw.length);
            }
            verticesBufferSkinEye.put(skinEyeVerticesDraw).flip();

            if (textureID == -1) {
               textureID = glGenTextures();
               
               glBindTexture(GL_TEXTURE_2D,textureID);
               //glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
               //glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
               
               System.out.println("about to do glTexImage2D");
               glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,textureWidth.get(),textureHeight.get(),0,GL_RGBA,GL_UNSIGNED_BYTE,textureData);
               stbi_image_free(textureData);
               System.out.println("done with glTexImage2D");

               
               
               glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
               glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);         
               
               glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
               glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);               
   
               //System.out.println("texture width and height : "+textureWidth.get() + " " +textureHeight.get());
               if(textureData==null)
               {System.out.println("about to make texture with null textureData");}
            
            }
            //glBindTexture(GL_TEXTURE_2D, textureID);

            if (skinEyeVAOID == -1) {
               skinEyeVAOID = glGenVertexArrays();
            }
            glBindVertexArray(skinEyeVAOID);

            if (skinEyeVBOID == -1) {
               skinEyeVBOID = glGenBuffers();
            }
            glBindBuffer(GL_ARRAY_BUFFER, skinEyeVBOID);
            glBufferData(GL_ARRAY_BUFFER, verticesBufferSkinEye, GL_DYNAMIC_DRAW);
            //works without texture vals in vertices[]
            //glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); // the one that works without texture
            glVertexAttribPointer(0, 3, GL_FLOAT, false, 20, 0);
            glVertexAttribPointer(0, 2, GL_FLOAT, false, 20, 12);
            //glVertexAttribPointer(2, 2, GL_FLOAT, false, 8*4, 0);
            glBindBuffer(GL_ARRAY_BUFFER, 0);
            // glBindVertexArray(0);
            //glEnableVertexAttribArray(2);
            
            
   
            
            
         

            

            if (!isSkinEyeIndexBound) {
               skinEyeIndicesCount = skinEyeIndicesDraw.length;
               IntBuffer indicesBuffer = BufferUtils.createIntBuffer(skinEyeIndicesCount);
               indicesBuffer.put(skinEyeIndicesDraw);
               indicesBuffer.flip();

               skinEyeVBOIID = glGenBuffers();
               glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skinEyeVBOIID);
               glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer, GL_DYNAMIC_DRAW);
               glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

               isSkinEyeIndexBound = true;
            }
         }

         // isDrawChange = false;
      }
   }

   public void calculateJointsVertices() {
      // System.out.println("human1.move(); called");

      double radian = Math.toRadians(degreeRotateZ);
      float cosRadian = (float) Math.cos(radian);
      float sinRadian = (float) Math.sin(radian);

      float fX, fY, fZ;

      int indexCount = 0;
      float[] vertices = {};// .clone();// act.getVertices();

      // jointsVerticesDraw =
      actionJoints();
      vertices = skinEyeVerticesDraw;

      for (int i = vertices.length; indexCount < i; indexCount += 5) {

         fX = vertices[indexCount];
         fY = vertices[indexCount + 1];
         fZ = vertices[indexCount + 2];
         setVertices(indexCount, cosRadian, sinRadian, fX, fY, fZ, vertices);
      }

       //for(int i = 0; i < vertices.length; i++)
       //{ System.out.println("skinEye draw vertex : i:"+i+" val:"+vertices);}

   }

   public void draw() {
      calculateJointsVertices();
      drawSkinEye();
   }

   public void drawSkinEye() {// System.out.println("human.drawJoints");
      glEnable(GL_DEPTH_TEST);
      glEnable(GL_CULL_FACE);
      glCullFace(GL_FRONT);
      glEnable(GL_TEXTURE_2D);
      //glEnable(GL_BLEND);
      //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
      glUseProgram(skinEyeProgramId);
      bindSkinEyeVertexData();
      

      
      
      
      

      glUniformMatrix4fv(skinEyeGLMVPUniformLocation, false, MVP.get(skinEyeFB));
      // glUniform4f(skinEyeGLRGBAUniformLocation, skinRed, skinGreen,
      // skinBlue, 1.0f);
      //glUniform

      glBindVertexArray(skinEyeVAOID);
      glEnableVertexAttribArray(0);
      //glEnableVertexAttribArray(1);

      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skinEyeVBOIID);
      glBindTexture(GL_TEXTURE_2D,textureID);
      glDrawElements(GL_TRIANGLES, skinEyeIndicesCount, GL_UNSIGNED_INT, 0);
      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
      // System.out.println("human.drawJoints
      // jointsIndicesCount:"+jointsIndicesLinesCount);
      glDisableVertexAttribArray(0);
       //glDisableVertexAttribArray(1);
      glBindVertexArray(0);
      
      //glBindTexture(GL_TEXTURE_2D,textureID);

      glUseProgram(0);

      // System.out.println("just drew eye");
      glDisable(GL_BLEND);
      //glDisable(GL_TEXTURE_2D);
   }

   public void glConstruct() {

      glConstructSkinEye();

   }

   public void glConstructSkinEye() {
      try {
         try {
            skinEyeProgramId = glCreateProgram();

            glCreateVertexShaderSkinEye("#version 130         \n"//
                  + "uniform mat4 MVP;                       \n"//
                  + "in vec3 position;                       \n"//
                  + "in vec2 texcoord;                       \n"//
                  // +"in vec4 in_color; \n"//
                  // +"out vec4 pass_color; \n"//
                  + "out vec2 textureCoord;              \n"//
                  + "void main() {                           \n"//
                  + "     gl_Position =MVP* vec4(position, 1.0); \n"//
                  // +" pass_color=in_color; \n"//
                  // +" pass_color=vec4(1.0,1.0,1.0,1.0); \n"//
                  + "       textureCoord = texcoord;           \n"//
                  + "}");

            glCreateFragmentShaderSkinEye("#version 130       \n"//
                  // +"in vec4 pass_color; \n"//
                  + "in vec2 textureCoord;              \n"//
                  + "uniform sampler2D texImage;             \n"//
                  + "out vec4 out_color;                     \n"//
                  + "void main() {                           \n"//
                  // +" vec4 textureColor =
                  // texture(texImage,textureCoord);\n"//
                  // +" out_color=pass_color*textureColor; \n"//
                  // +" out_color=vec4(1f,1f,1f,1f); \n"//
                  //+ "   out_color= vec4(1.0,1.0,1.0,1.0);\n"//texture(texImage,textureCoord);\n"//
                  + "   out_color= texture(texImage,textureCoord)*vec4(1.0f,1.0f,1.0f,1.0f);\n"//
                  + "}   ");

            glLink(skinEyeProgramId);

            glUseProgram(skinEyeProgramId);
            skinEyeGLMVPUniformLocation = glGetUniformLocation(skinEyeProgramId, "MVP");
            // skinEyeGLRGBAUniformLocation =
            // glGetUniformLocation(skinEyeProgramId, "RGBA");
            skinEyeGLTextureCoordLocation = glGetAttribLocation(skinEyeProgramId, "texcoord");
            skinEyeGLTextureImageUniform = glGetUniformLocation(skinEyeProgramId, "texImage");

            glUseProgram(0);

            // glEnable(GL_PROGRAM_POINT_SIZE);

         } catch (Exception e) {
            System.out.println("exception caught:" + e.getMessage() + " " + e.getStackTrace());
         }

         if (skinEyeProgramId == 0) {
            throw new Exception("Could not create Shader");
         }

      } catch (Exception e) {
         System.out.println("exception caught in init " + e.getMessage() + " " + e.getStackTrace());
      }
      // move();
   }

   public void glCreateFragmentShaderSkinEye(String shaderCode) throws Exception {
      skinEyeFragmentShaderId = glCreateThisShader(shaderCode, GL_FRAGMENT_SHADER, skinEyeProgramId);
   }

   protected int glCreateThisShader(String shaderCode, int shaderType, int programID) throws Exception {
      int shaderId = glCreateShader(shaderType);
      if (shaderId == 0) {
         throw new Exception("Error creating shader. Code: " + shaderId);
      }
      glShaderSource(shaderId, shaderCode);
      glCompileShader(shaderId);
      if (glGetShaderi(shaderId, GL_COMPILE_STATUS) == 0) {
         throw new Exception("Error compiling Shader code: " + glGetShaderInfoLog(shaderId, 1024));
      }
      glAttachShader(programID, shaderId);
      return shaderId;
   }

   public void glCreateVertexShaderSkinEye(String shaderCode) throws Exception {
      skinEyeVertexShaderId = glCreateThisShader(shaderCode, GL_VERTEX_SHADER, skinEyeProgramId);
   }

   public void glLink(int programId) throws Exception {
      glLinkProgram(programId);
      if (glGetProgrami(programId, GL_LINK_STATUS) == 0) {
         throw new Exception("Error linking Shader code: " + glGetProgramInfoLog(programId, 1024));
      }
      glValidateProgram(programId);
      if (glGetProgrami(programId, GL_VALIDATE_STATUS) == 0) {
         System.err.println("Warning validating Shader code: " + glGetProgramInfoLog(programId, 1024));
      }
   }

   public ByteBuffer ioResourceToByteBuffer(String resource, int bufferSize) throws IOException {
      //System.out.println("ioResourceToByteBuffer entered");
      ByteBuffer buffer;  //    System.out.println("ioResourceToByteBuffer buffer made");
      //URL url = Thread.currentThread().getContextClassLoader().getResource(resource);   System.out.println("ioResourceToByteBuffer attempting to get resource");
      //URL url = Thread.currentThread().getContextClassLoader().getResource(resource);   System.out.println("ioResourceToByteBuffer attempting to get resource");
      //URL url = new URL("file",resource);
      //ClassLoader cl = getClass().getClassLoader();
      //URL url = cl.getResource(resource);
      File file = new File(resource);// new File(url.getFile());   System.out.println("ioResourceToByteBuffer file created");
      URL url = file.toURI().toURL();
      
      
      if(url==null)
      {System.out.println("ioResourceToByteBuffer url is null");}
      
      
      
      //System.out.println("ioResourceToByteBuffer url:"+url.toString());
      
      if (file.isFile()) {    //    System.out.println("ioResourcetoByteBuffer file is a file");
         FileInputStream fis = new FileInputStream(file);
         FileChannel fc = fis.getChannel();
         buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); //System.out.println("figured out buffer size itself : "+fc.size());
         fc.close();
         fis.close();
      } else { //System.out.println("ioResourcetoByteBuffer file is not a file");
         buffer = BufferUtils.createByteBuffer(bufferSize);
         InputStream source =  url.openStream();
         if (source == null)
            throw new FileNotFoundException(resource);
         try {
            ReadableByteChannel rbc = Channels.newChannel(source);
            try {
               while (true) {
                  int bytes = rbc.read(buffer);
                  if (bytes == -1)
                     break;
                  if (buffer.remaining() == 0)
                     buffer = resizeBuffer(buffer, buffer.capacity() * 2);
               }
               buffer.flip();          //System.out.println("didn't figure out buffersize myself ");
            } finally {
               rbc.close();
            }
         } finally {
            source.close();
         }
      }
      return buffer;
   }

   private ByteBuffer resizeBuffer(ByteBuffer buffer, int newCapacity) {
      ByteBuffer newBuffer = BufferUtils.createByteBuffer(newCapacity);
      buffer.flip();
      newBuffer.put(buffer);
      return newBuffer;
   }


   public void setKeyVertices(Vector3f topLeftVertex, Vector3f topRightVertex, Vector3f botLeftVertex, Vector3f botRightVertex) {
      this.topLeftVertex = topLeftVertex;
      this.topRightVertex = topRightVertex;
      this.botLeftVertex = botLeftVertex;
      this.botRightVertex = botRightVertex;
   }

   public void setMVP(Matrix4f mvp) {
      MVP = mvp;
   }

}