Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package de.finalspace.lwjgltest;
- import java.awt.Canvas;
- import java.awt.Component;
- import java.awt.event.ComponentAdapter;
- import java.awt.event.ComponentEvent;
- import java.awt.event.WindowAdapter;
- import java.awt.event.WindowEvent;
- import java.awt.image.BufferedImage;
- import java.awt.image.DataBufferByte;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import java.nio.ByteBuffer;
- import java.nio.ByteOrder;
- import java.nio.FloatBuffer;
- import java.nio.ShortBuffer;
- import javax.imageio.ImageIO;
- import javax.swing.JFrame;
- import javax.swing.WindowConstants;
- import org.lwjgl.input.Keyboard;
- import org.lwjgl.input.Mouse;
- import org.lwjgl.opengl.Display;
- import org.lwjgl.opengl.GL11;
- import org.lwjgl.opengl.GL12;
- import org.lwjgl.opengl.GL13;
- import org.lwjgl.opengl.GL15;
- import org.lwjgl.opengl.GL20;
- public class LWJGLTextureTest extends JFrame {
- private static final long serialVersionUID = -3422852982258512645L;
- private final Canvas canvas;
- private boolean isRunning;
- private int shaderID;
- private int vertexAttribLocation;
- private int texcoordAttribLocation;
- private int textureID;
- private int textureSamplerLocation;
- private int indexCount;
- private int texcoordOffset;
- private int vboID;
- private int iboID;
- private final String vertShaderSource = "" +
- "attribute vec4 vPosition;\n"+
- "attribute vec2 vTexcoord;\n"+
- "varying vec2 texcoord;\n"+
- "void main() {\n"+
- " gl_Position = vPosition;\n"+
- " texcoord = vTexcoord;\n"+
- "}\n";
- private final String fragShaderSource = "\n" +
- "uniform sampler2D uTexture;\n"+
- "varying vec2 texcoord;\n"+
- "void main() {\n"+
- " vec4 texColor = texture2D(uTexture, texcoord);\n"+
- " gl_FragColor = texColor;\n"+
- " //gl_FragColor = vec4(texcoord.x, texcoord.y, 0.0, 1.0);\n"+
- "}\n";
- public LWJGLTextureTest() {
- super();
- // Setup native lwjgl path
- File nativePath = new File(System.getProperty("user.dir"),
- "lwjgl-2.9.0/native/linux");
- System.out.println(nativePath);
- System.setProperty("org.lwjgl.librarypath",
- nativePath.getAbsolutePath());
- // Initialize canvas
- canvas = new Canvas();
- canvas.setSize(800, 600);
- add(canvas);
- this.setTitle("Texture test");
- setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
- this.addWindowListener(new WindowAdapter() {
- @Override
- public void windowClosing(WindowEvent e) {
- isRunning = false;
- }
- @Override
- public void windowLostFocus(WindowEvent e) {
- }
- @Override
- public void windowGainedFocus(WindowEvent e) {
- }
- });
- this.addComponentListener(new ComponentAdapter() {
- @Override
- public void componentResized(ComponentEvent evt) {
- Component c = (Component) evt.getSource();
- canvas.setSize(c.getWidth(), c.getHeight());
- }
- });
- }
- void handleEvents() {
- // Keyboard events
- while (Keyboard.next()) {
- }
- // Mouse events
- while (Mouse.next()) {
- }
- }
- private void update() {
- }
- private void draw() {
- GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
- GL13.glActiveTexture(GL13.GL_TEXTURE0);
- GL11.glEnable(GL11.GL_TEXTURE_2D);
- GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
- GL20.glUseProgram(shaderID);
- GL20.glUniform1i(textureSamplerLocation, 0);
- GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboID);
- GL20.glEnableVertexAttribArray(vertexAttribLocation);
- GL20.glVertexAttribPointer(vertexAttribLocation, 3, GL11.GL_FLOAT, false, 3 * 4, 0);
- GL20.glEnableVertexAttribArray(texcoordAttribLocation);
- GL20.glVertexAttribPointer(texcoordAttribLocation, 2, GL11.GL_FLOAT, false, 2 * 4, texcoordOffset);
- GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, iboID);
- GL11.glDrawElements(GL11.GL_TRIANGLES, indexCount, GL11.GL_UNSIGNED_SHORT, 0);
- GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
- GL20.glDisableVertexAttribArray(texcoordAttribLocation);
- GL20.glDisableVertexAttribArray(vertexAttribLocation);
- GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
- GL20.glUseProgram(0);
- GL13.glActiveTexture(GL13.GL_TEXTURE0);
- GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
- GL11.glDisable(GL11.GL_TEXTURE_2D);
- }
- private int _loadShader(final String name, final int type,
- final String source) {
- // Create a new shader object
- int shader = GL20.glCreateShader(type);
- // Pass the shader source
- GL20.glShaderSource(shader, source);
- // Compile shader
- GL20.glCompileShader(shader);
- // Get compilation status
- final int compileStatus = GL20.glGetShaderi(shader,
- GL20.GL_COMPILE_STATUS);
- // If the compilation failed, delete the shader.
- String infoLog = GL20.glGetShaderInfoLog(shader, 1024);
- if (compileStatus == 0) {
- String shaderType = type == GL20.GL_FRAGMENT_SHADER ? "Fragment"
- : "Vertex";
- GL20.glDeleteShader(shader);
- throw new IllegalArgumentException(shaderType + " shader '" + name
- + "' could not compile: " + infoLog);
- } else {
- System.out.println(infoLog);
- }
- return shader;
- }
- private int loadShaders(final String name, final String vertSource,
- final String fragSource) {
- int program = GL20.glCreateProgram();
- // Load vertex shader
- int vertexShader = _loadShader(name, GL20.GL_VERTEX_SHADER, vertSource);
- // Load fragment shader
- int fragShader = _loadShader(name, GL20.GL_FRAGMENT_SHADER, fragSource);
- // Bind the vertex shader to the program.
- GL20.glAttachShader(program, vertexShader);
- // Bind the fragment shader to the program.
- GL20.glAttachShader(program, fragShader);
- // Link the two shaders together into a program.
- GL20.glLinkProgram(program);
- // Delete both shaders, does not matter when compile failed or was
- // successfully
- GL20.glDeleteShader(fragShader);
- GL20.glDeleteShader(vertexShader);
- // If the link failed, delete the program.
- final int linkStatus = GL20.glGetProgrami(program, GL20.GL_LINK_STATUS);
- if (linkStatus == 0) {
- String infoLog = GL20.glGetProgramInfoLog(program, 1024);
- GL20.glDeleteProgram(program);
- throw new IllegalStateException("Program '" + name
- + "' could not link: " + infoLog);
- }
- return program;
- }
- // private String streamToText(final InputStream inputStream) {
- // InputStreamReader reader = new InputStreamReader(inputStream);
- // char[] buffer = new char[256];
- // int read = 0;
- // StringBuffer out = new StringBuffer();
- // try {
- // while ((read = reader.read(buffer)) > 0) {
- // out.append(buffer, 0, read);
- // }
- // return out.toString();
- // } catch (IOException e) {
- // e.printStackTrace();
- // }
- // return null;
- // }
- private ByteBuffer getImageData(final BufferedImage image) {
- byte[] imageData = ((DataBufferByte) image.getRaster().getDataBuffer())
- .getData();
- byte[] buffer = new byte[image.getWidth() * image.getHeight() * 4];
- int c = 0;
- for (int i = 0; i < imageData.length; i += 3) {
- buffer[c] = imageData[i + 2]; // * Rot *
- buffer[c + 1] = imageData[i + 1]; // * Gruen *
- buffer[c + 2] = imageData[i]; // * Blau *
- buffer[c + 3] = (byte) 255; // * Alpha *
- c += 4;
- }
- ByteBuffer textureData = ByteBuffer.allocateDirect(buffer.length);
- textureData.order(ByteOrder.nativeOrder());
- textureData.put(buffer, 0, buffer.length);
- textureData.flip();
- return textureData;
- }
- private int loadTexture(final String name, final InputStream inputStream) {
- BufferedImage image;
- try {
- image = ImageIO.read(inputStream);
- } catch (IOException e) {
- throw new IllegalStateException("Could not read texture '" + name
- + "'!", e);
- }
- int width = image.getWidth();
- int height = image.getHeight();
- ByteBuffer data = getImageData(image);
- int handle = GL11.glGenTextures();
- int target = GL11.GL_TEXTURE_2D;
- GL11.glBindTexture(target, handle);
- GL11.glTexParameteri(target, GL11.GL_TEXTURE_WRAP_S,
- GL12.GL_CLAMP_TO_EDGE);
- GL11.glTexParameteri(target, GL11.GL_TEXTURE_WRAP_T,
- GL12.GL_CLAMP_TO_EDGE);
- GL11.glTexParameterf(target, GL11.GL_TEXTURE_MIN_FILTER,
- GL11.GL_NEAREST);
- GL11.glTexParameterf(target, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
- GL11.glBindTexture(target, 0);
- GL11.glTexImage2D(target, 0, GL11.GL_RGBA8, width, height, 0,
- GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, data);
- return handle;
- }
- private void createQuad(final float width, final float height) {
- float[] verts = new float[] { -width / 2, height / 2, 0.0f, // top left
- width / 2, height / 2, 0.0f, // top right
- width / 2, -height / 2, 0.0f, // bottom right
- -width / 2, -height / 2, 0.0f // bottom left
- };
- final float[] texcoords = new float[] { 0.0f, 1.0f, 1.0f, 1.0f, 1.0f,
- 0.0f, 0.0f, 0.0f };
- short[] index = new short[] { 1, 0, 3, 3, 2, 1 };
- final int vertsSize = verts.length * 4;
- final int texcoordsSize = texcoords.length * 4;
- final int indicesSize = index.length * 2;
- final int size = vertsSize + texcoordsSize;
- texcoordOffset = vertsSize;
- indexCount = index.length;
- FloatBuffer vertBuffer = ByteBuffer.allocateDirect(vertsSize)
- .order(ByteOrder.nativeOrder()).asFloatBuffer();
- vertBuffer.put(verts);
- vertBuffer.flip();
- FloatBuffer texcoordBuffer = ByteBuffer.allocateDirect(texcoordsSize)
- .order(ByteOrder.nativeOrder()).asFloatBuffer();
- texcoordBuffer.put(texcoords);
- texcoordBuffer.flip();
- ShortBuffer indexBuffer = ByteBuffer.allocateDirect(indicesSize)
- .order(ByteOrder.nativeOrder()).asShortBuffer();
- indexBuffer.put(index);
- indexBuffer.flip();
- vboID = GL15.glGenBuffers();
- GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboID);
- GL15.glBufferData(GL15.GL_ARRAY_BUFFER, size, GL15.GL_STATIC_DRAW);
- GL15.glBufferSubData(GL15.GL_ARRAY_BUFFER, 0, vertBuffer);
- GL15.glBufferSubData(GL15.GL_ARRAY_BUFFER, vertsSize, texcoordBuffer);
- GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
- iboID = GL15.glGenBuffers();
- GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, iboID);
- GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, indexBuffer, GL15.GL_STATIC_DRAW);
- GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0);
- }
- private InputStream loadResource(final String name) {
- return getClass().getClassLoader().getResourceAsStream(name);
- }
- private void init() {
- // Create vbo and ibo
- createQuad(1.0f, 1.0f);
- System.out.println("vbo id: " + vboID);
- System.out.println("ibo id: " + iboID);
- // Load shader
- shaderID = loadShaders("simple", vertShaderSource, fragShaderSource);
- System.out.println("shader id: " + shaderID);
- // Get shader locations
- GL20.glUseProgram(shaderID);
- textureSamplerLocation = GL20.glGetUniformLocation(shaderID, "uTexture");
- vertexAttribLocation = GL20.glGetAttribLocation(shaderID, "vPosition");
- texcoordAttribLocation = GL20.glGetAttribLocation(shaderID, "vTexcoord");
- GL20.glUseProgram(0);
- System.out.println("uTexture location: " + textureSamplerLocation);
- System.out.println("vPosition location: " + vertexAttribLocation);
- System.out.println("vTexcoord location: " + texcoordAttribLocation);
- // Load texture
- textureID = loadTexture("test.jpg", loadResource("textures/test.jpg"));
- System.out.println("texture id: " + textureID);
- GL11.glClearColor(1.0f, 0.0f, 1.0f, 1.0f);
- }
- public void run() {
- isRunning = true;
- this.pack();
- this.setVisible(true);
- this.requestFocus();
- canvas.requestFocusInWindow();
- try {
- Display.setParent(canvas);
- Display.create();
- init();
- while (isRunning) {
- Display.sync(60);
- handleEvents();
- update();
- draw();
- Display.update();
- }
- Display.destroy();
- } catch (Exception e) {
- e.printStackTrace();
- }
- System.exit(0);
- }
- public static void main(String[] args) {
- LWJGLTextureTest app = new LWJGLTextureTest();
- app.run();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement