Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (477)
Games in Android Showcase (108)
games submitted by our members
Games in WIP (536)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
  JavaGaming.org - Pastebin



Author: theagentd (posted 2012-10-09 18:38:42, viewed 366 times)

1   2   3   4   5   6   7   8   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33   34   35   36   37   38   39   40   41   42   43   44   45   46   47   48   49   50   51   52   53   54   55   56   57   58   59   60   61   62   63   64   65   66   67   68   69   70   71   72   73   74   75   76   77   78   79   80   81   82   83   84   85   86   87   88   89   90   91   92   93   94   95   96   97   98   99   100   101   102   103   104   105   106   107   108   109   110   111   112   113   114   115   116   117   118   119   120   121   122   123   124   125   126   127   128   129   130   131   132   133   134   135   136   137   138   139   140   141   142   143   144   145   146   147   148   149   150   151   152   153   154   155   156   157   158   159   160   161   162   163   164   165   166   167   168   169   170   171   172   173   174   175   176   177   178   179   180   181   182   183   184   185   186   187   188   189   190   191   192   193   194   195   196   197   198   199   200   201   202   203   204   205   206   207   208   209   210   211   212   213   214   215   216   217   218   219   220   221   222   223   224   225   226   227   228   229   230   231   232   233   234   235   236   237   238   239   240   241   242   243   244   245   246   247   248   249   250   251   252   253   254   255   256   257   258   259   260   261   262   263   264   265   266   267   268   269   270   271   272   273   274   275   276   277   278   279   280   281   282   283   284   285   286   287   288   289   290   291   292   293   294   295   296   297   298   299   300   301   302   303   304   305   306   307   308   309   310   311   312   313   314   315   316   317   318   319   320   321   322   323   324   325   326   327   328   329   330   331   332   333   334   335   336   337   338   339   340   341   342   343   344   345   346   347   348   349   350   351   352   353   354   355   356   357   358   359   360   361   362   363   364   365   366   367  
package dam.test;

import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.*;
import static org.lwjgl.opengl.GL13.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.*;

import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.Random;

import javax.imageio.ImageIO;

import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.PixelFormat;

public class TileRenderingTest {

   //Screen size
    private static final int WIDTH = 800, HEIGHT = 600;
    
    //Map size in tiles
    private static final int MAP_WIDTH = 2048, MAP_HEIGHT = 2048;
    
    //Tileset settings (might want to load these from a file, but this will do for now)
    private static final int TILE_WIDTH = 16, TILE_HEIGHT = 16, TILES_PER_ROW = 30, TOTAL_TILES = 16*30;
    
    //Movement speed of arrow keys
    private static final double MOVE_SPEED = 0.5;
    
    //Shader program, LOD uniform location and tileset texture
    private int program;
    private int lodLocation, scaleLocation;
    private int tilesetTexture;
    
    private TileRenderer renderer;
    private double targetScale = 2, currentScale = 2;
    private double x = MAP_WIDTH / 2.0, y = MAP_HEIGHT / 2.0;
    private ArrayList<Integer> keys;
    
    public TileRenderingTest(){
       try{
          Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT));
          //Display.setDisplayModeAndFullscreen(Display.getDesktopDisplayMode());
          Display.create(new PixelFormat(24, 0, 0, 0, 0));
       } catch(LWJGLException ex){
          ex.printStackTrace();
       }
       
       glOrtho(0, WIDTH, HEIGHT, 0, -1, 1);
       glEnable(GL_TEXTURE_2D);
       
       //Load the shader
        program = glCreateProgram();
        glAttachShader(program, loadShader(GL_VERTEX_SHADER, loadFileSource(new File("shaders/tile/tile.vert"))));
        glAttachShader(program, loadShader(GL_FRAGMENT_SHADER, loadFileSource(new File("shaders/tile/tile2.frag"))));
        glLinkProgram(program);
        String log = glGetProgramInfoLog(program, 65536);
        if(log.length() != 0){
            System.out.println("Program link log:\n" + log);
        }
        
        //Submit uniforms
        glUseProgram(program);
        glUniform2f(glGetUniformLocation(program, "mapSize"), MAP_WIDTH, MAP_HEIGHT);
        glUniform1i(glGetUniformLocation(program, "tileTexture"), 0);
        glUniform1i(glGetUniformLocation(program, "tilesetTexture"), 1);

        lodLocation = glGetUniformLocation(program, "lod");
        scaleLocation = glGetUniformLocation(program, "scale");
        
        //Load tileset texture
        tilesetTexture = glGenTextures();
        glBindTexture(GL_TEXTURE_2D_ARRAY, tilesetTexture);
        
        //Use whatever filtering you want! Mipmaps work!
        
        //Mipmaps:
        glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        
        //Blocky mipmaps
        //glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
        //glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        
        //Clamp coordinates to edge
        glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        
        //Allocate a TILE_WIDTH x TILE_HEIGHT 2D texture array with TOTAL_TILES layers. 
        glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGB8, TILE_WIDTH, TILE_HEIGHT, TOTAL_TILES, 0, GL_RGB, GL_UNSIGNED_BYTE, (ByteBuffer)null);
        
        BufferedImage image = null;
        try{
           image = ImageIO.read(new File("files/tiles/tileset.png")); 
        }catch(IOException ex){
           ex.printStackTrace();
        }
        
       int[] pixels = new int[TILE_WIDTH * TILE_HEIGHT];
       ByteBuffer buffer = BufferUtils.createByteBuffer(pixels.length * 3);
       
        int x = 0, y = 0;
        for(int i = 0; i < TOTAL_TILES; i++){
           //Split the big tileset into one tile per image
           BufferedImage subImage = image.getSubimage(x*TILE_WIDTH, y*TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT);
            PixelGrabber pg = new PixelGrabber(subImage, 0, 0, TILE_WIDTH, TILE_HEIGHT, pixels, 0, TILE_WIDTH);
            try {
                pg.grabPixels();
            } catch (InterruptedException ex) {
                System.err.println("Interrupted while loading texture. Epic error.");
            }
            for(int j = 0; j < pixels.length; j++){
               int pixel = pixels[j];
                buffer.put((byte) ((pixel >> 16) & 0xFF));     // Red component
                buffer.put((byte) ((pixel >> 8) & 0xFF));      // Green component
                buffer.put((byte) (pixel & 0xFF));
            }
            buffer.flip();
            //Load a single tile (a layer of the texture array).
            glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, i, TILE_WIDTH, TILE_HEIGHT, 1, GL_RGB, GL_UNSIGNED_BYTE, buffer);
           
           if(++x == TILES_PER_ROW){
              x = 0;
              y++;
           }
        }
        
        //Generate mipmaps.
        glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
        
        //Create tile renderer and set each tile to a random tile 
        renderer = new TileRenderer(program, lodLocation, scaleLocation, tilesetTexture, MAP_WIDTH, MAP_HEIGHT);
        
        Random r = new Random(8235928375l);
        ShortBuffer b = BufferUtils.createShortBuffer(MAP_WIDTH * MAP_HEIGHT * 3);
        for(y = 0; y < MAP_HEIGHT; y++){
           for(x = 0; x < MAP_WIDTH; x++){
              int tile = (int)(r.nextInt(TOTAL_TILES));
              b.put((short) tile)
              .put((short) x)
              .put((short) y);
           }
        }
        b.flip();
        renderer.bindTileTexture();
        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, MAP_WIDTH, MAP_HEIGHT, GL_RGB, GL_UNSIGNED_SHORT, b);
        
        //Currently pressed keys
        keys = new ArrayList<Integer>();
    }
    
    //Loads shader source from a file.
    private static String loadFileSource(File file){
        if(!file.exists()){
            System.out.println("Unable to open file " + file.getAbsolutePath() + "!!!");
            return null;
        }

        StringBuilder source = new StringBuilder();
        String line;
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            while ((line = reader.readLine()) != null) {
                source.append(line).append('\n');
            }
        } catch (Exception e) {
            System.out.println("Failed to read shader source!");
            e.printStackTrace();
            return null;
        }
        return source.toString();
    }
    
    //Creates a shader of the specified type with the specified source code
    private int loadShader(int type, String source){
       int id = glCreateShader(type);
        glShaderSource(id, source);
        glCompileShader(id);

        String errorLog = glGetShaderInfoLog(id, 65536);
        if(errorLog.length() != 0){
            System.out.println("Shader compile log: \n" + errorLog);
        }
        return id;
    }
    
    
    public void gameloop(){
       while(!Display.isCloseRequested()){
          
          //Test program input handling
          while(Mouse.next()){
             if(Mouse.getEventDWheel() > 0){
                targetScale *= 1.1;
             }
             if(Mouse.getEventDWheel() < 0){
                targetScale /= 1.1;
             }
          }
          
          while(Keyboard.next()){
             int button = Keyboard.getEventKey();
             if(Keyboard.getEventKeyState()){
                if(!keys.contains(button)){
                   keys.add(button);
                }
             }else{
                keys.remove((Integer)button);
             }
          }
          
          if(keys.contains(Keyboard.KEY_LEFT)){
             x -= MOVE_SPEED/currentScale;
          }
          
          if(keys.contains(Keyboard.KEY_RIGHT)){
             x += MOVE_SPEED/currentScale;
          }
          
          if(keys.contains(Keyboard.KEY_UP)){
             y -= MOVE_SPEED/currentScale;
          }
          
          if(keys.contains(Keyboard.KEY_DOWN)){
             y += MOVE_SPEED/currentScale;
          }
          
          //Smooth scaling
          currentScale += (targetScale - currentScale) / 100;
          
          //Clear color buffer
          glClear(GL_COLOR_BUFFER_BIT);
          glPushMatrix();
          
          glTranslated(WIDTH/2.0, HEIGHT/2.0, 0);
          glScaled(currentScale, currentScale, 1);
          

          //Comment out these two lines for non-isometric view:
          //glScalef(1, 0.5f, 1);
          //glRotatef(-45, 0, 0, 1);
          
          //glRotatef(f, 0, 0, 1);
          //f += 0.01f;
          
          
          glTranslated(-x, -y, 0);
          
          double size = Math.min(TILE_WIDTH, TILE_HEIGHT) / currentScale;
          float lod = (float)(Math.log(size) / Math.log(2));
          renderer.render(lod, Math.max(1, Math.min(16, (float)currentScale)));
          

          glPopMatrix();
          
          Display.update();
       }
    }
    
    float f = 11;
    
    public static class TileRenderer{
       
       private int shaderProgram;
       private int lodLocation, scaleLocation;
       private int tilesetTexture;
       
       private int width, height;
       private int tileTexture;
       private ShortBuffer buffer;
       
       public TileRenderer(int shaderProgram, int lodLocation, int scaleLocation, int tilesetTexture, int width, int height){
          this.shaderProgram = shaderProgram;
          this.lodLocation = lodLocation;
          this.scaleLocation = scaleLocation;
          this.tilesetTexture = tilesetTexture;
          
          this.width = width;
          this.height = height;
          
          /*Create a texture to hold tile indices for each tile.
          Uses the red and green channels of an RGB texture for a maximum of
          65536 tiles. The maximum texture size is 16384, so that is the 
          real limit as we can't have more texture layers than that
          in the other shader. This can be worked around though by not using
          a texture array.*/
          tileTexture = glGenTextures();
          glBindTexture(GL_TEXTURE_2D, tileTexture);
          
          //NO FILTERING! IMPORTANT!
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, (ByteBuffer)null);
            
            buffer = BufferUtils.createShortBuffer(3);
       }
       
       public void bindTileTexture(){
          glBindTexture(GL_TEXTURE_2D, tileTexture);
       }
       
       //Remember to bind the tile texture before calling setTile(...).
       public void setTile(int x, int y, int tile){
          buffer.put((short) tile)
          .put((short)x)
          .put((short)y)
          .flip();
          glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, 1, 1, GL_RGB, GL_UNSIGNED_SHORT, buffer);
          System.out.println((short) tile);
       }
       
       public void render(float lod, float scale){
          glUseProgram(shaderProgram);

          glUniform1f(lodLocation, lod);
          glUniform1f(scaleLocation, scale);
          
          //Bind tile index texture
          glActiveTexture(GL_TEXTURE0);
          glBindTexture(GL_TEXTURE_2D, tileTexture);
          
          //Bind tileset texture array
          glActiveTexture(GL_TEXTURE1);
          glBindTexture(GL_TEXTURE_2D_ARRAY, tilesetTexture);
          
          glBegin(GL_QUADS);
          {
             glTexCoord2f(0, 0);
             glVertex2f(0, 0);

             glTexCoord2f(width, 0);
             glVertex2f(width, 0);

             glTexCoord2f(width, height);
             glVertex2f(width, height);

             glTexCoord2f(0, height);
             glVertex2f(0, height);
          }
          glEnd();

          glActiveTexture(GL_TEXTURE0);
          glBindTexture(GL_TEXTURE_2D, 0);
       }
    }
    
    public static void main(String[] args){
       new TileRenderingTest().gameloop();
    }
}





Dump your java code here :



Special syntax:
  • To highlight a line (yellow background), prefix it with '@@'
  • To indicate that a line should be removed (red background), prefix it with '-'
  • To indicate that a line should be added (green background), prefix it with '+'
  • To post multiple snippets, seperate them by '~~~~'
  EOF
 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

CogWheelz (18 views)
2014-07-30 21:08:39

Riven (23 views)
2014-07-29 18:09:19

Riven (15 views)
2014-07-29 18:08:52

Dwinin (12 views)
2014-07-29 10:59:34

E.R. Fleming (33 views)
2014-07-29 03:07:13

E.R. Fleming (12 views)
2014-07-29 03:06:25

pw (43 views)
2014-07-24 01:59:36

Riven (43 views)
2014-07-23 21:16:32

Riven (30 views)
2014-07-23 21:07:15

Riven (31 views)
2014-07-23 20:56:16
List of Learning Resources
by SilverTiger
2014-07-31 18:29:50

List of Learning Resources
by SilverTiger
2014-07-31 18:26:06

List of Learning Resources
by SilverTiger
2014-07-31 13:54:12

HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!