_-Katsu-_

OpenGL Texture Tutorial Java

Mar 2nd, 2015
387
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.22 KB | None | 0 0
  1. //Import everything..
  2. import static org.lwjgl.glfw.Callbacks.errorCallbackPrint;
  3. import static org.lwjgl.glfw.GLFW.*;
  4. import static org.lwjgl.opengl.GL11.*;
  5. import static org.lwjgl.opengl.GL12.GL_CLAMP_TO_EDGE;
  6. import static org.lwjgl.opengl.GL15.*;
  7. import static org.lwjgl.opengl.GL20.*;
  8. import static org.lwjgl.opengl.GL30.*;
  9. import static org.lwjgl.system.MemoryUtil.NULL;
  10.  
  11. import java.awt.image.BufferedImage;
  12. import java.io.File;
  13. import java.nio.ByteBuffer;
  14. import java.nio.FloatBuffer;
  15. import java.nio.IntBuffer;
  16.  
  17. import javax.imageio.ImageIO;
  18.  
  19. import org.lwjgl.BufferUtils;
  20. import org.lwjgl.glfw.GLFWErrorCallback;
  21. import org.lwjgl.opengl.GLContext;
  22.  
  23. public class OpenGLTextureTutorial {
  24.     private static GLFWErrorCallback errorCallback;
  25.     private static long window;
  26.    
  27.     private static String vertexShaderSource =
  28.             "#version 150 core\n" +
  29.             "in vec2 position;" +
  30.             "in vec3 color;" +
  31.             "in vec2 texcoord;" +
  32.             "out vec3 Color;" +
  33.             "out vec2 Texcoord;" +
  34.             "void main() {" +
  35.             "   Color = color;" +
  36.             "   Texcoord = texcoord;" +
  37.             "   gl_Position = vec4(position, 0.0, 1.0);" +
  38.             "}";
  39.    
  40.     private static String fragmentShaderSource =
  41.             "#version 150 core\n" +
  42.             "in vec3 Color;" +
  43.             "in vec2 Texcoord;" +
  44.             "out vec4 outColor;" +
  45.             "uniform sampler2D tex;" +
  46.             "void main() {" +
  47.             "   outColor = texture(tex, Texcoord) * vec4(Color, 1.0);" +
  48.             "}";
  49.    
  50.     public static void main(String[] args) {
  51.         //Initialize GLFW and create the window
  52.        
  53.         glfwSetErrorCallback(errorCallback = errorCallbackPrint(System.err));
  54.  
  55.         if (glfwInit() != GL_TRUE)
  56.             throw new IllegalStateException("Unable to initialize GLFW");
  57.  
  58.         glfwDefaultWindowHints();
  59.  
  60.         glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
  61.        
  62.         window = glfwCreateWindow(800, 600, "OpenGL ", NULL, NULL);
  63.         if (window == NULL)
  64.             throw new RuntimeException("Failed to create the GLFW window");
  65.  
  66.         glfwMakeContextCurrent(window);
  67.  
  68.         glfwShowWindow(window);
  69.  
  70.         GLContext.createFromCurrent();
  71.        
  72.         //Create Vertex Array Object
  73.         int vaoID = glGenVertexArrays();
  74.         glBindVertexArray(vaoID);
  75.        
  76.         //Create a Vertex Buffer Object and copy the vertex data to it
  77.         int vboID = glGenBuffers();
  78.        
  79.         float[] vertices = {
  80.                   //Position     Color             Texcoords
  81.                    -0.5f,  0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // Top-left
  82.                     0.5f,  0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Top-right
  83.                     0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // Bottom-right
  84.                    -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f  // Bottom-left
  85.         };
  86.        
  87.         glBindBuffer(GL_ARRAY_BUFFER, vboID);
  88.         glBufferData(GL_ARRAY_BUFFER, convertToFloatBuffer(vertices), GL_STATIC_DRAW);
  89.        
  90.         //Create an element array
  91.         int eboID = glGenBuffers();
  92.        
  93.         int[] elements = {
  94.                 0, 1, 2,
  95.                 2, 3, 0
  96.         };
  97.        
  98.         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, eboID);
  99.         glBufferData(GL_ELEMENT_ARRAY_BUFFER, convertToIntBuffer(elements), GL_STATIC_DRAW);
  100.        
  101.         //Create and compile the vertex shader
  102.         int vertexShaderID = glCreateShader(GL_VERTEX_SHADER);
  103.         glShaderSource(vertexShaderID, vertexShaderSource);
  104.         glCompileShader(vertexShaderID);
  105.        
  106.         //Create and compile the fragment shader
  107.         int fragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
  108.         glShaderSource(fragmentShaderID, fragmentShaderSource);
  109.         glCompileShader(fragmentShaderID);
  110.        
  111.         // Link the vertex and fragment shader into a shader program
  112.         int shaderProgram = glCreateProgram();
  113.         glAttachShader(shaderProgram, vertexShaderID);
  114.         glAttachShader(shaderProgram, fragmentShaderID);
  115.         glBindFragDataLocation(shaderProgram, 0, "outColor");
  116.         glLinkProgram(shaderProgram);
  117.         glUseProgram(shaderProgram);
  118.        
  119.         int sizeOfFloat = 4;
  120.        
  121.         // Specify the layout of the vertex data
  122.         int positionAttribute = glGetAttribLocation(shaderProgram, "position");
  123.         glEnableVertexAttribArray(positionAttribute);
  124.         glVertexAttribPointer(positionAttribute, 2, GL_FLOAT, false, 7 * sizeOfFloat, 0);
  125.        
  126.         int colorAttribute = glGetAttribLocation(shaderProgram, "color");
  127.         glEnableVertexAttribArray(colorAttribute);
  128.         glVertexAttribPointer(colorAttribute, 3, GL_FLOAT, false, 7 * sizeOfFloat, 2 * sizeOfFloat);
  129.        
  130.         int textureAttribute = glGetAttribLocation(shaderProgram, "texcoord");
  131.         glEnableVertexAttribArray(textureAttribute);
  132.         glVertexAttribPointer(textureAttribute, 2, GL_FLOAT, false, 7 * sizeOfFloat, 5 * sizeOfFloat);
  133.        
  134.         //Load texture
  135.         int textureID = loadTexture("test.jpg");
  136.        
  137.         while (glfwWindowShouldClose(window) != GL_TRUE)
  138.         {
  139.             glfwPollEvents();
  140.  
  141.             // Clear the screen to black
  142.             glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
  143.             glClear(GL_COLOR_BUFFER_BIT);
  144.            
  145.             glBindTexture(GL_TEXTURE_2D, textureID);
  146.  
  147.             // Draw a rectangle from the 2 triangles using 6 indices
  148.             glDrawElements(GL_TRIANGLES, elements.length, GL_UNSIGNED_INT, 0);
  149.  
  150.             // Swap buffers
  151.             glfwSwapBuffers(window);
  152.         }
  153.        
  154.         //Delete all the textures, buffers and shaders we created
  155.         glDeleteTextures(textureID);
  156.        
  157.         glDeleteProgram(shaderProgram);
  158.         glDeleteShader(vertexShaderID);
  159.         glDeleteShader(fragmentShaderID);
  160.  
  161.         glDeleteBuffers(vboID);
  162.         glDeleteBuffers(eboID);
  163.  
  164.         glDeleteVertexArrays(vaoID);
  165.        
  166.         //Destroy the window and terminate GLFW
  167.         glfwDestroyWindow(window);
  168.  
  169.         glfwTerminate();
  170.         errorCallback.release();
  171.     }
  172.    
  173.     private static int loadTexture(String fileName) {
  174.         try {
  175.             BufferedImage image = ImageIO.read(new File(fileName));
  176.  
  177.             int[] pixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth());
  178.  
  179.             ByteBuffer buffer = BufferUtils.createByteBuffer(image.getHeight() * image.getWidth() * 4);
  180.  
  181.             boolean hasAlpha = image.getColorModel().hasAlpha();
  182.  
  183.             for (int y = 0; y < image.getHeight(); y++) {
  184.                 for (int x = 0; x < image.getWidth(); x++) {
  185.                     int pixel = pixels[y * image.getWidth() + x];
  186.                     buffer.put((byte) ((pixel >> 16) & 0xFF));
  187.                     buffer.put((byte) ((pixel >> 8) & 0xFF));
  188.                     buffer.put((byte) ((pixel) & 0xFF));
  189.                     if (hasAlpha) buffer.put((byte) ((pixel >> 24) & 0xFF));
  190.                     else
  191.                         buffer.put((byte) (0xFF));
  192.                 }
  193.             }
  194.  
  195.             buffer.flip();
  196.  
  197.             int id = glGenTextures();
  198.  
  199.             glBindTexture(GL_TEXTURE_2D, id);
  200.            
  201.             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  202.             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  203.            
  204.             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  205.             glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  206.            
  207.             glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
  208.            
  209.             return id;
  210.         } catch (Exception ex) {
  211.             ex.printStackTrace();
  212.             return -1;
  213.         }
  214.     }
  215.    
  216.     public static FloatBuffer convertToFloatBuffer(float[] vertices) {
  217.         FloatBuffer buffer = BufferUtils.createFloatBuffer(vertices.length);
  218.         for(int i = 0; i < vertices.length; i++) {
  219.             buffer.put(vertices[i]);
  220.         }
  221.         buffer.flip();
  222.  
  223.         return buffer;
  224.     }
  225.    
  226.     public static IntBuffer convertToIntBuffer(int... values) {
  227.         IntBuffer buffer = BufferUtils.createIntBuffer(values.length);
  228.         buffer.put(values);
  229.         buffer.flip();
  230.  
  231.         return buffer;
  232.     }
  233. }
Advertisement
Add Comment
Please, Sign In to add comment