Advertisement
Guest User

Untitled

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