Advertisement
Guest User

Untitled

a guest
Jun 3rd, 2013
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.36 KB | None | 0 0
  1. package de.finalspace.lwjgltest;
  2.  
  3. import java.awt.Canvas;
  4. import java.awt.Component;
  5. import java.awt.event.ComponentAdapter;
  6. import java.awt.event.ComponentEvent;
  7. import java.awt.event.WindowAdapter;
  8. import java.awt.event.WindowEvent;
  9. import java.awt.image.BufferedImage;
  10. import java.awt.image.DataBufferByte;
  11. import java.io.File;
  12. import java.io.IOException;
  13. import java.io.InputStream;
  14. import java.nio.ByteBuffer;
  15. import java.nio.ByteOrder;
  16. import java.nio.FloatBuffer;
  17. import java.nio.ShortBuffer;
  18.  
  19. import javax.imageio.ImageIO;
  20. import javax.swing.JFrame;
  21. import javax.swing.WindowConstants;
  22.  
  23. import org.lwjgl.input.Keyboard;
  24. import org.lwjgl.input.Mouse;
  25. import org.lwjgl.opengl.Display;
  26. import org.lwjgl.opengl.GL11;
  27. import org.lwjgl.opengl.GL12;
  28. import org.lwjgl.opengl.GL13;
  29. import org.lwjgl.opengl.GL15;
  30. import org.lwjgl.opengl.GL20;
  31.  
  32. public class LWJGLTextureTest extends JFrame {
  33.     private static final long serialVersionUID = -3422852982258512645L;
  34.     private final Canvas canvas;
  35.     private boolean isRunning;
  36.  
  37.     private int shaderID;
  38.     private int vertexAttribLocation;
  39.     private int texcoordAttribLocation;
  40.  
  41.     private int textureID;
  42.     private int textureSamplerLocation;
  43.     private int mvpMatrixLocation;
  44.  
  45.     private int indexCount;
  46.     private int texcoordOffset;
  47.     private int vboID;
  48.     private int iboID;
  49.    
  50.     private FloatBuffer mvpMatrix;
  51.        
  52.     private final String vertShaderSource = "" +
  53.         "attribute vec4 vPosition;\n"+
  54.         "attribute vec2 vTexcoord;\n"+
  55.         "uniform mat4 uMVPMatrix;\n"+
  56.         "varying vec2 texcoord;\n"+
  57.         "void main() {\n"+
  58.         "   gl_Position = uMVPMatrix * vPosition;\n"+
  59.         "   texcoord = vTexcoord;\n"+
  60.         "}\n";
  61.  
  62.     private final String fragShaderSource = "\n" +
  63.             "uniform sampler2D uTexture;\n"+
  64.             "varying vec2 texcoord;\n"+
  65.             "void main() {\n"+
  66.             "   vec4 texColor = texture2D(uTexture, texcoord);\n"+
  67.             "   gl_FragColor = texColor;\n"+
  68.             "   //gl_FragColor = vec4(texcoord.x, texcoord.y, 0.0, 1.0);\n"+
  69.             "}\n";
  70.  
  71.     public LWJGLTextureTest() {
  72.         super();
  73.  
  74.         final float[] mvp = new float[]{
  75.                 1.0f, 0.0f, 0.0f, 0.0f,
  76.                 0.0f, 1.0f, 0.0f, 0.0f,
  77.                 0.0f, 0.0f, 1.0f, 0.0f,
  78.                 0.0f, 0.0f, 0.0f, 1.0f
  79.         };
  80.         mvpMatrix = ByteBuffer.allocateDirect(mvp.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
  81.         mvpMatrix.put(mvp);
  82.         mvpMatrix.flip();
  83.        
  84.         // Setup native lwjgl path
  85.         File nativePath = new File(System.getProperty("user.dir"),
  86.                 "lwjgl-2.9.0/native/linux");
  87.         System.out.println(nativePath);
  88.         System.setProperty("org.lwjgl.librarypath",
  89.                 nativePath.getAbsolutePath());
  90.  
  91.         // Initialize canvas
  92.         canvas = new Canvas();
  93.         canvas.setSize(800, 600);
  94.         add(canvas);
  95.  
  96.         this.setTitle("Texture test");
  97.         setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
  98.         this.addWindowListener(new WindowAdapter() {
  99.             @Override
  100.             public void windowClosing(WindowEvent e) {
  101.                 isRunning = false;
  102.             }
  103.  
  104.             @Override
  105.             public void windowLostFocus(WindowEvent e) {
  106.             }
  107.  
  108.             @Override
  109.             public void windowGainedFocus(WindowEvent e) {
  110.             }
  111.         });
  112.         this.addComponentListener(new ComponentAdapter() {
  113.             @Override
  114.             public void componentResized(ComponentEvent evt) {
  115.                 Component c = (Component) evt.getSource();
  116.                 canvas.setSize(c.getWidth(), c.getHeight());
  117.             }
  118.         });
  119.     }
  120.  
  121.     void handleEvents() {
  122.         // Keyboard events
  123.         while (Keyboard.next()) {
  124.         }
  125.  
  126.         // Mouse events
  127.         while (Mouse.next()) {
  128.         }
  129.     }
  130.  
  131.     private void update() {
  132.  
  133.     }
  134.  
  135.     private void draw() {
  136.         GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
  137.  
  138.         GL13.glActiveTexture(GL13.GL_TEXTURE0);
  139.         GL11.glEnable(GL11.GL_TEXTURE_2D);
  140.         GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
  141.  
  142.         GL20.glUseProgram(shaderID);
  143.         GL20.glUniformMatrix4(mvpMatrixLocation, false, mvpMatrix);
  144.         GL20.glUniform1i(textureSamplerLocation, 0);
  145.        
  146.         GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboID);
  147.  
  148.         GL20.glEnableVertexAttribArray(vertexAttribLocation);
  149.         GL20.glVertexAttribPointer(vertexAttribLocation, 3, GL11.GL_FLOAT, false, 3 * 4, 0);
  150.        
  151.         GL20.glEnableVertexAttribArray(texcoordAttribLocation);
  152.         GL20.glVertexAttribPointer(texcoordAttribLocation, 2, GL11.GL_FLOAT, false, 2 * 4, texcoordOffset);
  153.        
  154.         GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, iboID);
  155.         GL11.glDrawElements(GL11.GL_TRIANGLES, indexCount, GL11.GL_UNSIGNED_SHORT, 0);
  156.         GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
  157.        
  158.         GL20.glDisableVertexAttribArray(texcoordAttribLocation);
  159.         GL20.glDisableVertexAttribArray(vertexAttribLocation);
  160.  
  161.         GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
  162.  
  163.         GL20.glUseProgram(0);
  164.        
  165.         GL13.glActiveTexture(GL13.GL_TEXTURE0);
  166.         GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
  167.         GL11.glDisable(GL11.GL_TEXTURE_2D);
  168.     }
  169.  
  170.     private int _loadShader(final String name, final int type,
  171.             final String source) {
  172.         // Create a new shader object
  173.         int shader = GL20.glCreateShader(type);
  174.  
  175.         // Pass the shader source
  176.         GL20.glShaderSource(shader, source);
  177.  
  178.         // Compile shader
  179.         GL20.glCompileShader(shader);
  180.  
  181.         // Get compilation status
  182.         final int compileStatus = GL20.glGetShaderi(shader,
  183.                 GL20.GL_COMPILE_STATUS);
  184.  
  185.         // If the compilation failed, delete the shader.
  186.         String infoLog = GL20.glGetShaderInfoLog(shader, 1024);
  187.         if (compileStatus == 0) {
  188.             String shaderType = type == GL20.GL_FRAGMENT_SHADER ? "Fragment"
  189.                     : "Vertex";
  190.             GL20.glDeleteShader(shader);
  191.             throw new IllegalArgumentException(shaderType + " shader '" + name
  192.                     + "' could not compile: " + infoLog);
  193.         } else {
  194.             System.out.println(infoLog);
  195.         }
  196.  
  197.         return shader;
  198.     }
  199.  
  200.     private int loadShaders(final String name, final String vertSource,
  201.             final String fragSource) {
  202.         int program = GL20.glCreateProgram();
  203.  
  204.         // Load vertex shader
  205.         int vertexShader = _loadShader(name, GL20.GL_VERTEX_SHADER, vertSource);
  206.  
  207.         // Load fragment shader
  208.         int fragShader = _loadShader(name, GL20.GL_FRAGMENT_SHADER, fragSource);
  209.  
  210.         // Bind the vertex shader to the program.
  211.         GL20.glAttachShader(program, vertexShader);
  212.  
  213.         // Bind the fragment shader to the program.
  214.         GL20.glAttachShader(program, fragShader);
  215.  
  216.         // Link the two shaders together into a program.
  217.         GL20.glLinkProgram(program);
  218.  
  219.         // Delete both shaders, does not matter when compile failed or was
  220.         // successfully
  221.         GL20.glDeleteShader(fragShader);
  222.         GL20.glDeleteShader(vertexShader);
  223.  
  224.         // If the link failed, delete the program.
  225.         final int linkStatus = GL20.glGetProgrami(program, GL20.GL_LINK_STATUS);
  226.         if (linkStatus == 0) {
  227.             String infoLog = GL20.glGetProgramInfoLog(program, 1024);
  228.             GL20.glDeleteProgram(program);
  229.             throw new IllegalStateException("Program '" + name
  230.                     + "' could not link: " + infoLog);
  231.         }
  232.  
  233.         return program;
  234.     }
  235.  
  236. //  private String streamToText(final InputStream inputStream) {
  237. //      InputStreamReader reader = new InputStreamReader(inputStream);
  238. //      char[] buffer = new char[256];
  239. //      int read = 0;
  240. //      StringBuffer out = new StringBuffer();
  241. //      try {
  242. //          while ((read = reader.read(buffer)) > 0) {
  243. //              out.append(buffer, 0, read);
  244. //          }
  245. //          return out.toString();
  246. //      } catch (IOException e) {
  247. //          e.printStackTrace();
  248. //      }
  249. //      return null;
  250. //  }
  251.  
  252.     private ByteBuffer getImageData(final BufferedImage image) {
  253.         byte[] imageData = ((DataBufferByte) image.getRaster().getDataBuffer())
  254.                 .getData();
  255.         byte[] buffer = new byte[image.getWidth() * image.getHeight() * 4];
  256.  
  257.         int c = 0;
  258.         for (int i = 0; i < imageData.length; i += 3) {
  259.             buffer[c] = imageData[i + 2]; // * Rot *
  260.             buffer[c + 1] = imageData[i + 1]; // * Gruen *
  261.             buffer[c + 2] = imageData[i]; // * Blau *
  262.             buffer[c + 3] = (byte) 255; // * Alpha *
  263.             c += 4;
  264.         }
  265.  
  266.         ByteBuffer textureData = ByteBuffer.allocateDirect(buffer.length);
  267.         textureData.order(ByteOrder.nativeOrder());
  268.         textureData.put(buffer, 0, buffer.length);
  269.         textureData.flip();
  270.  
  271.         return textureData;
  272.     }
  273.  
  274.     private int loadTexture(final String name, final InputStream inputStream) {
  275.         BufferedImage image;
  276.         try {
  277.             image = ImageIO.read(inputStream);
  278.         } catch (IOException e) {
  279.             throw new IllegalStateException("Could not read texture '" + name
  280.                     + "'!", e);
  281.         }
  282.  
  283.         int width = image.getWidth();
  284.         int height = image.getHeight();
  285.  
  286.         ByteBuffer data = getImageData(image);
  287.  
  288.         int handle = GL11.glGenTextures();
  289.         int target = GL11.GL_TEXTURE_2D;
  290.         GL11.glBindTexture(target, handle);
  291.         GL11.glTexParameteri(target, GL11.GL_TEXTURE_WRAP_S,
  292.                 GL12.GL_CLAMP_TO_EDGE);
  293.         GL11.glTexParameteri(target, GL11.GL_TEXTURE_WRAP_T,
  294.                 GL12.GL_CLAMP_TO_EDGE);
  295.         GL11.glTexParameterf(target, GL11.GL_TEXTURE_MIN_FILTER,
  296.                 GL11.GL_NEAREST);
  297.         GL11.glTexParameterf(target, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
  298.         GL11.glBindTexture(target, 0);
  299.         GL11.glTexImage2D(target, 0, GL11.GL_RGBA8, width, height, 0,
  300.                 GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, data);
  301.         return handle;
  302.     }
  303.  
  304.     private void createQuad(final float width, final float height) {
  305.         float[] verts = new float[] { -width / 2, height / 2, 0.0f, // top left
  306.                 width / 2, height / 2, 0.0f, // top right
  307.                 width / 2, -height / 2, 0.0f, // bottom right
  308.                 -width / 2, -height / 2, 0.0f // bottom left
  309.         };
  310.         final float[] texcoords = new float[] { 0.0f, 1.0f, 1.0f, 1.0f, 1.0f,
  311.                 0.0f, 0.0f, 0.0f };
  312.         short[] index = new short[] { 1, 0, 3, 3, 2, 1 };
  313.  
  314.         final int vertsSize = verts.length * 4;
  315.  
  316.         final int texcoordsSize = texcoords.length * 4;
  317.  
  318.         final int indicesSize = index.length * 2;
  319.  
  320.         final int size = vertsSize + texcoordsSize;
  321.        
  322.         texcoordOffset = vertsSize;
  323.         indexCount = index.length;
  324.  
  325.         FloatBuffer vertBuffer = ByteBuffer.allocateDirect(vertsSize)
  326.                 .order(ByteOrder.nativeOrder()).asFloatBuffer();
  327.         vertBuffer.put(verts);
  328.         vertBuffer.flip();
  329.  
  330.         FloatBuffer texcoordBuffer = ByteBuffer.allocateDirect(texcoordsSize)
  331.                 .order(ByteOrder.nativeOrder()).asFloatBuffer();
  332.         texcoordBuffer.put(texcoords);
  333.         texcoordBuffer.flip();
  334.  
  335.         ShortBuffer indexBuffer = ByteBuffer.allocateDirect(indicesSize)
  336.                 .order(ByteOrder.nativeOrder()).asShortBuffer();
  337.         indexBuffer.put(index);
  338.         indexBuffer.flip();
  339.  
  340.         vboID = GL15.glGenBuffers();
  341.         GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboID);
  342.         GL15.glBufferData(GL15.GL_ARRAY_BUFFER, size, GL15.GL_STATIC_DRAW);
  343.         GL15.glBufferSubData(GL15.GL_ARRAY_BUFFER, 0, vertBuffer);
  344.         GL15.glBufferSubData(GL15.GL_ARRAY_BUFFER, vertsSize, texcoordBuffer);
  345.         GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
  346.  
  347.         iboID = GL15.glGenBuffers();
  348.         GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, iboID);
  349.         GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, indexBuffer, GL15.GL_STATIC_DRAW);
  350.         GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
  351.     }
  352.  
  353.     private InputStream loadResource(final String name) {
  354.         return getClass().getClassLoader().getResourceAsStream(name);
  355.     }
  356.  
  357.     private void init() {
  358.         // Create vbo and ibo
  359.         createQuad(1.0f, 1.0f);
  360.         System.out.println("vbo id: " + vboID);
  361.         System.out.println("ibo id: " + iboID);
  362.  
  363.         // Load shader
  364.         shaderID = loadShaders("simple", vertShaderSource, fragShaderSource);
  365.         System.out.println("shader id: " + shaderID);
  366.  
  367.         // Get shader locations
  368.         GL20.glUseProgram(shaderID);
  369.         mvpMatrixLocation = GL20.glGetUniformLocation(shaderID, "uMVPMatrix");
  370.         textureSamplerLocation = GL20.glGetUniformLocation(shaderID, "uTexture");
  371.         vertexAttribLocation = GL20.glGetAttribLocation(shaderID, "vPosition");
  372.         texcoordAttribLocation = GL20.glGetAttribLocation(shaderID, "vTexcoord");
  373.         GL20.glUseProgram(0);
  374.         System.out.println("uMVPMatrix location: " + mvpMatrixLocation);
  375.         System.out.println("uTexture location: " + textureSamplerLocation);
  376.         System.out.println("vPosition location: " + vertexAttribLocation);
  377.         System.out.println("vTexcoord location: " + texcoordAttribLocation);
  378.        
  379.         // Load texture
  380.         textureID = loadTexture("test.jpg", loadResource("textures/test.jpg"));
  381.         System.out.println("texture id: " + textureID);
  382.        
  383.         GL11.glClearColor(1.0f, 0.0f, 1.0f, 1.0f);
  384.     }
  385.  
  386.     public void run() {
  387.         isRunning = true;
  388.         this.pack();
  389.         this.setVisible(true);
  390.         this.requestFocus();
  391.         canvas.requestFocusInWindow();
  392.         try {
  393.             Display.setParent(canvas);
  394.             Display.create();
  395.             init();
  396.             while (isRunning) {
  397.                 Display.sync(60);
  398.                 handleEvents();
  399.                 update();
  400.                 draw();
  401.                 Display.update();
  402.             }
  403.             Display.destroy();
  404.         } catch (Exception e) {
  405.             e.printStackTrace();
  406.         }
  407.         System.exit(0);
  408.     }
  409.  
  410.     public static void main(String[] args) {
  411.         LWJGLTextureTest app = new LWJGLTextureTest();
  412.         app.run();
  413.     }
  414. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement